@adport/provider-tiktok 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1452 -5
- package/dist/index.js +3941 -192
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts","../src/provider.ts","../src/tools.ts","../src/index.ts"],"sourcesContent":["import { AdportError } from '@adport/core';\n\nexport interface TikTokCredentials {\n /** Long-term access token (does not expire; revoked by the advertiser). */\n accessToken: string;\n appId?: string;\n secret?: string;\n /** Use the sandbox environment (sandbox-ads.tiktok.com). */\n sandbox?: boolean;\n}\n\nexport const TIKTOK_API_VERSION = 'v1.3';\nconst PROD_BASE = 'https://business-api.tiktok.com/open_api';\nconst SANDBOX_BASE = 'https://sandbox-ads.tiktok.com/open_api';\n\n/** Business-error codes worth a targeted hint. */\nconst CODE_HINTS: Record<number, string> = {\n 40105: 'The access token is invalid — re-run `adport connect tiktok`.',\n 40102: 'The access token expired or was revoked — re-run `adport connect tiktok`.',\n 40100: 'Rate limited (app level) — back off and retry.',\n 40133: 'Rate limited (advertiser level) — back off and retry.',\n};\n\n/**\n * TikTok Business API client. Peculiarities handled here:\n * - every endpoint needs a TRAILING SLASH (404 otherwise)\n * - business errors arrive as HTTP 200 with a non-zero envelope `code`\n * - array query params are JSON-encoded strings\n */\nexport class TikTokClient {\n readonly baseUrl: string;\n\n constructor(\n private readonly credentials: TikTokCredentials,\n private readonly fetchImpl: typeof fetch = fetch,\n ) {\n this.baseUrl = `${credentials.sandbox ? SANDBOX_BASE : PROD_BASE}/${TIKTOK_API_VERSION}`;\n }\n\n async get<T>(path: string, params: Record<string, unknown> = {}): Promise<T> {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined) continue;\n search.set(key, typeof value === 'object' ? JSON.stringify(value) : String(value));\n }\n const query = search.size > 0 ? `?${search}` : '';\n return this.send<T>(`${path}${query}`, { method: 'GET' });\n }\n\n async post<T>(path: string, body: Record<string, unknown>): Promise<T> {\n return this.send<T>(path, { method: 'POST', body: JSON.stringify(body) });\n }\n\n private async send<T>(pathWithQuery: string, init: { method: string; body?: string }): Promise<T> {\n // Trailing slash is mandatory before the query string.\n const [path, query] = pathWithQuery.split('?');\n const url = `${this.baseUrl}/${path!.replace(/^\\/|\\/$/g, '')}/${query ? `?${query}` : ''}`;\n const response = await this.fetchImpl(url, {\n method: init.method,\n headers: {\n 'Access-Token': this.credentials.accessToken,\n ...(init.body ? { 'content-type': 'application/json' } : {}),\n },\n body: init.body,\n });\n const raw = await response.text();\n if (!response.ok) {\n throw new AdportError('PROVIDER_ERROR', `TikTok API HTTP ${response.status} for ${path} (check method and trailing slash)`, raw);\n }\n const envelope = JSON.parse(raw) as { code: number; message: string; request_id?: string; data?: T };\n if (envelope.code !== 0) {\n const hint = CODE_HINTS[envelope.code];\n throw new AdportError(\n 'PROVIDER_ERROR',\n `TikTok API error ${envelope.code}: ${envelope.message}${hint ? `\\n ${hint}` : ''}` +\n (envelope.request_id ? ` [request_id: ${envelope.request_id}]` : ''),\n envelope,\n );\n }\n return (envelope.data ?? {}) as T;\n }\n}\n","import {\n AdportError,\n resolveDateRange,\n type Account,\n type AdProvider,\n type MetricName,\n type NormalizedQuery,\n type ProviderCapabilities,\n type Report,\n type ReportRow,\n type StandardActions,\n type WriteGuard,\n type WriteOperation,\n type WritePreview,\n type WriteResult,\n} from '@adport/core';\nimport { TikTokClient } from './client.js';\n\n/** TikTok budgets are floats in whole account-currency units. */\nexport const UNITS_TO_MICROS = 1_000_000;\n\nconst DATA_LEVEL = {\n account: 'AUCTION_ADVERTISER',\n campaign: 'AUCTION_CAMPAIGN',\n ad_group: 'AUCTION_ADGROUP',\n ad: 'AUCTION_AD',\n} as const;\n\nconst ID_DIMENSION = {\n account: 'advertiser_id',\n campaign: 'campaign_id',\n ad_group: 'adgroup_id',\n ad: 'ad_id',\n} as const;\n\ninterface TikTokCampaign {\n campaign_id: string;\n campaign_name: string;\n operation_status: 'ENABLE' | 'DISABLE';\n secondary_status?: string;\n budget: number;\n budget_mode: string;\n objective_type: string;\n}\n\ninterface WritePlan {\n summary: string;\n changes: string[];\n coercions: string[];\n budgetDeltas: WritePreview['budgetDeltas'];\n execute: () => Promise<string[]>;\n}\n\nexport class TikTokAdsProvider implements AdProvider {\n readonly id = 'tiktok';\n\n constructor(\n private readonly client: TikTokClient,\n private readonly app: { appId: string; secret: string },\n ) {}\n\n capabilities(): ProviderCapabilities {\n // No server-side dry run in the Marketing API — previews are client-side diffs.\n return { serverDryRun: false };\n }\n\n standardActions(): StandardActions {\n return {\n pauseCampaign: (accountId, campaignId) => ({\n tool: 'tiktok_set_campaign_status',\n input: { account_id: accountId, campaign_ids: [campaignId], operation_status: 'DISABLE' },\n }),\n };\n }\n\n async listAccounts(): Promise<Account[]> {\n const authorized = await this.client.get<{ list?: Array<{ advertiser_id: string; advertiser_name: string }> }>(\n 'oauth2/advertiser/get',\n { app_id: this.appId(), secret: this.secret() },\n );\n const ids = (authorized.list ?? []).map((a) => a.advertiser_id);\n if (ids.length === 0) return [];\n const info = await this.client.get<{\n list?: Array<{ advertiser_id: string; name?: string; currency?: string; status?: string; timezone?: string }>;\n }>('advertiser/info', { advertiser_ids: ids.slice(0, 100), fields: ['name', 'currency', 'status', 'timezone'] });\n const byId = new Map((info.list ?? []).map((i) => [i.advertiser_id, i]));\n return ids.map((id) => {\n const details = byId.get(id);\n return {\n provider: this.id,\n id,\n name: details?.name ?? (authorized.list ?? []).find((a) => a.advertiser_id === id)?.advertiser_name ?? id,\n currency: details?.currency,\n status: details?.status?.replace('STATUS_', ''),\n };\n });\n }\n\n async report(query: NormalizedQuery): Promise<Report> {\n const range = resolveDateRange(query.dateRange);\n const accountIds = query.accountIds ?? (await this.listAccounts()).map((a) => a.id);\n const level = DATA_LEVEL[query.level];\n const idDim = ID_DIMENSION[query.level];\n const nameMetric = { campaign: 'campaign_name', ad_group: 'adgroup_name', ad: 'ad_name' }[\n query.level as string\n ];\n\n const rows: ReportRow[] = [];\n for (const accountId of accountIds) {\n const data = await this.client.get<{\n list?: Array<{ dimensions: Record<string, string>; metrics: Record<string, string> }>;\n page_info?: { total_number?: number };\n }>('report/integrated/get', {\n advertiser_id: accountId,\n report_type: 'BASIC',\n data_level: level,\n dimensions: [idDim],\n metrics: [\n ...(nameMetric ? [nameMetric] : []),\n 'spend',\n 'impressions',\n 'clicks',\n 'conversion',\n 'complete_payment_roas',\n 'total_complete_payment_rate',\n ],\n start_date: range.start,\n end_date: range.end,\n page: 1,\n page_size: Math.min(query.limit ?? 200, 1000),\n });\n for (const row of data.list ?? []) {\n rows.push(this.toReportRow(row, accountId, query, idDim, nameMetric));\n }\n }\n return { rows };\n }\n\n private toReportRow(\n row: { dimensions: Record<string, string>; metrics: Record<string, string> },\n accountId: string,\n query: NormalizedQuery,\n idDim: string,\n nameMetric?: string,\n ): ReportRow {\n // All TikTok metric values are strings (\"14.68\"); spend is whole currency units.\n const num = (key: string) => Number(row.metrics[key] ?? 0);\n const spend = num('spend');\n const impressions = num('impressions');\n const clicks = num('clicks');\n const conversions = num('conversion');\n // total_complete_payment_rate is (despite the name) total purchase VALUE.\n const conversionValue = num('total_complete_payment_rate');\n const all: Record<MetricName, number> = {\n spend: round2(spend),\n impressions,\n clicks,\n conversions,\n conversion_value: round2(conversionValue),\n ctr: impressions > 0 ? round2((clicks / impressions) * 100) : 0,\n cpc: clicks > 0 ? round2(spend / clicks) : 0,\n cpm: impressions > 0 ? round2((spend / impressions) * 1000) : 0,\n cpa: conversions > 0 ? round2(spend / conversions) : 0,\n roas: spend > 0 ? round2(conversionValue / spend) : 0,\n };\n const entityId = row.dimensions[idDim] ?? '';\n return {\n provider: this.id,\n accountId,\n entity: {\n level: query.level,\n id: entityId,\n name: (nameMetric ? row.metrics[nameMetric] : undefined) ?? entityId,\n },\n metrics: Object.fromEntries(query.metrics.map((m) => [m, all[m]])),\n };\n }\n\n async rawReport(input: {\n account_id: string;\n data_level: string;\n dimensions: string[];\n metrics: string[];\n start_date: string;\n end_date: string;\n page_size?: number;\n }): Promise<Array<Record<string, unknown>>> {\n const data = await this.client.get<{ list?: Array<Record<string, unknown>> }>('report/integrated/get', {\n advertiser_id: input.account_id,\n report_type: 'BASIC',\n data_level: input.data_level,\n dimensions: input.dimensions,\n metrics: input.metrics,\n start_date: input.start_date,\n end_date: input.end_date,\n page: 1,\n page_size: Math.min(input.page_size ?? 200, 1000),\n });\n return data.list ?? [];\n }\n\n async apiRead(input: {\n account_id: string;\n path: string;\n params?: Record<string, unknown>;\n }): Promise<unknown> {\n const path = validateTikTokPath(input.path);\n return this.client.get(path, { ...input.params, advertiser_id: input.account_id });\n }\n\n async listCampaigns(accountId: string, campaignIds?: string[]): Promise<TikTokCampaign[]> {\n const data = await this.client.get<{ list?: TikTokCampaign[] }>('campaign/get', {\n advertiser_id: accountId,\n ...(campaignIds ? { filtering: { campaign_ids: campaignIds } } : {}),\n page: 1,\n page_size: campaignIds ? campaignIds.length : 100,\n });\n return data.list ?? [];\n }\n\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const plan = await this.plan(op, guard);\n // No validate_only equivalent — the preview is a client-side diff from live lookups.\n return {\n summary: plan.summary,\n changes: plan.changes,\n coercions: plan.coercions,\n budgetDeltas: plan.budgetDeltas,\n serverValidated: false,\n };\n }\n\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n const plan = await this.plan(op, guard);\n const resourceIds = await plan.execute();\n return { applied: true, resourceIds };\n }\n\n private async plan(op: WriteOperation, guard: WriteGuard): Promise<WritePlan> {\n const payload = op.payload as never;\n switch (op.tool) {\n case 'tiktok_create_campaign':\n return this.planCreateCampaign(op.accountId, payload, guard);\n case 'tiktok_set_campaign_status':\n return this.planSetStatus(op.accountId, payload);\n case 'tiktok_set_budget':\n return this.planSetBudget(op.accountId, payload);\n case 'tiktok_api_create':\n return this.planApiCreate(op.accountId, payload, guard);\n case 'tiktok_api_update':\n return this.planApiUpdate(op.accountId, payload);\n case 'tiktok_api_delete':\n return this.planApiDelete(op.accountId, payload);\n default:\n throw new AdportError('PROVIDER_ERROR', `tiktok: unsupported write tool ${op.tool}`);\n }\n }\n\n private async planApiCreate(\n accountId: string,\n payload: { path: string; body: Record<string, unknown> },\n guard: WriteGuard,\n ): Promise<WritePlan> {\n const path = validateTikTokMutationPath(payload.path, 'create');\n const body = structuredClone(payload.body);\n body.advertiser_id = accountId;\n const coercions: string[] = [];\n if (guard.forcePausedCreation) {\n coerceTikTokCreatedStatuses(body, coercions);\n if (path === 'campaign/create' && body.operation_status !== 'DISABLE') {\n body.operation_status = 'DISABLE';\n coercions.push('operation_status set to DISABLE by policy (paused_creation)');\n }\n }\n return {\n summary: `Create TikTok resource via /${path}`,\n changes: [`+ POST /${path} ${JSON.stringify(body)}`],\n coercions,\n budgetDeltas: collectTikTokBudgets(body),\n execute: async () => extractTikTokIds(await this.client.post(path, body)),\n };\n }\n\n private async planApiUpdate(\n accountId: string,\n payload: { path: string; body: Record<string, unknown> },\n ): Promise<WritePlan> {\n const path = validateTikTokMutationPath(payload.path, 'update');\n if (containsTikTokBudget(payload.body)) {\n throw new AdportError('INVALID_INPUT', 'tiktok: budget updates require a typed budget tool for policy checks');\n }\n const body = { ...payload.body, advertiser_id: accountId };\n return {\n summary: `Update TikTok resource via /${path}`,\n changes: [`~ POST /${path} ${JSON.stringify(body)}`],\n coercions: [],\n budgetDeltas: [],\n execute: async () => extractTikTokIds(await this.client.post(path, body)),\n };\n }\n\n private async planApiDelete(\n accountId: string,\n payload: { path: string; body: Record<string, unknown> },\n ): Promise<WritePlan> {\n const path = validateTikTokMutationPath(payload.path, 'delete');\n const body = { ...payload.body, advertiser_id: accountId };\n return {\n summary: `Permanently delete TikTok resource via /${path}`,\n changes: [`- POST /${path} ${JSON.stringify(body)}`],\n coercions: [],\n budgetDeltas: [],\n execute: async () => extractTikTokIds(await this.client.post(path, body)),\n };\n }\n\n private async planCreateCampaign(\n accountId: string,\n payload: { campaign_name: string; objective_type: string; budget_mode: string; budget?: number; operation_status?: string },\n guard: WriteGuard,\n ): Promise<WritePlan> {\n const coercions: string[] = [];\n // TikTok creates campaigns ENABLED by default; DISABLE is its \"paused\".\n let operationStatus = payload.operation_status ?? 'ENABLE';\n if (guard.forcePausedCreation && operationStatus === 'ENABLE') {\n operationStatus = 'DISABLE';\n coercions.push('operation_status coerced to DISABLE (paused) by policy (paused_creation)');\n }\n if (payload.budget_mode !== 'BUDGET_MODE_INFINITE' && !payload.budget) {\n throw new AdportError('INVALID_INPUT', `tiktok: budget is required for ${payload.budget_mode}`);\n }\n const budgetDeltas: WritePreview['budgetDeltas'] = [];\n if (payload.budget) {\n budgetDeltas.push({\n target: `new campaign \"${payload.campaign_name}\" ${payload.budget_mode === 'BUDGET_MODE_DAY' ? 'daily' : 'total'} budget`,\n toMicros: payload.budget * UNITS_TO_MICROS,\n });\n }\n return {\n summary: `Create TikTok campaign \"${payload.campaign_name}\" (${payload.objective_type}, ${operationStatus === 'DISABLE' ? 'paused' : 'active'})`,\n changes: [\n `+ campaign \"${payload.campaign_name}\" objective=${payload.objective_type} ${payload.budget_mode}` +\n (payload.budget ? ` budget=${payload.budget}` : '') +\n ` operation_status=${operationStatus}`,\n ],\n coercions,\n budgetDeltas,\n execute: async () => {\n const data = await this.client.post<{ campaign_id?: string }>('campaign/create', {\n advertiser_id: accountId,\n campaign_name: payload.campaign_name,\n objective_type: payload.objective_type,\n budget_mode: payload.budget_mode,\n ...(payload.budget ? { budget: payload.budget } : {}),\n operation_status: operationStatus,\n });\n return data.campaign_id ? [data.campaign_id] : [];\n },\n };\n }\n\n private async planSetStatus(\n accountId: string,\n payload: { campaign_ids: string[]; operation_status: 'ENABLE' | 'DISABLE' },\n ): Promise<WritePlan> {\n const campaigns = await this.listCampaigns(accountId, payload.campaign_ids);\n const changes = payload.campaign_ids.map((id) => {\n const campaign = campaigns.find((c) => c.campaign_id === id);\n return `~ campaign ${id} (\"${campaign?.campaign_name ?? '?'}\") operation_status ${campaign?.operation_status ?? '?'} → ${payload.operation_status}`;\n });\n return {\n summary: `Set ${payload.campaign_ids.length} TikTok campaign(s) → ${payload.operation_status === 'DISABLE' ? 'paused' : 'active'}`,\n changes,\n coercions: [],\n budgetDeltas: [],\n execute: async () => {\n await this.client.post('campaign/status/update', {\n advertiser_id: accountId,\n campaign_ids: payload.campaign_ids,\n operation_status: payload.operation_status,\n });\n return payload.campaign_ids;\n },\n };\n }\n\n private async planSetBudget(\n accountId: string,\n payload: { campaign_id: string; budget: number },\n ): Promise<WritePlan> {\n const campaigns = await this.listCampaigns(accountId, [payload.campaign_id]);\n const campaign = campaigns[0];\n if (!campaign) {\n throw new AdportError('PROVIDER_ERROR', `tiktok: campaign ${payload.campaign_id} not found in advertiser ${accountId}`);\n }\n if (campaign.budget_mode === 'BUDGET_MODE_INFINITE') {\n throw new AdportError('PROVIDER_ERROR', `tiktok: campaign \"${campaign.campaign_name}\" has no budget (BUDGET_MODE_INFINITE)`);\n }\n return {\n summary: `Change TikTok campaign \"${campaign.campaign_name}\" budget ${campaign.budget} → ${payload.budget} (${campaign.budget_mode})`,\n changes: [\n `~ campaign ${payload.campaign_id} budget ${campaign.budget} → ${payload.budget}`,\n '! TikTok requires the new budget to be ≥105% of already-spent amount; the API rejects violations',\n ],\n coercions: [],\n budgetDeltas: [\n {\n target: `campaign \"${campaign.campaign_name}\" ${campaign.budget_mode === 'BUDGET_MODE_DAY' ? 'daily' : 'total'} budget`,\n fromMicros: campaign.budget * UNITS_TO_MICROS,\n toMicros: payload.budget * UNITS_TO_MICROS,\n },\n ],\n execute: async () => {\n await this.client.post('campaign/update', {\n advertiser_id: accountId,\n campaign_id: payload.campaign_id,\n budget: payload.budget,\n });\n return [payload.campaign_id];\n },\n };\n }\n\n private appId(): string {\n return this.app.appId;\n }\n\n private secret(): string {\n return this.app.secret;\n }\n}\n\nfunction round2(n: number): number {\n return Math.round(n * 100) / 100;\n}\n\nfunction validateTikTokPath(path: string): string {\n const normalized = path.replace(/^\\/+|\\/+$/g, '').trim();\n if (!/^[a-z0-9_/-]{3,160}$/.test(normalized) || normalized.includes('..') || normalized.includes('//')) {\n throw new AdportError('INVALID_INPUT', `tiktok: invalid Business API path \"${path}\"`);\n }\n return normalized;\n}\n\nfunction validateTikTokMutationPath(path: string, kind: 'create' | 'update' | 'delete'): string {\n const normalized = validateTikTokPath(path);\n if (!normalized.endsWith(`/${kind}`)) {\n throw new AdportError('INVALID_INPUT', `tiktok: ${kind} tool requires an endpoint ending in /${kind}`);\n }\n return normalized;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction coerceTikTokCreatedStatuses(value: unknown, coercions: string[], path = 'body'): void {\n if (Array.isArray(value)) return value.forEach((item, index) => coerceTikTokCreatedStatuses(item, coercions, `${path}[${index}]`));\n if (!isRecord(value)) return;\n for (const [key, child] of Object.entries(value)) {\n if (key === 'operation_status' && child === 'ENABLE') {\n value[key] = 'DISABLE';\n coercions.push(`${path}.${key} coerced to DISABLE by policy (paused_creation)`);\n } else {\n coerceTikTokCreatedStatuses(child, coercions, `${path}.${key}`);\n }\n }\n}\n\nfunction containsTikTokBudget(value: unknown): boolean {\n if (Array.isArray(value)) return value.some(containsTikTokBudget);\n if (!isRecord(value)) return false;\n return Object.entries(value).some(([key, child]) => /budget/i.test(key) || containsTikTokBudget(child));\n}\n\nfunction collectTikTokBudgets(value: unknown, path = 'body'): WritePreview['budgetDeltas'] {\n const deltas: WritePreview['budgetDeltas'] = [];\n if (Array.isArray(value)) {\n value.forEach((item, index) => deltas.push(...collectTikTokBudgets(item, `${path}[${index}]`)));\n return deltas;\n }\n if (!isRecord(value)) return deltas;\n for (const [key, child] of Object.entries(value)) {\n const childPath = `${path}.${key}`;\n if (/budget/i.test(key)) {\n const amount = Number(child);\n if (Number.isFinite(amount) && amount > 0) {\n deltas.push({ target: childPath, toMicros: Math.round(amount * UNITS_TO_MICROS) });\n }\n }\n deltas.push(...collectTikTokBudgets(child, childPath));\n }\n return deltas;\n}\n\nfunction extractTikTokIds(value: unknown): string[] {\n const ids: string[] = [];\n const visit = (item: unknown): void => {\n if (Array.isArray(item)) return item.forEach(visit);\n if (!isRecord(item)) return;\n for (const [key, child] of Object.entries(item)) {\n if (/(?:^|_)ids?$/.test(key)) {\n if (Array.isArray(child)) child.forEach((id) => ids.push(String(id)));\n else if (typeof child === 'string' || typeof child === 'number') ids.push(String(child));\n } else visit(child);\n }\n };\n visit(value);\n return [...new Set(ids)];\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { TikTokAdsProvider } from './provider.js';\n\nconst OBJECTIVES = [\n 'REACH',\n 'TRAFFIC',\n 'VIDEO_VIEWS',\n 'LEAD_GENERATION',\n 'ENGAGEMENT',\n 'APP_PROMOTION',\n 'WEB_CONVERSIONS',\n 'PRODUCT_SALES',\n] as const;\n\nconst operationStatusSchema = z.enum(['ENABLE', 'DISABLE']);\n\nexport function tiktokTools(provider: TikTokAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({\n name: 'tiktok_api_read',\n namespace: 'tiktok',\n description: 'Call any documented TikTok Business API v1.3 GET endpoint with advertiser scoping and API-shaped parameters.',\n input: z.object({\n account_id: z.string(),\n path: z.string().min(3).describe('Relative endpoint, e.g. adgroup/get, ad/get, creative/report/get'),\n params: z.record(z.string(), z.unknown()).optional(),\n }),\n annotations: { readOnly: true },\n async handler(input) {\n return provider.apiRead(input);\n },\n }),\n defineTool({\n name: 'tiktok_campaigns',\n namespace: 'tiktok',\n description: 'List TikTok campaigns (id, name, operation_status ENABLE/DISABLE, budget, budget_mode, objective).',\n input: z.object({\n account_id: z.string().describe('Advertiser id'),\n campaign_ids: z.array(z.string()).optional(),\n }),\n annotations: { readOnly: true },\n async handler(input) {\n const campaigns = await provider.listCampaigns(input.account_id, input.campaign_ids);\n return { campaigns };\n },\n }),\n defineTool({\n name: 'tiktok_report',\n namespace: 'tiktok',\n description:\n 'Raw TikTok synchronous reporting (report/integrated). Metric values come back as strings; ' +\n 'note total_complete_payment_rate is total purchase VALUE (misleading name), complete_payment_roas is purchase ROAS.',\n input: z.object({\n account_id: z.string(),\n data_level: z.enum(['AUCTION_ADVERTISER', 'AUCTION_CAMPAIGN', 'AUCTION_ADGROUP', 'AUCTION_AD']).default('AUCTION_CAMPAIGN'),\n dimensions: z.array(z.string()).min(1).default(['campaign_id']),\n metrics: z.array(z.string()).min(1).default(['spend', 'impressions', 'clicks', 'conversion']),\n start_date: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/),\n end_date: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/),\n page_size: z.number().int().positive().max(1000).default(200),\n }),\n annotations: { readOnly: true },\n async handler(input) {\n const rows = await provider.rawReport(input);\n return { rows, row_count: rows.length };\n },\n }),\n guardedWriteTool({\n name: 'tiktok_create_campaign',\n namespace: 'tiktok',\n description:\n 'Create a TikTok campaign. Budget is a float in whole account-currency units (min ~20 USD-equivalent for ' +\n 'DAY/TOTAL modes). TikTok has no server-side dry run — the preview is a client-side diff.',\n provider: 'tiktok',\n kind: 'create',\n payload: z.object({\n campaign_name: z.string().min(1).max(512),\n objective_type: z.enum(OBJECTIVES).default('TRAFFIC'),\n budget_mode: z.enum(['BUDGET_MODE_DAY', 'BUDGET_MODE_TOTAL', 'BUDGET_MODE_INFINITE']).default('BUDGET_MODE_DAY'),\n budget: z.number().positive().optional().describe('Whole currency units (float), required unless BUDGET_MODE_INFINITE'),\n operation_status: operationStatusSchema.optional(),\n }),\n }),\n guardedWriteTool({\n name: 'tiktok_set_campaign_status',\n namespace: 'tiktok',\n description: 'Enable or pause (DISABLE) up to 20 TikTok campaigns.',\n provider: 'tiktok',\n kind: 'update',\n payload: z.object({\n campaign_ids: z.array(z.string()).min(1).max(20),\n operation_status: operationStatusSchema,\n }),\n }),\n guardedWriteTool({\n name: 'tiktok_set_budget',\n namespace: 'tiktok',\n description:\n \"Change a TikTok campaign's budget (whole currency units). TikTok rejects new budgets below 105% of current spend.\",\n provider: 'tiktok',\n kind: 'update',\n payload: z.object({\n campaign_id: z.string(),\n budget: z.number().positive(),\n }),\n }),\n guardedWriteTool({\n name: 'tiktok_api_create',\n namespace: 'tiktok',\n description:\n 'Create through any documented TikTok Business API v1.3 /create endpoint. The advertiser is forced to account_id, campaign creation is paused, and budget fields are policy-checked.',\n provider: 'tiktok',\n kind: 'create',\n payload: z.object({ path: z.string().min(3), body: z.record(z.string(), z.unknown()) }),\n }),\n guardedWriteTool({\n name: 'tiktok_api_update',\n namespace: 'tiktok',\n description: 'Update non-budget fields through any documented TikTok Business API v1.3 /update endpoint.',\n provider: 'tiktok',\n kind: 'update',\n payload: z.object({ path: z.string().min(3), body: z.record(z.string(), z.unknown()) }),\n }),\n guardedWriteTool({\n name: 'tiktok_api_delete',\n namespace: 'tiktok',\n description: 'Permanently delete through any documented TikTok Business API v1.3 /delete endpoint.',\n provider: 'tiktok',\n kind: 'remove',\n destructive: true,\n payload: z.object({ path: z.string().min(3), body: z.record(z.string(), z.unknown()) }),\n }),\n ];\n}\n","import type { CredentialStore, ProviderModule } from '@adport/core';\nimport { TikTokClient, type TikTokCredentials } from './client.js';\nimport { TikTokAdsProvider } from './provider.js';\nimport { tiktokTools } from './tools.js';\n\nexport { TikTokClient, TIKTOK_API_VERSION, type TikTokCredentials } from './client.js';\nexport { TikTokAdsProvider, UNITS_TO_MICROS } from './provider.js';\nexport { tiktokTools } from './tools.js';\n\nexport async function resolveTikTokCredentials(\n store: CredentialStore,\n): Promise<(TikTokCredentials & { appId: string; secret: string }) | undefined> {\n const record = await store.get('tiktok');\n if (record?.data.access_token && record.data.app_id && record.data.secret) {\n return {\n accessToken: record.data.access_token,\n appId: record.data.app_id,\n secret: record.data.secret,\n sandbox: record.data.sandbox === 'true',\n };\n }\n const env = process.env;\n if (env.TIKTOK_ACCESS_TOKEN && env.TIKTOK_APP_ID && env.TIKTOK_APP_SECRET) {\n return {\n accessToken: env.TIKTOK_ACCESS_TOKEN,\n appId: env.TIKTOK_APP_ID,\n secret: env.TIKTOK_APP_SECRET,\n sandbox: env.TIKTOK_SANDBOX === 'true',\n };\n }\n return undefined;\n}\n\nexport async function createTikTokModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveTikTokCredentials(store);\n if (!credentials) return undefined;\n const provider = new TikTokAdsProvider(new TikTokClient(credentials), {\n appId: credentials.appId,\n secret: credentials.secret,\n });\n return { provider, tools: tiktokTools(provider) };\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;AAWrB,IAAM,qBAAqB;AAClC,IAAM,YAAY;AAClB,IAAM,eAAe;AAGrB,IAAM,aAAqC;AAAA,EACzC,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AACT;AAQO,IAAM,eAAN,MAAmB;AAAA,EAGxB,YACmB,aACA,YAA0B,OAC3C;AAFiB;AACA;AAEjB,SAAK,UAAU,GAAG,YAAY,UAAU,eAAe,SAAS,IAAI,kBAAkB;AAAA,EACxF;AAAA,EAJmB;AAAA,EACA;AAAA,EAJV;AAAA,EAST,MAAM,IAAO,MAAc,SAAkC,CAAC,GAAe;AAC3E,UAAM,SAAS,IAAI,gBAAgB;AACnC,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AACjD,UAAI,UAAU,OAAW;AACzB,aAAO,IAAI,KAAK,OAAO,UAAU,WAAW,KAAK,UAAU,KAAK,IAAI,OAAO,KAAK,CAAC;AAAA,IACnF;AACA,UAAM,QAAQ,OAAO,OAAO,IAAI,IAAI,MAAM,KAAK;AAC/C,WAAO,KAAK,KAAQ,GAAG,IAAI,GAAG,KAAK,IAAI,EAAE,QAAQ,MAAM,CAAC;AAAA,EAC1D;AAAA,EAEA,MAAM,KAAQ,MAAc,MA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A,EACH;AACF;;;AC7HA,eAAsB,yBACpB,OAC8E;AAC9E,QAAM,SAAS,MAAM,MAAM,IAAI,QAAQ;AACvC,MAAI,QAAQ,KAAK,gBAAgB,OAAO,KAAK,UAAU,OAAO,KAAK,QAAQ;AACzE,WAAO;AAAA,MACL,aAAa,OAAO,KAAK;AAAA,MACzB,OAAO,OAAO,KAAK;AAAA,MACnB,QAAQ,OAAO,KAAK;AAAA,MACpB,SAAS,OAAO,KAAK,YAAY;AAAA,IACnC;AAAA,EACF;AACA,QAAM,MAAM,QAAQ;AACpB,MAAI,IAAI,uBAAuB,IAAI,iBAAiB,IAAI,mBAAmB;AACzE,WAAO;AAAA,MACL,aAAa,IAAI;AAAA,MACjB,OAAO,IAAI;AAAA,MACX,QAAQ,IAAI;AAAA,MACZ,SAAS,IAAI,mBAAmB;AAAA,IAClC;AAAA,EACF;AACA,SAAO;AACT;AAEA,eAAsB,mBAAmB,OAA6D;AACpG,QAAM,cAAc,MAAM,yBAAyB,KAAK;AACxD,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,WAAW,IAAI,kBAAkB,IAAI,aAAa,WAAW,GAAG;AAAA,IACpE,OAAO,YAAY;AAAA,IACnB,QAAQ,YAAY;AAAA,EACtB,CAAC;AACD,SAAO,EAAE,UAAU,OAAO,YAAY,QAAQ,EAAE;AAClD;","names":["AdportError"]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/provider.ts","../src/creatives.ts","../src/audiences.ts","../src/pagination.ts","../src/custom-audiences.ts","../src/audience-file.ts","../src/custom-audience-schemas.ts","../src/audience-sources.ts","../src/audience-authoring-schemas.ts","../src/audience-authoring.ts","../src/measurement.ts","../src/automated-rules.ts","../src/catalogs.ts","../src/catalog-tools.ts","../src/catalog-schema.ts","../src/catalog-product-sets.ts","../src/product-set-conditions.ts","../src/catalog-feeds.ts","../src/catalog-products.ts","../src/catalog-product-authoring.ts","../src/catalog-product-contract.ts","../src/catalog-product-shapes.ts","../src/catalog-lifecycle.ts","../src/catalog-access.ts","../src/catalog-event-sources.ts","../src/catalog-videos.ts","../src/audience-sharing.ts","../src/audience-sharing-schemas.ts","../src/tools.ts","../src/creative-tools.ts","../src/custom-audience-tools.ts","../src/audience-authoring-tools.ts","../src/audience-sharing-tools.ts","../src/index.ts"],"sourcesContent":["import { AdportError } from '@adport/core';\nimport { createHmac, timingSafeEqual } from 'node:crypto';\n\nexport interface TikTokCredentials {\n /** Long-term access token (does not expire; revoked by the advertiser). */\n accessToken: string;\n appId?: string;\n secret?: string;\n /** Use the sandbox environment (sandbox-ads.tiktok.com). */\n sandbox?: boolean;\n}\n\nexport const TIKTOK_API_VERSION = 'v1.3';\nconst PROD_BASE = 'https://business-api.tiktok.com/open_api';\nconst SANDBOX_BASE = 'https://sandbox-ads.tiktok.com/open_api';\n\n/** Business-error codes worth a targeted hint. */\nconst CODE_HINTS: Record<number, string> = {\n 40105: 'The access token is invalid — re-run `adport connect tiktok`.',\n 40102: 'The access token expired or was revoked — re-run `adport connect tiktok`.',\n 40100: 'Rate limited (app level) — back off and retry.',\n 40133: 'Rate limited (advertiser level) — back off and retry.',\n};\n\n/**\n * TikTok Business API client. Peculiarities handled here:\n * - every endpoint needs a TRAILING SLASH (404 otherwise)\n * - business errors arrive as HTTP 200 with a non-zero envelope `code`\n * - array query params are JSON-encoded strings\n */\nexport class TikTokClient {\n readonly baseUrl: string;\n\n constructor(\n private readonly credentials: TikTokCredentials,\n private readonly fetchImpl: typeof fetch = fetch,\n ) {\n this.baseUrl = `${credentials.sandbox ? SANDBOX_BASE : PROD_BASE}/${TIKTOK_API_VERSION}`;\n }\n\n async get<T>(path: string, params: Record<string, unknown> = {}, options: { jsonContentType?: boolean } = {}): Promise<T> {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined) continue;\n search.set(key, typeof value === 'object' ? JSON.stringify(value) : String(value));\n }\n const query = search.size > 0 ? `?${search}` : '';\n return this.send<T>(`${path}${query}`, { method: 'GET', ...options });\n }\n\n async post<T>(path: string, body: Record<string, unknown>): Promise<T> {\n return this.send<T>(path, { method: 'POST', body: JSON.stringify(body) });\n }\n\n async postMultipart<T>(path: string, form: FormData): Promise<T> {\n return this.send<T>(path, { method: 'POST', body: form });\n }\n\n /** Account/file bindings are issued only after this credential accepts the native upload. */\n audienceFileReceipt(value: Record<string, unknown>): string {\n const payload = Buffer.from(JSON.stringify(value)).toString('base64url');\n return payload + '.' + this.audienceReceiptMac(payload).toString('base64url');\n }\n verifyAudienceFileReceipt(receipt: string): unknown {\n const invalid = () => new AdportError('INVALID_INPUT', 'Invalid audience upload receipt; use the receipt from this credential’s approved upload.');\n if (receipt.length > 8192 || !/^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]{43}$/.test(receipt)) throw invalid();\n const [payload, signature] = receipt.split('.'), actual = Buffer.from(signature!, 'base64url'), expected = this.audienceReceiptMac(payload!);\n if (actual.toString('base64url') !== signature || actual.length !== expected.length || !timingSafeEqual(actual, expected)) throw invalid();\n try { return JSON.parse(Buffer.from(payload!, 'base64url').toString('utf8')); } catch { throw invalid(); }\n }\n private audienceReceiptMac(payload: string): Buffer { return createHmac('sha256', this.credentials.accessToken).update('adport.tiktok.audience-file.v1.' + this.baseUrl + '.' + payload).digest(); }\n\n private async send<T>(pathWithQuery: string, init: { method: string; body?: string | FormData; jsonContentType?: boolean }): Promise<T> {\n // Trailing slash is mandatory before the query string.\n const [path, query] = pathWithQuery.split('?');\n const url = `${this.baseUrl}/${path!.replace(/^\\/|\\/$/g, '')}/${query ? `?${query}` : ''}`;\n const response = await this.fetchImpl(url, {\n method: init.method,\n headers: {\n 'Access-Token': this.credentials.accessToken,\n ...(typeof init.body === 'string' || init.jsonContentType ? { 'content-type': 'application/json' } : {}),\n },\n body: init.body,\n redirect: 'error',\n signal: AbortSignal.timeout(30_000),\n });\n const raw = await response.text();\n if (!response.ok) {\n throw new AdportError('PROVIDER_ERROR', `TikTok API HTTP ${response.status} for ${path} (check method and trailing slash)`, raw);\n }\n const envelope = JSON.parse(raw) as { code: number; message: string; request_id?: string; data?: T };\n if (envelope.code !== 0) {\n const hint = CODE_HINTS[envelope.code];\n throw new AdportError(\n 'PROVIDER_ERROR',\n `TikTok API error ${envelope.code}: ${envelope.message}${hint ? `\\n ${hint}` : ''}` +\n (envelope.request_id ? ` [request_id: ${envelope.request_id}]` : ''),\n envelope,\n );\n }\n return (envelope.data ?? {}) as T;\n }\n}\n","import {\n AdportError,\n LocalMediaResolver,\n type MediaResolver,\n resolveDateRange,\n type Account,\n type AdProvider,\n type MetricName,\n type NormalizedQuery,\n type ProviderCapabilities,\n type Report,\n type ReportRow,\n type StandardActions,\n type WriteGuard,\n type WriteOperation,\n type WritePreview,\n type WriteResult,\n} from '@adport/core';\nimport { TikTokClient } from './client.js';\nimport { TikTokCreativeService } from './creatives.js';\nimport { TikTokAudienceService } from './audiences.js';\nimport { TikTokCustomAudiences } from './custom-audiences.js';\nimport { TikTokAudienceSources } from './audience-sources.js';\nimport { TikTokAudienceAuthoring } from './audience-authoring.js';\nimport { TikTokMeasurementService } from './measurement.js';\nimport { TikTokAutomatedRulesService } from './automated-rules.js';\nimport { TikTokCatalogService } from './catalogs.js';\nimport { TikTokAudienceSharing } from './audience-sharing.js';\nimport { audienceSharingWrites } from './audience-sharing-schemas.js';\nimport type { TikTokCatalogAccessStore } from './catalog-access.js';\n\n/** TikTok budgets are floats in whole account-currency units. */\nexport const UNITS_TO_MICROS = 1_000_000;\n\nconst DATA_LEVEL = {\n account: 'AUCTION_ADVERTISER',\n campaign: 'AUCTION_CAMPAIGN',\n ad_group: 'AUCTION_ADGROUP',\n ad: 'AUCTION_AD',\n} as const;\n\nconst ID_DIMENSION = {\n account: 'advertiser_id',\n campaign: 'campaign_id',\n ad_group: 'adgroup_id',\n ad: 'ad_id',\n} as const;\n\ninterface TikTokCampaign {\n advertiser_id?: string;\n campaign_id: string;\n campaign_name: string;\n operation_status: 'ENABLE' | 'DISABLE';\n secondary_status?: string;\n budget: number;\n budget_mode: string;\n objective_type: string;\n}\n\ntype WritePlan = Omit<WritePreview, 'serverValidated'> & { execute: () => Promise<string[] | WriteResult> };\n\nexport class TikTokAdsProvider implements AdProvider {\n readonly id = 'tiktok';\n readonly creatives: TikTokCreativeService;\n readonly audiences: TikTokAudienceService;\n readonly customAudiences: TikTokCustomAudiences;\n readonly audienceSources: TikTokAudienceSources;\n readonly audienceAuthoring: TikTokAudienceAuthoring;\n readonly audienceSharing: TikTokAudienceSharing;\n readonly measurement: TikTokMeasurementService;\n readonly automatedRules: TikTokAutomatedRulesService;\n readonly catalogs: TikTokCatalogService;\n\n constructor(\n private readonly client: TikTokClient,\n private readonly app: { appId: string; secret: string },\n media: MediaResolver = new LocalMediaResolver(),\n catalogAccess?: TikTokCatalogAccessStore,\n ) {\n const authorizeAccounts = async (ids: string[]) => {\n const authorized = await client.get<{ list?: Array<{ advertiser_id: string }> }>('oauth2/advertiser/get', { app_id: this.appId(), secret: this.secret() });\n if (!Array.isArray(authorized.list) || authorized.list.some(row => typeof row.advertiser_id !== 'string') || ids.some(id => !authorized.list!.some(row => row.advertiser_id === id))) throw new AdportError('POLICY_VIOLATION', 'Every selected advertiser must be in the current native authorization.');\n };\n this.creatives = new TikTokCreativeService(client, media);\n this.audiences = new TikTokAudienceService(client);\n this.customAudiences = new TikTokCustomAudiences(client, media);\n this.audienceSources = new TikTokAudienceSources(client, account => authorizeAccounts([account]));\n this.audienceAuthoring = new TikTokAudienceAuthoring(client, this.customAudiences, this.audienceSources);\n this.audienceSharing = new TikTokAudienceSharing(client, this.customAudiences, authorizeAccounts);\n this.measurement = new TikTokMeasurementService(client);\n this.automatedRules = new TikTokAutomatedRulesService(client);\n this.catalogs = new TikTokCatalogService(client, catalogAccess, media);\n }\n\n capabilities(): ProviderCapabilities {\n // No server-side dry run in the Marketing API — previews are client-side diffs.\n return { serverDryRun: false };\n }\n\n standardActions(): StandardActions {\n return {\n pauseCampaign: (accountId, campaignId) => ({\n tool: 'tiktok_set_campaign_status',\n input: { account_id: accountId, campaign_ids: [campaignId], operation_status: 'DISABLE' },\n }),\n };\n }\n\n async listAccounts(): Promise<Account[]> {\n const authorized = await this.client.get<{ list?: Array<{ advertiser_id: string; advertiser_name: string }> }>(\n 'oauth2/advertiser/get',\n { app_id: this.appId(), secret: this.secret() },\n );\n const ids = (authorized.list ?? []).map((a) => a.advertiser_id);\n if (ids.length === 0) return [];\n const info = await this.client.get<{\n list?: Array<{ advertiser_id: string; name?: string; currency?: string; status?: string; timezone?: string }>;\n }>('advertiser/info', { advertiser_ids: ids.slice(0, 100), fields: ['name', 'currency', 'status', 'timezone'] });\n const byId = new Map((info.list ?? []).map((i) => [i.advertiser_id, i]));\n return ids.map((id) => {\n const details = byId.get(id);\n return {\n provider: this.id,\n id,\n name: details?.name ?? (authorized.list ?? []).find((a) => a.advertiser_id === id)?.advertiser_name ?? id,\n currency: details?.currency,\n status: details?.status?.replace('STATUS_', ''),\n };\n });\n }\n\n async report(query: NormalizedQuery): Promise<Report> {\n const range = resolveDateRange(query.dateRange);\n const accountIds = query.accountIds ?? (await this.listAccounts()).map((a) => a.id);\n const level = DATA_LEVEL[query.level];\n const idDim = ID_DIMENSION[query.level];\n const nameMetric = { campaign: 'campaign_name', ad_group: 'adgroup_name', ad: 'ad_name' }[\n query.level as string\n ];\n\n const rows: ReportRow[] = [];\n for (const accountId of accountIds) {\n const data = await this.client.get<{\n list?: Array<{ dimensions: Record<string, string>; metrics: Record<string, string> }>;\n page_info?: { total_number?: number };\n }>('report/integrated/get', {\n advertiser_id: accountId,\n report_type: 'BASIC',\n data_level: level,\n dimensions: [idDim],\n metrics: [\n ...(nameMetric ? [nameMetric] : []),\n 'spend',\n 'impressions',\n 'clicks',\n 'conversion',\n 'complete_payment_roas',\n 'total_complete_payment_rate',\n ],\n start_date: range.start,\n end_date: range.end,\n page: 1,\n page_size: Math.min(query.limit ?? 200, 1000),\n });\n for (const row of data.list ?? []) {\n rows.push(this.toReportRow(row, accountId, query, idDim, nameMetric));\n }\n }\n return { rows };\n }\n\n private toReportRow(\n row: { dimensions: Record<string, string>; metrics: Record<string, string> },\n accountId: string,\n query: NormalizedQuery,\n idDim: string,\n nameMetric?: string,\n ): ReportRow {\n // All TikTok metric values are strings (\"14.68\"); spend is whole currency units.\n const num = (key: string) => Number(row.metrics[key] ?? 0);\n const spend = num('spend');\n const impressions = num('impressions');\n const clicks = num('clicks');\n const conversions = num('conversion');\n // total_complete_payment_rate is (despite the name) total purchase VALUE.\n const conversionValue = num('total_complete_payment_rate');\n const all: Record<MetricName, number> = {\n spend: round2(spend),\n impressions,\n clicks,\n conversions,\n conversion_value: round2(conversionValue),\n ctr: impressions > 0 ? round2((clicks / impressions) * 100) : 0,\n cpc: clicks > 0 ? round2(spend / clicks) : 0,\n cpm: impressions > 0 ? round2((spend / impressions) * 1000) : 0,\n cpa: conversions > 0 ? round2(spend / conversions) : 0,\n roas: spend > 0 ? round2(conversionValue / spend) : 0,\n };\n const entityId = row.dimensions[idDim] ?? '';\n return {\n provider: this.id,\n accountId,\n entity: {\n level: query.level,\n id: entityId,\n name: (nameMetric ? row.metrics[nameMetric] : undefined) ?? entityId,\n },\n metrics: Object.fromEntries(query.metrics.map((m) => [m, all[m]])),\n };\n }\n\n async rawReport(input: {\n account_id: string;\n data_level: string;\n dimensions: string[];\n metrics: string[];\n start_date: string;\n end_date: string;\n page_size?: number;\n }): Promise<Array<Record<string, unknown>>> {\n const data = await this.client.get<{ list?: Array<Record<string, unknown>> }>('report/integrated/get', {\n advertiser_id: input.account_id,\n report_type: 'BASIC',\n data_level: input.data_level,\n dimensions: input.dimensions,\n metrics: input.metrics,\n start_date: input.start_date,\n end_date: input.end_date,\n page: 1,\n page_size: Math.min(input.page_size ?? 200, 1000),\n });\n return data.list ?? [];\n }\n\n async apiRead(input: {\n account_id: string;\n path: string;\n params?: Record<string, unknown>;\n }): Promise<unknown> {\n const path = validateTikTokPath(input.path);\n return this.client.get(path, { ...input.params, advertiser_id: input.account_id });\n }\n\n async listCampaigns(accountId: string, campaignIds?: string[]): Promise<TikTokCampaign[]> {\n const data = await this.client.get<{ list?: TikTokCampaign[] }>('campaign/get', {\n advertiser_id: accountId,\n ...(campaignIds ? { filtering: { campaign_ids: campaignIds } } : {}),\n page: 1,\n page_size: campaignIds ? campaignIds.length : 100,\n });\n return data.list ?? [];\n }\n\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const plan = await this.plan(op, guard);\n // No validate_only equivalent — the preview is a client-side diff from live lookups.\n const { execute: _execute, ...preview } = plan;\n return { ...preview, serverValidated: false };\n }\n\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n const plan = await this.plan(op, guard);\n const resourceIds = await plan.execute();\n if (!Array.isArray(resourceIds)) return resourceIds;\n if (op.tool === 'tiktok_create_catalog') return { applied: true, resourceIds, details: { configuration_readback: 'VERIFIED', project_catalog_access: 'write', products_created: false, ads_created: false } };\n if (op.tool === 'tiktok_delete_catalog') return { applied: true, resourceIds, details: { deletion_readback: 'ABSENT_FROM_FILTERED_CATALOG_VIEW', resource_grant_retained: true } };\n if (op.tool === 'tiktok_upload_catalog_videos') {\n const payload = op.payload as { bc_id: string; catalog_id: string; media_id: string; expected_sha256: string; sync_to_selected_account?: boolean };\n return { applied: true, resourceIds, details: { status: 'ACCEPTED_FOR_PROCESSING', processed: false, feed_log_id: resourceIds[0], source_media_id: payload.media_id, source_sha256: payload.expected_sha256, advertiser_sync_requested: payload.sync_to_selected_account === true, advertiser_sync_confirmed: false, next_tool: 'tiktok_catalog_video_log', next_arguments: { account_id: op.accountId, bc_id: payload.bc_id, catalog_id: payload.catalog_id, feed_log_id: resourceIds[0] } } };\n }\n if (op.tool === 'tiktok_delete_catalog_video') return { applied: true, resourceIds, details: { deletion_readback: 'ABSENT_FROM_FILTERED_CATALOG_VIEW', synced_copies_may_remain: true } };\n if (['tiktok_import_catalog_file', 'tiktok_upsert_catalog_products', 'tiktok_update_catalog_products', 'tiktok_delete_catalog_products'].includes(op.tool)) {\n const payload = op.payload as { bc_id: string; catalog_id: string; feed_id: string; media_id: string; expected_sha256: string; media_assets?: unknown[] };\n return { applied: true, resourceIds, details: { status: 'ACCEPTED_FOR_PROCESSING', processed: false, feed_log_id: resourceIds[0], feed_id: payload.feed_id,\n ...(op.tool === 'tiktok_import_catalog_file' ? { source_media_id: payload.media_id, source_sha256: payload.expected_sha256 } : payload.media_assets?.length ? { source_media_assets: payload.media_assets } : {}), next_tool: 'tiktok_catalog_product_log',\n next_arguments: { account_id: op.accountId, bc_id: payload.bc_id, catalog_id: payload.catalog_id, feed_id: payload.feed_id, feed_log_id: resourceIds[0] },\n } };\n }\n return { applied: true, resourceIds };\n }\n\n private async plan(op: WriteOperation, guard: WriteGuard): Promise<WritePlan> {\n if (audienceSharingWrites.has(op.tool)) return this.audienceSharing.plan(op);\n if (['tiktok_create_rule_audience', 'tiktok_create_lookalike_audience', 'tiktok_refresh_lookalike_audiences'].includes(op.tool)) return this.audienceAuthoring.plan(op);\n if (['tiktok_upload_audience_file', 'tiktok_create_customer_audience', 'tiktok_update_customer_audience_users', 'tiktok_rename_custom_audience', 'tiktok_delete_custom_audiences'].includes(op.tool)) return this.customAudiences.plan(op);\n const payload = op.payload as never;\n switch (op.tool) {\n case 'tiktok_create_catalog':\n case 'tiktok_delete_catalog':\n case 'tiktok_bind_catalog_event_sources':\n case 'tiktok_unbind_catalog_event_sources':\n case 'tiktok_upload_catalog_videos':\n case 'tiktok_delete_catalog_video':\n case 'tiktok_upsert_catalog_products':\n case 'tiktok_update_catalog_products':\n case 'tiktok_delete_catalog_products':\n case 'tiktok_create_catalog_feed':\n case 'tiktok_import_catalog_file':\n case 'tiktok_update_catalog_feed':\n case 'tiktok_set_catalog_feed_schedule_status':\n case 'tiktok_delete_catalog_feed':\n case 'tiktok_rename_product_set':\n case 'tiktok_create_product_set':\n case 'tiktok_upload_product_set':\n case 'tiktok_update_product_set_conditions':\n case 'tiktok_delete_product_sets':\n case 'tiktok_update_catalog':\n case 'tiktok_set_catalog_access':\n return this.catalogs.plan(op);\n case 'tiktok_create_pixel':\n case 'tiktok_update_pixel':\n return this.measurement.plan(op);\n case 'tiktok_create_saved_audience':\n case 'tiktok_delete_saved_audiences':\n return this.audiences.plan(op);\n case 'tiktok_create_ad_group':\n case 'tiktok_create_ads':\n case 'tiktok_set_ad_group_status':\n case 'tiktok_set_ad_status':\n case 'tiktok_update_ad':\n case 'tiktok_update_targeting':\n case 'tiktok_set_ad_group_budget':\n case 'tiktok_set_ad_group_bidding':\n case 'tiktok_upload_image':\n case 'tiktok_upload_video':\n return this.creatives.plan(op, guard);\n case 'tiktok_create_campaign':\n return this.planCreateCampaign(op.accountId, payload, guard);\n case 'tiktok_set_campaign_status':\n return this.planSetStatus(op.accountId, payload);\n case 'tiktok_set_budget':\n return this.planSetBudget(op.accountId, payload);\n case 'tiktok_api_create':\n return this.planApiCreate(op.accountId, payload, guard);\n case 'tiktok_api_update':\n return this.planApiUpdate(op.accountId, payload);\n case 'tiktok_api_delete':\n return this.planApiDelete(op.accountId, payload);\n default:\n throw new AdportError('PROVIDER_ERROR', `tiktok: unsupported write tool ${op.tool}`);\n }\n }\n\n private async planApiCreate(\n accountId: string,\n payload: { path: string; body: Record<string, unknown> },\n guard: WriteGuard,\n ): Promise<WritePlan> {\n const path = validateTikTokMutationPath(payload.path, 'create');\n const body = structuredClone(payload.body);\n body.advertiser_id = accountId;\n const coercions: string[] = [];\n if (guard.forcePausedCreation) {\n coerceTikTokCreatedStatuses(body, coercions);\n if (['campaign/create', 'adgroup/create'].includes(path) && body.operation_status !== 'DISABLE') {\n body.operation_status = 'DISABLE';\n coercions.push('operation_status set to DISABLE by policy (paused_creation)');\n }\n if (path === 'ad/create' && Array.isArray(body.creatives)) {\n for (const [index, creative] of body.creatives.entries()) if (isRecord(creative) && creative.operation_status !== 'DISABLE') {\n creative.operation_status = 'DISABLE'; coercions.push(`creatives[${index}].operation_status set to DISABLE by policy (paused_creation)`);\n }\n }\n }\n return {\n summary: `Create TikTok resource via /${path}`,\n changes: [`+ POST /${path} ${JSON.stringify(body)}`],\n coercions,\n budgetDeltas: collectTikTokBudgets(body),\n execute: async () => extractTikTokIds(await this.client.post(path, body)),\n };\n }\n\n private async planApiUpdate(\n accountId: string,\n payload: { path: string; body: Record<string, unknown> },\n ): Promise<WritePlan> {\n const path = validateTikTokMutationPath(payload.path, 'update');\n if (containsTikTokBudget(payload.body)) {\n throw new AdportError('INVALID_INPUT', 'tiktok: budget updates require a typed budget tool for policy checks');\n }\n const body = { ...payload.body, advertiser_id: accountId };\n return {\n summary: `Update TikTok resource via /${path}`,\n changes: [`~ POST /${path} ${JSON.stringify(body)}`],\n coercions: [],\n budgetDeltas: [],\n execute: async () => extractTikTokIds(await this.client.post(path, body)),\n };\n }\n\n private async planApiDelete(\n accountId: string,\n payload: { path: string; body: Record<string, unknown> },\n ): Promise<WritePlan> {\n const path = validateTikTokMutationPath(payload.path, 'delete');\n const body = { ...payload.body, advertiser_id: accountId };\n return {\n summary: `Permanently delete TikTok resource via /${path}`,\n changes: [`- POST /${path} ${JSON.stringify(body)}`],\n coercions: [],\n budgetDeltas: [],\n execute: async () => extractTikTokIds(await this.client.post(path, body)),\n };\n }\n\n private async planCreateCampaign(\n accountId: string,\n payload: { campaign_name: string; objective_type: string; budget_mode: string; budget?: number; operation_status?: string },\n guard: WriteGuard,\n ): Promise<WritePlan> {\n const coercions: string[] = [];\n // TikTok creates campaigns ENABLED by default; DISABLE is its \"paused\".\n let operationStatus = payload.operation_status ?? 'ENABLE';\n if (guard.forcePausedCreation && operationStatus === 'ENABLE') {\n operationStatus = 'DISABLE';\n coercions.push('operation_status coerced to DISABLE (paused) by policy (paused_creation)');\n }\n if (payload.budget_mode !== 'BUDGET_MODE_INFINITE' && !payload.budget) {\n throw new AdportError('INVALID_INPUT', `tiktok: budget is required for ${payload.budget_mode}`);\n }\n const budgetDeltas: WritePreview['budgetDeltas'] = [];\n if (payload.budget) {\n budgetDeltas.push({\n target: `new campaign \"${payload.campaign_name}\" ${payload.budget_mode === 'BUDGET_MODE_DAY' ? 'daily' : 'total'} budget`,\n toMicros: payload.budget * UNITS_TO_MICROS,\n });\n }\n return {\n summary: `Create TikTok campaign \"${payload.campaign_name}\" (${payload.objective_type}, ${operationStatus === 'DISABLE' ? 'paused' : 'active'})`,\n changes: [\n `+ campaign \"${payload.campaign_name}\" objective=${payload.objective_type} ${payload.budget_mode}` +\n (payload.budget ? ` budget=${payload.budget}` : '') +\n ` operation_status=${operationStatus}`,\n ],\n coercions,\n budgetDeltas,\n execute: async () => {\n const data = await this.client.post<{ campaign_id?: string }>('campaign/create', {\n advertiser_id: accountId,\n campaign_name: payload.campaign_name,\n objective_type: payload.objective_type,\n budget_mode: payload.budget_mode,\n ...(payload.budget ? { budget: payload.budget } : {}),\n operation_status: operationStatus,\n });\n return data.campaign_id ? [data.campaign_id] : [];\n },\n };\n }\n\n private async planSetStatus(\n accountId: string,\n payload: { campaign_ids: string[]; operation_status: 'ENABLE' | 'DISABLE' },\n ): Promise<WritePlan> {\n const campaigns = await this.listCampaigns(accountId, payload.campaign_ids);\n if (payload.campaign_ids.some(id => !campaigns.some(campaign => campaign.campaign_id === id && (campaign.advertiser_id === undefined || campaign.advertiser_id === accountId)))) throw new AdportError('INVALID_INPUT', 'tiktok: campaign was not found in the selected advertiser');\n const changes = payload.campaign_ids.map((id) => {\n const campaign = campaigns.find((c) => c.campaign_id === id);\n return `~ campaign ${id} (\"${campaign?.campaign_name ?? '?'}\") operation_status ${campaign?.operation_status ?? '?'} → ${payload.operation_status}`;\n });\n return {\n summary: `Set ${payload.campaign_ids.length} TikTok campaign(s) → ${payload.operation_status === 'DISABLE' ? 'paused' : 'active'}`,\n changes,\n coercions: [],\n budgetDeltas: [],\n execute: async () => {\n await this.client.post('campaign/status/update', {\n advertiser_id: accountId,\n campaign_ids: payload.campaign_ids,\n operation_status: payload.operation_status,\n });\n return payload.campaign_ids;\n },\n };\n }\n\n private async planSetBudget(\n accountId: string,\n payload: { campaign_id: string; budget: number },\n ): Promise<WritePlan> {\n const campaigns = await this.listCampaigns(accountId, [payload.campaign_id]);\n const campaign = campaigns.find(campaign => campaign.campaign_id === payload.campaign_id);\n if (!campaign || (campaign.advertiser_id !== undefined && campaign.advertiser_id !== accountId)) {\n throw new AdportError('PROVIDER_ERROR', `tiktok: campaign ${payload.campaign_id} not found in advertiser ${accountId}`);\n }\n if (campaign.budget_mode === 'BUDGET_MODE_INFINITE') {\n throw new AdportError('PROVIDER_ERROR', `tiktok: campaign \"${campaign.campaign_name}\" has no budget (BUDGET_MODE_INFINITE)`);\n }\n return {\n summary: `Change TikTok campaign \"${campaign.campaign_name}\" budget ${campaign.budget} → ${payload.budget} (${campaign.budget_mode})`,\n changes: [\n `~ campaign ${payload.campaign_id} budget ${campaign.budget} → ${payload.budget}`,\n '! TikTok requires the new budget to be ≥105% of already-spent amount; the API rejects violations',\n ],\n coercions: [],\n budgetDeltas: [\n {\n target: `campaign \"${campaign.campaign_name}\" ${campaign.budget_mode === 'BUDGET_MODE_DAY' ? 'daily' : 'total'} budget`,\n fromMicros: campaign.budget * UNITS_TO_MICROS,\n toMicros: payload.budget * UNITS_TO_MICROS,\n },\n ],\n execute: async () => {\n await this.client.post('campaign/update', {\n advertiser_id: accountId,\n campaign_id: payload.campaign_id,\n budget: payload.budget,\n });\n return [payload.campaign_id];\n },\n };\n }\n\n private appId(): string {\n return this.app.appId;\n }\n\n private secret(): string {\n return this.app.secret;\n }\n}\n\nfunction round2(n: number): number {\n return Math.round(n * 100) / 100;\n}\n\nfunction validateTikTokPath(path: string): string {\n const normalized = path.replace(/^\\/+|\\/+$/g, '').trim();\n if (!/^[a-z0-9_/-]{3,160}$/.test(normalized) || normalized.includes('..') || normalized.includes('//')) {\n throw new AdportError('INVALID_INPUT', `tiktok: invalid Business API path \"${path}\"`);\n }\n return normalized;\n}\n\nfunction validateTikTokMutationPath(path: string, kind: 'create' | 'update' | 'delete'): string {\n const normalized = validateTikTokPath(path);\n if (normalized.startsWith('optimizer/rule/')) {\n throw new AdportError('INVALID_INPUT', 'tiktok: automated-rule mutations require a verified direct-advertiser workflow with scheduled-action budget and account checks; raw dispatch cannot enforce these limits');\n }\n if (!normalized.endsWith(`/${kind}`)) {\n throw new AdportError('INVALID_INPUT', `tiktok: ${kind} tool requires an endpoint ending in /${kind}`);\n }\n return normalized;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction coerceTikTokCreatedStatuses(value: unknown, coercions: string[], path = 'body'): void {\n if (Array.isArray(value)) return value.forEach((item, index) => coerceTikTokCreatedStatuses(item, coercions, `${path}[${index}]`));\n if (!isRecord(value)) return;\n for (const [key, child] of Object.entries(value)) {\n if (key === 'operation_status' && child === 'ENABLE') {\n value[key] = 'DISABLE';\n coercions.push(`${path}.${key} coerced to DISABLE by policy (paused_creation)`);\n } else {\n coerceTikTokCreatedStatuses(child, coercions, `${path}.${key}`);\n }\n }\n}\n\nfunction containsTikTokBudget(value: unknown): boolean {\n if (Array.isArray(value)) return value.some(containsTikTokBudget);\n if (!isRecord(value)) return false;\n return Object.entries(value).some(([key, child]) => /budget|^(?:bid_price|conversion_bid_price|deep_cpa_bid|roas_bid)$/i.test(key) || containsTikTokBudget(child));\n}\n\nfunction collectTikTokBudgets(value: unknown, path = 'body'): WritePreview['budgetDeltas'] {\n const deltas: WritePreview['budgetDeltas'] = [];\n if (Array.isArray(value)) {\n value.forEach((item, index) => deltas.push(...collectTikTokBudgets(item, `${path}[${index}]`)));\n return deltas;\n }\n if (!isRecord(value)) return deltas;\n for (const [key, child] of Object.entries(value)) {\n const childPath = `${path}.${key}`;\n if (/budget|^(?:bid_price|conversion_bid_price|deep_cpa_bid)$/i.test(key)) {\n const amount = Number(child);\n if (Number.isFinite(amount) && amount > 0) {\n deltas.push({ target: childPath, toMicros: Math.round(amount * UNITS_TO_MICROS) });\n }\n }\n deltas.push(...collectTikTokBudgets(child, childPath));\n }\n return deltas;\n}\n\nfunction extractTikTokIds(value: unknown): string[] {\n const ids: string[] = [];\n const visit = (item: unknown): void => {\n if (Array.isArray(item)) return item.forEach(visit);\n if (!isRecord(item)) return;\n for (const [key, child] of Object.entries(item)) {\n if (/(?:^|_)ids?$/.test(key)) {\n if (Array.isArray(child)) child.forEach((id) => ids.push(String(id)));\n else if (typeof child === 'string' || typeof child === 'number') ids.push(String(child));\n } else visit(child);\n }\n };\n visit(value);\n return [...new Set(ids)];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, creativeStatusAction, type Creative, type MediaResolver, type MediaSource, type WriteGuard, type WriteOperation, type WritePreview } from '@adport/core';\nimport type { z } from 'zod';\nimport type { groupPayload } from './creative-tools.js';\nimport type { TikTokClient } from './client.js';\n\ntype Row = Record<string, unknown>;\ntype PageInfo = { total_page?: number; total_number?: number };\ninterface Page { account_id: string; page: number; page_size: number }\ninterface List { list?: Row[]; page_info?: PageInfo }\ninterface Plan { summary: string; changes: string[]; coercions: string[]; budgetDeltas: WritePreview['budgetDeltas']; execute: () => Promise<string[]> }\n\n/** Contracts checked against TikTok-owned SDK f809c396 and v1.3 OpenAPI files. */\nexport class TikTokCreativeService {\n constructor(private readonly client: TikTokClient, private readonly media: MediaResolver) {}\n\n async read(path: string, input: { account_id: string } & Row, post = false) {\n const { account_id, ...params } = input;\n return post ? this.client.post(path, { ...params, advertiser_id: account_id }) : this.client.get(path, { ...params, advertiser_id: account_id });\n }\n\n async groups(input: Page & { campaign_ids?: string[]; ad_group_ids?: string[] }) {\n const data = await this.client.get<List>('adgroup/get', { advertiser_id: input.account_id, filtering: { ...(input.campaign_ids ? { campaign_ids: input.campaign_ids } : {}), ...(input.ad_group_ids ? { adgroup_ids: input.ad_group_ids } : {}) }, page: input.page, page_size: input.page_size });\n return { ad_groups: data.list ?? [], page_info: data.page_info, truncated: truncated(data, input) };\n }\n\n async ads(input: Page & { ad_group_ids?: string[]; ad_ids?: string[] }) {\n const data = await this.client.get<List>('ad/get', { advertiser_id: input.account_id, filtering: { ...(input.ad_group_ids ? { adgroup_ids: input.ad_group_ids } : {}), ...(input.ad_ids ? { ad_ids: input.ad_ids } : {}) }, page: input.page, page_size: input.page_size });\n const creatives: Creative[] = (data.list ?? []).map(row => {\n if (row.advertiser_id !== undefined && String(row.advertiser_id) !== input.account_id) throw new AdportError('PROVIDER_ERROR', 'tiktok: ad response belongs to another advertiser');\n const id = String(row.ad_id), group = String(row.adgroup_id ?? ''), status = String(row.operation_status ?? row.secondary_status ?? '');\n const args = { account_id: input.account_id, ad_group_id: group, ad_id: id };\n return { id, name: String(row.ad_name ?? id), account_id: input.account_id, provider: 'tiktok', type: String(row.ad_format ?? 'TIKTOK_AD'), status,\n ...(row.campaign_id ? { campaign_id: String(row.campaign_id) } : {}), ...(group ? { ad_group_id: group } : {}), headlines: [], descriptions: typeof row.ad_text === 'string' ? [row.ad_text] : [], landing_urls: safeUrl(row.landing_page_url),\n media: [...safeUrl(row.video_url).filter(url => url.startsWith('https:')).map(url => ({ type: 'video' as const, url })), ...safeUrl(row.image_url).filter(url => url.startsWith('https:')).map(url => ({ type: 'image' as const, url }))],\n actions: status === 'DELETE' ? [] : [\n ...(['ENABLE', 'DISABLE'].includes(status) ? [creativeStatusAction('tiktok_set_ad_status', { account_id: input.account_id, ad_ids: [id] }, status, ['ENABLE', 'DISABLE'])] : []),\n ...(group ? [{ label: 'Edit ad copy', tool: 'tiktok_update_ad', arguments: args, fields: [{ key: 'ad_name', label: 'Ad name', type: 'text' as const, value: String(row.ad_name ?? ''), max_length: 512 }, ...(!row.tiktok_item_id && typeof row.ad_text === 'string' ? [{ key: 'ad_text', label: 'Ad text', type: 'text' as const, value: row.ad_text, max_length: 100 }] : [])] }] : []),\n ],\n };\n });\n return { creatives, ads: data.list ?? [], page_info: data.page_info, truncated: truncated(data, input) };\n }\n\n private async owned(account: string, entity: 'campaign' | 'adgroup' | 'ad', ids: string[]): Promise<Row[]> {\n const key = `${entity}_id`;\n const data = await this.client.get<List>(`${entity}/get`, { advertiser_id: account, filtering: { [`${entity}_ids`]: ids }, page: 1, page_size: Math.max(ids.length, 100) });\n return ids.map(id => {\n const row = data.list?.find(row => String(row[key]) === id);\n if (!row || (row.advertiser_id !== undefined && String(row.advertiser_id) !== account) || row.operation_status === 'DELETE') throw new AdportError('INVALID_INPUT', `tiktok: ${entity} ${id} was not found in the selected advertiser`);\n return row;\n });\n }\n\n async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const p = op.payload;\n const coercions: string[] = [], budgetDeltas: WritePreview['budgetDeltas'] = [];\n let path: string, body: Row, ids: string[] = [];\n const paused = (value: unknown, label: string) => { if (guard.forcePausedCreation && value !== 'DISABLE') { coercions.push(`${label}.operation_status coerced to DISABLE by policy (paused_creation)`); return 'DISABLE'; } return value ?? 'DISABLE'; };\n if (op.tool === 'tiktok_upload_image' || op.tool === 'tiktok_upload_video') return this.upload(op, op.tool.endsWith('_image') ? 'image' : 'video');\n switch (op.tool) {\n case 'tiktok_create_ad_group': {\n const value = p as z.infer<typeof groupPayload>;\n await this.owned(op.accountId, 'campaign', [value.campaign_id]);\n const { targeting, ...fields } = value;\n path = 'adgroup/create'; body = { ...fields, ...targeting, advertiser_id: op.accountId, operation_status: paused(value.operation_status, 'adgroup') };\n for (const field of ['budget', 'bid_price', 'conversion_bid_price'] as const) if (value[field] !== undefined) budgetDeltas.push({ target: `new ad group ${value.adgroup_name} ${field}`, toMicros: Math.round(value[field]! * 1_000_000) });\n break;\n }\n case 'tiktok_create_ads': {\n const group = String(p.ad_group_id); await this.owned(op.accountId, 'adgroup', [group]);\n path = 'ad/create'; body = { advertiser_id: op.accountId, adgroup_id: group, creatives: (p.creatives as Row[]).map((creative, index) => ({ ...creative, operation_status: paused(creative.operation_status, `creative[${index}]`) })) };\n break;\n }\n case 'tiktok_set_ad_group_status':\n case 'tiktok_set_ad_status': {\n const entity = op.tool === 'tiktok_set_ad_status' ? 'ad' : 'adgroup';\n ids = p[entity === 'ad' ? 'ad_ids' : 'ad_group_ids'] as string[];\n const current = await this.owned(op.accountId, entity, ids);\n return { summary: `Set ${ids.length} TikTok ${entity}(s) → ${p.operation_status}`, changes: current.map(row => `~ ${row[`${entity}_id`]} status ${row.operation_status ?? 'unknown'} → ${p.operation_status}`), budgetDeltas, coercions, execute: async () => { await this.client.post(`${entity}/status/update`, { advertiser_id: op.accountId, [`${entity}_ids`]: ids, operation_status: p.operation_status, ...(entity === 'adgroup' ? { allow_partial_success: false } : {}) }); return ids; } };\n }\n case 'tiktok_update_ad': {\n const [ad] = await this.owned(op.accountId, 'ad', [String(p.ad_id)]);\n if (String(ad!.adgroup_id) !== p.ad_group_id) throw new AdportError('INVALID_INPUT', 'tiktok: ad does not belong to the selected ad group');\n await this.owned(op.accountId, 'adgroup', [String(p.ad_group_id)]);\n const { ad_group_id, ...fields } = p;\n path = 'ad/update'; body = { advertiser_id: op.accountId, adgroup_id: ad_group_id, patch_update: true, creatives: [fields] }; ids = [String(p.ad_id)];\n break;\n }\n case 'tiktok_update_targeting':\n case 'tiktok_set_ad_group_budget':\n case 'tiktok_set_ad_group_bidding': {\n const [current] = await this.owned(op.accountId, 'adgroup', [String(p.ad_group_id)]);\n const fields = op.tool === 'tiktok_update_targeting' ? p.targeting as Row : Object.fromEntries(Object.entries(p).filter(([key]) => key !== 'ad_group_id'));\n for (const key of ['budget', 'bid_price', 'conversion_bid_price']) if (fields[key] !== undefined) {\n if (current![key] === undefined || !Number.isFinite(Number(current![key]))) throw new AdportError('INVALID_INPUT', `tiktok: current ${key} is unavailable; cannot policy-check the change`);\n budgetDeltas.push({ target: `ad group ${p.ad_group_id} ${key}`, fromMicros: Math.round(Number(current![key]) * 1_000_000), toMicros: Math.round(Number(fields[key]) * 1_000_000) });\n }\n path = 'adgroup/update'; body = { advertiser_id: op.accountId, adgroup_id: p.ad_group_id, ...fields }; ids = [String(p.ad_group_id)];\n break;\n }\n default: throw new AdportError('PROVIDER_ERROR', `tiktok: unsupported creative tool ${op.tool}`);\n }\n return { summary: `TikTok ${op.tool.replace(/^tiktok_/, '').replaceAll('_', ' ')}`, changes: [`${op.kind === 'create' ? '+' : '~'} POST /${path} ${JSON.stringify(body)}`], budgetDeltas, coercions, execute: async () => {\n const result = await this.client.post<Row>(path, body);\n if (op.kind !== 'create') return ids;\n const created = resourceIds(result, path === 'adgroup/create' ? 'adgroup' : 'ad');\n if (!created.length) throw new AdportError('PROVIDER_ERROR', 'tiktok: creation returned no resource IDs; read configuration before retrying');\n return created;\n } };\n }\n\n private async upload(op: WriteOperation, type: 'image' | 'video'): Promise<Plan> {\n const file = await this.media.read(op.payload as unknown as MediaSource, { maxBytes: (type === 'image' ? 10 : 100) * 1024 * 1024, contentTypes: type === 'image' ? ['image/jpeg', 'image/png'] : ['video/mp4', 'video/quicktime'] });\n const signature = createHash('md5').update(file.bytes).digest('hex');\n return { summary: `Upload TikTok ${type} ${file.name} (${file.bytes.byteLength} bytes)`, changes: [`+ ${type} SHA-256=${file.sha256}; advertiser=${op.accountId}`], coercions: [], budgetDeltas: [], execute: async () => {\n const form = new FormData(); form.append('advertiser_id', op.accountId); form.append('file_name', file.name); form.append('upload_type', 'UPLOAD_BY_FILE'); form.append(`${type}_signature`, signature); form.append(`${type}_file`, new Blob([file.bytes], { type: file.contentType }), file.name);\n const result = await this.client.postMultipart<Row>(`file/${type}/ad/upload`, form), ids = resourceIds(result, type);\n if (!ids.length) throw new AdportError('PROVIDER_ERROR', 'tiktok: upload returned no media ID; inspect the asset library before retrying');\n return ids;\n } };\n }\n}\n\nfunction truncated(data: List, input: Page): boolean { return data.page_info?.total_page !== undefined ? input.page < data.page_info.total_page : data.page_info?.total_number !== undefined ? input.page * input.page_size < data.page_info.total_number : (data.list?.length ?? 0) >= input.page_size; }\nfunction safeUrl(value: unknown): string[] { try { const url = new URL(String(value)); return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password ? [url.toString()] : []; } catch { return []; } }\nfunction resourceIds(value: unknown, kind: 'ad' | 'adgroup' | 'image' | 'video'): string[] {\n if (Array.isArray(value)) return [...new Set(value.flatMap(item => resourceIds(item, kind)))];\n if (!value || typeof value !== 'object') return [];\n return [...new Set(Object.entries(value).flatMap(([key, item]) => key === `${kind}_id` || key === `${kind}_ids` ? (Array.isArray(item) ? item.filter(validId).map(String) : validId(item) ? [String(item)] : []) : resourceIds(item, kind)))];\n}\nfunction validId(value: unknown): value is string | number { return typeof value === 'string' && value.length > 0 || typeof value === 'number' && Number.isSafeInteger(value) && value > 0; }\n","import { createHash } from 'node:crypto';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { TikTokClient } from './client.js';\nimport type { TikTokAdsProvider } from './provider.js';\nimport { nativeListComplete } from './pagination.js';\n\nconst id = z.string().regex(/^\\d+$/);\nconst nativeId = z.union([id, z.number().int().positive().safe()]).transform(String);\nconst ids = z.array(id).refine(values => new Set(values).size === values.length, 'IDs must be unique');\nconst strings = z.array(z.string().min(1));\nconst name = z.string().trim().min(1).max(512).refine(value => !/[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20e3\\x00-\\x1f\\x7f]/u.test(value), 'Saved audience names cannot contain emoji or control characters');\nconst actions = z.object({\n action_category_ids: ids.min(1), action_period: z.union([z.literal(0), z.literal(7), z.literal(15)]),\n action_scene: z.enum(['VIDEO_RELATED', 'CREATOR_RELATED', 'HASHTAG_RELATED']),\n video_user_actions: strings.min(1),\n}).strict().refine(value => value.video_user_actions.every(action => ({ VIDEO_RELATED: ['WATCHED_TO_END', 'LIKED', 'COMMENTED', 'SHARED'], CREATOR_RELATED: ['FOLLOWING', 'VIEW_HOMEPAGE'], HASHTAG_RELATED: ['VIEW_HASHTAG'] })[value.action_scene].includes(action)), 'Action values must match their action scene');\nexport const savedAudienceCreate = z.object({\n saved_audience_name: name, location_ids: ids.min(1), actions: z.array(actions).optional(),\n age_groups: strings.optional(), audience_ids: ids.optional(), excluded_audience_ids: ids.optional(),\n carrier_ids: ids.optional(), device_model_ids: ids.optional(), device_price_ranges: z.array(z.number().int().safe()).optional(),\n gender: z.enum(['GENDER_FEMALE', 'GENDER_MALE', 'GENDER_UNLIMITED']).optional(),\n interest_category_ids: ids.optional(), interest_keyword_ids: ids.optional(), languages: strings.optional(),\n min_android_version: z.string().min(1).optional(), min_ios_version: z.string().min(1).optional(),\n network_types: strings.optional(), operating_systems: z.array(z.enum(['ANDROID', 'IOS'])).max(1).optional(),\n}).strict().refine(value => !(value.device_model_ids?.length && value.device_price_ranges?.length), 'Device model and device price targeting cannot be combined');\nconst target = z.object({ saved_audience_id: id, expected_snapshot_hash: z.string().regex(/^[a-f0-9]{64}$/) }).strict();\nexport const savedAudienceDelete = z.object({ targets: z.array(target).min(1).max(100).refine(values => new Set(values.map(value => value.saved_audience_id)).size === values.length, 'Targets must be unique') }).strict();\nexport const savedAudienceList = z.object({ account_id: id, saved_audience_ids: ids.min(1).max(100).optional(), page: z.number().int().positive().safe().default(1), page_size: z.number().int().positive().max(100).default(10) });\nconst row = z.looseObject({ saved_audience_id: nativeId, saved_audience_name: z.string(), advertiser_id: nativeId.optional() });\nconst pageInfo = z.looseObject({ page: z.number().int().positive().safe(), page_size: z.number().int().positive().max(100), total_number: z.number().int().nonnegative().safe().optional(), total_page: z.number().int().nonnegative().safe().optional() });\nconst response = z.looseObject({ saved_audiences: z.array(row), page_info: pageInfo.optional() });\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<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 digest = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex');\nconst snapshot = (account: string, value: z.infer<typeof row>) => digest({ account_id: account, audience: value });\nconst notes = ['Local preview only. A saved targeting template does not create or change ads, campaigns, budgets or delivery.', 'TikTok permissions and targeting eligibility remain authoritative. No automatic write retry; reconcile the ID or filtered list after an uncertain outcome.'];\n\n/** Wire contracts: TikTok-owned SDK/OpenAPI f809c396, dmp/saved_audience/{list,create,delete}. */\nexport class TikTokAudienceService {\n constructor(private readonly client: TikTokClient) {}\n\n async list(raw: z.input<typeof savedAudienceList>) {\n const input = savedAudienceList.parse(raw);\n const parsed = response.safeParse(await this.client.get('dmp/saved_audience/list', { advertiser_id: input.account_id, saved_audience_ids: input.saved_audience_ids, page: input.page, page_size: input.page_size }));\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'tiktok: saved-audience response shape could not be verified');\n const data = parsed.data, records = data.saved_audiences;\n if (records.length > input.page_size || new Set(records.map(item => item.saved_audience_id)).size !== records.length || records.some(item => item.advertiser_id !== undefined && item.advertiser_id !== input.account_id || input.saved_audience_ids && !input.saved_audience_ids.includes(item.saved_audience_id))) throw new AdportError('PROVIDER_ERROR', 'tiktok: saved-audience response does not match the selected advertiser, IDs or page size');\n const page = data.page_info;\n if (page && (page.page !== input.page || page.page_size !== input.page_size)) throw new AdportError('PROVIDER_ERROR', 'tiktok: saved-audience pagination does not match the requested page');\n const complete = nativeListComplete(page, records.length);\n return { ...data, saved_audiences: records.map(item => ({ ...item, snapshot_hash: snapshot(input.account_id, item) })), complete, truncated: complete !== true,\n ...(complete === false ? { next_page: input.page + 1 } : {}),\n ...(complete === null ? { pagination_note: 'Native pagination is missing or contradictory; completeness is unknown.' } : {}),\n };\n }\n\n async get(account: string, audienceId: string) {\n const result = await this.list({ account_id: account, saved_audience_ids: [audienceId], page: 1, page_size: 100 });\n const audience = result.saved_audiences.find(item => item.saved_audience_id === audienceId);\n if (!audience && result.complete !== true) throw new AdportError('PROVIDER_ERROR', 'tiktok: saved-audience lookup could not confirm absence; inspect native pagination before another operation');\n if (!audience) throw new AdportError('INVALID_INPUT', 'tiktok: saved audience was not found in the selected advertiser');\n return { audience };\n }\n\n async plan(op: WriteOperation): Promise<Plan> {\n if (op.tool === 'tiktok_create_saved_audience') {\n const input = savedAudienceCreate.parse(op.payload), coercions: string[] = [];\n const body = { ...input, ...(input.actions ? { actions: input.actions.map((item, index) => {\n if (item.action_scene !== 'VIDEO_RELATED' && item.action_period !== 0) { coercions.push(`actions[${index}].action_period coerced to 0 for ${item.action_scene} by TikTok`); return { ...item, action_period: 0 }; }\n return item;\n }) } : {}), advertiser_id: op.accountId };\n return { summary: `Create TikTok saved audience \"${input.saved_audience_name}\"`, changes: [`+ Saved targeting template ${JSON.stringify(body)}`], notes, coercions, budgetDeltas: [], execute: async () => {\n const result = z.looseObject({ saved_audience_id: nativeId }).safeParse(await this.client.post('dmp/saved_audience/create', body));\n if (!result.success) throw new AdportError('PROVIDER_ERROR', 'tiktok: creation did not return a verified saved-audience ID; inspect the advertiser list before another create');\n const audienceId = result.data.saved_audience_id;\n try {\n const actual = (await this.get(op.accountId, audienceId)).audience;\n if (!Object.entries(body).filter(([key]) => key !== 'advertiser_id').every(([key, value]) => canonical((actual as Record<string, unknown>)[key]) === canonical(value))) throw new Error('Targeting readback differs');\n } catch { throw new AdportError('PROVIDER_ERROR', 'tiktok: saved-audience creation readback unconfirmed; reconcile the returned ID before any new create', { resource_ids: [audienceId] }); }\n return [audienceId];\n } };\n }\n if (op.tool !== 'tiktok_delete_saved_audiences') throw new AdportError('INVALID_INPUT', 'tiktok: unsupported saved-audience operation');\n const input = savedAudienceDelete.parse(op.payload), audienceIds = input.targets.map(item => item.saved_audience_id);\n const current = await this.list({ account_id: op.accountId, saved_audience_ids: audienceIds, page: 1, page_size: 100 });\n const selected = input.targets.map(item => {\n const found = current.saved_audiences.find(value => value.saved_audience_id === item.saved_audience_id);\n if (!found || found.snapshot_hash !== item.expected_snapshot_hash) throw new AdportError('INVALID_INPUT', 'tiktok: a saved audience is missing or changed; read its current snapshot before a new preview');\n return found;\n });\n return { summary: `Permanently delete ${selected.length} TikTok saved audience(s)`, changes: selected.map(item => `- ${item.saved_audience_id}: ${item.saved_audience_name}. No native restore endpoint.`), notes, coercions: [], budgetDeltas: [], execute: async () => {\n await this.client.post('dmp/saved_audience/delete', { advertiser_id: op.accountId, saved_audience_ids: audienceIds });\n try {\n const remaining = await this.list({ account_id: op.accountId, saved_audience_ids: audienceIds, page: 1, page_size: 100 });\n if (remaining.saved_audiences.length || remaining.complete !== true) throw new Error('Deletion not confirmed');\n } catch { throw new AdportError('PROVIDER_ERROR', 'tiktok: deletion readback unconfirmed; reconcile every approved ID before any new delete', { resource_ids: audienceIds }); }\n return audienceIds;\n } };\n }\n}\n\nexport function tiktokAudienceTools(provider: TikTokAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'tiktok_saved_audiences', namespace: 'tiktok', description: 'List or filter saved targeting templates, up to100 IDs and100 rows/page. Returns snapshot_hash for deletion and explicit native completeness; does not upload customer data or send tracking events.', input: savedAudienceList, presentation: 'records', annotations: { readOnly: true }, handler: input => provider.audiences.list(input) }),\n defineTool({ name: 'tiktok_get_saved_audience', namespace: 'tiktok', description: 'Read one saved targeting template using TikTok’s ID-filtered list endpoint; verifies the selected advertiser and ID and returns its current snapshot_hash.', input: z.object({ account_id: id, saved_audience_id: id }), presentation: 'records', annotations: { readOnly: true }, handler: input => provider.audiences.get(input.account_id, input.saved_audience_id) }),\n guardedWriteTool({ name: 'tiktok_create_saved_audience', namespace: 'tiktok', provider: 'tiktok', kind: 'create', destructive: false, description: 'Create a reusable targeting template with native location, interest, audience, device and action fields. No campaign, budget or delivery update. Requires the existing advertiser permission; independently verifies creation and never retries automatically.', payload: savedAudienceCreate }),\n guardedWriteTool({ name: 'tiktok_delete_saved_audiences', namespace: 'tiktok', provider: 'tiktok', kind: 'remove', destructive: true, description: 'Permanently delete up to100 saved targeting templates using each current snapshot_hash. All IDs must match before any write; filtered readback confirms deletion. No restore endpoint or automatic retry.', payload: savedAudienceDelete }),\n ];\n}\n","interface NativePageInfo { page: number; page_size: number; total_page?: number; total_number?: number }\n\n/** A filtered empty page proves absence only when native totals are consistent. */\nexport function nativeListComplete(page: NativePageInfo | undefined, count: number): boolean | null {\n if (!page || page.total_page === undefined || count > page.page_size || page.total_page < page.page && count > 0) return null;\n if (page.total_number !== undefined) {\n const expectedPages = Math.ceil(page.total_number / page.page_size);\n if (page.total_number === 0 ? page.total_page > 1 : page.total_page !== expectedPages) return null;\n const expectedRows = Math.max(0, Math.min(page.page_size, page.total_number - (page.page - 1) * page.page_size));\n if (count !== expectedRows) return null;\n }\n return page.page >= page.total_page;\n}\n","import { createHash } from 'node:crypto';\nimport { z } from 'zod';\nimport { AdportError, type MediaResolver, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport type { TikTokClient } from './client.js';\nimport { nativeListComplete } from './pagination.js';\nimport { audienceFileRecords } from './audience-file.js';\nimport { audienceId, audienceIds, audienceNativeId, audienceFileProof, audienceFileUpload, customAudienceList, customAudienceGet, customerAudienceCreate, customerAudienceUpdate, customAudienceRename, customAudiencesDelete } from './custom-audience-schemas.js';\n\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<WriteResult> };\nconst text = z.string().max(100_000), nativeDetails = z.object({ audience_id: audienceNativeId, owner_id: audienceNativeId.optional(), name: z.string().max(4096), type: z.string().max(128), is_creator: z.boolean().optional(), shared: z.boolean().optional(), is_valid: z.boolean().optional(), is_expiring: z.boolean().optional(), expired_time: z.string().max(100).optional(), create_time: z.string().max(100).optional(), calculate_type: z.string().max(100).nullable().optional(), audience_sub_type: z.string().max(100).optional(), rule: text.nullable().optional(), is_auto_refresh: z.boolean().optional(), lookalike_spec: z.json().optional(), cover_num: z.number().nonnegative().safe().optional(), msg: text.nullable().optional(), error_msg: text.nullable().optional() });\ntype Details = z.infer<typeof nativeDetails>;\nconst listRow = z.object({ audience_id: audienceNativeId, name: z.string().max(4096), audience_type: z.string().max(128), is_creator: z.boolean().optional(), shared: z.boolean().optional(), is_valid: z.boolean().optional(), is_expiring: z.boolean().optional(), expired_time: z.string().max(100).optional(), create_time: z.string().max(100).optional(), calculate_type: z.string().max(100).nullable().optional(), cover_num: z.number().nonnegative().safe().optional() });\nconst pageInfo = z.object({ page: z.number().int().positive().safe(), page_size: z.number().int().positive().max(100), total_page: z.number().int().nonnegative().safe().optional(), total_number: z.number().int().nonnegative().safe().optional() });\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 digest = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex');\nconst ruleValue = (value: string | null | undefined): unknown => { if (typeof value !== 'string') return value;try { return JSON.parse(value); } catch { return value; } };\nconst configuration = (row: Details) => ({ audience_id: row.audience_id, owner_id: row.owner_id, name: row.name, type: row.type, calculate_type: row.calculate_type, audience_sub_type: row.audience_sub_type, rule: ruleValue(row.rule), is_auto_refresh: row.is_auto_refresh, lookalike_spec: row.lookalike_spec, create_time: row.create_time, is_creator: row.is_creator, shared: row.shared });\nconst snapshot = (account: string, row: Details) => digest({ account_id: account, configuration: configuration(row), is_valid: row.is_valid, is_expiring: row.is_expiring, expired_time: row.expired_time, native_error_reported: !!row.error_msg });\nconst publicDetails = (account: string, row: Details) => { const { msg, error_msg, ...fields } = row;return { ...fields, native_status_message_present: !!msg, native_error_reported: !!error_msg, snapshot_hash: snapshot(account, row) }; };\nconst invalid = () => new AdportError('PROVIDER_ERROR', 'TikTok custom-audience response, ownership scope or pagination could not be verified.');\nfunction failure(error: unknown, ids: string[] = []) {\n const details = error instanceof AdportError && error.details && typeof error.details === 'object' ? error.details as Record<string, unknown> : {};\n return new AdportError('PROVIDER_ERROR', 'TikTok audience operation is unconfirmed. No native upload or mutation was retried. Reconcile known IDs before another preview; provider bodies and customer identifiers stay hidden.', { ...(ids.length ? { resourceIds: ids } : {}), ...(Number.isSafeInteger(details.native_code ?? details.code) ? { native_code: details.native_code ?? details.code } : {}) });\n}\nconst notes = ['Custom audiences contain matched users; saved targeting templates are a different resource. No ads, budgets, spend, sharing grants or conversion events are changed by these tools.', 'Audience changes can affect existing ad groups and advertisers receiving a shared audience. Native audience expiry can detach audiences or pause campaigns that have no other targeting.', 'Native file and membership processing can take up to 48 hours. Acceptance, metadata readback and matched-user availability are distinct; individual membership is not readable through this API.', 'Concurrent native operations, quota and minimum matched-audience size remain authoritative. There is no conditional-write or atomic batch guarantee. Never replay an uncertain upload or mutation.'];\n\nexport { configuration as customAudienceConfiguration, failure as audienceOperationFailure };\n\n/** Official SDK f809c396 plus public v1.3 docs, refreshed 2026-11-06. */\nexport class TikTokCustomAudiences {\n constructor(private readonly client: TikTokClient, private readonly media: MediaResolver) {}\n private mediaScope() {\n if (!('scopeId' in this.media)) return 'local';\n if (typeof this.media.scopeId !== 'string' || !this.media.scopeId || this.media.scopeId.length > 200) throw new AdportError('POLICY_VIOLATION', 'Private media scope could not be bound to the audience upload.');return this.media.scopeId;\n }\n async list(value: unknown) {\n const input = customAudienceList.parse(value);let raw: unknown;\n try { raw = await this.client.get('dmp/custom_audience/list', { advertiser_id: input.account_id, custom_audience_ids: input.custom_audience_ids, page: input.page, page_size: input.page_size }); } catch (error) { throw failure(error); }\n const parsed = z.object({ list: z.array(listRow).max(100), page_info: pageInfo.optional() }).safeParse(raw);if (!parsed.success) throw invalid();\n const rows = parsed.data.list, page = parsed.data.page_info;\n if (rows.length > input.page_size || new Set(rows.map(row => row.audience_id)).size !== rows.length || rows.some(row => input.custom_audience_ids && !input.custom_audience_ids.includes(row.audience_id)) || page && (page.page !== input.page || page.page_size !== input.page_size)) throw invalid();\n const complete = nativeListComplete(page, rows.length);\n return { list: rows, page_info: page, audiences: rows, records: rows.map(row => ({ id: row.audience_id, name: row.name, type: row.audience_type, available: row.is_valid, matched_users: row.cover_num, owner: row.is_creator, shared: row.shared, expiring: row.is_expiring })), complete, truncated: complete !== true, ...(complete === false ? { next_page: input.page + 1 } : {}), ...(complete === null ? { pagination_note: 'Native completeness is unavailable; do not infer absence.' } : {}), notes };\n }\n private async details(account: string, ids: string[]) {\n let raw: unknown;try { raw = await this.client.get('dmp/custom_audience/get', { advertiser_id: account, custom_audience_ids: ids, history_size: 1 }); } catch (error) { throw failure(error, ids); }\n const parsed = z.object({ list: z.array(z.object({ audience_details: nativeDetails })).max(100) }).safeParse(raw);\n if (!parsed.success || parsed.data.list.length !== ids.length) throw invalid();const rows = parsed.data.list.map(row => row.audience_details);\n if (new Set(rows.map(row => row.audience_id)).size !== ids.length || rows.some(row => !ids.includes(row.audience_id) || row.is_creator === true && row.owner_id !== account || row.is_creator === false && row.owner_id === account)) throw invalid();return rows;\n }\n async get(value: unknown) {\n const input = customAudienceGet.parse(value), row = (await this.details(input.account_id, [input.custom_audience_id]))[0]!;\n return { audience: publicDetails(input.account_id, row), records: [{ id: row.audience_id, name: row.name, type: row.type, available: row.is_valid, matched_users: row.cover_num, shared: row.shared, owner: row.is_creator, expires: row.expired_time, native_error_reported: !!row.error_msg }], notes };\n }\n async inspect(account: string, ids: string[]) { audienceId.parse(account);audienceIds.parse(ids);return (await this.details(account, ids)).map(row => publicDetails(account, row)); }\n private uploads(account: string, receipts: string[]) {\n const now = Math.floor(Date.now() / 1000), files = receipts.map(receipt => audienceFileProof.parse(this.client.verifyAudienceFileReceipt(receipt)));\n if (files.some(row => row.account_id !== account || row.scope_id !== this.mediaScope() || row.expires_at <= now || row.expires_at > now + 86_400) || new Set(files.map(row => row.file_path)).size !== files.length || new Set(files.map(row => row.calculate_type)).size !== 1) throw new AdportError('INVALID_INPUT', 'Use distinct, unexpired audience upload receipts for this project/advertiser and one matching encryption type.');return files;\n }\n private owned(account: string, row: Details, available: boolean) {\n if (row.is_creator !== true || row.owner_id !== account) throw new AdportError('POLICY_VIOLATION', 'Only the selected advertiser’s own audiences can be modified. Shared recipient access is not ownership.');\n if (available && (row.is_valid !== true || row.is_expiring !== false || !!row.error_msg)) throw new AdportError('INVALID_INPUT', 'Audience readiness and non-expiring status must be proven before modification. Read its current state; unavailable, processing, expiring or failed audiences cannot be modified here.');\n }\n async plan(op: WriteOperation): Promise<Plan> {\n audienceId.parse(op.accountId);\n const upload = op.tool === 'tiktok_upload_audience_file', create = op.tool === 'tiktok_create_customer_audience', update = op.tool === 'tiktok_update_customer_audience_users', rename = op.tool === 'tiktok_rename_custom_audience', remove = op.tool === 'tiktok_delete_custom_audiences';\n if (op.provider !== 'tiktok' || !(upload && op.kind === 'create' || create && op.kind === 'create' || (update || rename) && op.kind === 'update' || remove && op.kind === 'remove')) throw new AdportError('INVALID_INPUT', 'Unsupported TikTok custom-audience operation/kind.');\n if (upload) return this.uploadPlan(op);\n if (create) return this.createPlan(op);\n if (remove) return this.deletePlan(op);\n const input = rename ? customAudienceRename.parse(op.payload) : customerAudienceUpdate.parse(op.payload);\n const prepare = async () => {\n const row = (await this.details(op.accountId, [input.custom_audience_id]))[0]!;this.owned(op.accountId, row, true);\n if (snapshot(op.accountId, row) !== input.expected_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'Audience configuration, availability or ownership changed; read it and preview again.');\n const files = 'upload_receipts' in input ? this.uploads(op.accountId, input.upload_receipts) : undefined;\n if (files && (row.type !== 'Customer File Audience' || files[0]!.calculate_type !== row.calculate_type)) throw new AdportError('INVALID_INPUT', 'Membership updates require an owned Customer File Audience with matching encryption type.');\n if ('custom_audience_name' in input && input.custom_audience_name === row.name) throw new AdportError('INVALID_INPUT', 'Choose a different audience name.');return { row, files };\n };\n const before = await prepare(), title = rename ? 'Rename custom audience' : 'Update customer audience members', action = 'action' in input ? input.action : undefined;\n const membershipChange = action === 'APPEND' ? 'Add matches from these files; retain existing members' : action === 'REMOVE' ? 'Remove matches from these files; retain other members' : 'Replace the entire membership with matches from these files';\n return { summary: `${title} · ${before.row.name}`, changes: [rename ? '~ Audience name' : `~ ${action} using ${before.files!.length} approved files`], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'tiktok', accountId: op.accountId, kind: 'update', title, subject: before.row.name, fields: [{ label: 'Audience', after: input.custom_audience_id }, ...('custom_audience_name' in input ? [{ label: 'Name', before: before.row.name, after: input.custom_audience_name }] : [{ label: 'Membership operation', before: 'Individual members are not readable through this API', after: { action, effect: membershipChange } }, { label: 'Approved source files', after: before.files!.map(file => ({ sha256: file.sha256, records: file.record_count, calculate_type: file.calculate_type })) }])], notices: notes },\n execute: async () => {\n const fresh = await prepare(), body = { advertiser_id: op.accountId, custom_audience_id: input.custom_audience_id, ...('custom_audience_name' in input ? { custom_audience_name: input.custom_audience_name } : { file_paths: fresh.files!.map(file => file.file_path), action: input.action }) };\n try {\n z.object({}).strict().parse(await this.client.post('dmp/custom_audience/update', body));const actual = (await this.details(op.accountId, [input.custom_audience_id]))[0]!;this.owned(op.accountId, actual, false);\n const expected = { ...configuration(fresh.row), ...('custom_audience_name' in input ? { name: input.custom_audience_name } : {}) };\n if (canonical(configuration(actual)) !== canonical(expected) || actual.error_msg) throw invalid();\n return { applied: true, resourceIds: [input.custom_audience_id], details: rename ? { configuration_readback: 'VERIFIED', membership_changed: false } : { status: 'ACCEPTED_FOR_PROCESSING', processed: false, membership_verified: false, action, source_files: fresh.files!.map(file => ({ sha256: file.sha256, record_count: file.record_count })), native_is_valid: actual.is_valid, next_tool: 'tiktok_get_custom_audience', next_arguments: { account_id: op.accountId, custom_audience_id: input.custom_audience_id } }, warnings: rename ? ['Native audience modification can reset its expiry under TikTok’s retention policy.'] : notes.slice(1) };\n } catch (error) { throw failure(error, [input.custom_audience_id]); }\n } };\n }\n private async uploadPlan(op: WriteOperation): Promise<Plan> {\n const input = audienceFileUpload.parse(op.payload), scope = this.mediaScope(), source = await this.media.read(input, { contentTypes: ['text/csv'], maxBytes: 50 * 1024 * 1024 }), file = { ...source, bytes: Uint8Array.from(source.bytes) };\n const sha256 = createHash('sha256').update(file.bytes).digest('hex');\n if (file.bytes.byteLength < 1 || file.bytes.byteLength > 50 * 1024 * 1024 || file.contentType !== 'text/csv' || sha256 !== input.expected_sha256.toLowerCase() || file.sha256 !== sha256) throw new AdportError('INVALID_INPUT', 'Audience file bytes, type or checksum changed; prepare a new preview.');\n if (!/\\.(csv|txt)$/.test(file.name)) throw new AdportError('INVALID_INPUT', 'TikTok customer files require the exact lowercase .csv or .txt suffix.');\n const count = audienceFileRecords(file.bytes, input.calculate_type), signature = createHash('md5').update(file.bytes).digest('hex');\n return { summary: `Upload customer audience file · ${count} rows`, changes: [`+ ${file.bytes.byteLength} bytes; SHA-256 ${file.sha256}; ${input.calculate_type}`], coercions: [], budgetDeltas: [], notes: ['Identifier values and file contents are excluded from previews, results and native error diagnostics. This upload does not create an audience.', 'Upload receipts bind the current credential, advertiser, exact source hash, encryption type and native file handle. Adport receipts expire after24 hours; native file retention is not inferred.', ...notes],\n review: { provider: 'tiktok', accountId: op.accountId, kind: 'create', title: 'Upload customer audience file', subject: `${count} rows`, fields: [{ label: 'Source SHA-256', after: file.sha256 }, { label: 'File size', after: file.bytes.byteLength }, { label: 'Rows', after: count }, { label: 'Identifier encryption', after: input.calculate_type }], notices: ['Only already-hashed identifiers are accepted. Source normalization and data authority remain the uploader’s responsibility.', 'This creates an advertiser-bound native upload handle. It does not create an audience or change targeting.'] },\n execute: async () => {\n if (this.mediaScope() !== scope) throw new AdportError('PENDING_MISMATCH', 'Private media scope changed before native upload.');\n const form = new FormData();form.append('advertiser_id', op.accountId);form.append('calculate_type', input.calculate_type);form.append('file_signature', signature);form.append('file', new Blob([file.bytes], { type: 'text/csv' }), file.name);\n try {\n const result = z.object({ file_path: audienceFileProof.shape.file_path }).parse(await this.client.postMultipart('dmp/custom_audience/file/upload', form));\n const proof = audienceFileProof.parse({ kind: 'tiktok_audience_file_v1', account_id: op.accountId, scope_id: scope, file_path: result.file_path, calculate_type: input.calculate_type, sha256: file.sha256, byte_length: file.bytes.byteLength, record_count: count, expires_at: Math.floor(Date.now() / 1000) + 86_400 });\n return { applied: true, resourceIds: [digest({ account_id: op.accountId, file_path: result.file_path })], details: { upload_receipt: this.client.audienceFileReceipt(proof), sha256: proof.sha256, byte_length: proof.byte_length, record_count: count, calculate_type: input.calculate_type, audience_created: false, native_upload_accepted: true, native_content_readback_available: false, receipt_expires_at: new Date(proof.expires_at * 1000).toISOString() } };\n } catch (error) { throw failure(error); }\n } };\n }\n private async createPlan(op: WriteOperation): Promise<Plan> {\n const input = customerAudienceCreate.parse(op.payload), files = this.uploads(op.accountId, input.upload_receipts);\n return { summary: `Create customer audience · ${input.custom_audience_name}`, changes: [`+ Customer File Audience from ${files.length} approved uploads`], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'tiktok', accountId: op.accountId, kind: 'create', title: 'Create customer audience', subject: input.custom_audience_name, fields: [{ label: 'Name', after: input.custom_audience_name }, { label: 'Audience subtype', after: input.audience_sub_type }, { label: 'Audience enhancement', after: 'Disabled' }, { label: 'Approved source files', after: files.map(file => ({ sha256: file.sha256, records: file.record_count, calculate_type: file.calculate_type })) }, { label: 'Retention requested', after: input.retention_in_days ?? 'Native default; expiry can reset on eligible use/modification' }], notices: notes },\n execute: async () => {\n const fresh = this.uploads(op.accountId, input.upload_receipts);let id: string | undefined;\n try {\n const result = z.object({ custom_audience_id: audienceNativeId }).parse(await this.client.post('dmp/custom_audience/create', { advertiser_id: op.accountId, custom_audience_name: input.custom_audience_name, calculate_type: fresh[0]!.calculate_type, file_paths: fresh.map(file => file.file_path), audience_enhancement: false, audience_sub_type: input.audience_sub_type, ...(input.retention_in_days ? { retention_in_days: input.retention_in_days } : {}) }));id = result.custom_audience_id;\n const actual = (await this.details(op.accountId, [id]))[0]!;this.owned(op.accountId, actual, false);\n if (actual.name !== input.custom_audience_name || actual.type !== 'Customer File Audience' || actual.calculate_type !== fresh[0]!.calculate_type || actual.audience_sub_type !== input.audience_sub_type || actual.error_msg) throw invalid();\n return { applied: true, resourceIds: [id], details: { status: 'ACCEPTED_FOR_PROCESSING', processed: false, metadata_readback: 'VERIFIED', membership_verified: false, native_is_valid: actual.is_valid, retention_requested: input.retention_in_days, native_expired_time: actual.expired_time, next_tool: 'tiktok_get_custom_audience', next_arguments: { account_id: op.accountId, custom_audience_id: id } }, warnings: notes.slice(1) };\n } catch (error) { throw failure(error, id ? [id] : []); }\n } };\n }\n private async deletePlan(op: WriteOperation): Promise<Plan> {\n const input = customAudiencesDelete.parse(op.payload), ids = input.targets.map(target => target.custom_audience_id);\n const prepare = async () => { const rows = await this.details(op.accountId, ids);for (const row of rows) { this.owned(op.accountId, row, false);const target = input.targets.find(target => target.custom_audience_id === row.audience_id)!;if (snapshot(op.accountId, row) !== target.expected_snapshot_hash || row.name !== target.confirm_name) throw new AdportError('PENDING_MISMATCH', 'Audience configuration or name changed; read every selected audience and preview again.'); }return rows; };\n const before = await prepare();return { summary: `Permanently delete ${ids.length} custom audiences`, changes: before.map(row => '- Audience ' + row.name), coercions: [], budgetDeltas: [], notes: ['Native deletion has no restore endpoint. Dependent ads and shared-recipient usage are not enumerated or frozen.', ...notes], review: { provider: 'tiktok', accountId: op.accountId, kind: 'remove', title: 'Delete custom audiences permanently', subject: `${ids.length} selected`, fields: before.map(row => ({ label: row.name, before: { id: row.audience_id, type: row.type, shared: row.shared }, after: 'Permanently deleted' })), notices: notes }, execute: async () => {\n await prepare();try {\n z.object({}).strict().parse(await this.client.post('dmp/custom_audience/delete', { advertiser_id: op.accountId, custom_audience_ids: ids }));\n const remaining = await this.list({ account_id: op.accountId, custom_audience_ids: ids, page: 1, page_size: 100 });\n if (remaining.audiences.length || remaining.complete !== true) throw invalid();\n return { applied: true, resourceIds: ids, details: { deletion_readback: 'ABSENT_FROM_COMPLETE_FILTERED_LIST' }, warnings: ['Dependent ad groups and shared recipients can be affected. Their usage was not enumerated or frozen.'] };\n } catch (error) { throw failure(error, ids); }\n } };\n }\n}\n","import { AdportError, csvRows } from '@adport/core';\nimport type { z } from 'zod';\nimport type { calculateType } from './custom-audience-schemas.js';\n\n/** Validate prehashed identifiers; never normalize/re-hash private source data implicitly. */\nexport function audienceFileRecords(bytes: Uint8Array, type: z.infer<typeof calculateType>): number {\n const invalid = () => new AdportError('INVALID_INPUT', 'Choose a nonempty UTF-8 customer file containing only the declared hashed identifier types. Single-type files have one hash per row and no header. Multiple-type files require unique hashed identifier headers; raw identifiers are not accepted.');\n const rows = csvRows(bytes, { maxRows: 100_000, maxColumns: 4 }), hashed = (value: string, length: number) => new RegExp(`^[a-fA-F0-9]{${length}}$`).test(value);\n let lengths: number[] | undefined, count = 0;\n for (const row of rows) {\n if (type === 'MULTIPLE_TYPES' && !lengths) {\n const headers = row.map(value => value.toLowerCase()), allowed: Record<string, number> = { email_sha256: 64, phone_sha256: 64, maid_sha256: 64, maid_md5: 32 };\n if (new Set(headers).size !== headers.length || headers.some(header => !Object.hasOwn(allowed, header))) throw invalid();lengths = headers.map(header => allowed[header]!);continue;\n }\n if (type === 'MULTIPLE_TYPES' ? row.length !== lengths!.length || row.every(value => value === '') || row.some((value, index) => value !== '' && !hashed(value, lengths![index]!)) : row.length !== 1 || !hashed(row[0]!, type.endsWith('MD5') ? 32 : 64)) throw invalid();\n count++;\n }\n if (!count) throw invalid();return count;\n}\n","import { z } from 'zod';\nimport { mediaSourceFields } from '@adport/core';\n\nexport const audienceId = z.string().regex(/^\\d+$/);\nexport const audienceNativeId = z.union([audienceId, z.number().int().positive().safe()]).transform(String);\nexport const audienceIds = z.array(audienceId).min(1).max(100).refine(ids => new Set(ids).size === ids.length, 'Audience IDs must be unique');\nexport const audienceName = z.string().trim().min(1).max(128).regex(/^[^\\x00-\\x1f\\x7f]+$/);\nexport const calculateType = z.enum(['EMAIL_SHA256', 'PHONE_SHA256', 'FIRST_SHA256', 'FIRST_MD5', 'IDFA_SHA256', 'IDFA_MD5', 'GAID_SHA256', 'GAID_MD5', 'MULTIPLE_TYPES']);\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nconst receipt = z.string().min(80).max(8192);\nconst receipts = z.array(receipt).min(1).max(49).refine(values => new Set(values).size === values.length, 'Upload receipts must be unique');\nexport const customAudienceList = z.object({ account_id: audienceId, custom_audience_ids: audienceIds.optional(), page: z.number().int().positive().safe().default(1), page_size: z.number().int().positive().max(100).default(100) }).strict();\nexport const customAudienceGet = z.object({ account_id: audienceId, custom_audience_id: audienceId }).strict();\nexport const audienceFileUpload = z.object({ ...mediaSourceFields, calculate_type: calculateType }).strict().refine(value => Number(!!value.media_id) + Number(!!value.file_path) === 1, 'Choose exactly one project media ID or local file path');\nexport const customerAudienceCreate = z.object({ custom_audience_name: audienceName, upload_receipts: receipts, audience_sub_type: z.enum(['NORMAL', 'REACH_FREQUENCY']).default('NORMAL'), retention_in_days: z.number().int().min(1).max(365).optional() }).strict();\nconst selected = { custom_audience_id: audienceId, expected_snapshot_hash: hash, acknowledge_shared_effects: z.literal(true) };\nexport const customerAudienceUpdate = z.object({ ...selected, upload_receipts: receipts, action: z.enum(['APPEND', 'REMOVE', 'REPLACE']) }).strict();\nexport const customAudienceRename = z.object({ ...selected, custom_audience_name: audienceName }).strict();\nexport const customAudiencesDelete = z.object({ targets: z.array(z.object({ custom_audience_id: audienceId, expected_snapshot_hash: hash, confirm_name: z.string().min(1).max(4096) }).strict()).min(1).max(100).refine(values => new Set(values.map(v => v.custom_audience_id)).size === values.length, 'Audience IDs must be unique'), acknowledge_shared_effects: z.literal(true), acknowledge_permanent_deletion: z.literal(true) }).strict();\nexport const audienceFileProof = z.object({ kind: z.literal('tiktok_audience_file_v1'), account_id: audienceId, scope_id: z.string().min(1).max(200), file_path: z.string().min(1).max(4096).regex(/^[^\\x00-\\x1f\\x7f]+$/), calculate_type: calculateType, sha256: hash, byte_length: z.number().int().positive().max(50 * 1024 * 1024), record_count: z.number().int().positive().max(100_000), expires_at: z.number().int().positive().safe() }).strict();\n","import { createHash } from 'node:crypto';\nimport { z } from 'zod';\nimport { AdportError } from '@adport/core';\nimport type { TikTokClient } from './client.js';\nimport { audienceNativeId } from './custom-audience-schemas.js';\nimport { audienceSourceList, audienceIdentityList, audienceRuleContext, ruleSelection } from './audience-authoring-schemas.js';\nimport { nativeListComplete } from './pagination.js';\nimport { audienceOperationFailure } from './custom-audiences.js';\n\ntype Input = z.infer<typeof audienceSourceList>;\ntype Source = { id: string; name: string; eligible: boolean; configuration: Record<string, unknown> };\nconst opaque = z.string().min(1).max(128).regex(/^[^\\x00-\\x1f\\x7f]+$/), native = z.union([opaque, z.number().int().positive().safe()]).transform(String);\nconst pageInfo = z.object({ page: z.number().int().positive().safe(), page_size: z.number().int().positive().safe(), total_page: z.number().int().nonnegative().safe().optional(), total_number: z.number().int().nonnegative().safe().optional() });\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 digest = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex');\nconst invalid = () => new AdportError('PROVIDER_ERROR', 'TikTok audience source scope, identity, response or pagination could not be verified.');\nconst cursorSchema = z.object({ selection: z.string(), page: z.number().int().positive().safe().optional(), timestamp: z.string().regex(/^\\d+$/).optional(), offset: z.number().int().nonnegative().max(5000).optional(), snapshot: z.string().optional() }).strict();\nconst encode = (value: z.infer<typeof cursorSchema>) => Buffer.from(JSON.stringify(value)).toString('base64url');\nconst timestamp = z.union([z.string().regex(/^\\d+$/), z.number().int().nonnegative().safe()]).transform(String);\n\n/** Native advertiser-scoped reads; no account/BC sharing or grant mutation. */\nexport class TikTokAudienceSources {\n constructor(private readonly client: TikTokClient, private readonly requireAdvertiser: (account: string) => Promise<void>) {}\n private async get(path: string, params: Record<string, unknown>) { try { return await this.client.get<unknown>(path, params); } catch (error) { throw audienceOperationFailure(error); } }\n private async account(account: string) { try { await this.requireAdvertiser(account); } catch (error) { throw audienceOperationFailure(error); } }\n async identities(value: unknown) {\n const input = audienceIdentityList.parse(value), { account_id, ...params } = input;\n try {\n const data = z.object({ identity_list: z.array(z.object({ identity_id: opaque, identity_type: z.string(), identity_authorized_bc_id: audienceNativeId.optional(), display_name: z.string().optional(), username: z.string().optional(), available_status: z.string().optional() })).max(100), page_info: pageInfo.optional() }).parse(await this.get('identity/get', { advertiser_id: account_id, ...params }));\n if (new Set(data.identity_list.map(row => `${row.identity_type}:${row.identity_id}:${row.identity_authorized_bc_id ?? ''}`)).size !== data.identity_list.length || data.identity_list.length > input.page_size || data.page_info && (data.page_info.page !== input.page || data.page_info.page_size !== input.page_size)) throw invalid();\n const complete = input.identity_type ? nativeListComplete(data.page_info, data.identity_list.length) : null;\n return { ...data, records: data.identity_list.map(row => ({ id: `${row.identity_type}:${row.identity_id}:${row.identity_authorized_bc_id ?? ''}`, name: row.display_name ?? row.username ?? row.identity_id, identity_id: row.identity_id, identity_type: row.identity_type, business_center: row.identity_authorized_bc_id, availability: row.available_status })), complete, truncated: complete !== true, ...(complete === false ? { next_page: input.page + 1 } : {}), notes: ['Native identity pagination is reliable only when identity_type is specified. A BC query may return all identities linked to the advertiser; returned BC references are preserved. Exact video source selection rechecks identity/info.'] };\n } catch (error) { if (error instanceof AdportError) throw error;throw invalid(); }\n }\n private async identity(input: Input) {\n const raw = await this.get('identity/info', { advertiser_id: input.account_id, identity_id: input.identity_id, identity_type: input.identity_type, ...(input.identity_authorized_bc_id ? { identity_authorized_bc_id: input.identity_authorized_bc_id } : {}) });\n const row = z.object({ identity_info: z.object({ identity_id: opaque, identity_type: z.string(), identity_authorized_bc_id: audienceNativeId.optional(), available_status: z.string(), can_pull_video: z.boolean().optional(), can_use_live_ads: z.boolean().optional() }) }).parse(raw).identity_info;\n if (row.identity_id !== input.identity_id || row.identity_type !== input.identity_type || row.available_status !== 'AVAILABLE' || input.identity_type === 'BC_AUTH_TT' && row.identity_authorized_bc_id !== input.identity_authorized_bc_id) throw invalid();return row;\n }\n async list(value: unknown) {\n const input = audienceSourceList.parse(value);\n try {\n const { cursor, ...selection } = input, key = digest({ ...selection, source_ids: input.source_ids ? [...input.source_ids].sort() : undefined });let navigation: z.infer<typeof cursorSchema> = { selection: key };\n if (cursor) { try { navigation = cursorSchema.parse(JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'))); } catch { throw new AdportError('INVALID_INPUT', 'Invalid source cursor; restart this selection.'); }if (navigation.selection !== key) throw new AdportError('PENDING_MISMATCH', 'Audience source selection changed; restart its first page.'); }\n const page = navigation.page ?? 1, offset = navigation.offset ?? 0, params = { advertiser_id: input.account_id }, type = input.source_type;let rows: Source[], next: string | undefined, complete: boolean | null = true;\n if (['ENGAGEMENT_LIVE_VIDEO', 'ENGAGEMENT_ORGANIC_VIDEO'].includes(type)) {\n const identity = await this.identity(input), current = navigation.timestamp ?? '0';if (!Number.isSafeInteger(Number(current))) throw invalid();\n const raw = await this.get(type === 'ENGAGEMENT_LIVE_VIDEO' ? 'identity/live/get' : 'identity/video/get', { ...params, identity_id: input.identity_id, identity_type: input.identity_type, ...(input.identity_authorized_bc_id ? { identity_authorized_bc_id: input.identity_authorized_bc_id } : {}), cursor: Number(current), ...(type === 'ENGAGEMENT_ORGANIC_VIDEO' ? { count: input.page_size, item_type: 'VIDEO', exclude_adsonly: true } : {}) });\n const data = z.object({ cursor: timestamp, has_more: z.boolean(), video_list: z.array(z.object({ item_id: native, item_type: z.string(), status: z.string(), text: z.string().max(100_000).optional() })).max(20).optional(), live_list: z.array(z.object({ live_id: native, finish_timestamp: z.string().optional() })).max(5000).optional() }).parse(raw);\n if (type === 'ENGAGEMENT_LIVE_VIDEO') { if (!data.live_list) throw invalid();rows = data.live_list.map(row => ({ id: row.live_id, name: 'Live video ' + row.live_id, eligible: true, configuration: { identity, finish_timestamp: row.finish_timestamp } })); }\n else { if (!data.video_list) throw invalid();rows = data.video_list.map(row => ({ id: row.item_id, name: row.text?.slice(0, 240) || 'Video ' + row.item_id, eligible: row.item_type === 'VIDEO' && row.status === 'ITEM_STATUS_HESITATE_RECOMMEND', configuration: { identity, item_type: row.item_type, status: row.status } })); }\n this.unique(rows);if (data.has_more && (!rows.length || data.cursor === current)) throw invalid();const fingerprint = digest(rows);\n if (offset && navigation.snapshot !== fingerprint) throw new AdportError('PENDING_MISMATCH', 'Native video page changed; restart its first page.');\n const total = rows.length;rows = rows.slice(offset, offset + input.page_size);\n if (offset && offset >= total) throw invalid();\n if (offset + rows.length < total) next = encode({ selection: key, timestamp: current, offset: offset + rows.length, snapshot: fingerprint });else if (data.has_more) next = encode({ selection: key, timestamp: data.cursor });complete = !next;\n } else if (type === 'ENGAGEMENT' || type === 'PIXEL') {\n const adgroup = type === 'ENGAGEMENT', raw = await this.get(adgroup ? 'adgroup/get' : 'pixel/list', { ...params, page, page_size: input.page_size, ...(adgroup ? { fields: ['advertiser_id', 'adgroup_id', 'adgroup_name', 'campaign_id'], ...(input.source_ids ? { filtering: { adgroup_ids: input.source_ids } } : {}) } : input.source_ids?.length === 1 ? { pixel_id: input.source_ids[0] } : {}) });\n const data = z.object({ list: z.array(z.object({ adgroup_id: native, advertiser_id: audienceNativeId, campaign_id: audienceNativeId, adgroup_name: z.string() })).max(20).optional(), pixels: z.array(z.object({ pixel_id: native, advertiser_id: audienceNativeId.optional(), pixel_name: z.string() })).max(20).optional(), page_info: pageInfo.optional() }).parse(raw);\n if (data.page_info && (data.page_info.page !== page || data.page_info.page_size !== input.page_size)) throw invalid();\n if (adgroup) { if (!data.list || data.list.some(row => row.advertiser_id !== input.account_id || input.source_ids && !input.source_ids.includes(row.adgroup_id))) throw invalid();rows = data.list.map(row => ({ id: row.adgroup_id, name: row.adgroup_name, eligible: true, configuration: { advertiser_id: row.advertiser_id, campaign_id: row.campaign_id } })); }\n else { if (!data.pixels || data.pixels.some(row => row.advertiser_id !== undefined && row.advertiser_id !== input.account_id || input.source_ids?.length === 1 && row.pixel_id !== input.source_ids[0])) throw invalid();rows = data.pixels.map(row => ({ id: row.pixel_id, name: row.pixel_name, eligible: true, configuration: { advertiser_id: input.account_id } })); }\n this.unique(rows);complete = nativeListComplete(data.page_info, rows.length);if (complete === false) next = encode({ selection: key, page: page + 1 });\n } else {\n if (type === 'LEAD_GENERATION' || type === 'BUSINESS_ACCOUNT') await this.account(input.account_id);\n if (type === 'LEAD_GENERATION') rows = [{ id: 'ALL_LEAD_EVENTS:' + input.account_id, name: 'All available lead-generation form events', eligible: true, configuration: { advertiser_id: input.account_id, includes_future_available_sources: true } }];\n else if (type === 'BUSINESS_ACCOUNT') {\n // v1.3 renamed old numeric id to core_user_id. Never substitute the old example.\n const row = z.object({ core_user_id: audienceNativeId }).parse(await this.get('user/info', {}));rows = [{ id: row.core_user_id, name: 'Authorized TikTok for Business user', eligible: true, configuration: { advertiser_id: input.account_id, core_user_id: row.core_user_id } }];\n } else if (type === 'APP') {\n const data = z.object({ apps: z.array(z.object({ app_id: native, advertiser_id: audienceNativeId, app_name: z.string(), platform: z.string().optional(), app_platform_id: native.optional() })).max(5000) }).parse(await this.get('app/list', params));if (data.apps.some(row => row.advertiser_id !== input.account_id)) throw invalid();rows = data.apps.map(row => ({ id: row.app_id, name: row.app_name, eligible: true, configuration: { advertiser_id: row.advertiser_id, platform: row.platform, app_platform_id: row.app_platform_id } }));\n } else if (type === 'OFFLINE') {\n const data = z.object({ event_set_list: z.array(z.object({ event_set_id: native, advertiser_id: audienceNativeId, name: z.string() })).max(5000) }).parse(await this.get('offline/get', { ...params, ...(input.source_ids ? { event_set_ids: input.source_ids } : {}) }));if (data.event_set_list.some(row => row.advertiser_id !== input.account_id || input.source_ids && !input.source_ids.includes(row.event_set_id))) throw invalid();rows = data.event_set_list.map(row => ({ id: row.event_set_id, name: row.name, eligible: true, configuration: { advertiser_id: row.advertiser_id } }));\n } else {\n const data = z.object({ stores: z.array(z.object({ store_id: native, store_type: z.literal('TIKTOK_SHOP'), store_name: z.string(), store_authorized_bc_id: audienceNativeId.optional() })).max(5000) }).parse(await this.get('store/list', { ...params, store_type: 'TIKTOK_SHOP', ...(input.source_ids?.length === 1 ? { store_id: input.source_ids[0] } : {}) }));\n const stores = new Map<string, Source>();for (const row of data.stores) { if (input.source_ids?.length === 1 && row.store_id !== input.source_ids[0]) throw invalid();const prior = stores.get(row.store_id);if (prior && prior.name !== row.store_name) throw invalid();const bcs = new Set((prior?.configuration.authorized_business_centers ?? []) as string[]);if (row.store_authorized_bc_id) bcs.add(row.store_authorized_bc_id);stores.set(row.store_id, { id: row.store_id, name: row.store_name, eligible: true, configuration: { advertiser_id: input.account_id, store_type: row.store_type, authorized_business_centers: [...bcs].sort() } }); }rows = [...stores.values()];\n }\n this.unique(rows);rows.sort((a, b) => a.id.localeCompare(b.id));if (input.source_ids) rows = rows.filter(row => input.source_ids!.includes(row.id));const fingerprint = digest(rows);\n if (offset && navigation.snapshot !== fingerprint) throw new AdportError('PENDING_MISMATCH', 'Native source inventory changed; restart its first page.');const count = rows.length;if (offset && offset >= count) throw invalid();rows = rows.slice(offset, offset + input.page_size);if (offset + rows.length < count) next = encode({ selection: key, offset: offset + rows.length, snapshot: fingerprint });complete = !next;\n }\n if (input.source_ids) rows = rows.filter(row => input.source_ids!.includes(row.id));\n return { sources: rows, records: rows.map(row => ({ id: row.id, name: row.name, type, eligible: row.eligible })), complete, truncated: complete !== true, ...(next ? { next_cursor: next } : {}), notes: [type === 'ENGAGEMENT_ORGANIC_VIDEO' ? 'Native organic discovery covers at most 500 most recent public organic posts; it is not all historic posts.' : 'Completeness describes the native selected read window, not a frozen account inventory.', 'Source IDs, advertiser scope and exact identity are rechecked for rule creation. Missing pagination cannot prove absence. No source, sharing permission or tracking event is modified.'] };\n } catch (error) { if (error instanceof AdportError) throw error;throw invalid(); }\n }\n private unique(rows: Source[]) { if (new Set(rows.map(row => row.id)).size !== rows.length) throw invalid(); }\n async context(value: unknown) {\n const input = audienceRuleContext.parse(value), selection = ruleSelection(input), rules = [...input.rule_spec.inclusion_rule_set.rules, ...(input.rule_spec.exclusion_rule_set?.rules ?? [])], ids = [...new Set(rules.flatMap(row => row.event_source_ids ?? []))], all = rules.some(row => !row.event_source_ids), selected = new Map<string, Source>();\n if (all) { await this.account(input.account_id);selected.set('ALL:' + input.account_id, { id: 'ALL:' + input.account_id, name: 'All current/future available advertiser ' + (input.audience_type === 'LEAD_GENERATION' ? 'lead-form events' : 'ad-group events'), eligible: true, configuration: { advertiser_id: input.account_id, audience_type: input.audience_type, includes_future_available_sources: true } }); }\n if (ids.length) {\n let cursor: string | undefined;const seenCursors = new Set<string>(), seenIds = new Set<string>();let complete = false;\n for (let page = 0; page < 100; page++) {\n const result = await this.list({ account_id: input.account_id, source_type: input.audience_type, source_ids: ids, identity_id: input.identity_id, identity_type: input.identity_type, identity_authorized_bc_id: input.identity_authorized_bc_id, page_size: 20, cursor });\n for (const row of result.sources) { if (seenIds.has(row.id)) throw invalid();seenIds.add(row.id);if (ids.includes(row.id)) { if (!row.eligible) throw new AdportError('INVALID_INPUT', 'A selected event source is not eligible in this advertiser/identity.');selected.set(row.id, row); } }\n if (ids.every(id => selected.has(id))) { complete = true;break; }\n if (!result.next_cursor || result.complete === true) break;if (seenCursors.has(result.next_cursor)) throw invalid();seenCursors.add(result.next_cursor);cursor = result.next_cursor;\n }\n if (!complete) throw new AdportError('INVALID_INPUT', 'Every selected event source must be positively verified within the native visible window and 100-page Adport bound. No absence or cross-account authority is inferred.');\n }\n const sources = [...selected.values()].sort((a, b) => a.id.localeCompare(b.id));return { context_hash: digest({ account_id: input.account_id, selection, sources }), sources, records: sources.map(row => ({ id: row.id, name: row.name, eligible: row.eligible })), selected_sources_verified: true, notes: ['The hash binds exact rule selection and positively verified source metadata. It does not freeze event history or matched users.', ...(all ? ['All-source rules intentionally include current and future sources available to the advertiser.'] : [])] };\n }\n}\n","import { z } from 'zod';\nimport { audienceId, audienceName } from './custom-audience-schemas.js';\n\nexport const audienceSourceType = z.enum(['APP', 'BUSINESS_ACCOUNT', 'ENGAGEMENT', 'ENGAGEMENT_LIVE_VIDEO', 'ENGAGEMENT_ORGANIC_VIDEO', 'LEAD_GENERATION', 'OFFLINE', 'PIXEL', 'TIKTOK_SHOP']);\nexport const eventSourceId = z.string().min(1).max(128).regex(/^[^\\x00-\\x1f\\x7f]+$/);\nconst sourceIds = z.array(eventSourceId).min(1).max(100).refine(ids => new Set(ids).size === ids.length, 'Source IDs must be unique');\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nexport const audienceIdentityFields = { identity_id: eventSourceId.optional(), identity_type: z.enum(['TT_USER', 'BC_AUTH_TT']).optional(), identity_authorized_bc_id: audienceId.optional() };\nconst identityIssues = (input: { identity_id?: string; identity_type?: string; identity_authorized_bc_id?: string }, needed: boolean, ctx: z.RefinementCtx) => {\n if (needed ? !input.identity_id || !input.identity_type : input.identity_id !== undefined || input.identity_type !== undefined || input.identity_authorized_bc_id !== undefined) ctx.addIssue({ code: 'custom', message: needed ? 'Select an exact TT_USER or BC_AUTH_TT identity for video sources' : 'Identity fields apply only to organic/live video sources' });\n if (input.identity_type === 'BC_AUTH_TT' ? !input.identity_authorized_bc_id : input.identity_authorized_bc_id !== undefined) ctx.addIssue({ code: 'custom', message: 'Only BC_AUTH_TT requires identity_authorized_bc_id' });\n};\nexport const audienceSourceList = z.object({ account_id: audienceId, source_type: audienceSourceType, source_ids: sourceIds.optional(), ...audienceIdentityFields, page_size: z.number().int().positive().max(20).default(20), cursor: z.string().min(1).max(8192).optional() }).strict().superRefine((input, ctx) => {\n identityIssues(input, ['ENGAGEMENT_LIVE_VIDEO', 'ENGAGEMENT_ORGANIC_VIDEO'].includes(input.source_type), ctx);\n if (input.source_type === 'LEAD_GENERATION' && input.source_ids) ctx.addIssue({ code: 'custom', message: 'Lead-generation audiences use all available advertiser form events, not source IDs' });\n});\nexport const audienceIdentityList = z.object({ account_id: audienceId, identity_type: z.enum(['TT_USER', 'BC_AUTH_TT', 'CUSTOMIZED_USER', 'AUTH_CODE']), identity_authorized_bc_id: audienceId.optional(), page: z.number().int().positive().safe().default(1), page_size: z.number().int().positive().max(100).default(100) }).strict().superRefine((input, ctx) => {\n if (input.identity_type === 'BC_AUTH_TT' ? !input.identity_authorized_bc_id : input.identity_authorized_bc_id !== undefined) ctx.addIssue({ code: 'custom', message: 'Only BC_AUTH_TT requires identity_authorized_bc_id' });\n});\nconst parameterValues = z.array(z.string().min(1).max(100).regex(/^[^\\x00-\\x1f\\x7f]+$/)).min(1).max(10);\nexport const audienceParameterFilter = z.discriminatedUnion('field', [\n z.object({ field: z.literal('URL'), operator: z.enum(['CONTAINS', 'DOES_NOT_CONTAIN', 'EQ', 'NOT_EQUAL']), values: parameterValues }).strict(),\n z.object({ field: z.enum(['CONTENT_TYPE', 'PRICE', 'VALUE', 'CONTENT_ID', 'CONTENT_CATEGORY']), operator: z.enum(['CONTAINS', 'DOES_NOT_CONTAIN', 'EQ', 'NOT_EQUAL', 'IS_LESS_THAN', 'IS_GREATER_THAN', 'IS_LESS_THAN_OR_EQUAL_TO', 'IS_GREATER_THAN_OR_EQUAL_TO']), values: parameterValues }).strict(),\n]);\nconst parameterFilters = z.array(audienceParameterFilter).min(1).max(11).superRefine((filters, ctx) => {\n const urls = filters.filter(filter => filter.field === 'URL').length;\n if (urls > 1 || filters.length - urls > 10) ctx.addIssue({ code: 'custom', message: 'Use at most one URL condition and ten parameter conditions per event filter' });\n});\n// SDK f809c396 schema, generated models and portal table agree on this nesting.\n// The prose example is malformed JSON; event aliases remain native-authoritative.\nconst eventFilter = z.object({ field: z.literal('EVENT'), operator: z.literal('EQ'), value: z.string().min(1).max(128).regex(/^[^\\x00-\\x1f\\x7f]+$/), parameter_filters: parameterFilters.optional() }).strict();\nconst rule = z.object({ event_source_ids: sourceIds.optional(), retention_days: z.union([z.literal(7), z.literal(14), z.literal(30), z.literal(60), z.literal(90), z.literal(180)]), filter_set: z.object({ operator: z.literal('OR'), filters: z.array(eventFilter).length(1) }).strict() }).strict();\nconst ruleSet = z.object({ operator: z.literal('OR'), rules: z.array(rule).min(1).max(20) }).strict();\nexport const audienceRuleSelection = z.object({ audience_type: audienceSourceType, ...audienceIdentityFields, rule_spec: z.object({ inclusion_rule_set: ruleSet, exclusion_rule_set: ruleSet.optional() }).strict(), acknowledge_all_event_sources: z.literal(true).optional() }).strict().superRefine((input, ctx) => {\n const video = ['ENGAGEMENT_LIVE_VIDEO', 'ENGAGEMENT_ORGANIC_VIDEO'].includes(input.audience_type);identityIssues(input, video, ctx);\n const rules = [...input.rule_spec.inclusion_rule_set.rules, ...(input.rule_spec.exclusion_rule_set?.rules ?? [])], ids = new Set(rules.flatMap(row => row.event_source_ids ?? []));\n if (ids.size > (video ? 10 : 100)) ctx.addIssue({ code: 'custom', message: video ? 'Select at most 10 distinct videos' : 'Select at most 100 distinct event sources' });\n for (const row of rules) {\n if (input.audience_type === 'LEAD_GENERATION' && row.event_source_ids !== undefined) ctx.addIssue({ code: 'custom', message: 'TikTok forbids event_source_ids for Lead Generation audiences' });\n if (!row.event_source_ids && !['ENGAGEMENT', 'LEAD_GENERATION'].includes(input.audience_type)) ctx.addIssue({ code: 'custom', message: 'Explicit event_source_ids are required for this audience type' });\n if (!row.event_source_ids && input.acknowledge_all_event_sources !== true) ctx.addIssue({ code: 'custom', message: 'Omitted event sources require acknowledgement of all current/future available advertiser sources' });\n if ((video || input.audience_type === 'BUSINESS_ACCOUNT' && row.filter_set.filters[0]!.value !== 'BUSINESS ACCOUNT PROFILE FOLLOW') && row.retention_days > 30) ctx.addIssue({ code: 'custom', message: 'This video/business event supports only 7, 14 or 30 lookback days' });\n }\n});\nexport const audienceRuleContext = audienceRuleSelection.safeExtend({ account_id: audienceId });\nexport const ruleAudienceCreate = audienceRuleSelection.safeExtend({ custom_audience_name: audienceName, expected_context_hash: hash, is_auto_refresh: z.boolean(), audience_sub_type: z.enum(['NORMAL', 'REACH_FREQUENCY']).default('NORMAL'), retention_in_days: z.number().int().min(1).max(365).optional() });\nexport const lookalikeSpec = z.object({ source_audience_id: audienceId, include_source: z.boolean(), mobile_os: z.enum(['ALL', 'ANDROID', 'IOS']), placements: z.array(z.enum(['TikTok', 'TopBuzz & BuzzVideo', 'Pangle'])).min(1).max(3).refine(values => new Set(values).size === values.length), location_ids: z.array(z.string().regex(/^[A-Z]{2}$/)).min(1).max(100).refine(values => new Set(values).size === values.length), audience_size: z.enum(['NARROW', 'BALANCED', 'BROAD']) }).strict();\nexport const lookalikeAudienceCreate = z.object({ custom_audience_name: audienceName, expected_source_snapshot_hash: hash, lookalike_spec: lookalikeSpec }).strict();\nexport const lookalikeAudiencesRefresh = z.object({ targets: z.array(z.object({ custom_audience_id: audienceId, expected_snapshot_hash: hash }).strict()).min(1).max(100).refine(values => new Set(values.map(v => v.custom_audience_id)).size === values.length), acknowledge_shared_effects: z.literal(true) }).strict();\nexport function ruleSelection(input: z.infer<typeof audienceRuleSelection>) { return audienceRuleSelection.parse({ audience_type: input.audience_type, rule_spec: input.rule_spec, ...(input.identity_id ? { identity_id: input.identity_id, identity_type: input.identity_type, ...(input.identity_authorized_bc_id ? { identity_authorized_bc_id: input.identity_authorized_bc_id } : {}) } : {}), ...(input.acknowledge_all_event_sources ? { acknowledge_all_event_sources: true } : {}) }); }\n","import { z } from 'zod';\nimport { AdportError, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport type { TikTokClient } from './client.js';\nimport { audienceId, audienceNativeId } from './custom-audience-schemas.js';\nimport { audienceRuleContext, ruleSelection, ruleAudienceCreate, lookalikeAudienceCreate, lookalikeAudiencesRefresh } from './audience-authoring-schemas.js';\nimport { TikTokCustomAudiences, customAudienceConfiguration, audienceOperationFailure } from './custom-audiences.js';\nimport type { TikTokAudienceSources } from './audience-sources.js';\n\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<WriteResult> };\ntype Audience = Awaited<ReturnType<TikTokCustomAudiences['get']>>['audience'];\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 notes = ['A new audience does not attach itself to an ad group. Refresh can affect current ad groups or shared recipients already using that audience.', 'TikTok processes audience work asynchronously, potentially up to 48 hours. Acceptance and metadata readback do not prove matching, final rule/specification or availability.', 'Native source eligibility, event names, sharing permissions and quotas remain authoritative. The preview is local; there is no conditional-write or atomic-batch guarantee.', 'No native mutation is automatically retried. Reconcile known audience IDs after a partial or uncertain outcome.'];\nconst invalid = () => new AdportError('PROVIDER_ERROR', 'TikTok audience creation/refresh metadata could not be verified.');\nconst ready = (row: Audience) => { if (row.is_valid !== true || row.is_expiring !== false || row.native_error_reported) throw new AdportError('INVALID_INPUT', 'An available, non-expiring audience without a reported native error is required.'); };\nconst owned = (account: string, row: Audience) => { if (row.is_creator !== true || row.owner_id !== account) throw new AdportError('POLICY_VIOLATION', 'Refresh requires an audience created by this advertiser; recipient access is not ownership.'); };\n// The published get table has no OFFLINE type mapping; report it rather than invent one.\nconst ruleTypes: Partial<Record<z.infer<typeof ruleAudienceCreate>['audience_type'], string>> = { APP: 'App Activity Audience', ENGAGEMENT: 'Engagement Audience', ENGAGEMENT_LIVE_VIDEO: 'Engagement Audience', ENGAGEMENT_ORGANIC_VIDEO: 'Engagement Audience', PIXEL: 'Website Audience', LEAD_GENERATION: 'Lead Generation', BUSINESS_ACCOUNT: 'Rule Business Account', TIKTOK_SHOP: 'Rule ad shop' };\nfunction lookalikeEcho(actual: unknown, expected: z.infer<typeof lookalikeAudienceCreate>['lookalike_spec']) {\n const item = Array.isArray(actual) ? actual.length === 1 ? actual[0] : undefined : actual;\n if (!item || typeof item !== 'object' || Array.isArray(item) || Object.keys(item).some(key => !Object.hasOwn(lookalikeAudienceCreate.shape.lookalike_spec.shape, key))) return false;\n const row = item as Record<string, unknown>, parsed = lookalikeAudienceCreate.shape.lookalike_spec.safeParse({ source_audience_id: row.source_audience_id, include_source: row.include_source, mobile_os: row.mobile_os, placements: typeof row.placements === 'string' ? [row.placements] : row.placements, location_ids: row.location_ids, audience_size: row.audience_size });\n if (!parsed.success) return false;const normalized = (value: typeof expected) => ({ ...value, placements: [...value.placements].sort(), location_ids: [...value.location_ids].sort() });\n if (canonical(normalized(parsed.data)) !== canonical(normalized(expected))) throw invalid();return true;\n}\nfunction ruleEcho(raw: string | null | undefined, expected: z.infer<typeof ruleAudienceCreate>['rule_spec']) {\n let value: unknown;try { value = JSON.parse(raw ?? 'null'); } catch { return false; }\n const parsed = audienceRuleContext.shape.rule_spec.safeParse(value);if (!parsed.success) return false;\n const set = (value: typeof expected.inclusion_rule_set) => ({\n ...value,\n rules: value.rules.map(row => ({\n ...row,\n event_source_ids: row.event_source_ids ? [...row.event_source_ids].sort() : undefined,\n filter_set: {\n ...row.filter_set,\n filters: row.filter_set.filters.map(filter => ({\n ...filter,\n ...(filter.parameter_filters ? {\n parameter_filters: filter.parameter_filters.map(condition => ({ ...condition, values: [...condition.values].sort() })).sort((a, b) => canonical(a).localeCompare(canonical(b))),\n } : {}),\n })),\n },\n })).sort((a, b) => canonical(a).localeCompare(canonical(b))),\n });\n const normalized = (value: typeof expected) => ({ inclusion_rule_set: set(value.inclusion_rule_set), ...(value.exclusion_rule_set ? { exclusion_rule_set: set(value.exclusion_rule_set) } : {}) });\n if (canonical(normalized(parsed.data)) !== canonical(normalized(expected))) throw invalid();return true;\n}\nexport class TikTokAudienceAuthoring {\n constructor(private readonly client: TikTokClient, private readonly audiences: TikTokCustomAudiences, private readonly sources: TikTokAudienceSources) {}\n async context(value: unknown) { return this.sources.context(audienceRuleContext.parse(value)); }\n private async read(account: string, id: string) { return (await this.audiences.get({ account_id: account, custom_audience_id: id })).audience; }\n private async created(account: string, id: string, name: string, expectedType?: string) {\n const row = await this.read(account, id);owned(account, row);\n if (!row.type.trim() || row.name !== name || row.native_error_reported || expectedType && row.type.trim() !== expectedType) throw invalid();return row;\n }\n private receipt(account: string, row: Audience, extra: Record<string, unknown>): WriteResult { return { applied: true, resourceIds: [row.audience_id], details: { status: 'ACCEPTED_FOR_PROCESSING', processed: false, metadata_readback: 'VERIFIED', membership_verified: false, native_is_valid: row.is_valid, native_reported_type: row.type, ...extra, next_tool: 'tiktok_get_custom_audience', next_arguments: { account_id: account, custom_audience_id: row.audience_id } }, warnings: notes.slice(1) }; }\n async plan(op: WriteOperation): Promise<Plan> {\n audienceId.parse(op.accountId);\n if (op.provider !== 'tiktok' || !(op.tool === 'tiktok_create_lookalike_audience' && op.kind === 'create' || op.tool === 'tiktok_create_rule_audience' && op.kind === 'create' || op.tool === 'tiktok_refresh_lookalike_audiences' && op.kind === 'update')) throw new AdportError('INVALID_INPUT', 'Unsupported audience authoring operation/provider kind.');\n if (op.tool === 'tiktok_create_rule_audience') return this.rulePlan(op);\n if (op.tool === 'tiktok_refresh_lookalike_audiences') return this.refreshPlan(op);\n const input = lookalikeAudienceCreate.parse(op.payload), spec = input.lookalike_spec;\n const prepare = async () => { const row = await this.read(op.accountId, spec.source_audience_id);ready(row);if (!(row.is_creator === true && row.owner_id === op.accountId || row.is_creator === false && row.shared === true && row.owner_id !== undefined && row.owner_id !== op.accountId)) throw new AdportError('POLICY_VIOLATION', 'The seed must have proven creator or shared-recipient access under this advertiser.');if (row.snapshot_hash !== input.expected_source_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'Seed configuration or availability changed; read it and preview again.');if (row.type === 'Lookalike Audience' || row.cover_num === undefined || row.cover_num < 100) throw new AdportError('INVALID_INPUT', 'The seed must be a non-lookalike audience with at least 100 native matched users.');return row; };\n const source = await prepare();return { summary: `Create lookalike audience · ${input.custom_audience_name}`, changes: ['+ Lookalike audience from ' + source.name], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'tiktok', accountId: op.accountId, kind: 'create', title: 'Create lookalike audience', subject: input.custom_audience_name, fields: [{ label: 'Seed audience', after: { id: source.audience_id, name: source.name, matched_users: source.cover_num, owner: source.is_creator, shared: source.shared } }, { label: 'Include seed members', after: spec.include_source }, { label: 'Operating systems', after: spec.mobile_os }, { label: 'Placements', after: spec.placements }, { label: 'Locations', after: spec.location_ids }, { label: 'Audience breadth', after: spec.audience_size }], notices: notes },\n execute: async () => { await prepare();let id: string | undefined;try {\n id = z.object({ custom_audience_id: audienceNativeId }).parse(await this.client.post('dmp/custom_audience/lookalike/create', { advertiser_id: op.accountId, custom_audience_name: input.custom_audience_name, lookalike_spec: spec })).custom_audience_id;\n const actual = await this.created(op.accountId, id, input.custom_audience_name, 'Lookalike Audience');return this.receipt(op.accountId, actual, { requested_source_audience_id: spec.source_audience_id, specification_readback: lookalikeEcho(actual.lookalike_spec, spec) ? 'VERIFIED_NATIVE_ECHO' : 'UNCONFIRMED_NATIVE_REPRESENTATION' });\n } catch (error) { throw audienceOperationFailure(error, id ? [id] : []); } } };\n }\n private async rulePlan(op: WriteOperation): Promise<Plan> {\n const input = ruleAudienceCreate.parse(op.payload), selection = ruleSelection(input);\n const prepare = async () => { const context = await this.sources.context({ account_id: op.accountId, ...selection });if (context.context_hash !== input.expected_context_hash) throw new AdportError('PENDING_MISMATCH', 'Rule selection, source metadata or source permissions changed; read the context and preview again.');return context; };\n const before = await prepare(), display = (set: typeof input.rule_spec.inclusion_rule_set) => set.rules.map(row => { const event = row.filter_set.filters[0]!;return { event: event.value, lookback_days: row.retention_days, sources: row.event_source_ids ?? 'All available advertiser sources', ...(event.parameter_filters ? { all_conditions: event.parameter_filters.map(condition => ({ field: condition.field, operator: condition.operator, any_values: condition.values })) } : {}) }; });\n const filtered = [...input.rule_spec.inclusion_rule_set.rules, ...(input.rule_spec.exclusion_rule_set?.rules ?? [])].some(row => row.filter_set.filters[0]!.parameter_filters?.length), ruleNotes = [...notes, ...(filtered ? ['Each rule requires its event AND every parameter condition. Values within each condition use OR. Inclusion rules use OR; matching exclusion rules remove users.'] : [])];\n return { summary: `Create rule audience · ${input.custom_audience_name}`, changes: ['+ ' + input.audience_type + ' audience; inclusion rules use OR logic' + (input.rule_spec.exclusion_rule_set ? '; matching exclusion rules remove users' : '')], coercions: [], budgetDeltas: [], notes: ruleNotes,\n review: { provider: 'tiktok', accountId: op.accountId, kind: 'create', title: 'Create rule audience', subject: input.custom_audience_name, fields: [{ label: 'Audience type', after: input.audience_type }, { label: 'Verified source selection', after: before.records }, { label: 'Include any', after: display(input.rule_spec.inclusion_rule_set) }, ...(input.rule_spec.exclusion_rule_set ? [{ label: 'Exclude any', after: display(input.rule_spec.exclusion_rule_set) }] : []), { label: 'Refresh automatically', after: input.is_auto_refresh }, { label: 'Audience enhancement', after: 'Disabled' }, { label: 'Audience subtype', after: input.audience_sub_type }, { label: 'Retention requested', after: input.retention_in_days ?? 'Native default; independent of event lookback' }], notices: [...ruleNotes, ...before.notes] },\n execute: async () => { await prepare();let id: string | undefined;try {\n const { acknowledge_all_event_sources: _acknowledgement, ...nativeSelection } = selection;\n id = z.object({ custom_audience_id: audienceNativeId }).parse(await this.client.post('dmp/custom_audience/rule/create', { advertiser_id: op.accountId, ...nativeSelection, custom_audience_name: input.custom_audience_name, is_auto_refresh: input.is_auto_refresh, audience_enhancement: false, audience_sub_type: input.audience_sub_type, ...(input.retention_in_days !== undefined ? { retention_in_days: input.retention_in_days } : {}) })).custom_audience_id;\n const actual = await this.created(op.accountId, id, input.custom_audience_name, ruleTypes[input.audience_type]);return this.receipt(op.accountId, actual, { requested_audience_type: input.audience_type, type_mapping_verified: input.audience_type in ruleTypes, rule_readback: ruleEcho(actual.rule, input.rule_spec) ? 'VERIFIED_NATIVE_ECHO' : 'UNCONFIRMED_NATIVE_REPRESENTATION', source_selection_verified: true, retention_requested: input.retention_in_days, native_expired_time: actual.expired_time });\n } catch (error) { throw audienceOperationFailure(error, id ? [id] : []); } } };\n }\n private async refreshPlan(op: WriteOperation): Promise<Plan> {\n const input = lookalikeAudiencesRefresh.parse(op.payload), ids = input.targets.map(row => row.custom_audience_id);\n const prepare = async () => { const rows = await this.audiences.inspect(op.accountId, ids);for (const row of rows) { const target = input.targets.find(target => target.custom_audience_id === row.audience_id)!;owned(op.accountId, row);ready(row);if (row.type !== 'Lookalike Audience') throw new AdportError('INVALID_INPUT', 'Every refresh target must be a native Lookalike Audience.');if (row.snapshot_hash !== target.expected_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'A lookalike target changed; read every target and preview again.'); }return rows; };\n const before = await prepare();return { summary: `Refresh ${ids.length} lookalike audiences`, changes: before.map(row => '~ Refresh ' + row.name), coercions: [], budgetDeltas: [], notes,\n review: { provider: 'tiktok', accountId: op.accountId, kind: 'update', title: 'Refresh lookalike audiences', subject: `${ids.length} selected`, fields: before.map(row => ({ label: row.name, before: { id: row.audience_id, shared: row.shared }, after: 'Recompute native lookalike membership' })), notices: notes },\n execute: async () => { const fresh = await prepare();try {\n z.object({}).strict().parse(await this.client.post('dmp/custom_audience/lookalike/update', { advertiser_id: op.accountId, custom_audience_ids: ids }));\n const results: Array<{ id: string; status: string; native_is_valid?: boolean }> = [];\n const actualRows = await this.audiences.inspect(op.accountId, ids);\n for (const row of fresh) { const actual = actualRows.find(actual => actual.audience_id === row.audience_id)!;owned(op.accountId, actual);if (actual.native_error_reported || canonical(customAudienceConfiguration(actual)) !== canonical(customAudienceConfiguration(row))) throw invalid();results.push({ id: row.audience_id, status: 'ACCEPTED_FOR_PROCESSING', native_is_valid: actual.is_valid }); }\n return { applied: true, resourceIds: ids, details: { status: 'ACCEPTED_FOR_PROCESSING', processed: false, metadata_preservation: 'VERIFIED', membership_verified: false, accepted_count: ids.length, results, next_tool: 'tiktok_get_custom_audience' }, warnings: notes.slice(1) };\n } catch (error) { throw audienceOperationFailure(error, ids); } } };\n }\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { TikTokClient } from './client.js';\nimport type { TikTokAdsProvider } from './provider.js';\nimport { nativeListComplete } from './pagination.js';\n\nconst id = z.string().regex(/^\\d+$/);\nconst nativeId = z.union([id, z.number().int().positive().safe()]).transform(String);\nconst matching = z.object({ email: z.boolean(), phone_number: z.boolean() }).strict();\nconst name = z.string().trim().min(1);\nexport const pixelList = z.object({\n account_id: id, pixel_id: id.optional(), code: z.string().min(1).optional(), name: name.optional(),\n order_by: z.enum(['EARLIEST_CREATE', 'LATEST_CREATE']).optional(),\n filtering: z.object({ available_for_catalog_only: z.boolean() }).strict().optional(),\n page: z.number().int().positive().safe().default(1), page_size: z.number().int().positive().max(20).default(20),\n});\nexport const pixelCreate = z.object({ pixel_name: name, pixel_category: z.enum(['CONTACTS', 'CUSTOMIZE_EVENTS', 'FILLING_FORM', 'LANDING_PAGE', 'ONLINE_STORE']).optional(), partner_name: z.string().min(1).optional() }).strict();\nexport const pixelUpdate = z.object({\n pixel_id: id, expected_configuration_hash: z.string().regex(/^[a-f0-9]{64}$/),\n pixel_name: name.optional(), advanced_matching_fields: matching.optional(),\n}).strict().refine(value => value.pixel_name !== undefined || value.advanced_matching_fields !== undefined, 'Provide a pixel name or both matching settings');\nconst date = z.iso.date();\nexport const pixelStats = z.object({\n account_id: id, pixel_ids: z.array(id).min(1).max(20).refine(values => new Set(values).size === values.length, 'Pixel IDs must be unique; Adport allows 20 per request'),\n date_range: z.object({ start_date: date, end_date: date }).strict().refine(value => value.start_date <= value.end_date, 'End date must not precede start date'),\n});\nconst row = z.looseObject({ pixel_id: nativeId, pixel_name: z.string(), advertiser_id: nativeId.optional() });\nconst pageInfo = z.looseObject({ page: z.number().int().positive().safe(), page_size: z.number().int().positive().max(20), total_page: z.number().int().nonnegative().safe().optional(), total_number: z.number().int().nonnegative().safe().optional() });\nconst listResponse = z.looseObject({ pixels: z.array(row), page_info: pageInfo.optional() });\ntype Pixel = z.infer<typeof row>;\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]> };\nconst canonical = (value: unknown) => 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 configuration = (value: Pixel) => Object.fromEntries(['pixel_id', 'pixel_name', 'pixel_code', 'pixel_category', 'partner_name', 'advanced_matching_fields'].filter(key => value[key] !== undefined).map(key => [key, value[key]]));\nconst hash = (account: string, value: Pixel) => createHash('sha256').update(canonical({ account_id: account, configuration: configuration(value) })).digest('hex');\nconst notes = ['Local preview only. This manages a Pixel record; it does not install tracking, send events or change ads, budgets or delivery.', 'TikTok permissions remain authoritative. No automatic write retry; reconcile the Pixel ID or list after an uncertain outcome.'];\n\n/** TikTok-owned SDK f809c396: pixel/{list,create,update} and pixel/event/stats. */\nexport class TikTokMeasurementService {\n constructor(private readonly client: TikTokClient) {}\n\n async list(raw: z.input<typeof pixelList>) {\n const { account_id, ...input } = pixelList.parse(raw);\n const parsed = listResponse.safeParse(await this.client.get('pixel/list', { advertiser_id: account_id, ...input }));\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'tiktok: Pixel response shape could not be verified');\n const data = parsed.data, pixels = data.pixels, page = data.page_info;\n if (pixels.length > input.page_size || new Set(pixels.map(value => value.pixel_id)).size !== pixels.length || pixels.some(value => value.advertiser_id !== undefined && value.advertiser_id !== account_id || input.pixel_id && value.pixel_id !== input.pixel_id)) throw new AdportError('PROVIDER_ERROR', 'tiktok: Pixel response does not match the selected advertiser, ID or page size');\n if (page && (page.page !== input.page || page.page_size !== input.page_size)) throw new AdportError('PROVIDER_ERROR', 'tiktok: Pixel pagination does not match the requested page');\n const complete = nativeListComplete(page, pixels.length);\n return { ...data, pixels: pixels.map((value): Pixel & { configuration_hash: string } => ({ ...value, configuration_hash: hash(account_id, value) })), complete, truncated: complete !== true,\n ...(complete === false ? { next_page: input.page + 1 } : {}),\n ...(complete === null ? { pagination_note: 'Native pagination is missing or contradictory; completeness is unknown.' } : {}),\n };\n }\n\n async get(account: string, pixelId: string) {\n const data = await this.list({ account_id: account, pixel_id: pixelId });\n const pixel = data.pixels.find(value => value.pixel_id === pixelId);\n if (!pixel && data.complete !== true) throw new AdportError('PROVIDER_ERROR', 'tiktok: Pixel lookup could not confirm absence');\n if (!pixel) throw new AdportError('INVALID_INPUT', 'tiktok: Pixel was not found in the selected advertiser');\n return { pixel };\n }\n\n async stats(raw: z.input<typeof pixelStats>) {\n const input = pixelStats.parse(raw);\n const parsed = z.looseObject({ list: z.array(z.record(z.string(), z.unknown())) }).safeParse(await this.client.get('pixel/event/stats', { advertiser_id: input.account_id, pixel_ids: input.pixel_ids, date_range: input.date_range }));\n if (!parsed.success || parsed.data.list.some(value => value.advertiser_id !== undefined && String(value.advertiser_id) !== input.account_id || value.pixel_id !== undefined && (!nativeId.safeParse(value.pixel_id).success || !input.pixel_ids.includes(String(value.pixel_id))))) throw new AdportError('PROVIDER_ERROR', 'tiktok: Pixel statistics response does not match the selected advertiser or IDs');\n return { ...parsed.data, pixel_ids: input.pixel_ids, date_range: input.date_range };\n }\n\n async plan(op: WriteOperation): Promise<Plan> {\n if (op.tool === 'tiktok_create_pixel') {\n const input = pixelCreate.parse(op.payload);\n return { summary: `Create TikTok Pixel \"${input.pixel_name}\"`, changes: [`+ Pixel ${JSON.stringify(input)}`], notes: [...notes, 'Creation uses TikTok’s native matching defaults; inspect the returned configuration before separately approving matching changes or installing tracking.'], coercions: [], budgetDeltas: [], execute: async () => {\n let result: unknown;\n try { result = await this.client.post('pixel/create', { ...input, advertiser_id: op.accountId }); }\n catch (error) { if (error instanceof AdportError) throw error; throw new AdportError('PROVIDER_ERROR', 'tiktok: Pixel creation outcome unconfirmed; inspect the advertiser list before another create'); }\n const receipt = z.looseObject({ pixel_id: nativeId }).safeParse(result);\n if (!receipt.success) throw new AdportError('PROVIDER_ERROR', 'tiktok: Pixel creation returned no verified ID; inspect the advertiser list before another create');\n const pixelId = receipt.data.pixel_id;\n try {\n const actual = (await this.get(op.accountId, pixelId)).pixel;\n if (!Object.entries(input).every(([key, value]) => actual[key] === value)) throw new Error('Pixel readback differs');\n } catch { throw new AdportError('PROVIDER_ERROR', 'tiktok: Pixel creation readback unconfirmed; reconcile the returned ID before another create', { resource_ids: [pixelId] }); }\n return [pixelId];\n } };\n }\n if (op.tool !== 'tiktok_update_pixel') throw new AdportError('INVALID_INPUT', 'tiktok: unsupported Pixel operation');\n const input = pixelUpdate.parse(op.payload), current = (await this.get(op.accountId, input.pixel_id)).pixel;\n if (current.configuration_hash !== input.expected_configuration_hash) throw new AdportError('INVALID_INPUT', 'tiktok: Pixel configuration changed; read it again before a new preview');\n const previousMatching = matching.safeParse(current.advanced_matching_fields);\n if (!previousMatching.success) throw new AdportError('PROVIDER_ERROR', 'tiktok: current Pixel matching settings could not be verified; no update sent');\n const fields = { pixel_name: input.pixel_name ?? current.pixel_name, advanced_matching_fields: input.advanced_matching_fields ?? previousMatching.data };\n const expected = { ...current, ...fields };\n const updateNotes = [...notes, 'Email and phone matching settings are explicit; a name-only update preserves both current values.'];\n return { summary: `Update TikTok Pixel \"${current.pixel_name}\"`, changes: [`~ Pixel ${input.pixel_id}: ${JSON.stringify(configuration(current))} → ${JSON.stringify(configuration(expected))}`], notes: updateNotes, coercions: [], budgetDeltas: [],\n review: { provider: 'tiktok', accountId: op.accountId, kind: op.kind, title: 'Update Pixel', subject: current.pixel_name, fields: [\n { label: 'Name', before: current.pixel_name, after: fields.pixel_name },\n { label: 'Email matching', before: previousMatching.data.email, after: fields.advanced_matching_fields.email },\n { label: 'Phone matching', before: previousMatching.data.phone_number, after: fields.advanced_matching_fields.phone_number },\n ], notices: updateNotes }, execute: async () => {\n let accepted = false;\n try {\n await this.client.post('pixel/update', { advertiser_id: op.accountId, pixel_id: input.pixel_id, ...fields });\n accepted = true;\n const actual = (await this.get(op.accountId, input.pixel_id)).pixel;\n if (hash(op.accountId, actual) !== hash(op.accountId, expected)) throw new Error('Pixel update readback differs');\n } catch (error) {\n if (!accepted && error instanceof AdportError && error.message.startsWith('TikTok API error ')) throw error;\n throw new AdportError('PROVIDER_ERROR', 'tiktok: Pixel update outcome unconfirmed; reconcile the returned ID before any further update', { resource_ids: [input.pixel_id] });\n }\n return [input.pixel_id];\n } };\n }\n}\n\nexport function tiktokMeasurementTools(provider: TikTokAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'tiktok_pixels', namespace: 'tiktok', description: 'Read/filter advertiser Pixels by native ID, code, name, order or catalog availability; max 20/page. Returns configuration_hash and explicit pagination certainty; no tracking events or configuration changes.', input: pixelList, presentation: 'records', annotations: { readOnly: true }, handler: input => provider.measurement.list(input) }),\n defineTool({ name: 'tiktok_get_pixel', namespace: 'tiktok', description: 'Read one advertiser Pixel and its configuration_hash using the ID-filtered native list endpoint. Matching settings are returned for review; tracking is not installed.', input: z.object({ account_id: id, pixel_id: id }), presentation: 'records', annotations: { readOnly: true }, handler: input => provider.measurement.get(input.account_id, input.pixel_id) }),\n defineTool({ name: 'tiktok_pixel_event_stats', namespace: 'tiktok', description: 'Read native event statistics for explicit Pixel IDs and a date range. Adport limit 20 IDs/request. Returns provider-native fields; does not send test or live conversion events.', input: pixelStats, presentation: 'records', annotations: { readOnly: true }, handler: input => provider.measurement.stats(input) }),\n guardedWriteTool({ name: 'tiktok_create_pixel', namespace: 'tiktok', provider: 'tiktok', kind: 'create', destructive: false, description: 'Create a native advertiser Pixel record and independently verify the returned ID and fields. Does not install tracking, send events or change ads. TikTok controls creation defaults; no automatic retry.', payload: pixelCreate }),\n guardedWriteTool({ name: 'tiktok_update_pixel', namespace: 'tiktok', provider: 'tiktok', kind: 'update', destructive: false, description: 'Update Pixel name or explicit email/phone matching flags using its current configuration_hash. Verifies current settings before writing and independently reads back the result. Omitted flags are preserved; no tracking install or event sending.', payload: pixelUpdate }),\n ];\n}\n","import { AdportError, defineTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { TikTokClient } from './client.js';\nimport type { TikTokAdsProvider } from './provider.js';\nimport { nativeListComplete } from './pagination.js';\n\nconst id = z.string().regex(/^[1-9]\\d*$/);\nconst nativeId = z.union([z.string().regex(/^\\d+$/), z.number().int().nonnegative().safe()]).transform(String);\nconst dimension = z.enum(['CAMPAIGN', 'ADGROUP', 'AD']);\nconst status = z.enum(['ON', 'OFF', 'DELETED']);\nconst lang = z.enum(['EN', 'ZH', 'JA']).default('EN');\nconst paging = { page: z.number().int().positive().safe().default(1), page_size: z.number().int().positive().max(100).default(10).describe('Adport limit: 100 records per page') };\nconst ruleInfo = z.array(z.string().min(1)).min(1).max(100);\nconst filters = { status: status.optional(), rule_info: ruleInfo.optional(), data_dimension: dimension.optional() };\nconst datetime = z.string().regex(/^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/).refine(value => {\n const parsed = new Date(value.replace(' ', 'T') + 'Z');\n return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 19).replace('T', ' ') === value;\n}, 'Use a valid UTC datetime: YYYY-MM-DD HH:MM:SS');\nexport const automatedRuleList = z.object({ account_id: id, filtering: z.object(filters).strict().optional(), tzone: z.string().min(1).optional(), ...paging }).strict();\nexport const automatedRuleGet = z.object({ account_id: id, rule_ids: z.array(id).min(1).max(100).refine(values => new Set(values).size === values.length, 'Rule IDs must be unique; Adport limit: 100') }).strict();\nexport const automatedRuleResults = z.object({ account_id: id, lang, filtering: z.object({\n ...filters,\n // The published result-filter enum uses this spelling; keep the documented wire value.\n action: z.enum(['TURN_ON', 'TURN_OFF', 'MESSAGE', 'DAILY_BUDGET', 'LIFERIME_BUDGET', 'BID']).optional(),\n time: z.tuple([datetime, datetime]).refine(([start, end]) => start <= end, 'End time must not precede start time').optional(),\n}).strict().optional(), ...paging }).strict();\nconst resultPair = z.object({ rule_id: id, exec_id: id }).strict();\nexport const automatedRuleResultDetails = z.object({ account_id: id, lang, result_detail: z.array(resultPair).min(1).max(100).refine(values => new Set(values.map(value => `${value.rule_id}:${value.exec_id}`)).size === values.length, 'Rule/execution pairs must be unique; Adport limit: 100') }).strict();\n\nconst rule = z.looseObject({ rule_id: nativeId, name: z.string().optional(), rule_status: z.string().optional() });\nconst pageInfo = z.looseObject({ page: z.number().int().positive().safe(), page_size: z.number().int().positive().safe(), total_page: z.number().int().nonnegative().safe().optional(), total_number: z.number().int().nonnegative().safe().optional() });\nconst pageResponse = z.looseObject({ rules: z.array(rule), page_info: pageInfo.optional() });\nconst resultResponse = z.looseObject({ result_details: z.array(z.looseObject({ rule_id: nativeId, exec_id: nativeId })) });\nconst record = z.record(z.string(), z.unknown());\nconst output = z.looseObject({ records: z.array(record), complete: z.boolean().nullable(), truncated: z.boolean(), next_page: z.number().int().positive().safe().optional() });\nconst notes = ['TikTok restricts automated-rule creation to direct advertisers; its current documentation excludes SaaS platforms managing advertisers. These tools only inspect existing rules and execution results.'];\ntype Row = Record<string, unknown>;\nconst object = (value: unknown): value is Row => value !== null && typeof value === 'object' && !Array.isArray(value);\n\n/** Native v1.3 docs and TikTok-owned SDK f809c396, inspected 2026-11-05. */\nexport class TikTokAutomatedRulesService {\n constructor(private readonly client: TikTokClient) {}\n\n private scoped(value: unknown, account: string): unknown {\n if (Array.isArray(value)) return value.map(item => this.scoped(item, account));\n if (!object(value)) return value;\n return Object.fromEntries(Object.entries(value).map(([key, item]) => {\n if (['advertiser_id', 'rule_id', 'exec_id', 'task_exec_id', 'object_dimension_id'].includes(key)) {\n const parsed = nativeId.safeParse(item);\n if (!parsed.success || key === 'advertiser_id' && parsed.data !== account) throw new AdportError('PROVIDER_ERROR', 'tiktok: rule response contains an unverifiable ID or a different advertiser');\n return [key, parsed.data];\n }\n if (key === 'dimension_ids') {\n const parsed = z.array(nativeId).safeParse(item);\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'tiktok: rule object IDs could not be verified');\n return [key, parsed.data];\n }\n return [key, this.scoped(item, account)];\n }));\n }\n\n private records(rows: Array<z.infer<typeof rule>>, history: boolean): Row[] {\n return rows.map(value => {\n const result = object(value.rule_check_result) ? value.rule_check_result : object(value.last_check_result_summary) ? value.last_check_result_summary : undefined;\n const identity = history ? { ...(result?.task_exec_id !== undefined ? { id: `${value.rule_id}:${result.task_exec_id}` } : {}), rule_id: value.rule_id } : { id: value.rule_id };\n return { ...identity, ...(value.name !== undefined ? { name: value.name } : {}), ...(value.rule_status !== undefined ? { status: value.rule_status } : {}),\n ...(Array.isArray(value.actions) ? { action_types: value.actions.filter(object).map(action => action.subject_type) } : {}),\n ...(Array.isArray(value.apply_objects) ? { applies_to: value.apply_objects.filter(object).map(target => target.dimension) } : {}),\n ...(object(value.rule_exec_info) ? { schedule: value.rule_exec_info } : {}),\n ...(result ? { last_result: result } : {}),\n };\n });\n }\n\n private async readPage(path: string, account: string, params: Row, requestedIds?: string[]) {\n const parsed = pageResponse.safeParse(this.scoped(await this.client.get(path, { advertiser_id: account, ...params }), account));\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'tiktok: automated-rule response shape could not be verified');\n const data = parsed.data, page = data.page_info, history = path === 'optimizer/rule/result/list';\n if (!history && new Set(data.rules.map(value => value.rule_id)).size !== data.rules.length || requestedIds && data.rules.some(value => !requestedIds.includes(value.rule_id))) throw new AdportError('PROVIDER_ERROR', 'tiktok: automated-rule response has duplicate or unrequested rule IDs');\n if (typeof params.page === 'number' && (data.rules.length > Number(params.page_size) || page && (page.page !== params.page || page.page_size !== params.page_size))) throw new AdportError('PROVIDER_ERROR', 'tiktok: automated-rule pagination does not match the requested page');\n const complete = nativeListComplete(page, data.rules.length);\n return { ...data, records: this.records(data.rules, history), complete, truncated: complete !== true, next_page: undefined,\n ...(!requestedIds && complete === false && Number.isSafeInteger(Number(params.page) + 1) ? { next_page: Number(params.page) + 1 } : {}),\n ...(requestedIds ? { requested_rule_ids: requestedIds, unreturned_rule_ids: requestedIds.filter(value => !data.rules.some(row => row.rule_id === value)), all_requested_ids_returned: requestedIds.every(value => data.rules.some(row => row.rule_id === value)) } : {}),\n notes: [...notes, ...(complete === null ? ['Native pagination is missing or contradictory; completeness and absence are unconfirmed.'] : []), ...(requestedIds ? ['Unreturned IDs are not proof that a rule does not exist. This endpoint has no documented continuation parameter.'] : [])],\n };\n }\n\n list(raw: z.input<typeof automatedRuleList>) {\n const { account_id, ...input } = automatedRuleList.parse(raw);\n return this.readPage('optimizer/rule/list', account_id, input);\n }\n\n get(raw: z.input<typeof automatedRuleGet>) {\n const { account_id, rule_ids } = automatedRuleGet.parse(raw);\n return this.readPage('optimizer/rule/get', account_id, { rule_ids }, rule_ids);\n }\n\n results(raw: z.input<typeof automatedRuleResults>) {\n const { account_id, ...input } = automatedRuleResults.parse(raw);\n return this.readPage('optimizer/rule/result/list', account_id, input);\n }\n\n async details(raw: z.input<typeof automatedRuleResultDetails>) {\n const { account_id, ...input } = automatedRuleResultDetails.parse(raw);\n const parsed = resultResponse.safeParse(this.scoped(await this.client.get('optimizer/rule/result/get', { advertiser_id: account_id, ...input }), account_id));\n if (!parsed.success || parsed.data.result_details.some(row => !input.result_detail.some(pair => pair.rule_id === row.rule_id && pair.exec_id === row.exec_id))) throw new AdportError('PROVIDER_ERROR', 'tiktok: execution details do not match the requested rule/execution pairs');\n return { ...parsed.data, records: parsed.data.result_details, complete: null, truncated: true, notes: [...notes, 'Native execution details have no documented paging/completeness marker; omitted objects or executions are not proof of absence.'] };\n }\n}\n\nexport function tiktokAutomatedRuleTools(provider: TikTokAdsProvider): AnyToolDefinition[] {\n const shared = { namespace: 'tiktok', output, presentation: 'records' as const, catalog: { category: 'administration' as const, exposure: 'specialist' as const }, annotations: { readOnly: true } };\n const pagination = { cursorInput: 'page', cursorOutput: 'next_page' };\n return [\n defineTool({ ...shared, name: 'tiktok_automated_rules', description: 'Inspect existing advertiser automated rules by native status, ID/name and object dimension. Explicit page certainty and Load more; Adport limit100/page. Does not create rules or trigger actions.', input: automatedRuleList, pagination, handler: input => provider.automatedRules.list(input) }),\n defineTool({ ...shared, name: 'tiktok_get_automated_rules', description: 'Inspect explicit advertiser rule IDs, preserving configuration, native IDs and execution summaries. Unreturned IDs are not proof of absence; Adport limit100 IDs/request.', input: automatedRuleGet, handler: input => provider.automatedRules.get(input) }),\n defineTool({ ...shared, name: 'tiktok_automated_rule_results', description: 'Read existing rule execution history with native filters and UTC time range. Preserves rule configuration and execution summaries; supports paging, not action execution.', input: automatedRuleResults, pagination, handler: input => provider.automatedRules.results(input) }),\n defineTool({ ...shared, name: 'tiktok_automated_rule_result_details', description: 'Read per-object results for explicit native rule/execution ID pairs. Provider errors and exact IDs are retained; no execution, notifications or budget changes.', input: automatedRuleResultDetails, handler: input => provider.automatedRules.details(input) }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, type MediaResolver, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport { catalogAccessChange, catalogInput, catalogRename } from './catalog-tools.js';\nimport { creationScope, catalogScopeKey, requireCatalogAccess, type TikTokCatalogAccessStore, type TikTokCatalogScope } from './catalog-access.js';\nimport type { TikTokClient } from './client.js';\nimport { TikTokCatalogProductSets } from './catalog-product-sets.js';\nimport { TikTokCatalogFeeds } from './catalog-feeds.js';\nimport { TikTokCatalogProducts } from './catalog-products.js';\nimport { TikTokCatalogProductAuthoring } from './catalog-product-authoring.js';\nimport { catalogPermissionSnapshot } from './catalog-schema.js';\nimport { TikTokCatalogLifecycle } from './catalog-lifecycle.js';\nimport { TikTokCatalogVideos } from './catalog-videos.js';\nimport { TikTokCatalogEventSources } from './catalog-event-sources.js';\n\ntype Row = Record<string, unknown>;\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]> };\nconst id = z.string().regex(/^\\d{1,30}$/);\nconst nativeCatalog = z.looseObject({ catalog_id: id, catalog_name: z.string(), catalog_type: z.string(), bc_info: z.looseObject({ bc_id: id, bc_name: z.string().optional() }), catalog_conf: z.record(z.string(), z.unknown()) });\ntype Catalog = z.infer<typeof nativeCatalog>;\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 config = (value: Catalog) => ({ catalog_id: value.catalog_id, catalog_name: value.catalog_name, catalog_type: value.catalog_type, bc_id: value.bc_info.bc_id, catalog_conf: value.catalog_conf });\nconst configurationHash = (account: string, value: Catalog) => createHash('sha256').update(canonical({ account_id: account, ...config(value) })).digest('hex');\nconst scopeOf = (input: { account_id: string; bc_id: string; catalog_id: string }): TikTokCatalogScope => ({ accountId: input.account_id, businessId: input.bc_id, resourceId: input.catalog_id, kind: 'catalog' });\nconst nativeError = (error: unknown) => {\n const details = error instanceof AdportError && error.details && typeof error.details === 'object' ? error.details as Row : {};\n return new AdportError('PROVIDER_ERROR', 'TikTok catalog request failed. Check the token’s Business Center/catalog permissions and native API eligibility. No request was retried.', { ...(Number.isInteger(details.code) ? { provider_code: details.code } : {}), ...(typeof details.request_id === 'string' && /^[a-zA-Z0-9_-]{1,128}$/.test(details.request_id) ? { request_id: details.request_id } : {}) });\n};\n\n/** Account scope and catalog-resource scope are independent authorization checks. */\nexport class TikTokCatalogService {\n readonly productSets: TikTokCatalogProductSets;\n readonly feeds: TikTokCatalogFeeds;\n readonly products: TikTokCatalogProducts;\n readonly productAuthoring: TikTokCatalogProductAuthoring;\n readonly videos: TikTokCatalogVideos;\n readonly eventSources: TikTokCatalogEventSources;\n readonly lifecycle: TikTokCatalogLifecycle;\n constructor(private readonly client: Pick<TikTokClient, 'get' | 'post'> & Partial<Pick<TikTokClient, 'postMultipart'>>, private readonly store?: TikTokCatalogAccessStore, media?: MediaResolver) {\n const authorizeParent = async (input: z.infer<typeof catalogInput>, write?: boolean) => {\n const grant = await requireCatalogAccess(this.store, scopeOf(input), write);\n const catalog = await this.native(input);\n return { ...catalog, configuration_hash: configurationHash(input.account_id, catalog), can_write: grant.mode === 'write' && this.store?.canWrite === true };\n };\n this.productSets = new TikTokCatalogProductSets(client, authorizeParent, media);\n this.feeds = new TikTokCatalogFeeds(client, authorizeParent);\n this.products = new TikTokCatalogProducts(client, authorizeParent, this.feeds, media);\n this.productAuthoring = new TikTokCatalogProductAuthoring(client, authorizeParent, this.feeds, this.products, media);\n this.videos = new TikTokCatalogVideos(client, authorizeParent, media);\n this.eventSources = new TikTokCatalogEventSources(client, authorizeParent);\n this.lifecycle = new TikTokCatalogLifecycle(client, store, authorizeParent, input => this.native(input, true));\n }\n private manager() {\n if (!this.store?.canManage) throw new AdportError('POLICY_VIOLATION', 'Only the local owner or a signed-in project owner/admin in Accounts can change catalog access.');\n return this.store;\n }\n private async native(input: z.infer<typeof catalogInput>): Promise<Catalog>;\n private async native(input: z.infer<typeof catalogInput>, allowAbsent: true): Promise<Catalog | undefined>;\n private async native(input: z.infer<typeof catalogInput>, allowAbsent = false): Promise<Catalog | undefined> {\n let data: unknown;\n try { data = await this.client.get('catalog/get', { bc_id: input.bc_id, catalog_id: input.catalog_id, page: 1, page_size: 1000 }); } catch (error) { if (error instanceof AdportError && ['POLICY_VIOLATION', 'NOT_CONNECTED'].includes(error.code)) throw error;throw nativeError(error); }\n const result = z.looseObject({ list: allowAbsent ? z.array(nativeCatalog).max(1) : z.array(nativeCatalog).length(1), page_info: z.looseObject({ page: z.number().int().positive(), total_page: z.number().int().nonnegative() }).optional() }).safeParse(data);\n if (!result.success || result.data.list.some(row => row.catalog_id !== input.catalog_id || row.bc_info.bc_id !== input.bc_id) || result.data.page_info && (result.data.page_info.page !== 1 || result.data.page_info.total_page > 1 || !result.data.list.length && typeof result.data.page_info.total_number === 'number' && result.data.page_info.total_number !== 0)) throw new AdportError('PROVIDER_ERROR', 'TikTok returned an unexpected catalog/Business Center scope or incomplete exact-ID response.');\n return result.data.list[0]!;\n }\n async access(accountId: string) {\n id.parse(accountId);\n const grants = await this.store?.list(accountId) ?? [];\n if (grants.some(value => value.scope.accountId !== accountId)) throw new AdportError('POLICY_VIOLATION', 'Catalog grants do not match the selected advertiser.');\n return { grants, records: grants.map(value => ({ id: value.scope.resourceId, name: value.scope.kind === 'catalog' ? 'Catalog ' + value.scope.resourceId : 'Catalog creation', business_center_id: value.scope.businessId, access: value.mode })), notes: ['Only explicit project grants are returned. An advertiser account does not implicitly authorize other Business Center assets.'] };\n }\n async accessSnapshot(value: unknown) {\n const input = catalogPermissionSnapshot.parse(value), scope = input.resource_kind === 'catalog_creation' ? creationScope(input.account_id, input.bc_id) : scopeOf({ ...input, catalog_id: input.catalog_id! }), grant = await this.manager().get(scope);\n return { grant, records: [{ id: scope.resourceId, name: scope.kind === 'catalog_creation' ? 'Creation delegation' : 'Catalog access', business_center_id: input.bc_id, access: grant.mode }] };\n }\n async get(value: unknown) {\n const input = catalogInput.parse(value);await requireCatalogAccess(this.store, scopeOf(input));\n const catalog = await this.native(input), data = { ...catalog, configuration_hash: configurationHash(input.account_id, catalog) };\n return { catalog: data, records: [{ id: catalog.catalog_id, name: catalog.catalog_name, native_ad_eligibility: catalog.ad_creation_eligible ?? 'Not reported', type: catalog.catalog_type, business_center: catalog.bc_info.bc_name ?? input.bc_id, currency: catalog.catalog_conf.currency ?? 'Not reported', country: catalog.catalog_conf.country ?? 'Not reported' }] };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n if (['tiktok_create_catalog', 'tiktok_delete_catalog'].includes(op.tool)) return this.lifecycle.plan(op);\n if (['tiktok_bind_catalog_event_sources', 'tiktok_unbind_catalog_event_sources'].includes(op.tool)) return this.eventSources.plan(op);\n if (['tiktok_upload_catalog_videos', 'tiktok_delete_catalog_video'].includes(op.tool)) return this.videos.plan(op);\n if (this.productAuthoring.supports(op.tool)) return this.productAuthoring.plan(op);\n if (op.tool === 'tiktok_import_catalog_file') return this.products.plan(op);\n if (['tiktok_create_catalog_feed', 'tiktok_update_catalog_feed', 'tiktok_set_catalog_feed_schedule_status', 'tiktok_delete_catalog_feed'].includes(op.tool)) return this.feeds.plan(op);\n if (['tiktok_create_product_set', 'tiktok_upload_product_set', 'tiktok_update_product_set_conditions', 'tiktok_delete_product_sets', 'tiktok_rename_product_set'].includes(op.tool)) return this.productSets.plan(op);\n if (op.provider !== 'tiktok' || op.kind !== 'update') throw new AdportError('INVALID_INPUT', 'TikTok catalog provider/operation kind mismatch.');\n const account = id.parse(op.accountId);\n if (op.tool === 'tiktok_set_catalog_access') {\n const store = this.manager(), input = catalogAccessChange.parse(op.payload), scope = input.resource_kind === 'catalog_creation' ? creationScope(account, input.bc_id) : scopeOf({ ...input, account_id: account, catalog_id: input.catalog_id! }), current = await store.get(scope);\n if (current.hash !== input.expected_access_hash) throw new AdportError('POLICY_VIOLATION', 'Catalog access changed. Read and review it again.');\n // Revocation must remain possible after token/catalog access has been lost.\n const creation = scope.kind === 'catalog_creation';\n if (creation && input.mode !== 'none') await this.lifecycle.availableCountries(input.bc_id);\n const catalog = creation || input.mode === 'none' ? undefined : await this.native({ account_id: account, bc_id: input.bc_id, catalog_id: input.catalog_id! });\n const title = input.mode === 'none' ? 'Revoke catalog access' : creation ? 'Delegate catalog creation' : 'Grant catalog access', notes = ['This changes Adport project access, not TikTok’s native user permissions.', 'Write access covers this Business Center catalog wherever it is reused. Agents cannot expand their own hosted access.', ...(creation ? ['Delegates creation in this exact Business Center and read/write management of verified new catalog IDs only. Existing catalogs are excluded.', 'Revoking creation delegation does not revoke independent grants already issued for new catalogs. Native eligibility remains authoritative.'] : [])];\n return { summary: `${title} · ${catalog?.catalog_name ?? (creation ? 'Business Center ' + input.bc_id : input.catalog_id!)}`, changes: [`~ Project access ${current.mode} → ${input.mode} for Business Center ${input.bc_id}, ${creation ? 'new catalogs only' : 'catalog ' + input.catalog_id}`], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'tiktok', accountId: account, kind: 'update', title, subject: catalog?.catalog_name ?? (creation ? 'Business Center ' + input.bc_id : input.catalog_id!), fields: [{ label: 'Business Center', after: catalog?.bc_info.bc_name ?? input.bc_id }, { label: creation ? 'Resource' : 'Catalog', after: creation ? 'New catalogs created through this project' : input.catalog_id }, { label: 'Project access', before: current.mode, after: input.mode === 'create' ? 'Create and manage verified new catalogs' : input.mode }], notices: notes },\n execute: async () => { const result = await store.compareAndSet(scope, input.expected_access_hash, input.mode), actual = await store.get(scope);if (catalogScopeKey(result.scope) !== catalogScopeKey(scope) || result.mode !== input.mode || actual.hash !== result.hash) throw new AdportError('POLICY_VIOLATION', 'Catalog access receipt is unconfirmed. Inspect access before retrying.');return [scope.resourceId]; } };\n }\n if (op.tool !== 'tiktok_update_catalog') throw new AdportError('INVALID_INPUT', 'Unsupported TikTok catalog mutation.');\n const input = catalogRename.parse(op.payload), source = { account_id: account, bc_id: input.bc_id, catalog_id: input.catalog_id }, scope = scopeOf(source);\n await requireCatalogAccess(this.store, scope, true);const current = await this.native(source);\n if (configurationHash(account, current) !== input.expected_configuration_hash) throw new AdportError('INVALID_INPUT', 'Catalog configuration changed. Read and preview it again.');\n const notes = ['Local preview only; TikTok checks native permissions and eligibility on apply.', 'The catalog may be reused by other ads or accounts. This operation updates its name and does not activate ads or change a budget.', 'No automatic retry. Inspect the exact catalog after an uncertain result.'];\n return { summary: `Rename TikTok catalog ${current.catalog_name}`, changes: [`~ Catalog name ${JSON.stringify(current.catalog_name)} → ${JSON.stringify(input.name)}`], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'tiktok', accountId: account, kind: 'update', title: 'Rename catalog', subject: current.catalog_name, fields: [{ label: 'Name', before: current.catalog_name, after: input.name }, { label: 'Business Center', after: current.bc_info.bc_name ?? input.bc_id }], notices: notes }, execute: async () => {\n await requireCatalogAccess(this.store, scope, true);\n try {\n const result = z.object({ catalog_id: id }).parse(await this.client.post('catalog/update', { bc_id: input.bc_id, catalog_id: input.catalog_id, name: input.name }));\n if (result.catalog_id !== input.catalog_id) throw new Error('ID differs');\n const actual = await this.native(source);\n if (canonical(config(actual)) !== canonical({ ...config(current), catalog_name: input.name })) throw new Error('Configuration differs');\n return [input.catalog_id];\n } catch {\n throw new AdportError('PROVIDER_ERROR', 'TikTok catalog rename outcome is unconfirmed. Read the known catalog before another write; do not replay automatically.', { resource_ids: [input.catalog_id] });\n }\n } };\n }\n}\n","import { creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { TikTokAdsProvider } from './provider.js';\nimport { catalogId, catalogInput, catalogPermissionSelection, catalogPermissionSnapshot, validCatalogPermission } from './catalog-schema.js';\nimport { productSetCreate, productSetDelete, productSetList, productSetProducts, productSetRename, productSetUpdateConditions, productSetUpload } from './catalog-product-sets.js';\nimport { catalogFeedCreate, catalogFeedDelete, catalogFeedList, catalogFeedLog, catalogFeedSwitch, catalogFeedUpdate } from './catalog-feeds.js';\nimport { catalogFileImport, catalogProductList, catalogProductLog } from './catalog-products.js';\nimport { catalogProductSchema, catalogProductContext, catalogProductUpsert, catalogProductUpdate, catalogProductDelete } from './catalog-product-authoring.js';\nimport { catalogCreationInput, catalogCreate, catalogDelete } from './catalog-lifecycle.js';\nimport { catalogEventList, catalogEventApps, catalogEventContext, catalogEventChange } from './catalog-event-sources.js';\nimport { catalogVideoList, catalogVideoLog, catalogVideoImportContext, catalogVideoUpload, catalogVideoDelete } from './catalog-videos.js';\n\nexport { catalogId, catalogInput } from './catalog-schema.js';\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nexport const catalogRename = catalogInput.omit({ account_id: true }).extend({ name: z.string().trim().min(1).max(128), expected_configuration_hash: hash, acknowledge_shared_effects: z.literal(true) }).strict();\nexport const catalogAccessChange = catalogPermissionSelection.omit({ account_id: true }).extend({ mode: z.enum(['none', 'read', 'write', 'create']), expected_access_hash: hash }).strict().refine(validCatalogPermission, 'Creation delegation accepts create/none without a catalog ID; catalog grants accept read/write/none with an exact catalog ID');\n\nexport function tiktokCatalogTools(provider: Pick<TikTokAdsProvider, 'catalogs'>, accessManagement = false): AnyToolDefinition[] {\n const read = { namespace: 'tiktok', annotations: { readOnly: true }, presentation: 'records' as const, output: z.looseObject({ records: z.array(z.record(z.string(), z.unknown())) }) };\n return [\n defineTool({ ...read, name: 'tiktok_catalog_creation_context', catalog: { category: 'creatives', exposure: 'specialist' }, description: 'Read an owner-delegated creation grant hash and available regions for one advertiser/Business Center. Covers all ten catalog types; native allowlists and currency combinations remain authoritative. No existing catalogs are enumerated or granted.', input: catalogCreationInput, handler: input => provider.catalogs.lifecycle.context(input) }),\n guardedWriteTool({ name: 'tiktok_create_catalog', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'create', destructive: false, description: 'Create an empty catalog using creation-delegation/region hashes and explicit immutable configuration. Independently verifies the native ID/configuration, then adopts only that new ID for project read/write access under owner delegation. No ads, products or spend; no automatic replay.', payload: catalogCreate }),\n guardedWriteTool({ name: 'tiktok_delete_catalog', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'remove', destructive: true, description: 'Permanently delete one writable catalog with fresh configuration_hash, exact name confirmation and contents/shared-effects acknowledgement. Deletes current products/feeds; contents are not enumerated/frozen. Verifies native receipt and filtered absence; errors are not absence. No restore or replay.', payload: catalogDelete }),\n defineTool({ ...read, name: 'tiktok_catalog_event_sources', catalog: { category: 'measurement', exposure: 'specialist' }, description: 'Read app/Pixel bindings in an explicitly granted Business Center catalog. Returns binding/catalog hashes. Native list is unpaged; bounded snapshot pages preserve scope. Catalog-level bindings do not establish selected-advertiser source ownership.', input: catalogEventList, pagination: { cursorInput: 'cursor' }, handler: input => provider.catalogs.eventSources.list(input) }),\n defineTool({ ...read, name: 'tiktok_catalog_event_source_apps', catalog: { category: 'measurement', exposure: 'specialist' }, description: 'Discover apps under the selected advertiser for catalog source selection. Native app_id differs from platform/TikTok App IDs. Safe summaries only; local snapshot paging over the unpaged native response. No tracking URLs/tokens or eligibility guarantee.', input: catalogEventApps, pagination: { cursorInput: 'cursor' }, handler: input => provider.catalogs.eventSources.apps(input) }),\n defineTool({ ...read, name: 'tiktok_catalog_event_source_context', catalog: { category: 'measurement', exposure: 'specialist' }, description: 'Verify one app_id, pixel_code or both under the selected advertiser and read catalog/binding/source hashes for bind or unbind. Bind checks Pixel catalog availability; unbind checks existing membership. No events or writes.', input: catalogEventContext, handler: input => provider.catalogs.eventSources.context(input) }),\n guardedWriteTool({ name: 'tiktok_bind_catalog_event_sources', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'measurement', exposure: 'specialist' }, kind: 'update', destructive: true, description: 'Bind selected advertiser app/Pixel sources to a writable catalog using fresh context hashes and shared/measurement-effects acknowledgement. Can affect existing catalog matching/ads. Rechecks sources and all bindings; no tracking installation, event sending or automatic replay.', payload: catalogEventChange }),\n guardedWriteTool({ name: 'tiktok_unbind_catalog_event_sources', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'measurement', exposure: 'specialist' }, kind: 'remove', destructive: true, description: 'Unbind explicit selected advertiser app/Pixel sources using fresh context hashes. Requires existing membership and shared/measurement-effects acknowledgement. Verifies absence and preservation of unselected binding identities. No unbind-all inference or replay; no events sent.', payload: catalogEventChange }),\n defineTool({ ...read, name: 'tiktok_catalog_videos', catalog: { category: 'creatives', exposure: 'specialist' }, description: 'Browse catalog videos with SKU associations, extraction/activation states and six-hour native previews. Composite IDs remain strings. Native pages append; explicit IDs ignore pagination. Writable catalog grants offer a normal guarded removal preview; synced advertiser copies are separate.', input: catalogVideoList, output: creativesOutput.extend({ videos: z.array(z.record(z.string(), z.unknown())), complete: z.boolean().nullable(), next_page: z.number().int().positive().optional(), notes: z.array(z.string()), page_info: z.record(z.string(), z.unknown()).optional(), missing_ids: z.array(z.string()).optional() }), presentation: 'creatives', pagination: { cursorInput: 'page', cursorOutput: 'next_page' }, handler: input => provider.catalogs.videos.list(input) }),\n defineTool({ ...read, name: 'tiktok_catalog_video_log', catalog: { category: 'creatives', exposure: 'specialist' }, description: 'Read one catalog-video handling task with exact catalog binding. Preserves native processing states/counts and bounded diagnostic field counts. Does not certify video extraction, ad eligibility or advertiser sync; source links/downloads and free-form diagnostics stay hidden.', input: catalogVideoLog, handler: input => provider.catalogs.videos.log(input) }),\n defineTool({ ...read, name: 'tiktok_catalog_video_import_context', catalog: { category: 'creatives', exposure: 'specialist' }, description: 'Inspect a checksum-bound project CSV for catalog videos and verify every referenced SKU is AVAILABLE for ad creation. Returns catalog/association hashes for upload. Up to 5,000 rows/distinct SKUs and 20 SKUs/video; source URLs stay private. No upload or media-eligibility claim.', input: catalogVideoImportContext, handler: input => provider.catalogs.videos.importContext(input) }),\n guardedWriteTool({ name: 'tiktok_upload_catalog_videos', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'create', destructive: true, description: 'Submit a checksum-bound library CSV to the native catalog-video file API, using fresh import-context hashes. May feed existing catalog ads; explicit delivery/shared/async acknowledgement required. Optional sync targets only the selected advertiser and requires copy acknowledgement. Returns an accepted job, not ingestion/sync success; no replay.', payload: catalogVideoUpload }),\n guardedWriteTool({ name: 'tiktok_delete_catalog_video', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'remove', destructive: true, description: 'Remove one composite catalog-video ID with its fresh configuration_hash and shared-effects acknowledgement. Rechecks native state, issues one delete and verifies filtered-view absence. Existing catalog ads may be affected; synced advertiser-library copies remain separate. No automatic replay or restore.', payload: catalogVideoDelete }),\n defineTool({ ...read, name: 'tiktok_catalog_product_schema', catalog: { category: 'creatives', exposure: 'specialist' }, presentation: undefined, output: z.looseObject({ schema: z.record(z.string(), z.unknown()) }), description: 'Read the official structural product schema for this granted catalog’s native type and upload/update operation. Covers all ten catalog types. Native semantic requirements still apply; no products or ads are changed.', input: catalogProductSchema, handler: input => provider.catalogs.productAuthoring.schema(input) }),\n defineTool({ ...read, name: 'tiktok_catalog_product_context', catalog: { category: 'creatives', exposure: 'specialist' }, description: 'Read exact native product IDs, safe editable configuration and products_hash for JSON edits/removal. Verifies catalog/feed and every selected ID; URL origins/fingerprints only. This is selected configuration, not complete catalog inventory or proof of feed membership.', input: catalogProductContext, handler: input => provider.catalogs.productAuthoring.context(input) }),\n guardedWriteTool({ name: 'tiktok_upsert_catalog_products', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'update', destructive: true, description: 'Upload up to5,000 native JSON products using the catalog-type schema. Can replace existing external identities; fresh catalog/feed hashes and explicit replacement/shared/async acknowledgements required. Returns an accepted task, not completed ingestion. No automatic replay.', payload: catalogProductUpsert, sensitiveInputs: ['products'] }),\n guardedWriteTool({ name: 'tiktok_update_catalog_products', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'update', destructive: true, description: 'Patch product fields selected by verified native product IDs and products_hash. External identities are derived from native context and cannot be edited. Fresh catalog/feed hashes required; asynchronous task and shared-effects acknowledgements. Read the schema first; no automatic replay.', payload: catalogProductUpdate, sensitiveInputs: ['updates'] }),\n guardedWriteTool({ name: 'tiktok_delete_catalog_products', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'remove', destructive: true, description: 'Remove verified native product IDs using products_hash and fresh catalog/feed hashes. Maps native external IDs to documented deletion selectors; Entertainment removal is undocumented and refused. Requires removal/shared/async acknowledgements. Returns accepted task; never replays.', payload: catalogProductDelete }),\n defineTool({ ...read, name: 'tiktok_catalog_access', catalog: { category: 'administration', exposure: 'specialist' }, description: 'List only this project/account’s explicit Business Center catalog grants. Advertiser access alone grants no catalog access. No native Business Center inventory is enumerated.', input: z.object({ account_id: catalogId }).strict(), handler: input => provider.catalogs.access(input.account_id) }),\n defineTool({ ...read, name: 'tiktok_get_catalog', description: 'Read one explicitly granted Business Center catalog, native eligibility and configuration_hash. Verifies exact catalog and Business Center IDs; does not enumerate unrelated catalogs.', input: catalogInput, handler: input => provider.catalogs.get(input) }),\n defineTool({ ...read, name: 'tiktok_catalog_products', catalog: { category: 'creatives', exposure: 'specialist' }, description: 'Browse product/media summaries in an explicitly granted catalog. Native product-ID or ECOM SKU filters, exact string IDs and page navigation. At most100/page and10,000 accessible matches; missing pagination stays unknown. Compact view, not full editable configuration.', input: catalogProductList, output: creativesOutput.extend({ products: z.array(z.record(z.string(), z.unknown())), complete: z.boolean().nullable(), next_page: z.number().int().positive().optional(), native_access_limit: z.literal(10_000), native_limit_reached: z.boolean(), notes: z.array(z.string()), page_info: z.record(z.string(), z.unknown()).optional() }), presentation: 'creatives', pagination: { cursorInput: 'page', cursorOutput: 'next_page' }, handler: input => provider.catalogs.products.list(input) }),\n defineTool({ ...read, name: 'tiktok_catalog_product_log', catalog: { category: 'creatives', exposure: 'specialist' }, description: 'Read one product import task after verifying its catalog/feed. Native processing state, counts and bounded diagnostic field counts; no free-form error text or download capabilities. SUCCESS is not ad eligibility. Requires the feed_log_id returned on import.', input: catalogProductLog, handler: input => provider.catalogs.products.log(input) }),\n guardedWriteTool({ name: 'tiktok_import_catalog_file', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'update', destructive: true, description: 'Submit a checksum-bound project CSV as a one-time catalog feed import. Fresh catalog/feed hashes, explicit mode and asynchronous/shared-effects acknowledgement; OVERWRITE also requires deletion acknowledgement. Returns an accepted native job, not completed ingestion. Never automatically replay.', payload: catalogFileImport }),\n defineTool({ ...read, name: 'tiktok_catalog_feeds', catalog: { category: 'creatives', exposure: 'specialist' }, description: 'Browse feeds in one explicitly granted catalog, with safe source fingerprints and configuration_hash. Native lists are unpaged; Adport bounds to 5,000 and snapshot-pages locally. Credentials, source paths and query values stay hidden.', input: catalogFeedList, pagination: { cursorInput: 'cursor' }, handler: input => provider.catalogs.feeds.list(input) }),\n defineTool({ ...read, name: 'tiktok_catalog_feed_log', catalog: { category: 'creatives', exposure: 'specialist' }, description: 'Read the latest 10 native processing operations for an exact verified feed. Shows status, counts and timestamps only; not full history or proof of catalog ad eligibility.', input: catalogFeedLog, handler: input => provider.catalogs.feeds.log(input) }),\n guardedWriteTool({ name: 'tiktok_create_catalog_feed', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'create', destructive: true, description: 'Create a feed using its catalog hash. Optional source/schedule can start product processing; OVERWRITE can remove products. Native config readback required. Source arguments stay private; use the agent to apply when supplied.', payload: catalogFeedCreate, sensitiveInputs: ['schedule_param.source'] }),\n guardedWriteTool({ name: 'tiktok_update_catalog_feed', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'update', destructive: true, description: 'Update feed mode/source/schedule using its configuration_hash. OVERWRITE can remove products; explicit automatic-processing acknowledgement required. Native auth cannot be read back. Source arguments stay out of widget approvals.', payload: catalogFeedUpdate, sensitiveInputs: ['schedule_param.source'] }),\n guardedWriteTool({ name: 'tiktok_set_catalog_feed_schedule_status', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'update', destructive: true, description: 'Switch a verified feed ON/OFF with a fresh configuration_hash. ON can resume automatic product changes; requires an existing source, interval and timezone. Opposite state only; independent preservation readback and no replay.', payload: catalogFeedSwitch }),\n guardedWriteTool({ name: 'tiktok_delete_catalog_feed', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'remove', destructive: true, description: 'Permanently delete one verified shared feed using its configuration_hash. Exact native receipt and complete catalog feed absence check required. Dependent products/ads must be reviewed; uncertain results are never replayed.', payload: catalogFeedDelete }),\n defineTool({ ...read, name: 'tiktok_product_sets', catalog: { category: 'creatives', exposure: 'specialist' }, description: 'Browse one granted catalog’s product sets or an exact set, with configuration hashes. Snapshot-bound local paging; native endpoint returns all sets, bounded to 5,000. Product counts default off to avoid native timeouts.', input: productSetList, pagination: { cursorInput: 'cursor' }, handler: input => provider.catalogs.productSets.list(input) }),\n defineTool({ ...read, name: 'tiktok_product_set_products', catalog: { category: 'creatives', exposure: 'specialist' }, description: 'Read products in one verified product set within a granted catalog. Native page navigation, safe string IDs and explicit pagination certainty. Adport limits each page to 100 products.', input: productSetProducts, pagination: { cursorInput: 'page', cursorOutput: 'next_page' }, handler: input => provider.catalogs.productSets.products(input) }),\n guardedWriteTool({ name: 'tiktok_upload_product_set', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'create', destructive: false, description: 'Create an ECOM product set from a checksum-bound CSV in project media (or local file_path). Official sku_id header, 1–5,000 distinct rows, unique name up to28 chars and fresh catalog hash. Native multipart/MD5; verifies created ID/name, not full membership. Never replay an uncertain create.', payload: productSetUpload }),\n guardedWriteTool({ name: 'tiktok_rename_product_set', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'update', destructive: false, description: 'Rename one verified product set using its configuration_hash and shared-effects acknowledgement. Preserves filter conditions, independently reads back the set and never automatically replays an uncertain write.', payload: productSetRename }),\n guardedWriteTool({ name: 'tiktok_create_product_set', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'create', destructive: false, description: 'Create a filter-defined set in a writable catalog using its configuration_hash. Native and/or operators, up to 1,024 combined values; no ad activation. Independently verifies the created set; never automatically replays an uncertain create.', payload: productSetCreate }),\n guardedWriteTool({ name: 'tiktok_update_product_set_conditions', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'update', destructive: true, description: 'Replace one set’s entire product filter definition using its configuration_hash. Existing ads may select different products. Preserves name, requires shared-effects acknowledgement and independently verifies the result.', payload: productSetUpdateConditions }),\n guardedWriteTool({ name: 'tiktok_delete_product_sets', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'remove', destructive: true, description: 'Permanently delete 1–10 verified shared product sets with a fresh hash for each. Preview lists every name/ID; exact native receipt and independent catalog readback required. No automatic replay after uncertain/partial outcomes.', payload: productSetDelete }),\n guardedWriteTool({ name: 'tiktok_update_catalog', namespace: 'tiktok', provider: 'tiktok', kind: 'update', destructive: false, description: 'Rename an explicitly writable catalog using a fresh configuration_hash and shared-effects acknowledgement. Native JSON POST plus independent readback; no ads activated and no automatic retry.', payload: catalogRename }),\n ...(accessManagement ? [\n defineTool({ ...read, name: 'tiktok_catalog_access_snapshot', catalog: { category: 'administration', exposure: 'specialist' }, description: 'Owner settings/local owner only: read the exact current catalog grant hash before reviewing an access change. Not exposed by hosted MCP or public API.', input: catalogPermissionSnapshot, handler: input => provider.catalogs.accessSnapshot(input) }),\n guardedWriteTool({ name: 'tiktok_set_catalog_access', namespace: 'tiktok', provider: 'tiktok', catalog: { category: 'administration', exposure: 'specialist' }, kind: 'update', destructive: true, description: 'Owner settings/local owner only: grant read/write access to one exact catalog, delegate creation and management of new catalogs in one Business Center, or revoke access. Shared preview/apply policy, exact grant hash and atomic storage; no native permission grant or ad change.', payload: catalogAccessChange }),\n ] : []),\n ];\n}\n","import { z } from 'zod';\n\nexport const catalogId = z.string().regex(/^\\d{1,30}$/);\nexport const catalogInput = z.object({ account_id: catalogId, bc_id: catalogId, catalog_id: catalogId }).strict();\n\nexport const catalogPermissionSelection = z.object({ account_id: catalogId, bc_id: catalogId, catalog_id: catalogId.optional(), resource_kind: z.enum(['catalog', 'catalog_creation']).optional() }).strict();\nexport const validCatalogPermission = (input: { catalog_id?: string; resource_kind?: string; mode?: string }) => input.resource_kind === 'catalog_creation' ? !input.catalog_id && (!input.mode || ['none', 'create'].includes(input.mode)) : !!input.catalog_id && input.mode !== 'create';\nexport const catalogPermissionSnapshot = catalogPermissionSelection.refine(validCatalogPermission, 'Choose an exact catalog or creation delegation without a catalog ID');\n","import { createHash } from 'node:crypto';\nimport { AdportError, csvRows, MAX_PROJECT_MEDIA_BYTES, mediaSourceFields, verifyMedia, type MediaResolver, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { TikTokClient } from './client.js';\nimport { catalogId, catalogInput } from './catalog-schema.js';\nimport { nativeListComplete } from './pagination.js';\nimport { describeProductSetConditions, nativeProductSetConditions, productSetConditions } from './product-set-conditions.js';\n\nconst count = z.number().int().nonnegative().safe();\nconst nativeId = z.union([catalogId, z.number().int().positive().safe()]).transform(String);\nconst selected = catalogInput.extend({ product_set_id: catalogId }).strict();\nexport const productSetList = catalogInput.extend({\n product_set_id: catalogId.optional(),\n return_product_count: z.boolean().default(false),\n page_size: z.number().int().min(1).max(100).default(30),\n cursor: z.string().min(1).max(512).optional(),\n}).strict();\nexport const productSetProducts = selected.extend({\n page: z.number().int().min(1).max(100_000).default(1),\n page_size: z.number().int().min(1).max(100).default(20),\n}).strict();\nexport const productSetRename = selected.omit({ account_id: true }).extend({\n product_set_name: z.string().trim().min(1).max(128),\n expected_configuration_hash: z.string().regex(/^[a-f0-9]{64}$/),\n acknowledge_shared_effects: z.literal(true),\n}).strict();\nexport const productSetCreate = catalogInput.omit({ account_id: true }).extend({\n product_set_name: z.string().trim().min(1).max(128), conditions: productSetConditions,\n expected_catalog_hash: z.string().regex(/^[a-f0-9]{64}$/), acknowledge_shared_effects: z.literal(true),\n}).strict();\nexport const productSetUpload = catalogInput.omit({ account_id: true }).extend({\n ...mediaSourceFields, product_set_name: z.string().trim().min(1).max(28),\n expected_catalog_hash: z.string().regex(/^[a-f0-9]{64}$/), acknowledge_shared_effects: z.literal(true),\n}).strict().refine(value => Number(!!value.media_id) + Number(!!value.file_path) === 1, 'Choose one project media_id or local file_path');\nexport const productSetUpdateConditions = selected.omit({ account_id: true }).extend({\n conditions: productSetConditions, expected_configuration_hash: z.string().regex(/^[a-f0-9]{64}$/), acknowledge_shared_effects: z.literal(true),\n}).strict();\nexport const productSetDelete = catalogInput.omit({ account_id: true }).extend({\n sets: z.array(z.object({ product_set_id: catalogId, expected_configuration_hash: z.string().regex(/^[a-f0-9]{64}$/) }).strict()).min(1).max(10).refine(rows => new Set(rows.map(row => row.product_set_id)).size === rows.length, 'Product-set IDs must be unique'),\n acknowledge_shared_effects: z.literal(true),\n}).strict();\n\nconst setRow = z.looseObject({\n product_set_id: nativeId, catalog_id: nativeId, bc_id: nativeId.optional(),\n product_set_name: z.string().optional(), name: z.string().optional(),\n conditions: nativeProductSetConditions, product_count: count.optional(),\n}).refine(row => typeof row.product_set_name === 'string' || typeof row.name === 'string')\n .refine(row => row.product_set_name === undefined || row.name === undefined || row.product_set_name === row.name)\n .transform(({ name, ...row }) => ({ ...row, product_set_name: row.product_set_name ?? name! }));\ntype ProductSet = z.infer<typeof setRow>;\ntype CatalogSelection = z.infer<typeof catalogInput>;\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]> };\nconst canonical = (value: unknown): string => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item)\n ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);\nconst digest = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex');\nconst configuration = (row: ProductSet) => ({ product_set_id: row.product_set_id, catalog_id: row.catalog_id, product_set_name: row.product_set_name, conditions: row.conditions });\nconst hash = (input: CatalogSelection, row: ProductSet) => digest({ ...input, configuration: configuration(row) });\nconst invalid = () => new AdportError('PROVIDER_ERROR', 'TikTok product-set data has an unexpected scope, identifier or shape. No write was retried.');\n\n/** Native set lists are unpaged; Adport pages a bounded, snapshot-bound result. */\nexport class TikTokCatalogProductSets {\n constructor(\n private readonly client: Pick<TikTokClient, 'get' | 'post'> & Partial<Pick<TikTokClient, 'postMultipart'>>,\n private readonly authorizeParent: (input: CatalogSelection, write?: boolean) => Promise<{ configuration_hash: string; catalog_type?: string }>,\n private readonly media?: MediaResolver,\n ) {}\n\n private async request(path: string, params: Record<string, unknown>): Promise<unknown> {\n try { return await this.client.get(path, params, { jsonContentType: path === 'catalog/set/product/get' }); }\n catch (error) {\n if (error instanceof AdportError && ['POLICY_VIOLATION', 'NOT_CONNECTED'].includes(error.code)) throw error;\n throw new AdportError('PROVIDER_ERROR', 'TikTok product-set read failed. Check native catalog permissions. No provider error body is returned and no request was retried.');\n }\n }\n\n private async native(input: CatalogSelection, productSetId?: string, returnCount = false): Promise<ProductSet[]> {\n const parsed = z.object({ list: z.array(setRow).max(5000), page_info: z.object({ page: count, total_page: count, total_number: count.optional() }).optional() }).safeParse(await this.request('catalog/set/get', {\n bc_id: input.bc_id, catalog_id: input.catalog_id,\n ...(productSetId ? { product_set_id: productSetId } : {}), return_product_count: returnCount,\n }));\n if (!parsed.success) throw invalid();\n const rows = parsed.data.list;\n if (new Set(rows.map(row => row.product_set_id)).size !== rows.length || rows.some(row => row.catalog_id !== input.catalog_id || row.bc_id !== undefined && row.bc_id !== input.bc_id || productSetId && row.product_set_id !== productSetId) || productSetId && rows.length !== 1 || parsed.data.page_info && (parsed.data.page_info.page !== 1 || parsed.data.page_info.total_page > 1 || parsed.data.page_info.total_number !== undefined && parsed.data.page_info.total_number !== rows.length)) throw invalid();\n return rows;\n }\n\n async list(value: unknown) {\n const input = productSetList.parse(value), scope = catalogInput.parse({ account_id: input.account_id, bc_id: input.bc_id, catalog_id: input.catalog_id });\n await this.authorizeParent(scope);\n const rows = (await this.native(scope, input.product_set_id, input.return_product_count)).sort((a, b) => a.product_set_id.localeCompare(b.product_set_id));\n const snapshot = digest({ ...scope, product_set_id: input.product_set_id, return_product_count: input.return_product_count, page_size: input.page_size, sets: rows.map(configuration) });\n let offset = 0;\n if (input.cursor) {\n let cursor;\n try { cursor = z.object({ offset: count.max(4999), snapshot: z.string().regex(/^[a-f0-9]{64}$/) }).strict().parse(JSON.parse(Buffer.from(input.cursor, 'base64url').toString('utf8'))); }\n catch { throw new AdportError('INVALID_INPUT', 'Invalid product-set cursor. Refresh the first page.'); }\n if (cursor.snapshot !== snapshot || cursor.offset === 0 || cursor.offset >= rows.length || cursor.offset % input.page_size !== 0) throw new AdportError('INVALID_INPUT', 'Product sets or selection changed. Refresh the first page.');\n offset = cursor.offset;\n }\n const sets = rows.slice(offset, offset + input.page_size).map(row => ({ ...row, configuration_hash: hash(scope, row) }));\n const hasMore = offset + sets.length < rows.length;\n return {\n sets, records: sets.map(row => ({ id: row.product_set_id, name: row.product_set_name, catalog_id: row.catalog_id, ...(row.product_count !== undefined ? { product_count: row.product_count } : {}), conditions: row.conditions })),\n complete: !hasMore, truncated: hasMore,\n ...(hasMore ? { next_cursor: Buffer.from(JSON.stringify({ offset: offset + sets.length, snapshot })).toString('base64url') } : {}),\n notes: ['TikTok returns the entire set list; Adport bounds it to 5,000 sets and pages it locally. Product counts are omitted by default to avoid native timeouts.'],\n };\n }\n\n async products(value: unknown) {\n const input = productSetProducts.parse(value);\n const scope = catalogInput.parse({ account_id: input.account_id, bc_id: input.bc_id, catalog_id: input.catalog_id });\n await this.authorizeParent(scope);await this.native(scope, input.product_set_id);\n const parsed = z.object({\n product_set_id: nativeId, catalog_id: nativeId, product_count: count,\n products: z.array(z.looseObject({ product_id: nativeId, product_name: z.string(), catalog_id: nativeId.optional(), product_set_id: nativeId.optional(), bc_id: nativeId.optional() })).max(input.page_size),\n page_info: z.object({ page: z.number().int().positive().safe(), page_size: z.number().int().min(1).max(100), total_number: count.optional(), total_page: count.optional() }).optional(),\n }).safeParse(await this.request('catalog/set/product/get', { bc_id: input.bc_id, catalog_id: input.catalog_id, product_set_id: input.product_set_id, page: input.page, page_size: input.page_size }));\n if (!parsed.success || parsed.data.catalog_id !== input.catalog_id || parsed.data.product_set_id !== input.product_set_id) throw invalid();\n const data = parsed.data;\n if (new Set(data.products.map(row => row.product_id)).size !== data.products.length || data.page_info && (data.page_info.page !== input.page || data.page_info.page_size !== input.page_size) || data.products.some(row => row.catalog_id !== undefined && row.catalog_id !== input.catalog_id || row.product_set_id !== undefined && row.product_set_id !== input.product_set_id || row.bc_id !== undefined && row.bc_id !== input.bc_id)) throw invalid();\n const complete = data.page_info?.total_number !== undefined && data.page_info.total_number !== data.product_count ? null : nativeListComplete(data.page_info, data.products.length);\n return {\n ...data, records: data.products.map(row => ({ id: row.product_id, name: row.product_name, ...row })), complete, truncated: complete !== true,\n ...(complete === false ? { next_page: input.page + 1 } : {}),\n ...(complete === null ? { pagination_note: 'Native pagination is missing or contradictory; completeness is unknown.' } : {}),\n };\n }\n\n async plan(op: WriteOperation): Promise<Plan> {\n if (op.provider !== 'tiktok') throw new AdportError('INVALID_INPUT', 'TikTok product-set provider mismatch.');\n if (op.tool === 'tiktok_upload_product_set' && op.kind === 'create') return this.uploadPlan(op);\n if (op.tool === 'tiktok_create_product_set' && op.kind === 'create') return this.createPlan(op);\n if (op.tool === 'tiktok_update_product_set_conditions' && op.kind === 'update') return this.conditionsPlan(op);\n if (op.tool === 'tiktok_delete_product_sets' && op.kind === 'remove') return this.deletePlan(op);\n if (op.provider !== 'tiktok' || op.kind !== 'update' || op.tool !== 'tiktok_rename_product_set') throw new AdportError('INVALID_INPUT', 'Unsupported TikTok product-set mutation.');\n const input = productSetRename.parse(op.payload), scope = catalogInput.parse({ account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id });\n await this.authorizeParent(scope, true);\n const current = (await this.native(scope, input.product_set_id))[0]!;\n if (hash(scope, current) !== input.expected_configuration_hash) throw new AdportError('INVALID_INPUT', 'Product-set configuration changed. Read and preview it again.');\n const notes = ['The set may be reused by other ads or accounts. Only its name changes; filter conditions are preserved.', 'Preview is local. TikTok checks native eligibility on apply. No ads are activated or tracking events sent.', 'An uncertain result retains the known set ID. Inspect it before another write; never replay automatically.'];\n return {\n summary: `Rename TikTok product set ${current.product_set_name}`,\n changes: [`~ Product-set name ${JSON.stringify(current.product_set_name)} → ${JSON.stringify(input.product_set_name)}`], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'tiktok', accountId: scope.account_id, kind: 'update', title: 'Rename product set', subject: current.product_set_name, fields: [{ label: 'Name', before: current.product_set_name, after: input.product_set_name }, { label: 'Catalog', after: input.catalog_id }, { label: 'Product set', after: input.product_set_id }], notices: notes },\n execute: async () => {\n await this.authorizeParent(scope, true);\n try {\n const receipt = z.object({ product_set_id: nativeId }).parse(await this.client.post('catalog/set/update', { bc_id: input.bc_id, catalog_id: input.catalog_id, product_set_id: input.product_set_id, product_set_name: input.product_set_name }));\n if (receipt.product_set_id !== input.product_set_id) throw new Error('Set ID differs');\n const actual = (await this.native(scope, input.product_set_id))[0]!;\n if (canonical(configuration(actual)) !== canonical({ ...configuration(current), product_set_name: input.product_set_name })) throw new Error('Configuration differs');\n return [input.product_set_id];\n } catch {\n throw new AdportError('PROVIDER_ERROR', 'TikTok product-set rename outcome is unconfirmed. Read the known set before another write; do not replay automatically.', { resource_ids: [input.product_set_id] });\n }\n },\n };\n }\n\n private async uploadPlan(op: WriteOperation): Promise<Plan> {\n const input = productSetUpload.parse(op.payload), scope = catalogInput.parse({ account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id });\n const media = this.media, multipart = this.client.postMultipart?.bind(this.client);\n if (!media || !multipart) throw new AdportError('NOT_CONNECTED', 'This runtime does not support checksum-bound catalog file uploads.');\n const prepare = async () => {\n const parent = await this.authorizeParent(scope, true);\n if (parent.configuration_hash !== input.expected_catalog_hash) throw new AdportError('INVALID_INPUT', 'Catalog configuration changed. Read and preview creation again.');\n if (parent.catalog_type !== 'ECOM') throw new AdportError('INVALID_INPUT', 'CSV product-set creation requires an E-commerce (ECOM) catalog.');\n if ((await this.native(scope)).some(row => row.product_set_name === input.product_set_name)) throw new AdportError('INVALID_INPUT', 'This catalog already has a product set with that name. Choose a unique name.');\n const source = await media.read(input, { maxBytes: MAX_PROJECT_MEDIA_BYTES, contentTypes: ['text/csv'] });\n const file = verifyMedia(source.bytes, source.name, input.expected_sha256, { maxBytes: MAX_PROJECT_MEDIA_BYTES, contentTypes: ['text/csv'] });\n const rows = csvRows(file.bytes, { maxRows: 5001, maxColumns: 1 }), header = rows.next().value;\n if (header?.[0] !== 'sku_id') throw new AdportError('INVALID_INPUT', 'Use TikTok’s CSV template: one column named sku_id and 1–5,000 distinct SKU IDs.');\n const skus = new Set<string>();\n for (const row of rows) {\n const sku = row[0]!;\n if (!sku.trim() || skus.has(sku)) throw new AdportError('INVALID_INPUT', 'The sku_id column must contain 1–5,000 nonempty, distinct IDs. Values are preserved as text.');\n skus.add(sku);\n }\n if (!skus.size) throw new AdportError('INVALID_INPUT', 'The sku_id column needs at least one SKU ID.');\n return { file, count: skus.size };\n };\n const prepared = await prepare();\n const notes = ['Creates an E-commerce set from the exact approved CSV; no ads are activated or budgets changed.', 'Adport caps the template at 5,000 SKU rows. TikTok checks SKU eligibility and membership on apply; independent readback confirms the set ID/name, not full membership or ingestion.', 'No automatic retry. Reconcile an uncertain creation by its known ID or unique name before another upload.'];\n return {\n summary: `Create TikTok product set ${input.product_set_name} from CSV`, changes: [`+ Product set ${JSON.stringify(input.product_set_name)} from ${prepared.count} SKU rows`, `+ File ${JSON.stringify(prepared.file.name)}; ${prepared.file.bytes.byteLength} bytes; SHA-256 ${prepared.file.sha256}`], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'tiktok', accountId: scope.account_id, kind: 'create', title: 'Upload product set', subject: input.product_set_name, fields: [{ label: 'Catalog', after: input.catalog_id }, { label: 'File', after: prepared.file.name }, { label: 'SKU rows', after: String(prepared.count) }, { label: 'SHA-256', after: prepared.file.sha256 }], notices: notes },\n execute: async () => {\n const { file } = await prepare();\n const form = new FormData();\n form.set('bc_id', input.bc_id); form.set('catalog_id', input.catalog_id); form.set('product_set_name', input.product_set_name);\n form.set('file', new Blob([file.bytes], { type: 'text/csv' }), 'product-set.csv');\n form.set('file_signature', createHash('md5').update(file.bytes).digest('hex'));\n let createdId: string | undefined;\n try {\n const receipt = z.looseObject({ product_set_id: nativeId }).parse(await multipart('catalog/set/upload', form));\n createdId = receipt.product_set_id;\n if (receipt.product_set_name !== input.product_set_name) throw new Error('Receipt name differs');\n const actual = (await this.native(scope, createdId))[0]!;\n if (actual.product_set_name !== input.product_set_name) throw new Error('Readback name differs');\n return [createdId];\n } catch {\n throw new AdportError('PROVIDER_ERROR', 'TikTok CSV product-set creation outcome is unconfirmed. Inspect catalog sets by the approved unique name or known ID before another write; do not replay automatically.', createdId ? { resource_ids: [createdId] } : undefined);\n }\n },\n };\n }\n\n private async createPlan(op: WriteOperation): Promise<Plan> {\n const input = productSetCreate.parse(op.payload), scope = catalogInput.parse({ account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id });\n const verifyParent = async () => {\n const parent = await this.authorizeParent(scope, true);\n if (parent.configuration_hash !== input.expected_catalog_hash) throw new AdportError('INVALID_INPUT', 'Catalog configuration changed. Read the catalog and review creation again.');\n };\n await verifyParent();\n const notes = ['Creates a filter-defined set in the selected catalog; it does not create or activate an ad.', 'Field names and catalog-specific values are checked by TikTok on apply; this is a local preview. Adport allows up to 1,024 combined values.', 'No automatic retry. An unknown creation outcome must be reconciled before another create.'];\n return {\n summary: `Create TikTok product set ${input.product_set_name}`, changes: [`+ Product set ${JSON.stringify(input.product_set_name)}`, `+ Product selection ${canonical(input.conditions)}`], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'tiktok', accountId: scope.account_id, kind: 'create', title: 'Create product set', subject: input.product_set_name, fields: [{ label: 'Catalog', after: input.catalog_id }, { label: 'Product selection', after: describeProductSetConditions(input.conditions), format: 'text' }], notices: notes },\n execute: async () => {\n await verifyParent();let createdId: string | undefined;\n try {\n const receipt = z.object({ product_set_id: nativeId }).parse(await this.client.post('catalog/set/create', { bc_id: input.bc_id, catalog_id: input.catalog_id, product_set_name: input.product_set_name, conditions: input.conditions }));\n createdId = receipt.product_set_id;\n const actual = (await this.native(scope, createdId))[0]!;\n if (actual.product_set_name !== input.product_set_name || canonical(actual.conditions) !== canonical(input.conditions)) throw new Error('Creation readback differs');\n return [createdId];\n } catch {\n throw new AdportError('PROVIDER_ERROR', 'TikTok product-set creation outcome is unconfirmed. Inspect catalog sets before another create; do not replay automatically.', createdId ? { resource_ids: [createdId] } : undefined);\n }\n },\n };\n }\n\n private async conditionsPlan(op: WriteOperation): Promise<Plan> {\n const input = productSetUpdateConditions.parse(op.payload), scope = catalogInput.parse({ account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id });\n await this.authorizeParent(scope, true);\n const current = (await this.native(scope, input.product_set_id))[0]!;\n if (hash(scope, current) !== input.expected_configuration_hash) throw new AdportError('INVALID_INPUT', 'Product-set configuration changed. Read and review it again.');\n const notes = ['Replaces the complete filter definition. Existing ads using this shared set may select different products after apply.', 'The name is preserved. No ad is activated and no budget or tracking event is changed.', 'Catalog-specific fields and values are checked by TikTok on apply; preview is local. No automatic retry after an uncertain result.'];\n return {\n summary: `Change TikTok product selection for ${current.product_set_name}`, changes: [`~ Product selection ${canonical(current.conditions)} → ${canonical(input.conditions)}`], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'tiktok', accountId: scope.account_id, kind: 'update', title: 'Change product selection', subject: current.product_set_name, fields: [{ label: 'Product selection', before: describeProductSetConditions(current.conditions), after: describeProductSetConditions(input.conditions), format: 'text' }, { label: 'Catalog', after: input.catalog_id }, { label: 'Product set', after: input.product_set_id }], notices: notes },\n execute: async () => {\n await this.authorizeParent(scope, true);\n try {\n const receipt = z.object({ product_set_id: nativeId }).parse(await this.client.post('catalog/set/update', { bc_id: input.bc_id, catalog_id: input.catalog_id, product_set_id: input.product_set_id, conditions: input.conditions }));\n if (receipt.product_set_id !== input.product_set_id) throw new Error('Set ID differs');\n const actual = (await this.native(scope, input.product_set_id))[0]!;\n if (canonical(configuration(actual)) !== canonical({ ...configuration(current), conditions: input.conditions })) throw new Error('Filter or name preservation differs');\n return [input.product_set_id];\n } catch {\n throw new AdportError('PROVIDER_ERROR', 'TikTok product-set filter change outcome is unconfirmed. Read the known set before another write; do not replay automatically.', { resource_ids: [input.product_set_id] });\n }\n },\n };\n }\n\n private async deletePlan(op: WriteOperation): Promise<Plan> {\n const input = productSetDelete.parse(op.payload), scope = catalogInput.parse({ account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id });\n await this.authorizeParent(scope, true);\n const current: ProductSet[] = [];\n for (const target of input.sets) {\n const row = (await this.native(scope, target.product_set_id))[0]!;\n if (hash(scope, row) !== target.expected_configuration_hash) throw new AdportError('INVALID_INPUT', 'A product-set configuration changed. Read and review every selected set again.');\n current.push(row);\n }\n const ids = current.map(row => row.product_set_id);\n const notes = ['Permanently deletes the selected shared set definitions. Existing ads may reference them; there is no automatic restoration.', 'The full selected set list and each configuration hash are checked before apply. TikTok checks native dependencies and eligibility.', 'No automatic retry after a partial or uncertain result. Reconcile every known ID before another delete.'];\n return {\n summary: `Delete ${current.length} TikTok product set${current.length === 1 ? '' : 's'}`, changes: current.map(row => `- Product set ${row.product_set_id}: ${JSON.stringify(row.product_set_name)}`), coercions: [], budgetDeltas: [], notes,\n review: { provider: 'tiktok', accountId: scope.account_id, kind: 'remove', title: 'Delete product sets', subject: current.length === 1 ? current[0]!.product_set_name : `${current.length} product sets`, fields: current.map(row => ({ label: `Product set ${row.product_set_id}`, before: row.product_set_name, after: 'Permanently deleted' })), notices: notes },\n execute: async () => {\n await this.authorizeParent(scope, true);\n try {\n const receipt = z.object({ product_set_ids: z.array(nativeId).min(1).max(10) }).parse(await this.client.post('catalog/set/delete', { bc_id: input.bc_id, catalog_id: input.catalog_id, product_set_ids: ids }));\n if (receipt.product_set_ids.length !== ids.length || new Set(receipt.product_set_ids).size !== ids.length || receipt.product_set_ids.some(id => !ids.includes(id))) throw new Error('Deletion receipt differs');\n const remaining = await this.native(scope);\n if (remaining.some(row => ids.includes(row.product_set_id))) throw new Error('Deleted set remains in catalog');\n return ids;\n } catch {\n throw new AdportError('PROVIDER_ERROR', 'TikTok product-set deletion outcome is partial or unconfirmed. Inspect every known set ID before another write; do not replay automatically.', { resource_ids: ids });\n }\n },\n };\n }\n}\n","import { z } from 'zod';\n\n// TikTok's product-set operator reference, doc1740673108747265, checked 2026-11-05.\nconst operator = z.enum(['EQUAL', 'NOT_EQUAL', 'GT', 'LT', 'GTE', 'LTE', 'CONTAIN', 'I_CONTAIN', 'EXCLUDE', 'I_EXCLUDE', 'WILDCARD', 'I_WILDCARD', 'NOT_WILDCARD', 'I_NOT_WILDCARD', 'PREFIX', 'I_PREFIX']);\nconst text = z.string().min(1).max(2048);\nconst scalar = z.union([text, z.number().finite().refine(value => !Number.isInteger(value) || Number.isSafeInteger(value), 'Use a string for integers beyond JavaScript’s safe range')]);\nexport const nativeProductSetConditions = z.record(z.string(), z.unknown()).refine(value => {\n const stack: Array<{ value: unknown; depth: number }> = [{ value, depth: 0 }];let visited = 0;\n while (stack.length) {\n const item = stack.pop()!;if (++visited > 20_000 || item.depth > 16) return false;\n if (typeof item.value === 'number' && (!Number.isFinite(item.value) || Number.isInteger(item.value) && !Number.isSafeInteger(item.value))) return false;\n if (item.value && typeof item.value === 'object') for (const key in item.value) {\n if (!Object.hasOwn(item.value, key)) continue;\n if (visited + stack.length >= 20_000) return false;\n stack.push({ value: (item.value as Record<string, unknown>)[key], depth: item.depth + 1 });\n }\n }\n return true;\n}, 'Native filter values exceed exact numeric or inspection bounds');\nconst condition = z.object({\n field: z.string().regex(/^[a-z][a-z0-9_]*(?:\\.[a-z][a-z0-9_]*)*$/).max(128),\n operation: operator, value: z.union([scalar, z.array(scalar).min(1).max(1024)]),\n}).strict().superRefine((row, ctx) => {\n const list = Array.isArray(row.value);\n if (['EQUAL', 'NOT_EQUAL', 'GT', 'LT', 'GTE', 'LTE'].includes(row.operation) && list) ctx.addIssue({ code: 'custom', path: ['value'], message: 'This operator requires a single value' });\n if (['CONTAIN', 'I_CONTAIN', 'EXCLUDE', 'I_EXCLUDE'].includes(row.operation) && !list) ctx.addIssue({ code: 'custom', path: ['value'], message: 'This operator requires a list of values' });\n if (/WILDCARD|PREFIX/.test(row.operation) && (list ? (row.value as Array<string | number>).some(value => typeof value !== 'string') : typeof row.value !== 'string')) ctx.addIssue({ code: 'custom', path: ['value'], message: 'Substring and prefix operators require strings' });\n});\nconst clauses = z.array(condition).min(1).max(1024);\nexport const productSetConditions = z.object({ and: clauses.optional(), or: clauses.optional() }).strict().superRefine((value, ctx) => {\n if (Number(value.and !== undefined) + Number(value.or !== undefined) !== 1) ctx.addIssue({ code: 'custom', message: 'Choose either an AND group or an OR group' });\n const total = [...(value.and ?? []), ...(value.or ?? [])].reduce((n, row) => n + (Array.isArray(row.value) ? row.value.length : 1), 0);\n if (total > 1024) ctx.addIssue({ code: 'custom', message: 'Adport limits the combined number of filter values to 1,024 to avoid native timeouts' });\n});\n\nconst phrases: Record<z.infer<typeof operator>, string> = {\n EQUAL: 'equals', NOT_EQUAL: 'does not equal', GT: 'is greater than', LT: 'is less than', GTE: 'is at least', LTE: 'is at most',\n CONTAIN: 'matches any value', I_CONTAIN: 'matches any value (case insensitive)', EXCLUDE: 'excludes every value', I_EXCLUDE: 'excludes every value (case insensitive)',\n WILDCARD: 'contains', I_WILDCARD: 'contains (case insensitive)', NOT_WILDCARD: 'does not contain', I_NOT_WILDCARD: 'does not contain (case insensitive)', PREFIX: 'starts with', I_PREFIX: 'starts with (case insensitive)',\n};\nexport function describeProductSetConditions(raw: unknown): string {\n const parsed = productSetConditions.safeParse(raw);\n if (!parsed.success) return JSON.stringify(raw);\n const value = parsed.data;\n return (value.and ? 'All conditions' : 'Any condition') + ':\\n' + (value.and ?? value.or!).map(row => `${row.field.replace(/[_.]/g, ' ')} ${phrases[row.operation]} ${JSON.stringify(row.value)}`).join('\\n');\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, type WriteOperation, type WritePreview, type ReviewField } from '@adport/core';\nimport { z } from 'zod';\nimport type { TikTokClient } from './client.js';\nimport { catalogId, catalogInput } from './catalog-schema.js';\n\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nconst nativeId = z.union([catalogId, z.number().int().positive().safe()]).transform(String);\nconst count = z.number().int().nonnegative().safe();\nconst nativeTime = z.string().max(40).regex(/^[0-9TZ :.+-]*$/);\nconst mode = z.enum(['INCREMENTAL', 'OVERWRITE', 'SUPPLEMENT']);\nconst interval = z.enum(['HOURLY', 'DAILY', 'MONTHLY']);\nconst sourceUri = z.string().min(1).max(8192).refine(value => {\n try { const uri = new URL(value);return ['http:', 'https:', 'ftp:', 'sftp:'].includes(uri.protocol) && !!uri.hostname && !uri.username && !uri.password && !uri.hash && !/[\\x00-\\x20\\x7f]/.test(value); } catch { return false; }\n}, 'Use an HTTP(S), FTP or SFTP source URL without embedded credentials or a fragment');\nconst schedule = z.object({\n source: z.object({ uri: sourceUri, username: z.string().min(1).max(1024).optional(), password: z.string().min(1).max(4096).optional() }).strict(),\n interval_type: interval, interval_count: z.number().int().min(1).max(30).default(1),\n timezone: z.string().min(1).max(128).refine(value => { try { new Intl.DateTimeFormat('en', { timeZone: value });return true; } catch { return false; } }, 'Use an IANA time zone'),\n day_of_month: z.number().int().min(1).max(31).optional(), hour: z.number().int().min(0).max(23).default(0), minute: z.number().int().min(0).max(59).default(0),\n}).strict().superRefine((value, ctx) => {\n const max = { HOURLY: 23, DAILY: 30, MONTHLY: 12 }[value.interval_type];\n if (value.interval_count > max) ctx.addIssue({ code: 'custom', path: ['interval_count'], message: `Maximum ${value.interval_type.toLowerCase()} interval is ${max}` });\n if (value.day_of_month !== undefined && value.interval_type !== 'MONTHLY') ctx.addIssue({ code: 'custom', path: ['day_of_month'], message: 'day_of_month applies only to monthly schedules' });\n if (value.interval_type === 'MONTHLY' && value.day_of_month === undefined) ctx.addIssue({ code: 'custom', path: ['day_of_month'], message: 'Choose an explicit day for monthly schedules' });\n});\nconst payload = catalogInput.omit({ account_id: true });\nconst selected = catalogInput.extend({ feed_id: catalogId }).strict();\nexport const catalogFeedList = catalogInput.extend({ feed_id: catalogId.optional(), page_size: z.number().int().min(1).max(100).default(30), cursor: z.string().min(1).max(512).optional() }).strict();\nexport const catalogFeedLog = selected;\nexport const catalogFeedCreate = payload.extend({\n feed_name: z.string().trim().min(1).max(256), update_mode: z.enum(['INCREMENTAL', 'OVERWRITE']), feed_type: z.enum(['DATA_FEED', 'COUNTRY_FEED']).optional(),\n schedule_param: schedule.optional(), expected_catalog_hash: hash, acknowledge_shared_effects: z.literal(true), acknowledge_automatic_processing: z.literal(true),\n}).strict();\nexport const catalogFeedUpdate = payload.extend({\n feed_id: catalogId, update_mode: mode, schedule_param: schedule.optional(), expected_configuration_hash: hash,\n acknowledge_shared_effects: z.literal(true), acknowledge_automatic_processing: z.literal(true),\n}).strict();\nexport const catalogFeedSwitch = payload.extend({ feed_id: catalogId, status: z.enum(['ON', 'OFF']), expected_configuration_hash: hash, acknowledge_shared_effects: z.literal(true), acknowledge_automatic_processing: z.literal(true) }).strict();\nexport const catalogFeedDelete = payload.extend({ feed_id: catalogId, expected_configuration_hash: hash, acknowledge_shared_effects: z.literal(true) }).strict();\n\nconst nativeSchedule = z.looseObject({\n uri: z.string().nullable().optional(), update_mode: mode.nullable().optional(), timezone: z.string().nullable().optional(), interval_type: interval.nullable().optional(),\n interval_count: count.nullable().optional(), day_of_month: count.nullable().optional(), hour: count.nullable().optional(), minute: count.nullable().optional(),\n});\nconst feed = z.looseObject({\n feed_id: nativeId, feed_name: z.string(), feed_type: z.enum(['DATA_FEED', 'COUNTRY_FEED']).optional(), status: z.enum(['ON', 'OFF']).optional(),\n bc_id: nativeId.optional(), catalog_id: nativeId.optional(), region_codes: z.array(z.string()).optional(), override_fields: z.array(z.string()).optional(),\n last_update_param: nativeSchedule.nullable().optional(), next_update_time: nativeTime.nullable().optional(), number_of_products: count.optional(),\n});\ntype Feed = z.infer<typeof feed>;\ntype Selection = z.infer<typeof catalogInput>;\ntype Parent = { configuration_hash: string; catalog_conf: Record<string, unknown> };\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<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 digest = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex');\nconst origin = (value: unknown) => { try { const uri = new URL(String(value));return `${uri.protocol}//${uri.host}`; } catch { return 'Not reported'; } };\nconst scheduleConfig = (value: Feed['last_update_param']) => ({ uri: value?.uri ?? null, update_mode: value?.update_mode ?? null, timezone: value?.timezone ?? null, interval_type: value?.interval_type ?? null, interval_count: value?.interval_count ?? null, hour: value?.hour ?? null, minute: value?.minute ?? null, day_of_month: value?.interval_type === 'MONTHLY' ? value.day_of_month ?? null : null });\nconst config = (value: Feed) => ({ feed_id: value.feed_id, feed_name: value.feed_name, feed_type: value.feed_type ?? null, status: value.status ?? null, region_codes: value.region_codes ?? [], override_fields: value.override_fields ?? [], schedule: scheduleConfig(value.last_update_param) });\nconst configurationHash = (scope: Selection, value: Feed) => digest({ ...scope, configuration: config(value) });\nconst invalid = () => new AdportError('PROVIDER_ERROR', 'TikTok feed response has an unexpected scope, identifier or shape. No request was retried.');\nconst secrets = (value: Feed): string[] => {\n const source = value.last_update_param;\n return [source?.uri, source?.username, source?.password].filter((item): item is string => typeof item === 'string' && item.length > 0);\n};\nconst publicText = (text: string, value: Feed) => secrets(value).reduce((out, secret) => out.replaceAll(secret, '[redacted]'), text);\nfunction publicFeed(scope: Selection, value: Feed) {\n const source = value.last_update_param;\n return {\n feed_id: value.feed_id, feed_name: publicText(value.feed_name, value), status: value.status ?? 'UNKNOWN', feed_type: value.feed_type ?? 'Not reported',\n region_codes: value.region_codes?.map(text => publicText(text, value)), override_fields: value.override_fields?.map(text => publicText(text, value)),\n source_origin: publicText(origin(source?.uri), value), source_configured: !!source?.uri,\n ...(source?.uri ? { source_fingerprint: digest(source.uri) } : {}), update_mode: source?.update_mode ?? 'Not reported',\n schedule: { timezone: source?.timezone ? publicText(source.timezone, value) : null, interval_type: source?.interval_type ?? null, interval_count: source?.interval_count ?? null, day_of_month: source?.day_of_month ?? null, hour: source?.hour ?? null, minute: source?.minute ?? null },\n number_of_products: value.number_of_products, next_update_time: value.next_update_time || null, configuration_hash: configurationHash(scope, value),\n };\n}\nfunction frequency(value: ReturnType<typeof publicFeed>): string {\n const s = value.schedule;\n if (!s.interval_type) return 'Not configured';\n const unit = { HOURLY: 'hour', DAILY: 'day', MONTHLY: 'month' }[s.interval_type];\n const every = s.interval_count === null ? `${s.interval_type.toLowerCase()} interval not reported` : `Every ${s.interval_count} ${unit}${s.interval_count === 1 ? '' : 's'}`;\n const time = s.hour === null || s.minute === null ? '' : `${String(s.hour).padStart(2, '0')}:${String(s.minute).padStart(2, '0')}`;\n return [every, s.interval_type === 'MONTHLY' && s.day_of_month !== null ? `day ${s.day_of_month}` : '', s.timezone, time].filter(Boolean).join(' · ');\n}\nconst commonNotes = ['The catalog and its feeds may be reused by other ads or accounts. No campaign status or budget is changed.', 'Stored configuration is not proof of authenticated source access or successful product ingestion. Read the native processing log.', 'Native reads do not confirm authentication values; a configuration hash cannot detect password-only changes.', 'No automatic retry. Reconcile the known feed after an uncertain result.'];\n\n/** Business Center catalog feeds. Native lists are unpaged and locally bounded. */\nexport class TikTokCatalogFeeds {\n constructor(private readonly client: Pick<TikTokClient, 'get' | 'post'>, private readonly authorizeParent: (input: Selection, write?: boolean) => Promise<Parent>) {}\n private async read(path: string, params: Record<string, unknown>): Promise<unknown> {\n try { return await this.client.get(path, params); }\n catch (error) {\n if (error instanceof AdportError && ['POLICY_VIOLATION', 'NOT_CONNECTED'].includes(error.code)) throw error;\n throw new AdportError('PROVIDER_ERROR', 'TikTok feed read failed. Check native catalog permissions. Provider bodies and source credentials are hidden; no request was retried.');\n }\n }\n private async native(scope: Selection, feedId?: string): Promise<Feed[]> {\n const parsed = z.object({ feed_list: z.array(feed).max(5000), bc_id: nativeId.optional(), catalog_id: nativeId.optional(), page_info: z.object({ page: count, total_page: count, total_number: count.optional() }).optional() }).safeParse(await this.read('catalog/feed/get', { bc_id: scope.bc_id, catalog_id: scope.catalog_id, ...(feedId ? { feed_id: feedId } : {}) }));\n if (!parsed.success) throw invalid();const data = parsed.data, rows = data.feed_list;\n if (data.bc_id !== undefined && data.bc_id !== scope.bc_id || data.catalog_id !== undefined && data.catalog_id !== scope.catalog_id || new Set(rows.map(row => row.feed_id)).size !== rows.length || rows.some(row => row.catalog_id !== undefined && row.catalog_id !== scope.catalog_id || row.bc_id !== undefined && row.bc_id !== scope.bc_id || feedId && row.feed_id !== feedId) || feedId && rows.length !== 1 || data.page_info && (data.page_info.page !== 1 || data.page_info.total_page > 1 || data.page_info.total_number !== undefined && data.page_info.total_number !== rows.length)) throw invalid();\n return rows;\n }\n async list(value: unknown) {\n const input = catalogFeedList.parse(value), scope = catalogInput.parse({ account_id: input.account_id, bc_id: input.bc_id, catalog_id: input.catalog_id });await this.authorizeParent(scope);\n const rows = (await this.native(scope, input.feed_id)).sort((a, b) => a.feed_id.localeCompare(b.feed_id)), snapshot = digest({ ...scope, feed_id: input.feed_id, page_size: input.page_size, feeds: rows.map(config) });let offset = 0;\n if (input.cursor) {\n let cursor;\n try { cursor = z.object({ offset: count.max(4999), snapshot: hash }).strict().parse(JSON.parse(Buffer.from(input.cursor, 'base64url').toString('utf8'))); } catch { throw new AdportError('INVALID_INPUT', 'Invalid feed cursor. Refresh the first page.'); }\n if (cursor.snapshot !== snapshot || cursor.offset === 0 || cursor.offset >= rows.length || cursor.offset % input.page_size !== 0) throw new AdportError('INVALID_INPUT', 'Feed configuration or selection changed. Refresh the first page.');offset = cursor.offset;\n }\n const feeds = rows.slice(offset, offset + input.page_size).map(row => publicFeed(scope, row)), more = offset + feeds.length < rows.length;\n return { feeds, records: feeds.map(row => ({ id: row.feed_id, name: row.feed_name, status: row.status, type: row.feed_type, frequency: frequency(row), update_mode: row.update_mode, source: row.source_origin })), complete: !more, truncated: more, ...(more ? { next_cursor: Buffer.from(JSON.stringify({ offset: offset + feeds.length, snapshot })).toString('base64url') } : {}), notes: ['TikTok returns all catalog feeds; Adport bounds the list to 5,000 and pages a snapshot locally. Source paths, query values and authentication are hidden.', ...commonNotes.slice(1, 3)] };\n }\n async log(value: unknown) {\n const input = catalogFeedLog.parse(value), scope = catalogInput.parse({ account_id: input.account_id, bc_id: input.bc_id, catalog_id: input.catalog_id });await this.authorizeParent(scope);await this.native(scope, input.feed_id);\n const status = z.object({ add_count: count, error_count: count, remove_count: count, process_status: z.enum(['PROCESSING', 'SUCCESS', 'FAILED', 'WAITING']), update_count: count, warn_count: count });\n const time = z.object({ start_time: nativeTime.nullable().optional(), end_time: nativeTime.nullable().optional() });\n const entry = z.object({ update_status: status.optional(), last_update_status: status.optional(), update_time: time.optional(), last_update_time: time.optional() }).refine(row => !!(row.update_status ?? row.last_update_status) && !!(row.update_time ?? row.last_update_time) && (!row.update_status || !row.last_update_status || canonical(row.update_status) === canonical(row.last_update_status)) && (!row.update_time || !row.last_update_time || canonical(row.update_time) === canonical(row.last_update_time)));\n const parsed = z.object({ feed_logs: z.array(entry).max(10), feed_id: nativeId.optional(), bc_id: nativeId.optional(), catalog_id: nativeId.optional() }).safeParse(await this.read('catalog/feed/log', { bc_id: input.bc_id, catalog_id: input.catalog_id, feed_id: input.feed_id }));\n if (!parsed.success || parsed.data.feed_id !== undefined && parsed.data.feed_id !== input.feed_id || parsed.data.bc_id !== undefined && parsed.data.bc_id !== input.bc_id || parsed.data.catalog_id !== undefined && parsed.data.catalog_id !== input.catalog_id) throw invalid();\n const logs = parsed.data.feed_logs.map(row => ({ ...(row.update_status ?? row.last_update_status!), ...(row.update_time ?? row.last_update_time!) }));\n return { feed_id: input.feed_id, logs, records: logs.map((row, index) => ({ id: `${input.feed_id}:${index}:${digest(row)}`, name: row.start_time || `Feed operation ${index + 1}`, status: row.process_status, added: row.add_count, updated: row.update_count, removed: row.remove_count, errors: row.error_count, warnings: row.warn_count, completed_at: row.end_time })), complete: true, truncated: false, history_scope: 'latest_10_operations_only', more_history_available: null, notes: ['This endpoint returns up to the latest 10 feed operations, not full history. Native SUCCESS and product counts do not establish ad delivery eligibility.'] };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n const kinds: Record<string, string> = { tiktok_create_catalog_feed: 'create', tiktok_update_catalog_feed: 'update', tiktok_set_catalog_feed_schedule_status: 'update', tiktok_delete_catalog_feed: 'remove' };\n if (op.provider !== 'tiktok' || !Object.hasOwn(kinds, op.tool) || op.kind !== kinds[op.tool]) throw new AdportError('INVALID_INPUT', 'TikTok feed operation/provider kind mismatch.');\n const create = op.tool === 'tiktok_create_catalog_feed', input = create ? catalogFeedCreate.parse(op.payload) : op.tool === 'tiktok_update_catalog_feed' ? catalogFeedUpdate.parse(op.payload) : op.tool === 'tiktok_set_catalog_feed_schedule_status' ? catalogFeedSwitch.parse(op.payload) : catalogFeedDelete.parse(op.payload);\n const scope = catalogInput.parse({ account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id }), parent = await this.authorizeParent(scope, true);\n const review = (title: string, subject: string, fields: ReviewField[], notes: string[]) => ({ provider: 'tiktok', accountId: scope.account_id, kind: op.kind, title, subject, fields: [{ label: 'Catalog', after: input.catalog_id }, ...fields], notices: notes });\n if ('expected_catalog_hash' in input) {\n if (input.expected_catalog_hash !== parent.configuration_hash) throw new AdportError('INVALID_INPUT', 'Catalog configuration changed. Read and review feed creation again.');\n if (input.feed_type === 'COUNTRY_FEED' && parent.catalog_conf.is_multi_country !== true) throw new AdportError('INVALID_INPUT', 'A country feed requires a verified multi-country catalog. Native existing-product eligibility is checked on apply.');\n const sourceSecrets = input.schedule_param ? [input.schedule_param.source.uri, input.schedule_param.source.username, input.schedule_param.source.password].filter((item): item is string => typeof item === 'string' && item.length > 0) : [];\n const displayName = sourceSecrets.reduce((name, secret) => name.replaceAll(secret, '[redacted]'), input.feed_name);\n const fields: ReviewField[] = [{ label: 'Name', after: displayName }, { label: 'Update mode', after: input.update_mode }, ...(input.feed_type ? [{ label: 'Feed type', after: input.feed_type }] : []), ...scheduleFields(input.schedule_param)];\n const notes = [input.schedule_param ? 'Supplying a source schedule can start automatic native product processing immediately. OVERWRITE can remove products missing from the source.' : 'No source schedule is supplied. The created feed must remain OFF with no source URI.', 'Country feeds also require existing products; native eligibility is checked on apply.', ...commonNotes];\n return { summary: `Create TikTok catalog feed ${displayName}`, changes: fields.map(field => `+ ${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes, review: review('Create catalog feed', displayName, fields, notes), execute: async () => {\n const fresh = await this.authorizeParent(scope, true);if (fresh.configuration_hash !== input.expected_catalog_hash) throw new AdportError('INVALID_INPUT', 'Catalog changed before creating the feed. Review again.');let createdId: string | undefined;\n try {\n const body = { bc_id: input.bc_id, catalog_id: input.catalog_id, feed_name: input.feed_name, update_mode: input.update_mode, ...(input.feed_type ? { feed_type: input.feed_type } : {}), ...(input.schedule_param ? { schedule_param: input.schedule_param } : {}) };\n const receipt = z.object({ feed_id: nativeId }).parse(await this.client.post('catalog/feed/create', body));createdId = receipt.feed_id;\n const actual = (await this.native(scope, createdId))[0]!;\n if (actual.feed_name !== input.feed_name || input.feed_type && actual.feed_type !== input.feed_type || actual.last_update_param?.update_mode !== input.update_mode || input.schedule_param && !matchesSchedule(actual, input.schedule_param) || !input.schedule_param && (actual.status !== 'OFF' || !!actual.last_update_param?.uri)) throw new Error('Creation readback differs');return [createdId];\n } catch { throw new AdportError('PROVIDER_ERROR', 'TikTok feed creation outcome is unconfirmed. Inspect catalog feeds before another create; do not replay automatically.', createdId ? { resource_ids: [createdId] } : undefined); }\n } };\n }\n const current = (await this.native(scope, input.feed_id))[0]!, name = publicText(current.feed_name, current);\n if (input.expected_configuration_hash !== configurationHash(scope, current)) throw new AdportError('INVALID_INPUT', 'Feed configuration changed. Read and review it again.');\n let path: string, body: Record<string, unknown>, expected = config(current), fields: ReviewField[], notes: string[];\n if (op.tool === 'tiktok_delete_catalog_feed') {\n path = 'catalog/feed/delete';body = { bc_id: input.bc_id, catalog_id: input.catalog_id, feed_id: input.feed_id };fields = [{ label: 'Feed', before: name, after: 'Permanently deleted' }];notes = ['Permanently removes this shared feed. Review dependent catalog products and ads; no restoration or compensating write is automatic.', ...commonNotes];\n } else if (op.tool === 'tiktok_set_catalog_feed_schedule_status') {\n const targetStatus = catalogFeedSwitch.parse(input).status;\n if (!current.status || current.status === targetStatus) throw new AdportError('INVALID_INPUT', 'Schedule status must be known and change to the opposite ON/OFF value.');\n const source = current.last_update_param;if (targetStatus === 'ON' && (!source?.uri || !sourceUri.safeParse(source.uri).success || !source.interval_type || !source.timezone)) throw new AdportError('INVALID_INPUT', 'Enabling a feed requires a configured source URI, interval and time zone.');\n path = 'catalog/feed/switch';body = { bc_id: input.bc_id, catalog_id: input.catalog_id, feed_id: input.feed_id, status: targetStatus };expected = { ...expected, status: targetStatus };fields = [{ label: 'Automatic processing', before: current.status, after: targetStatus }, { label: 'Source', after: { origin: origin(source?.uri), fingerprint: source?.uri ? digest(source.uri) : 'Not configured' } }];notes = ['ON resumes automatic product processing and may change products selected by existing ads. OFF stops future scheduled runs; it does not undo previous imports.', ...commonNotes];\n } else {\n const update = catalogFeedUpdate.parse(input);path = 'catalog/feed/update';body = { bc_id: input.bc_id, catalog_id: input.catalog_id, feed_id: input.feed_id, update_mode: update.update_mode, ...(update.schedule_param ? { schedule_param: update.schedule_param } : {}) };\n expected = { ...expected, schedule: { ...expected.schedule, update_mode: update.update_mode } };\n if (update.schedule_param) expected.schedule = { ...expected.schedule, ...scheduleConfig({ ...update.schedule_param, uri: update.schedule_param.source.uri, update_mode: update.update_mode }) };\n fields = [{ label: 'Update mode', before: current.last_update_param?.update_mode ?? 'Not reported', after: update.update_mode }, ...scheduleFields(update.schedule_param, current)];notes = ['Replaces the supplied source/schedule configuration. Existing automatic runs can use it immediately; OVERWRITE can remove products missing from the source.', 'Supply any required source authentication explicitly when replacing the schedule. Native credential values are unavailable for preservation/readback.', ...commonNotes];\n }\n const remove = op.kind === 'remove', title = remove ? 'Delete catalog feed' : 'status' in input ? 'Change feed schedule status' : 'Update catalog feed';\n return { summary: `${title} ${name}`, changes: fields.map(field => `${remove ? '-' : '~'} ${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes, review: review(title, name, fields, notes), execute: async () => {\n await this.authorizeParent(scope, true);\n try {\n const raw = await this.client.post(path, body);\n if (path === 'catalog/feed/switch') { const receipt = z.object({ feed_id: nativeId.optional() }).parse(raw);if (receipt.feed_id !== undefined && receipt.feed_id !== input.feed_id) throw new Error('Feed ID differs'); }\n else if (z.object({ feed_id: nativeId }).parse(raw).feed_id !== input.feed_id) throw new Error('Feed ID differs');\n if (remove) { if ((await this.native(scope)).some(row => row.feed_id === input.feed_id)) throw new Error('Deleted feed remains'); }\n else if (canonical(config((await this.native(scope, input.feed_id))[0]!)) !== canonical(expected)) throw new Error('Configuration preservation differs');\n return [input.feed_id];\n } catch { throw new AdportError('PROVIDER_ERROR', 'TikTok feed mutation outcome is unconfirmed. Read the known feed/catalog before another write; do not replay automatically.', { resource_ids: [input.feed_id] }); }\n } };\n }\n}\nfunction scheduleFields(value: z.infer<typeof schedule> | undefined, before?: Feed): ReviewField[] {\n const current = before?.last_update_param;\n return value ? [\n { label: 'Source', ...(before ? { before: { origin: origin(current?.uri), fingerprint: current?.uri ? digest(current.uri) : 'Not configured' } } : {}), after: { origin: origin(value.source.uri), fingerprint: digest(value.source.uri) } },\n { label: 'Source authentication', ...(before ? { before: 'Native values are not readable' } : {}), after: value.source.username || value.source.password ? 'Supplied; values hidden' : 'Not supplied' },\n { label: 'Schedule', ...(before ? { before: { interval_type: current?.interval_type, interval_count: current?.interval_count, timezone: current?.timezone ? publicText(current.timezone, before) : null, day_of_month: current?.day_of_month, hour: current?.hour, minute: current?.minute } } : {}), after: { interval_type: value.interval_type, interval_count: value.interval_count, timezone: value.timezone, day_of_month: value.day_of_month, hour: value.hour, minute: value.minute } },\n ] : [{ label: 'Source schedule', after: before ? 'Preserve current schedule' : 'Not supplied' }];\n}\nfunction matchesSchedule(actual: Feed, wanted: z.infer<typeof schedule>) {\n const current = actual.last_update_param;\n return current?.uri === wanted.source.uri && current.timezone === wanted.timezone && current.interval_type === wanted.interval_type && current.interval_count === wanted.interval_count && current.hour === wanted.hour && current.minute === wanted.minute && (wanted.day_of_month === undefined || current.day_of_month === wanted.day_of_month);\n}\n","import { AdportError, csvRows, MAX_PROJECT_MEDIA_BYTES, verifyMedia, type Creative, type MediaResolver, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { TikTokClient } from './client.js';\nimport type { TikTokCatalogFeeds } from './catalog-feeds.js';\nimport { catalogId, catalogInput } from './catalog-schema.js';\nimport { nativeListComplete } from './pagination.js';\n\nconst count = z.number().int().nonnegative().safe();\nconst nativeId = z.union([catalogId, z.number().int().positive().safe()]).transform(String);\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nconst uniqueIds = z.array(catalogId).min(1).max(1000).refine(values => new Set(values).size === values.length, 'IDs must be unique');\nexport const catalogProductList = catalogInput.extend({\n product_ids: uniqueIds.optional(), sku_ids: z.array(z.string().min(1).max(100)).min(1).max(1000).refine(values => new Set(values).size === values.length, 'SKU IDs must be unique').optional(),\n page: z.number().int().positive().max(10_000).default(1), page_size: z.number().int().min(1).max(100).default(20),\n}).strict().refine(value => !(value.product_ids && value.sku_ids), 'Choose product_ids or sku_ids, not both')\n .refine(value => value.page * value.page_size <= 10_000, 'TikTok only exposes the first 10,000 matching products');\nexport const catalogProductLog = catalogInput.extend({ feed_id: catalogId, feed_log_id: catalogId }).strict();\nexport const catalogFileImport = catalogInput.omit({ account_id: true }).extend({\n feed_id: catalogId, media_id: z.string().uuid(), expected_sha256: hash,\n expected_catalog_hash: hash, expected_feed_hash: hash, update_mode: z.enum(['INCREMENTAL', 'OVERWRITE']),\n acknowledge_shared_effects: z.literal(true), acknowledge_async_processing: z.literal(true), acknowledge_overwrite: z.literal(true).optional(),\n}).strict().refine(value => value.update_mode !== 'OVERWRITE' || value.acknowledge_overwrite === true, 'OVERWRITE can delete products missing from the CSV; explicitly acknowledge it');\ntype Selection = z.infer<typeof catalogInput>;\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]> };\nconst product = z.object({\n product_id: nativeId, catalog_id: nativeId.optional(), bc_id: nativeId.optional(),\n sku_id: z.string().max(100).optional(), hotel_id: z.string().max(512).optional(), flight_id: z.string().max(512).optional(), destination_id: z.string().max(512).optional(),\n vehicle_id: z.string().max(512).optional(), series_id: z.string().max(512).optional(), item_id: z.string().max(512).optional(), listing_id: z.string().max(512).optional(),\n title: z.string().max(10_000).optional(), name: z.string().max(10_000).optional(), destination_name: z.string().max(10_000).optional(),\n description: z.string().max(10_000).optional(), brand: z.string().max(1000).optional(), availability: z.string().max(100).optional(), active_status: z.string().max(100).optional(),\n available: z.boolean().optional(), ad_creation_eligible: z.string().max(100).optional(), audit: z.object({ audit_status: z.string().max(100).optional() }).optional(),\n image_url: z.string().max(8192).optional(), video_url: z.string().max(8192).optional(),\n});\nconst invalid = () => new AdportError('PROVIDER_ERROR', 'TikTok catalog-product response has an unexpected scope, identifier or shape. No request was retried.');\nconst mediaUrl = (value?: string) => {\n try { const url = new URL(value ?? '');return url.protocol === 'https:' && !url.username && !url.password ? url.href : undefined; } catch { return undefined; }\n};\n\n/** Native file imports return task IDs. Acceptance never certifies completed ingestion. */\nexport class TikTokCatalogProducts {\n constructor(\n private readonly client: Pick<TikTokClient, 'get' | 'post'>,\n private readonly authorizeParent: (input: Selection, write?: boolean) => Promise<{ configuration_hash: string; catalog_type: string }>,\n private readonly feeds: Pick<TikTokCatalogFeeds, 'list'>,\n private readonly media?: MediaResolver,\n ) {}\n private async request(path: string, input: Record<string, unknown>): Promise<unknown> {\n try { return await this.client.get(path, input, { jsonContentType: true }); }\n catch (error) {\n if (error instanceof AdportError && ['POLICY_VIOLATION', 'NOT_CONNECTED'].includes(error.code)) throw error;\n throw new AdportError('PROVIDER_ERROR', 'TikTok catalog-product read failed. Check native permissions and the exact catalog/feed/job. Provider bodies and file URLs stay hidden; no request was retried.');\n }\n }\n async list(value: unknown) {\n const input = catalogProductList.parse(value), scope = catalogInput.parse({ account_id: input.account_id, bc_id: input.bc_id, catalog_id: input.catalog_id });\n const parent = await this.authorizeParent(scope);\n if (input.sku_ids && parent.catalog_type !== 'ECOM') throw new AdportError('INVALID_INPUT', 'The SKU filter requires an E-commerce catalog; use native product IDs for other catalog types.');\n const result = z.object({ list: z.array(product).max(input.page_size), page_info: z.object({ page: z.number().int().positive().safe(), page_size: z.number().int().positive().max(500), total_number: count.optional(), total_page: count.optional() }).optional() }).safeParse(await this.request('catalog/product/get', {\n bc_id: input.bc_id, catalog_id: input.catalog_id, page: input.page, page_size: input.page_size,\n ...(input.product_ids ? { product_ids: input.product_ids } : {}), ...(input.sku_ids ? { sku_ids: input.sku_ids } : {}),\n }));\n if (!result.success) throw invalid();\n const rows = result.data.list, page = result.data.page_info;\n if (new Set(rows.map(row => row.product_id)).size !== rows.length || rows.some(row => row.catalog_id !== undefined && row.catalog_id !== input.catalog_id || row.bc_id !== undefined && row.bc_id !== input.bc_id || input.product_ids && !input.product_ids.includes(row.product_id) || input.sku_ids && (!row.sku_id || !input.sku_ids.includes(row.sku_id))) || page && (page.page !== input.page || page.page_size !== input.page_size)) throw invalid();\n const products = rows.map(row => ({ product_id: row.product_id, external_id: row.sku_id ?? row.hotel_id ?? row.flight_id ?? row.destination_id ?? row.vehicle_id ?? row.series_id ?? row.item_id ?? row.listing_id,\n name: row.title ?? row.name ?? row.destination_name ?? row.product_id, availability: row.availability, active_status: row.active_status,\n available: row.available, ad_creation_eligible: row.ad_creation_eligible, audit_status: row.audit?.audit_status, brand: row.brand,\n image_url: mediaUrl(row.image_url), video_url: mediaUrl(row.video_url), description: row.description?.slice(0, 300), description_truncated: (row.description?.length ?? 0) > 300,\n }));\n const complete = nativeListComplete(page, rows.length), ceiling = complete !== true && (input.page + 1) * input.page_size > 10_000;\n const creatives: Creative[] = products.map(row => ({ id: row.product_id, provider: 'tiktok', account_id: input.account_id, type: 'catalog_product', name: row.name,\n ...(row.audit_status ? { status: row.audit_status } : {}), headlines: [], descriptions: row.description ? [row.description] : [], landing_urls: [], actions: [],\n media: [...(row.image_url ? [{ type: 'image' as const, url: row.image_url, alt: row.name }] : []), ...(row.video_url ? [{ type: 'video' as const, url: row.video_url, alt: row.name }] : [])],\n }));\n return { products, creatives, complete, truncated: complete !== true, ...(complete === false && !ceiling ? { next_page: input.page + 1 } : {}),\n ...(page ? { page_info: page } : {}), native_access_limit: 10_000, native_limit_reached: ceiling,\n notes: ['This is a compact product/media view, not full editable configuration. Product audit, stock and advertiser activation are separate from ad-creation eligibility.', 'TikTok exposes at most the first 10,000 matching products. Use ID filters to narrow larger catalogs; no continuation is fabricated beyond that cap.', ...(complete === null ? ['Native pagination is absent or contradictory; completeness is unknown.'] : [])],\n };\n }\n private async selectedFeed(scope: Selection, feedId: string) {\n const result = await this.feeds.list({ ...scope, feed_id: feedId });\n if (result.feeds.length !== 1 || result.feeds[0]!.feed_id !== feedId) throw invalid();\n return result.feeds[0]!;\n }\n async log(value: unknown) {\n const input = catalogProductLog.parse(value), scope = catalogInput.parse({ account_id: input.account_id, bc_id: input.bc_id, catalog_id: input.catalog_id });\n await this.authorizeParent(scope);await this.selectedFeed(scope, input.feed_id);\n const issue = z.object({ field: z.string().max(256 * 1024).nullable().optional(), affected_product_count: count });\n const result = z.object({ product_feed_log: z.object({\n catalog_id: nativeId.optional(), bc_id: nativeId.optional(), feed_id: nativeId.optional(), feeds_id: nativeId.optional(), feed_log_id: nativeId.optional(),\n process_status: z.enum(['WAITING', 'PROCESSING', 'SUCCESS', 'FAILED']), update_mode: z.union([z.enum(['INCREASE', 'REPLACE', 'INCREMENTAL', 'OVERWRITE']), count]).optional(),\n add_count: count.optional(), update_count: count.optional(), delete_count: count.optional(), error_count: count.optional(), warn_count: count.optional(),\n start_time: z.string().max(40).regex(/^[0-9TZ :.+-]*$/).nullable().optional(), end_time: z.string().max(40).regex(/^[0-9TZ :.+-]*$/).nullable().optional(),\n feed_log_data: z.object({ error_affected_products: z.array(issue).max(1000).nullable().optional(), warn_affected_products: z.array(issue).max(1000).nullable().optional() }).nullable().optional(),\n }) }).safeParse(await this.request('catalog/product/log', { bc_id: input.bc_id, catalog_id: input.catalog_id, feed_log_id: input.feed_log_id, language: 'en' }));\n if (!result.success) throw invalid();\n const row = result.data.product_feed_log, feedId = row.feed_id ?? row.feeds_id;\n if (feedId !== input.feed_id || row.feed_id !== undefined && row.feeds_id !== undefined && row.feed_id !== row.feeds_id || row.catalog_id !== undefined && row.catalog_id !== input.catalog_id || row.bc_id !== undefined && row.bc_id !== input.bc_id || row.feed_log_id !== undefined && row.feed_log_id !== input.feed_log_id) throw invalid();\n const { feed_log_data: issues, feeds_id: _legacy, ...fields } = row;\n const publicIssues = (rows: Array<z.infer<typeof issue>>) => rows.slice(0, 50).map(row => ({ field: typeof row.field === 'string' && row.field.length <= 128 && /^[a-zA-Z0-9_.\\[\\]-]+$/.test(row.field) ? row.field : 'Unrecognized field', affected_product_count: row.affected_product_count }));\n const log = { ...fields, feed_id: input.feed_id, feed_log_id: input.feed_log_id,\n ...(row.update_mode !== undefined ? { update_mode_recognized: typeof row.update_mode === 'string' } : {}),\n ...(issues?.error_affected_products ? { error_fields: publicIssues(issues.error_affected_products) } : {}), ...(issues?.warn_affected_products ? { warning_fields: publicIssues(issues.warn_affected_products) } : {}),\n diagnostic_fields_truncated: (issues?.error_affected_products?.length ?? 0) > 50 || (issues?.warn_affected_products?.length ?? 0) > 50,\n };\n return { log, records: [{ id: input.feed_log_id, name: 'Product import', status: row.process_status === 'SUCCESS' && (row.error_count ?? 0) > 0 ? 'Completed with item errors' : row.process_status, added: row.add_count, updated: row.update_count, removed: row.delete_count, errors: row.error_count, warnings: row.warn_count }],\n processing_complete: ['SUCCESS', 'FAILED'].includes(row.process_status), complete: true, truncated: false,\n notes: ['Counts and processing state are native; missing counts remain unavailable. SUCCESS does not establish ad eligibility or delivery.', 'The native reference labels update_mode as numeric but documents string enum values. Numeric codes are retained without an invented mapping and cannot verify the approved import mode.', 'Diagnostic field/count groups are bounded to 50 per severity. Native download links, free-form error text and product samples are omitted to keep file capabilities private.'],\n };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n if (op.provider !== 'tiktok' || op.tool !== 'tiktok_import_catalog_file' || op.kind !== 'update') throw new AdportError('INVALID_INPUT', 'Unsupported TikTok product import operation.');\n const input = catalogFileImport.parse(op.payload), scope = catalogInput.parse({ account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id });\n const media = this.media, providerUrl = media?.providerUrl?.bind(media);\n if (!media || !providerUrl) throw new AdportError('NOT_CONNECTED', 'CSV feed imports require the hosted project media library. Stage the file through an agent, widget, dashboard or cloud media CLI, then use its media_id and SHA-256.');\n const prepare = async () => {\n const parent = await this.authorizeParent(scope, true), feed = await this.selectedFeed(scope, input.feed_id);\n if (parent.configuration_hash !== input.expected_catalog_hash || feed.configuration_hash !== input.expected_feed_hash) throw new AdportError('INVALID_INPUT', 'Catalog or feed configuration changed. Read and preview the import again.');\n if (!['DATA_FEED', 'COUNTRY_FEED'].includes(feed.feed_type)) throw new AdportError('INVALID_INPUT', 'Read a feed with a known native DATA_FEED or COUNTRY_FEED type before importing.');\n const source = await media.read(input, { maxBytes: MAX_PROJECT_MEDIA_BYTES, contentTypes: ['text/csv'] });\n const file = verifyMedia(source.bytes, source.name, input.expected_sha256, { maxBytes: MAX_PROJECT_MEDIA_BYTES, contentTypes: ['text/csv'] });\n const rows = csvRows(file.bytes), first = rows.next();let rowCount = 0;\n if (first.done) throw new AdportError('INVALID_INPUT', 'The catalog CSV needs a header and at least one product row.');\n const header = first.value;\n if (header.some(field => !field.trim()) || new Set(header).size !== header.length) throw new AdportError('INVALID_INPUT', 'The catalog CSV needs nonempty, distinct column headers matching the selected catalog/feed template.');\n for (const row of rows) { if (!row.some(field => field.trim())) throw new AdportError('INVALID_INPUT', 'Remove blank product rows before importing.');rowCount++; }\n if (!rowCount) throw new AdportError('INVALID_INPUT', 'The catalog CSV needs at least one product row.');\n return { parent, feed, file, rowCount, columns: header.length };\n };\n const initial = await prepare();\n const notes = ['Submits a one-time asynchronous import into this existing feed. Native processing validates catalog-specific columns, feed ownership and product eligibility; local CSV validation does not certify the provider template.', input.update_mode === 'OVERWRITE' ? 'OVERWRITE removes existing feed products missing from this file and can change ads using them.' : 'INCREMENTAL adds products and updates matching products; products omitted from the CSV remain.', 'This request does not change the feed’s saved update mode or activate ads. Feed scheduling is managed separately; read fresh feed state before changing automation.', 'The result is an accepted task ID, not completed ingestion. Read tiktok_catalog_product_log until terminal and inspect item errors. Never automatically replay an uncertain import.'];\n return { summary: `Import ${initial.rowCount} product rows into TikTok feed ${input.feed_id}`, changes: [`~ One-time ${input.update_mode} product import into ${initial.feed.feed_type} ${input.feed_id}`, `+ CSV ${JSON.stringify(initial.file.name)}; ${initial.file.bytes.byteLength} bytes; SHA-256 ${initial.file.sha256}`], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'tiktok', accountId: scope.account_id, kind: 'update', title: 'Import catalog file', subject: initial.file.name, fields: [{ label: 'Catalog', after: input.catalog_id }, { label: 'Feed', after: input.feed_id }, { label: 'Feed type', after: initial.feed.feed_type }, { label: 'Feed schedule', after: initial.feed.status }, { label: 'Import mode', after: input.update_mode }, { label: 'Product rows', after: String(initial.rowCount) }, { label: 'CSV columns', after: String(initial.columns) }, { label: 'SHA-256', after: initial.file.sha256 }], notices: notes },\n execute: async () => {\n await prepare();\n const grant = await providerUrl(input, { maxBytes: MAX_PROJECT_MEDIA_BYTES, contentTypes: ['text/csv'] });\n if (grant.sha256 !== input.expected_sha256 || !mediaUrl(grant.url) || !Number.isFinite(Date.parse(grant.expires_at)) || Date.parse(grant.expires_at) <= Date.now() + 60_000) throw new AdportError('PROVIDER_ERROR', 'The private CSV download grant could not be verified. No TikTok import was submitted.');\n let jobId: string | undefined;\n try {\n const receipt = z.object({ feed_log_id: nativeId }).parse(await this.client.post('catalog/product/file', { bc_id: input.bc_id, catalog_id: input.catalog_id, feed_id: input.feed_id, file_url: grant.url, update_mode: input.update_mode }));jobId = receipt.feed_log_id;\n const actual = await this.log({ ...scope, feed_id: input.feed_id, feed_log_id: jobId });\n const expectedModes = input.update_mode === 'INCREMENTAL' ? ['INCREMENTAL', 'INCREASE'] : ['OVERWRITE', 'REPLACE'];\n if (actual.log.update_mode !== undefined && (typeof actual.log.update_mode !== 'string' || !expectedModes.includes(actual.log.update_mode))) throw new Error('Native processing mode is unrecognized or differs from approval');\n if (actual.log.process_status === 'FAILED' || actual.log.process_status === 'SUCCESS' && (actual.log.error_count ?? 0) > 0) throw new Error('Native processing reports failure or item errors');\n return [jobId];\n } catch {\n throw new AdportError('PROVIDER_ERROR', 'TikTok product import failed, has item errors or its outcome is unconfirmed. Read the known import job or feed history before another write; do not replay automatically.', jobId ? { resource_ids: [jobId], feed_log_id: jobId, feed_id: input.feed_id } : undefined);\n }\n },\n };\n }\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, MAX_PROJECT_MEDIA_BYTES, verifyMedia, type MediaResolver, type WriteOperation, type WritePreview, type ReviewField } from '@adport/core';\nimport { z } from 'zod';\nimport type { TikTokClient } from './client.js';\nimport type { TikTokCatalogFeeds } from './catalog-feeds.js';\nimport type { TikTokCatalogProducts } from './catalog-products.js';\nimport { catalogId, catalogInput } from './catalog-schema.js';\nimport { catalogProductFields } from './catalog-product-contract.js';\nimport { catalogProductKinds, parseProduct, productShape, productIdentityFields, productDeleteFields, type CatalogProductKind } from './catalog-product-shapes.js';\n\ntype Row = Record<string, unknown>;\ntype Selection = z.infer<typeof catalogInput>;\ntype Parent = { configuration_hash: string; catalog_type: string };\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]> };\nconst hash = z.string().regex(/^[a-f0-9]{64}$/), kind = z.enum(catalogProductKinds);\nconst nativeId = z.union([catalogId, z.number().int().positive().safe()]).transform(String);\nconst nativeIds = z.array(catalogId).min(1).max(5000).refine(values => new Set(values).size === values.length, 'Product IDs must be unique');\nconst jsonRow = z.record(z.string(), z.json());\nconst mediaAsset = z.strictObject({ product_index: z.number().int().min(0).max(4999), field: z.enum(['image_url', 'video_url', 'additional_image_urls']), image_index: z.number().int().min(0).max(19).optional(), media_id: z.string().uuid(), expected_sha256: hash }).refine(value => value.field === 'additional_image_urls' ? value.image_index !== undefined : value.image_index === undefined, 'image_index is required only for additional_image_urls');\nconst mediaAssets = z.array(mediaAsset).max(1000).default([]);\nconst selected = catalogInput.extend({ feed_id: catalogId }).strict();\nconst payload = selected.omit({ account_id: true }).extend({ catalog_type: kind, expected_catalog_hash: hash, expected_feed_hash: hash, acknowledge_shared_effects: z.literal(true), acknowledge_async_processing: z.literal(true) });\nexport const catalogProductSchema = catalogInput.extend({ operation: z.enum(['upload', 'update']).default('upload') }).strict();\nexport const catalogProductContext = selected.extend({ product_ids: nativeIds }).strict();\nexport const catalogProductUpsert = payload.extend({ products: z.array(jsonRow).min(1).max(5000), media_assets: mediaAssets, acknowledge_replacement: z.literal(true) }).strict();\nexport const catalogProductUpdate = payload.extend({ expected_products_hash: hash, updates: z.array(z.strictObject({ product_id: catalogId, fields: jsonRow })).min(1).max(5000), media_assets: mediaAssets }).strict();\nexport const catalogProductDelete = payload.extend({ expected_products_hash: hash, product_ids: nativeIds, acknowledge_removal: z.literal(true) }).strict();\nconst object = (value: unknown): Row => value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};\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 digest = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex');\nconst fail = () => new AdportError('PROVIDER_ERROR', 'TikTok returned an unexpected product scope, identifier or selection. No request was retried.');\nfunction bound(value: unknown, input = false) {\n let nodes = 0;\n const walk = (item: unknown, depth: number) => {\n if (++nodes > 200000 || depth > 12 || typeof item === 'number' && (!Number.isFinite(item) || Number.isInteger(item) && !Number.isSafeInteger(item))) throw new AdportError(input ? 'INVALID_INPUT' : 'PROVIDER_ERROR', 'Catalog product data exceeds safe structural bounds.');\n if (typeof item === 'object' && item !== null) for (const child of Object.values(item)) walk(child, depth + 1);\n };\n walk(value, 0);\n if (Buffer.byteLength(canonical(value)) > 2 * 1024 * 1024) throw new AdportError(input ? 'INVALID_INPUT' : 'PROVIDER_ERROR', 'Catalog product batch exceeds 2 MiB. Use smaller batches.');\n}\nfunction publicValue(value: unknown, key = ''): unknown {\n if (Array.isArray(value)) return value.map(item => publicValue(item, key));\n if (value !== null && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, publicValue(item, key)]));\n if (typeof value === 'string' && /url|uri|link/i.test(key)) {\n if (value.startsWith('https://adport.invalid/media/')) { const parts = value.split('/');return { media_id: parts[4], sha256: parts[5] }; }\n try { const url = new URL(value);return { origin: url.origin === 'null' ? url.protocol : url.origin, sha256: digest(value) }; } catch { return { sha256: digest(value) }; }\n }\n return value;\n}\nconst identity = (type: CatalogProductKind, value: Row): Row => Object.fromEntries(productIdentityFields[type].map(key => {\n const direct = value[key], nested = object(value.product_detail)[key];\n if (direct !== undefined && nested !== undefined && direct !== nested) throw fail();\n const id = direct ?? nested;\n if (typeof id !== 'string' || !id.trim() || /[\\u0000-\\u001f\\u007f]/.test(id)) throw new AdportError('INVALID_INPUT', 'A product lacks a safe native external identity for its catalog type.');\n return [key, id];\n}));\nconst operationTools = ['tiktok_upsert_catalog_products', 'tiktok_update_catalog_products', 'tiktok_delete_catalog_products'];\nconst leaves = (value: Row, prefix = ''): Array<[string, unknown]> => Object.entries(value).flatMap(([key, item]) => {\n const path = prefix ? `${prefix}.${key}` : key;\n return item !== null && typeof item === 'object' && !Array.isArray(item) && Object.keys(item).length ? leaves(item as Row, path) : [[path, item]];\n});\nconst atPath = (value: Row, path: string) => path.split('.').reduce<unknown>((item, key) => object(item)[key], value);\n\n/** Fixed native product endpoints; every apply is a single asynchronous submission. */\nexport class TikTokCatalogProductAuthoring {\n constructor(private readonly client: Pick<TikTokClient, 'get' | 'post'>, private readonly authorizeParent: (selection: Selection, write?: boolean) => Promise<Parent>, private readonly feeds: Pick<TikTokCatalogFeeds, 'list'>, private readonly products: Pick<TikTokCatalogProducts, 'log'>, private readonly media?: MediaResolver) {}\n supports(tool: string) { return operationTools.includes(tool); }\n private async request(path: string, args: Row) {\n try { return await this.client.get(path, args, { jsonContentType: true }); }\n catch { throw new AdportError('PROVIDER_ERROR', 'TikTok product configuration read failed. Verify native permissions and the selected catalog. Provider bodies and source URLs stay hidden; no request was retried.'); }\n }\n private async feed(scope: z.infer<typeof selected>) {\n const result = await this.feeds.list({ account_id: scope.account_id, bc_id: scope.bc_id, catalog_id: scope.catalog_id, feed_id: scope.feed_id });\n if (result.feeds.length !== 1 || result.feeds[0]!.feed_id !== scope.feed_id) throw fail();\n return result.feeds[0]!;\n }\n async schema(value: unknown) {\n const input = catalogProductSchema.parse(value), { operation, ...scope } = input, parent = await this.authorizeParent(scope), type = kind.parse(parent.catalog_type);\n return { catalog_type: type, operation, schema: z.toJSONSchema(productShape(type, operation === 'update')), identity_fields: productIdentityFields[type], native_batch_limit: 5000, adport_batch_bytes: 2 * 1024 * 1024,\n media_assets_schema: z.toJSONSchema(mediaAsset), source: `https://business-api.tiktok.com/portal/docs?id=${operation === 'upload' ? '1740497429681153' : '1740562287852546'}`,\n notes: ['Structural schema from the official parameter tables; native eligibility, conditional requirements and semantic validation remain authoritative.', operation === 'update' ? 'Update fields are a partial object. External identity is supplied from verified product context, not editable fields. Nested update semantics remain native.' : 'Upload is an incremental upsert and may replace existing products with the same external identity.', 'For flights the native identity is the origin/destination airport pair; flight_id is generated by TikTok.'],\n };\n }\n private async mediaProducts(rows: Row[], assets: Array<z.infer<typeof mediaAsset>>, mint = false): Promise<Row[]> {\n const result = structuredClone(rows), targets = new Set<string>(), resolved = new Map<string, string>();\n if (assets.length && !this.media?.providerUrl) throw new AdportError('INVALID_INPUT', 'Project media URL staging is required for catalog media references. Upload the files through Adport media tools first.');\n for (const asset of assets) {\n const row = result[asset.product_index], key = `${asset.product_index}:${asset.field}:${asset.image_index ?? ''}`;\n if (!row || targets.has(key)) throw new AdportError('INVALID_INPUT', 'Media references require distinct fields on existing product indexes.');targets.add(key);\n if (Object.hasOwn(rows[asset.product_index]!, asset.field)) throw new AdportError('INVALID_INPUT', 'Choose native source URLs or project media references for a field, not both.');\n const options = { maxBytes: MAX_PROJECT_MEDIA_BYTES, contentTypes: asset.field === 'video_url' ? ['video/mp4', 'video/quicktime', 'video/webm'] : ['image/png', 'image/jpeg'] };\n const source = { media_id: asset.media_id, expected_sha256: asset.expected_sha256 }, cacheKey = `${asset.media_id}:${asset.expected_sha256}:${options.contentTypes.join(',')}`;\n let url = resolved.get(cacheKey);\n if (!url) {\n let file;\n try { file = await this.media!.read(source, options); } catch { throw new AdportError('INVALID_INPUT', 'Adport media bytes/checksum verification failed. Refresh the immutable media reference before previewing.'); }\n verifyMedia(file.bytes, file.name, asset.expected_sha256, { ...options, contentType: file.contentType });\n url = `https://adport.invalid/media/${asset.media_id}/${asset.expected_sha256}`;\n if (mint) {\n let grant;\n try { grant = await this.media!.providerUrl!(source, options); } catch { throw new AdportError('PROVIDER_ERROR', 'Adport media download staging was not confirmed. No native product request was sent.'); }\n let destination: URL;\n try { destination = new URL(grant.url); } catch { throw new AdportError('PROVIDER_ERROR', 'Project media staging returned an invalid download grant.'); }\n if (destination.protocol !== 'https:' || destination.username || destination.password || grant.sha256 !== asset.expected_sha256 || !(Date.parse(grant.expires_at) > Date.now() + 10 * 60_000)) throw new AdportError('PROVIDER_ERROR', 'Project media staging returned an unverified or short-lived download grant.');\n url = grant.url;\n }\n resolved.set(cacheKey, url);\n }\n if (asset.field === 'additional_image_urls') {\n const array = (row.additional_image_urls ??= []) as string[];array[asset.image_index!] = url;\n } else row[asset.field] = url;\n }\n for (const row of result) if (Array.isArray(row.additional_image_urls) && Array.from(row.additional_image_urls).some(value => typeof value !== 'string')) throw new AdportError('INVALID_INPUT', 'Additional media image indexes must be contiguous starting at zero.');\n return result;\n }\n private async readSet(scope: Selection, type: CatalogProductKind, ids: string[], feedId: string) {\n const rows: Row[] = [], seen = new Set<string>();\n for (let start = 0; start < ids.length; start += 1000) {\n const chunk = ids.slice(start, start + 1000), wanted = new Set(chunk);\n for (let page = 1; page <= 10; page++) {\n const result = z.object({ list: z.array(z.record(z.string(), z.unknown())).max(100), page_info: z.object({ page: z.number().int().positive(), page_size: z.number().int().positive(), total_number: z.number().int().nonnegative().safe().optional(), total_page: z.number().int().nonnegative().safe().optional() }).optional() }).safeParse(await this.request('catalog/product/get', { bc_id: scope.bc_id, catalog_id: scope.catalog_id, product_ids: chunk, page, page_size: 100 }));\n if (!result.success || result.data.page_info && (result.data.page_info.page !== page || result.data.page_info.page_size !== 100 || (result.data.page_info.total_number ?? 0) > chunk.length)) throw fail();\n for (const row of result.data.list) {\n bound(row);const parsed = nativeId.safeParse(row.product_id);\n if (!parsed.success || !wanted.has(parsed.data) || seen.has(parsed.data) || row.catalog_id !== undefined && nativeId.parse(row.catalog_id) !== scope.catalog_id || row.bc_id !== undefined && nativeId.parse(row.bc_id) !== scope.bc_id || row.feed_id !== undefined && nativeId.parse(row.feed_id) !== feedId) throw fail();\n const keys = new Set([...catalogProductFields[type].map(field => field.path.split('.')[0]!), ...productIdentityFields[type], 'flight_id', 'feed_id']);\n const config = Object.fromEntries(Object.entries(row).filter(([key]) => keys.has(key)));\n rows.push({ ...config, product_id: parsed.data });seen.add(parsed.data);\n }\n if (chunk.every(id => seen.has(id))) {\n if (result.data.page_info && ((result.data.page_info.total_number ?? chunk.length) !== chunk.length || (result.data.page_info.total_page ?? page) > page)) throw fail();\n break;\n }\n const info = result.data.page_info;\n if (!result.data.list.length || !info || info.total_page === undefined || page >= info.total_page) break;\n }\n if (!chunk.every(id => seen.has(id))) throw new AdportError('INVALID_INPUT', 'Not every selected native product ID could be verified. Refresh the selection before previewing.');\n }\n rows.sort((a, b) => String(a.product_id).localeCompare(String(b.product_id)));bound(rows);\n return rows;\n }\n async context(value: unknown) {\n const input = catalogProductContext.parse(value), scope = catalogInput.parse({ account_id: input.account_id, bc_id: input.bc_id, catalog_id: input.catalog_id });\n const parent = await this.authorizeParent(scope), type = kind.parse(parent.catalog_type), feed = await this.feed(input), rows = await this.readSet(scope, type, input.product_ids, input.feed_id);\n return { catalog_type: type, expected_catalog_hash: parent.configuration_hash, expected_feed_hash: feed.configuration_hash, products_hash: digest({ ...scope, feed_id: input.feed_id, type, rows }),\n products: rows.map(row => ({ ...publicValue(row) as Row, external_identity: identity(type, row) })), records: rows.map(row => ({ id: String(row.product_id), name: String(row.title ?? row.name ?? row.series_name ?? row.destination_name ?? row.product_id), external_identity: identity(type, row) })), selection_complete: true, truncated: false,\n notes: ['Exact native product IDs verified in this catalog. This is not a complete catalog inventory.', 'Source URLs are represented by origin/fingerprint; native omitted fields remain unavailable. Volatile audit/delivery fields are excluded from the snapshot.', 'Product feed membership is checked by TikTok when processing the submission; a selected feed is not proof that every product belongs to it.'],\n };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n if (op.provider !== 'tiktok' || !this.supports(op.tool)) throw new AdportError('INVALID_INPUT', 'Unsupported TikTok product operation.');\n const upload = op.tool === 'tiktok_upsert_catalog_products', remove = op.tool === 'tiktok_delete_catalog_products';\n if (op.kind !== (remove ? 'remove' : 'update')) throw new AdportError('INVALID_INPUT', 'TikTok product operation kind differs.');\n bound(op.payload, true);\n const input = upload ? catalogProductUpsert.parse(op.payload) : remove ? catalogProductDelete.parse(op.payload) : catalogProductUpdate.parse(op.payload);\n const scope = { account_id: catalogId.parse(op.accountId), bc_id: input.bc_id, catalog_id: input.catalog_id };\n const parent = await this.authorizeParent(scope, true), type = kind.parse(parent.catalog_type), selectedFeed = { ...scope, feed_id: input.feed_id }, feed = await this.feed(selectedFeed);\n if (type !== input.catalog_type || parent.configuration_hash !== input.expected_catalog_hash || feed.configuration_hash !== input.expected_feed_hash) throw new AdportError('PENDING_MISMATCH', 'Catalog type/configuration or feed changed. Read it and request a fresh preview.');\n const updates = 'updates' in input ? input.updates : [], ids = 'product_ids' in input ? input.product_ids : updates.map(item => item.product_id);\n if (new Set(ids).size !== ids.length) throw new AdportError('INVALID_INPUT', 'Product update IDs must be unique.');\n const current = upload ? [] : await this.readSet(scope, type, ids, input.feed_id);\n if ('expected_products_hash' in input && digest({ ...scope, feed_id: input.feed_id, type, rows: current }) !== input.expected_products_hash) throw new AdportError('PENDING_MISMATCH', 'Selected products changed. Read product context and request a fresh preview.');\n let products: Row[] = [], selector: string | undefined;\n const assets = 'media_assets' in input ? input.media_assets : [];\n if ('products' in input) {\n products = (await this.mediaProducts(input.products, assets)).map(row => parseProduct(type, row));\n const keys = products.map(row => canonical(identity(type, row)));\n if (new Set(keys).size !== keys.length) throw new AdportError('INVALID_INPUT', 'Product external identities must be unique.');\n } else if (!remove) {\n const patched = await this.mediaProducts(updates.map(update => update.fields), assets);\n products = updates.map((update, index) => {\n const row = current.find(row => row.product_id === update.product_id)!;\n if (!Object.keys(patched[index]!).length || productIdentityFields[type].some(key => Object.hasOwn(update.fields, key))) throw new AdportError('INVALID_INPUT', 'Supply editable product fields; external identities cannot be changed.');\n return { ...parseProduct(type, patched[index]!, true), ...identity(type, row) };\n });\n } else {\n selector = productDeleteFields[type];\n if (!selector) throw new AdportError('INVALID_INPUT', 'The official product-delete contract does not document an Entertainment selector. No deletion request was sent.');\n const max = ['GENERIC', 'ONLINE_TO_OFFLINE'].includes(type) ? 10000 : 1000;\n if (ids.length > max) throw new AdportError('INVALID_INPUT', `This native catalog deletion permits at most ${max} products. Use smaller batches.`);\n }\n const externalIds = remove ? current.map(row => type === 'FLIGHT' ? row.flight_id : Object.values(identity(type, row))[0]) : [];\n if (externalIds.some(id => typeof id !== 'string' || !id.length) || new Set(externalIds).size !== externalIds.length) throw new AdportError('INVALID_INPUT', 'Deletion requires unique verified external product IDs.');\n const body = { bc_id: input.bc_id, catalog_id: input.catalog_id, feed_id: input.feed_id, ...(remove ? { [selector!]: externalIds } : { products }) };\n bound(body, true);\n const title = remove ? 'Remove catalog products' : upload ? 'Upload catalog products' : 'Edit catalog products', count = remove ? ids.length : products.length;\n const reviewFields: ReviewField[] = [{ label: 'Catalog type', after: type }, { label: 'Feed', after: input.feed_id }, { label: 'Products', after: count }, { label: 'Payload SHA-256', after: digest(body) }];\n let reviewTruncated = count > 20;\n for (let index = 0; index < Math.min(count, 20); index++) {\n const source = upload ? undefined : current.find(row => row.product_id === ids[index]), proposed = products[index];\n if (remove) reviewFields.push({ label: 'Remove product', after: { product_id: source!.product_id, external_identity: identity(type, source!) } });\n else {\n const subject = Object.values(identity(type, proposed!)).join(' → '), fields = leaves(proposed!).filter(([path]) => !productIdentityFields[type].includes(path));\n for (const [path, value] of fields) {\n if (reviewFields.length >= 44) { reviewTruncated = true;break; }\n const before = source ? atPath(source, path) : undefined;\n reviewFields.push({ label: `${subject} · ${path.replaceAll('_', ' ')}`, ...(source ? { before: before === undefined ? 'Not reported' : publicValue(before, path) } : {}), after: publicValue(value, path) });\n }\n }\n }\n if (assets.length) reviewFields.push({ label: 'Adport media', after: assets });\n const notes = ['Local preview only. TikTok validates native permissions, product fields and feed membership during asynchronous processing.', 'Shared catalog changes can change existing ads wherever products or product sets are used; no ad status or budget is changed.', 'Acceptance is not completed processing, product audit approval or ad eligibility. Inspect the exact native job, then read product context.', 'TikTok permits one active product operation per catalog. Wait for prior jobs; busy/uncertain submissions are never automatically retried.', ...(assets.length ? ['Media bytes/checksums are verified at preview and apply. Private download grants are minted only at apply; the payload hash binds logical media references, not an expiring URL.', 'Images require at least 500×500 pixels. Native media fetching/audit and any ongoing URL refetch behavior remain unverified; grants expire.'] : []), ...(upload ? ['Incremental upsert: uploading an existing external identity may replace its product data. Existing configuration was not inspected by this upsert preview.'] : remove ? ['Removal cannot be undone through this operation; historical reporting may remain.'] : ['Only supplied top-level fields are sent. Nested-object merge behavior remains native; no unverified preservation is promised.']), ...(reviewTruncated ? [`Review is limited to 20 products and 40 editable fields from ${count} products; the full submitted payload is bound by its SHA-256 and identical-argument approval.`] : [])];\n return { summary: `${title} · ${count} ${type}`, changes: [`${remove ? '-' : '~'} ${count} selected ${type} products in catalog ${input.catalog_id}, feed ${input.feed_id}.`, `Approved native payload SHA-256 ${digest(body)}.`], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'tiktok', accountId: scope.account_id, kind: op.kind, title, subject: `${count} products`, fields: reviewFields, notices: notes }, execute: async () => {\n await this.authorizeParent(scope, true);\n let nativeBody = body;\n if (assets.length) {\n const sourceRows = 'products' in input ? input.products : updates.map(update => update.fields), resolved = await this.mediaProducts(sourceRows, assets, true);\n nativeBody = { ...body, products: resolved.map((row, index) => upload ? parseProduct(type, row) : { ...parseProduct(type, row, true), ...identity(type, current.find(value => value.product_id === ids[index])!) }) };\n bound(nativeBody, true);\n }\n let result: unknown;\n try { result = await this.client.post(`catalog/product/${remove ? 'delete' : upload ? 'upload' : 'update'}`, nativeBody); }\n catch { throw new AdportError('PROVIDER_ERROR', 'TikTok product submission was not confirmed. Inspect native jobs before another preview; no request was retried.'); }\n const parsed = z.object({ feed_log_id: nativeId }).safeParse(result);\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'TikTok did not return a safe product task ID. Inspect native jobs before retrying; no request was replayed.');\n const job = parsed.data.feed_log_id;\n try {\n const result = await this.products.log({ ...selectedFeed, feed_log_id: job });\n if (result.log.process_status === 'FAILED' || (result.log.error_count ?? 0) > 0) throw new Error('Native job failed or has item errors');\n } catch { throw new AdportError('PROVIDER_ERROR', 'Product task was accepted but processing or exact feed/catalog readback is unconfirmed. Reconcile this ID; do not replay the mutation.', { resourceIds: [job], feed_log_id: job, feed_id: input.feed_id, catalog_id: input.catalog_id }); }\n return [job];\n } };\n }\n}\n","// Structural field facts from TikTok's official product upload/update docs, fetched 2026-11-05.\n// Sources: portal/docs?id=1740497429681153 and portal/docs?id=1740562287852546.\n// Both endpoints expose the same fields/types; update permits partial fields.\nexport const catalogProductKinds = [\"ECOM\", \"HOTEL\", \"FLIGHT\", \"DESTINATION\", \"ENTERTAINMENT\", \"AUTO_VEHICLE\", \"AUTO_MODEL\", \"MINI_SERIES\", \"GENERIC\", \"ONLINE_TO_OFFLINE\"] as const;\nexport type CatalogProductKind = (typeof catalogProductKinds)[number];\nexport interface ProductFieldContract { path: string; type: string; required: boolean; max?: number; enum?: string[] }\nexport const catalogProductFields: Record<CatalogProductKind, ProductFieldContract[]> = {\n ECOM: [{\"path\":\"sku_id\",\"type\":\"string\",\"required\":true,\"max\":100},{\"path\":\"title\",\"type\":\"string\",\"required\":true,\"max\":500},{\"path\":\"description\",\"type\":\"string\",\"required\":true,\"max\":10000},{\"path\":\"availability\",\"type\":\"string\",\"required\":true,\"enum\":[\"IN_STOCK\",\"AVAILABLE_FOR_ORDER\",\"PREORDER\",\"OUT_OF_STOCK\",\"DISCONTINUED\"]},{\"path\":\"brand\",\"type\":\"string\",\"required\":true,\"max\":150},{\"path\":\"image_url\",\"type\":\"string\",\"required\":true},{\"path\":\"additional_image_urls\",\"type\":\"string[]\",\"required\":false,\"max\":10},{\"path\":\"video_url\",\"type\":\"string\",\"required\":false},{\"path\":\"item_group_id\",\"type\":\"string\",\"required\":false},{\"path\":\"google_product_category\",\"type\":\"string\",\"required\":false},{\"path\":\"global_trade_item_number\",\"type\":\"string\",\"required\":false},{\"path\":\"manufacturer_part_number\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail\",\"type\":\"object\",\"required\":true},{\"path\":\"product_detail.condition\",\"type\":\"string\",\"required\":true,\"enum\":[\"NEW\",\"REFURBISHED\",\"USED\"]},{\"path\":\"product_detail.age_group\",\"type\":\"string\",\"required\":false,\"enum\":[\"NEW_BORN\",\"INFANT\",\"TODDLER\",\"KIDS\",\"ADULT\"]},{\"path\":\"product_detail.color\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"product_detail.gender\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.material\",\"type\":\"string\",\"required\":false,\"max\":200},{\"path\":\"product_detail.pattern\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"product_detail.product_category\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.shipping\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.shipping_weight\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.size\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.tax\",\"type\":\"string\",\"required\":false},{\"path\":\"price_info\",\"type\":\"object\",\"required\":true},{\"path\":\"price_info.price\",\"type\":\"float\",\"required\":true},{\"path\":\"price_info.currency\",\"type\":\"string\",\"required\":false},{\"path\":\"price_info.sale_price\",\"type\":\"float\",\"required\":false},{\"path\":\"price_info.sale_price_effective_date\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page\",\"type\":\"object\",\"required\":true},{\"path\":\"landing_page.landing_page_url\",\"type\":\"string\",\"required\":true},{\"path\":\"landing_page.ios_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_app_store_id\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_app_name\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.iphone_app_store_id\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.iphone_app_name\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ipad_app_store_id\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ipad_app_name\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_package\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_app_name\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info\",\"type\":\"object\",\"required\":false},{\"path\":\"extra_info.custom_label_0\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_1\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_2\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_3\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_4\",\"type\":\"string\",\"required\":false}],\n HOTEL: [{\"path\":\"hotel_id\",\"type\":\"string\",\"required\":true,\"max\":100},{\"path\":\"name\",\"type\":\"string\",\"required\":true,\"max\":150},{\"path\":\"description\",\"type\":\"string\",\"required\":false,\"max\":10000},{\"path\":\"availability\",\"type\":\"string\",\"required\":false,\"enum\":[\"IN_STOCK\",\"OUT_OF_STOCK\"]},{\"path\":\"brand\",\"type\":\"string\",\"required\":true,\"max\":150},{\"path\":\"image_url\",\"type\":\"string\",\"required\":true},{\"path\":\"additional_image_urls\",\"type\":\"string[]\",\"required\":false,\"max\":20},{\"path\":\"video_url\",\"type\":\"string\",\"required\":false},{\"path\":\"hotel_category\",\"type\":\"string[]\",\"required\":false,\"max\":3},{\"path\":\"hotel_retailer_id\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"address\",\"type\":\"object\",\"required\":true},{\"path\":\"address.address\",\"type\":\"string\",\"required\":true,\"max\":150},{\"path\":\"address.secondary_address\",\"type\":\"string\",\"required\":false,\"max\":150},{\"path\":\"address.tertiary_address\",\"type\":\"string\",\"required\":false,\"max\":150},{\"path\":\"address.city\",\"type\":\"string\",\"required\":true,\"max\":150},{\"path\":\"address.region\",\"type\":\"string\",\"required\":false,\"max\":150},{\"path\":\"address.country\",\"type\":\"string\",\"required\":true,\"max\":150},{\"path\":\"neighborhood\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"postal_code\",\"type\":\"string\",\"required\":false,\"max\":150},{\"path\":\"latitude\",\"type\":\"float\",\"required\":false},{\"path\":\"longitude\",\"type\":\"float\",\"required\":false},{\"path\":\"margin_level\",\"type\":\"integer\",\"required\":false},{\"path\":\"loyalty_program\",\"type\":\"string\",\"required\":false},{\"path\":\"guest_ratings\",\"type\":\"object[]\",\"required\":false,\"max\":1},{\"path\":\"guest_ratings.rating_system\",\"type\":\"string\",\"required\":false,\"max\":150},{\"path\":\"guest_ratings.max_score\",\"type\":\"integer\",\"required\":false},{\"path\":\"guest_ratings.score\",\"type\":\"float\",\"required\":false},{\"path\":\"guest_ratings.number_of_reviewers\",\"type\":\"integer\",\"required\":false},{\"path\":\"star_rating\",\"type\":\"integer\",\"required\":false},{\"path\":\"room_type\",\"type\":\"string[]\",\"required\":false,\"max\":3},{\"path\":\"priority\",\"type\":\"integer\",\"required\":false},{\"path\":\"price_info\",\"type\":\"object\",\"required\":true},{\"path\":\"price_info.price\",\"type\":\"float\",\"required\":true},{\"path\":\"price_info.currency\",\"type\":\"string\",\"required\":false},{\"path\":\"price_info.sale_price\",\"type\":\"float\",\"required\":false},{\"path\":\"landing_page\",\"type\":\"object\",\"required\":false},{\"path\":\"landing_page.landing_page_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_app_store_id\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_app_name\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_package\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_app_name\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info\",\"type\":\"object\",\"required\":false},{\"path\":\"extra_info.custom_label_0\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_1\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_2\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_3\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_4\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.internal_label_0\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"extra_info.internal_label_1\",\"type\":\"string\",\"required\":false,\"max\":100}],\n FLIGHT: [{\"path\":\"origin_airport\",\"type\":\"string\",\"required\":true},{\"path\":\"destination_airport\",\"type\":\"string\",\"required\":true},{\"path\":\"origin_city\",\"type\":\"string\",\"required\":false,\"max\":150},{\"path\":\"destination_city\",\"type\":\"string\",\"required\":false,\"max\":150},{\"path\":\"description\",\"type\":\"string\",\"required\":false,\"max\":10000},{\"path\":\"cabin_class\",\"type\":\"string\",\"required\":false,\"enum\":[\"FIRST_CLASS\",\"FIRST_CLASS_SUITE\",\"BUSINESS_CLASS\",\"BUSINESS_CLASS_SUITE\",\"COMFORT_CLASS\",\"ECONOMY_CLASS\",\"BASIC_ECONOMY\",\"STANDARD_ECONOMY\",\"PREMIUM_ECONOMY\",\"LIE_FLAT_SEAT\",\"CHARTER_CLASS\",\"ELITE_CLASS\",\"QUIET_CLASS\"]},{\"path\":\"airline_company\",\"type\":\"string\",\"required\":false,\"enum\":[\"AEROFLOT\",\"AIR_FRANCE_KLM_GROUP\",\"ALASKA_AIRLINES\",\"ANA\",\"AMERICAN_AIRLINES\",\"BRITISH_AIRWAYS\",\"CATHAY_PACIFIC\",\"CHINA_SOUTHERN_AIRLINES\",\"CHINA_EASTERN_AIRLINES\",\"DELTA_AIR_LINES\",\"EMIRATES\",\"JAPAN_AIRLINES\",\"JETBLUE_AIRWAYS\",\"KLM_ROYAL_DUTCH_AIRLINES\",\"LUFTHANSA_GROUP\",\"QANTAS_AIRWAYS\",\"QATAR_AIRWAYS\",\"SINGAPORE_AIRLINES\",\"SOUTHWEST_AIRLINES\",\"TURKISH_AIRLINES\",\"UNITED_AIRLINES\",\"VIRGIN_ATLANTIC\"]},{\"path\":\"image_url\",\"type\":\"string\",\"required\":true},{\"path\":\"additional_image_urls\",\"type\":\"string[]\",\"required\":false,\"max\":20},{\"path\":\"video_url\",\"type\":\"string\",\"required\":false},{\"path\":\"priority\",\"type\":\"integer\",\"required\":false},{\"path\":\"price_info\",\"type\":\"object\",\"required\":false},{\"path\":\"price_info.price\",\"type\":\"float\",\"required\":false},{\"path\":\"price_info.currency\",\"type\":\"string\",\"required\":false},{\"path\":\"price_info.sale_price\",\"type\":\"float\",\"required\":false},{\"path\":\"landing_page\",\"type\":\"object\",\"required\":false},{\"path\":\"landing_page.landing_page_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_app_store_id\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_app_name\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_package\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_app_name\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info\",\"type\":\"object\",\"required\":false},{\"path\":\"extra_info.custom_label_0\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_1\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_2\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_3\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_4\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.internal_label_0\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"extra_info.internal_label_1\",\"type\":\"string\",\"required\":false,\"max\":100}],\n DESTINATION: [{\"path\":\"destination_id\",\"type\":\"string\",\"required\":true,\"max\":100},{\"path\":\"destination_name\",\"type\":\"string\",\"required\":true,\"max\":150},{\"path\":\"description\",\"type\":\"string\",\"required\":true,\"max\":10000},{\"path\":\"image_url\",\"type\":\"string\",\"required\":true},{\"path\":\"additional_image_urls\",\"type\":\"string[]\",\"required\":false,\"max\":10},{\"path\":\"video_url\",\"type\":\"string\",\"required\":false},{\"path\":\"address\",\"type\":\"object\",\"required\":true},{\"path\":\"address.address\",\"type\":\"string\",\"required\":true,\"max\":150},{\"path\":\"address.city\",\"type\":\"string\",\"required\":true,\"max\":150},{\"path\":\"address.region\",\"type\":\"string\",\"required\":true,\"max\":150},{\"path\":\"address.country\",\"type\":\"string\",\"required\":true,\"max\":150},{\"path\":\"neighborhood\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"postal_code\",\"type\":\"string\",\"required\":false},{\"path\":\"latitude\",\"type\":\"float\",\"required\":false},{\"path\":\"longitude\",\"type\":\"float\",\"required\":false},{\"path\":\"types\",\"type\":\"string[]\",\"required\":true,\"max\":20},{\"path\":\"price_info\",\"type\":\"object\",\"required\":false},{\"path\":\"price_info.price\",\"type\":\"float\",\"required\":false},{\"path\":\"price_info.currency\",\"type\":\"string\",\"required\":false},{\"path\":\"price_info.sale_price\",\"type\":\"float\",\"required\":false},{\"path\":\"landing_page\",\"type\":\"object\",\"required\":false},{\"path\":\"landing_page.landing_page_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_app_store_id\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_app_name\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_package\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_app_name\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info\",\"type\":\"object\",\"required\":false},{\"path\":\"extra_info.custom_label_0\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_1\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_2\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_3\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_4\",\"type\":\"string\",\"required\":false}],\n ENTERTAINMENT: [{\"path\":\"media_title_id\",\"type\":\"string\",\"required\":true,\"max\":100},{\"path\":\"title\",\"type\":\"string\",\"required\":true,\"max\":150},{\"path\":\"description\",\"type\":\"string\",\"required\":false,\"max\":10000},{\"path\":\"image_url\",\"type\":\"string\",\"required\":true},{\"path\":\"video_url\",\"type\":\"string\",\"required\":false},{\"path\":\"additional_image_urls\",\"type\":\"string[]\",\"required\":false,\"max\":20},{\"path\":\"genres\",\"type\":\"string[]\",\"required\":false,\"max\":2},{\"path\":\"qid\",\"type\":\"string\",\"required\":false,\"max\":150},{\"path\":\"price_info\",\"type\":\"object\",\"required\":false},{\"path\":\"price_info.price\",\"type\":\"float\",\"required\":false},{\"path\":\"price_info.currency\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page\",\"type\":\"object\",\"required\":false},{\"path\":\"landing_page.landing_page_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_app_store_id\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_app_name\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_package\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_app_name\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info\",\"type\":\"object\",\"required\":false},{\"path\":\"extra_info.custom_label_0\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_1\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_2\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_3\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_4\",\"type\":\"string\",\"required\":false}],\n AUTO_VEHICLE: [{\"path\":\"vehicle_id\",\"type\":\"string\",\"required\":true,\"max\":100},{\"path\":\"title\",\"type\":\"string\",\"required\":true,\"max\":500},{\"path\":\"description\",\"type\":\"string\",\"required\":true,\"max\":5000},{\"path\":\"availability\",\"type\":\"string\",\"required\":false,\"enum\":[\"AVAILABLE\",\"NOT_AVAILABLE\"]},{\"path\":\"image_url\",\"type\":\"string\",\"required\":true},{\"path\":\"additional_image_urls\",\"type\":\"string[]\",\"required\":false,\"max\":20},{\"path\":\"video_url\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail\",\"type\":\"object\",\"required\":false},{\"path\":\"product_detail.condition\",\"type\":\"string\",\"required\":false,\"enum\":[\"EXCELLENT\",\"GOOD\",\"FAIR\",\"POOR\",\"OTHER\"]},{\"path\":\"product_detail.offer_type\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"product_detail.term_length\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"product_detail.offer_term_qualifier\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"product_detail.amount_price\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.amount_percentage\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"product_detail.amount_qualifier\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"product_detail.downpayment\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.downpayment_qualifier\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"product_detail.offer_disclaimer\",\"type\":\"string\",\"required\":false,\"max\":5000},{\"path\":\"product_detail.offer_disclaimer_url\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.emission_disclaimer\",\"type\":\"string\",\"required\":false,\"max\":5000},{\"path\":\"product_detail.emission_disclaimer_url\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.emission_overlay_disclaimer\",\"type\":\"string\",\"required\":false,\"max\":500},{\"path\":\"product_detail.emission_image_link\",\"type\":\"string\",\"required\":false},{\"path\":\"state_of_vehicle\",\"type\":\"string\",\"required\":true,\"enum\":[\"NEW\",\"USED\",\"CPO\"]},{\"path\":\"vehicle_type\",\"type\":\"string\",\"required\":false,\"enum\":[\"BOAT\",\"CAR_TRUCK\",\"COMMERCIAL\",\"MOTORCYCLE\",\"POWERSPORT\",\"RV_CAMPER\",\"TRAILER\",\"OTHER\"]},{\"path\":\"make\",\"type\":\"string\",\"required\":true,\"max\":100},{\"path\":\"model\",\"type\":\"string\",\"required\":true,\"max\":100},{\"path\":\"trim\",\"type\":\"string\",\"required\":false,\"max\":50},{\"path\":\"year\",\"type\":\"integer\",\"required\":true},{\"path\":\"vin\",\"type\":\"string\",\"required\":false,\"max\":17},{\"path\":\"mileage\",\"type\":\"object\",\"required\":true},{\"path\":\"mileage.value\",\"type\":\"integer\",\"required\":true},{\"path\":\"mileage.unit\",\"type\":\"string\",\"required\":true,\"enum\":[\"MILE\",\"KILOMETER\"]},{\"path\":\"body_style\",\"type\":\"string\",\"required\":true,\"enum\":[\"CONVERTIBLE\",\"COUPE\",\"CROSSOVER\",\"HATCHBACK\",\"MINIVAN\",\"SMALL_CAR\",\"SEDAN\",\"SUV\",\"TRUCK\",\"VAN\",\"WAGON\",\"OTHER\"]},{\"path\":\"exterior_color\",\"type\":\"string\",\"required\":true,\"max\":100},{\"path\":\"interior_color\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"transmission\",\"type\":\"string\",\"required\":false,\"enum\":[\"AUTOMATIC\",\"MANUAL\"]},{\"path\":\"drivetrain\",\"type\":\"string\",\"required\":false,\"enum\":[\"4X2\",\"4X4\",\"AWD\",\"FWD\",\"RWD\",\"OTHER\"]},{\"path\":\"fuel_type\",\"type\":\"string\",\"required\":false,\"enum\":[\"DIESEL\",\"ELECTRIC\",\"FLEX\",\"GASOLINE\",\"HYBRID\",\"OTHER\"]},{\"path\":\"address\",\"type\":\"object\",\"required\":true},{\"path\":\"address.address\",\"type\":\"string\",\"required\":true,\"max\":150},{\"path\":\"address.city\",\"type\":\"string\",\"required\":true,\"max\":150},{\"path\":\"address.region\",\"type\":\"string\",\"required\":true,\"max\":150},{\"path\":\"address.postal_code\",\"type\":\"string\",\"required\":true,\"max\":150},{\"path\":\"latitude\",\"type\":\"float\",\"required\":true},{\"path\":\"longitude\",\"type\":\"float\",\"required\":true},{\"path\":\"dealer\",\"type\":\"object\",\"required\":false},{\"path\":\"dealer.dealer_id\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"dealer.dealer_name\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"dealer.dealer_phone\",\"type\":\"string\",\"required\":false,\"max\":15},{\"path\":\"dealer.stock_number\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"date_first_on_lot\",\"type\":\"string\",\"required\":false},{\"path\":\"days_on_lot\",\"type\":\"integer\",\"required\":false},{\"path\":\"price_info\",\"type\":\"object\",\"required\":true},{\"path\":\"price_info.price\",\"type\":\"float\",\"required\":true},{\"path\":\"price_info.currency\",\"type\":\"string\",\"required\":false},{\"path\":\"price_info.sale_price\",\"type\":\"float\",\"required\":false},{\"path\":\"price_info.sale_price_effective_date\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page\",\"type\":\"object\",\"required\":true},{\"path\":\"landing_page.landing_page_url\",\"type\":\"string\",\"required\":true},{\"path\":\"landing_page.ios_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_url\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info\",\"type\":\"object\",\"required\":false},{\"path\":\"extra_info.custom_label_0\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_1\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_2\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_3\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_4\",\"type\":\"string\",\"required\":false}],\n AUTO_MODEL: [{\"path\":\"vehicle_id\",\"type\":\"string\",\"required\":true,\"max\":100},{\"path\":\"title\",\"type\":\"string\",\"required\":true,\"max\":128},{\"path\":\"image_url\",\"type\":\"string\",\"required\":true},{\"path\":\"video_url\",\"type\":\"string\",\"required\":false},{\"path\":\"make\",\"type\":\"string\",\"required\":true,\"max\":100},{\"path\":\"model\",\"type\":\"string\",\"required\":true,\"max\":100},{\"path\":\"trim\",\"type\":\"string\",\"required\":false,\"max\":50},{\"path\":\"year\",\"type\":\"integer\",\"required\":true},{\"path\":\"exterior_color\",\"type\":\"string\",\"required\":true,\"max\":100},{\"path\":\"product_detail\",\"type\":\"object\",\"required\":false},{\"path\":\"product_detail.offer_type\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"product_detail.term_length\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"product_detail.offer_term_qualifier\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"product_detail.amount_price\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.amount_percentage\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"product_detail.amount_qualifier\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"product_detail.downpayment\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.downpayment_qualifier\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"product_detail.offer_disclaimer\",\"type\":\"string\",\"required\":false,\"max\":5000},{\"path\":\"product_detail.offer_disclaimer_url\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.emission_disclaimer\",\"type\":\"string\",\"required\":false,\"max\":5000},{\"path\":\"product_detail.emission_disclaimer_url\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.emission_overlay_disclaimer\",\"type\":\"string\",\"required\":false,\"max\":500},{\"path\":\"product_detail.emission_image_link\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page\",\"type\":\"object\",\"required\":true},{\"path\":\"landing_page.landing_page_url\",\"type\":\"string\",\"required\":true}],\n MINI_SERIES: [{\"path\":\"series_id\",\"type\":\"string\",\"required\":true,\"max\":100},{\"path\":\"series_name\",\"type\":\"string\",\"required\":true,\"max\":100},{\"path\":\"target_config\",\"type\":\"object\",\"required\":false},{\"path\":\"target_config.region_code\",\"type\":\"string\",\"required\":false},{\"path\":\"image_url\",\"type\":\"string\",\"required\":true},{\"path\":\"video_url\",\"type\":\"string\",\"required\":false},{\"path\":\"recharge\",\"type\":\"object[]\",\"required\":true},{\"path\":\"recharge.type\",\"type\":\"string\",\"required\":true,\"enum\":[\"BY_TIERS\",\"SUBSCRIPTION\",\"BY_EPISODES\"]},{\"path\":\"recharge.purchase_unit\",\"type\":\"string[]\",\"required\":true},{\"path\":\"recharge.cost\",\"type\":\"float[]\",\"required\":true},{\"path\":\"product_detail\",\"type\":\"object\",\"required\":true},{\"path\":\"product_detail.company_type\",\"type\":\"string\",\"required\":false,\"enum\":[\"COPYRIGHT_HOLDER\",\"DISTRIBUTOR\"]},{\"path\":\"product_detail.copyright_holder_name\",\"type\":\"string\",\"required\":false,\"max\":100},{\"path\":\"product_detail.app_id\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.minis_id\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.total_episodes\",\"type\":\"number\",\"required\":true},{\"path\":\"product_detail.initial_paid_episodes\",\"type\":\"number\",\"required\":true},{\"path\":\"product_detail.per_episode_duration\",\"type\":\"number\",\"required\":false},{\"path\":\"product_detail.spoken_language\",\"type\":\"string\",\"required\":true,\"enum\":[\"ar\",\"de\",\"cs\",\"en\",\"es\",\"fr\",\"he\",\"hi\",\"id\",\"it\",\"ja\",\"ko\",\"ms\",\"pl\",\"pt\",\"ro\",\"ru\",\"ta\",\"th\",\"tr\",\"vi\",\"zh\",\"zh-hant\"]},{\"path\":\"product_detail.subtitle_language\",\"type\":\"string\",\"required\":true,\"enum\":[\"ar\",\"de\",\"cs\",\"en\",\"es\",\"fr\",\"he\",\"hi\",\"id\",\"it\",\"ja\",\"ko\",\"ms\",\"pl\",\"pt\",\"ro\",\"ru\",\"ta\",\"th\",\"tr\",\"vi\",\"zh\",\"zh-hant\"]},{\"path\":\"product_detail.production_type\",\"type\":\"string\",\"required\":true,\"enum\":[\"LOCAL\",\"TRANSLATION\"]},{\"path\":\"product_detail.target_audience\",\"type\":\"string\",\"required\":true,\"enum\":[\"MALE\",\"FEMALE\",\"NEUTRAL\"]},{\"path\":\"product_detail.characters\",\"type\":\"string[]\",\"required\":true,\"max\":3},{\"path\":\"product_detail.genres\",\"type\":\"string[]\",\"required\":true,\"max\":3},{\"path\":\"product_detail.historical_context\",\"type\":\"string[]\",\"required\":false,\"max\":3},{\"path\":\"product_detail.actors\",\"type\":\"string[]\",\"required\":false,\"max\":20}],\n GENERIC: [{\"path\":\"item_id\",\"type\":\"string\",\"required\":true,\"max\":100},{\"path\":\"title\",\"type\":\"string\",\"required\":true,\"max\":500},{\"path\":\"description\",\"type\":\"string\",\"required\":false,\"max\":5000},{\"path\":\"availability\",\"type\":\"string\",\"required\":false,\"enum\":[\"IN_STOCK\",\"AVAILABLE\",\"PREORDER\",\"OUT_OF_STOCK\",\"DISCONTINUED\",\"UNAVAILABLE\"]},{\"path\":\"image_url\",\"type\":\"string\",\"required\":true},{\"path\":\"video_url\",\"type\":\"string\",\"required\":false},{\"path\":\"additional_image_urls\",\"type\":\"string[]\",\"required\":false},{\"path\":\"address\",\"type\":\"object\",\"required\":false},{\"path\":\"address.street\",\"type\":\"string\",\"required\":false,\"max\":150},{\"path\":\"address.city\",\"type\":\"string\",\"required\":false,\"max\":150},{\"path\":\"address.region\",\"type\":\"string\",\"required\":false,\"max\":150},{\"path\":\"address.postal_code\",\"type\":\"string\",\"required\":false,\"max\":150},{\"path\":\"longitude\",\"type\":\"double\",\"required\":false},{\"path\":\"latitude\",\"type\":\"double\",\"required\":false},{\"path\":\"product_detail\",\"type\":\"object\",\"required\":false},{\"path\":\"product_detail.rating\",\"type\":\"double\",\"required\":false},{\"path\":\"product_detail.availability_type\",\"type\":\"string\",\"required\":false,\"enum\":[\"REGION\",\"DMA\",\"RADIUS\",\"POSTAL_CODE\"]},{\"path\":\"product_detail.availability_region\",\"type\":\"string[][]\",\"required\":false},{\"path\":\"product_detail.availability_dma\",\"type\":\"string[]\",\"required\":false},{\"path\":\"product_detail.availability_circle_radius\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.availability_circle_radius_unit\",\"type\":\"string\",\"required\":false,\"enum\":[\"KM\",\"MI\"]},{\"path\":\"product_detail.availability_postal_codes\",\"type\":\"string[]\",\"required\":false},{\"path\":\"product_detail.custom_number_0\",\"type\":\"double\",\"required\":false},{\"path\":\"product_detail.custom_number_1\",\"type\":\"double\",\"required\":false},{\"path\":\"product_detail.custom_number_2\",\"type\":\"double\",\"required\":false},{\"path\":\"product_detail.custom_number_3\",\"type\":\"double\",\"required\":false},{\"path\":\"product_detail.custom_number_4\",\"type\":\"double\",\"required\":false},{\"path\":\"price_info\",\"type\":\"object\",\"required\":false},{\"path\":\"price_info.price\",\"type\":\"double\",\"required\":false},{\"path\":\"price_info.currency\",\"type\":\"string\",\"required\":false},{\"path\":\"price_info.sale_price\",\"type\":\"double\",\"required\":false},{\"path\":\"landing_page\",\"type\":\"object\",\"required\":false},{\"path\":\"landing_page.landing_page_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_app_store_id\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_app_name\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_package\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_app_name\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info\",\"type\":\"object\",\"required\":false},{\"path\":\"extra_info.custom_label_0\",\"type\":\"string\",\"required\":false,\"max\":500},{\"path\":\"extra_info.custom_label_1\",\"type\":\"string\",\"required\":false,\"max\":500},{\"path\":\"extra_info.custom_label_2\",\"type\":\"string\",\"required\":false,\"max\":500},{\"path\":\"extra_info.custom_label_3\",\"type\":\"string\",\"required\":false,\"max\":500},{\"path\":\"extra_info.custom_label_4\",\"type\":\"string\",\"required\":false,\"max\":500},{\"path\":\"extra_info.custom_label_5\",\"type\":\"string\",\"required\":false,\"max\":500},{\"path\":\"extra_info.custom_label_6\",\"type\":\"string\",\"required\":false,\"max\":500}],\n ONLINE_TO_OFFLINE: [{\"path\":\"listing_id\",\"type\":\"string\",\"required\":true},{\"path\":\"title\",\"type\":\"string\",\"required\":true},{\"path\":\"description\",\"type\":\"string\",\"required\":true,\"max\":5000},{\"path\":\"availability\",\"type\":\"string\",\"required\":true,\"enum\":[\"IN_STOCK\",\"AVAILABLE_FOR_ORDER\",\"PREORDER\",\"OUT_OF_STOCK\",\"DISCONTINUED\"]},{\"path\":\"image_url\",\"type\":\"string\",\"required\":true},{\"path\":\"brand\",\"type\":\"string\",\"required\":false,\"max\":150},{\"path\":\"google_product_category\",\"type\":\"string\",\"required\":false},{\"path\":\"item_group_id\",\"type\":\"string\",\"required\":false},{\"path\":\"additional_image_urls\",\"type\":\"string[]\",\"required\":false,\"max\":20},{\"path\":\"global_trade_item_number\",\"type\":\"string\",\"required\":false},{\"path\":\"address\",\"type\":\"object\",\"required\":false},{\"path\":\"address.street\",\"type\":\"string\",\"required\":false,\"max\":150},{\"path\":\"address.city\",\"type\":\"string\",\"required\":false,\"max\":150},{\"path\":\"address.region\",\"type\":\"string\",\"required\":false,\"max\":150},{\"path\":\"address.postal_code\",\"type\":\"string\",\"required\":false,\"max\":150},{\"path\":\"longitude\",\"type\":\"float\",\"required\":false},{\"path\":\"latitude\",\"type\":\"float\",\"required\":false},{\"path\":\"product_detail\",\"type\":\"object\",\"required\":false},{\"path\":\"product_detail.product_category\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.rating\",\"type\":\"double\",\"required\":false},{\"path\":\"product_detail.condition\",\"type\":\"string\",\"required\":false,\"enum\":[\"NEW\",\"USED\",\"REFURBISHED\"]},{\"path\":\"product_detail.color\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.size\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.material\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.pattern\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.tax\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.age_group\",\"type\":\"string\",\"required\":false,\"enum\":[\"NEW_BORN\",\"INFANT\",\"TODDLER\",\"KIDS\",\"ADULT\"]},{\"path\":\"product_detail.gender\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.availability_circle_radius\",\"type\":\"string\",\"required\":false},{\"path\":\"product_detail.availability_circle_radius_unit\",\"type\":\"string\",\"required\":false,\"enum\":[\"KM\",\"MI\"]},{\"path\":\"product_detail.custom_number_0\",\"type\":\"double\",\"required\":false},{\"path\":\"product_detail.custom_number_1\",\"type\":\"double\",\"required\":false},{\"path\":\"product_detail.custom_number_2\",\"type\":\"double\",\"required\":false},{\"path\":\"product_detail.custom_number_3\",\"type\":\"double\",\"required\":false},{\"path\":\"product_detail.custom_number_4\",\"type\":\"double\",\"required\":false},{\"path\":\"price_info\",\"type\":\"object\",\"required\":false},{\"path\":\"price_info.price\",\"type\":\"float\",\"required\":false},{\"path\":\"price_info.sale_price\",\"type\":\"float\",\"required\":false},{\"path\":\"price_info.sale_price_effective_date\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page\",\"type\":\"object\",\"required\":false},{\"path\":\"landing_page.landing_page_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_app_store_id\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.ios_app_name\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_url\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_package\",\"type\":\"string\",\"required\":false},{\"path\":\"landing_page.android_app_name\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info\",\"type\":\"object\",\"required\":false},{\"path\":\"extra_info.custom_label_0\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_1\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_2\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_3\",\"type\":\"string\",\"required\":false},{\"path\":\"extra_info.custom_label_4\",\"type\":\"string\",\"required\":false}],\n};\n","import { AdportError } from '@adport/core';\nimport { z } from 'zod';\nimport { catalogProductFields, catalogProductKinds, type CatalogProductKind, type ProductFieldContract } from './catalog-product-contract.js';\n\nexport { catalogProductKinds, type CatalogProductKind };\ntype Node = ProductFieldContract & { children: Record<string, Node> };\nexport const productIdentityFields: Record<CatalogProductKind, readonly string[]> = {\n ECOM: ['sku_id'], HOTEL: ['hotel_id'], FLIGHT: ['origin_airport', 'destination_airport'], DESTINATION: ['destination_id'], ENTERTAINMENT: ['media_title_id'],\n AUTO_VEHICLE: ['vehicle_id'], AUTO_MODEL: ['vehicle_id'], MINI_SERIES: ['series_id'], GENERIC: ['item_id'], ONLINE_TO_OFFLINE: ['listing_id'],\n};\nexport const productDeleteFields: Partial<Record<CatalogProductKind, string>> = { ECOM: 'sku_ids', HOTEL: 'hotel_ids', FLIGHT: 'flight_ids', DESTINATION: 'destination_ids', AUTO_VEHICLE: 'vehicle_ids', AUTO_MODEL: 'vehicle_ids', MINI_SERIES: 'series_ids', GENERIC: 'item_ids', ONLINE_TO_OFFLINE: 'listing_ids' };\nconst schemas = new Map<string, z.ZodObject>();\nexport function productShape(kind: CatalogProductKind, partial = false): z.ZodObject {\n const key = kind + ':' + partial, cached = schemas.get(key);if (cached) return cached;\n const roots: Record<string, Node> = {};\n for (const field of catalogProductFields[kind]) {\n const path = field.path.split('.');let children = roots;\n for (let index = 0; index < path.length; index++) {\n const part = path[index]!;\n if (index === path.length - 1) children[part] = { ...field, children: {} };\n const node = children[part];if (!node) throw new Error('Invalid product field contract');children = node.children;\n }\n }\n const object = (nodes: Record<string, Node>): z.ZodObject => z.strictObject(Object.fromEntries(Object.entries(nodes).map(([name, field]) => {\n const base = field.type.replace(/\\[\\]/g, ''), dimensions = (field.type.match(/\\[\\]/g) ?? []).length;\n let shape: z.ZodType = base === 'object' ? object(field.children) : base === 'string' ? field.enum?.length ? z.enum(field.enum as [string, ...string[]]) : !dimensions && field.max !== undefined ? z.string().max(field.max) : z.string() : base === 'integer' ? z.number().int().safe() : z.number().finite().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER);\n for (let index = 0; index < dimensions; index++) { const array = shape.array();shape = index === dimensions - 1 && field.max !== undefined ? array.max(field.max) : array; }\n return [name, !partial && field.required ? shape : shape.optional()];\n })));\n const result = object(roots);schemas.set(key, result);return result;\n}\nexport function parseProduct(kind: CatalogProductKind, value: unknown, partial = false): Record<string, unknown> {\n const parsed = productShape(kind, partial).safeParse(value);\n if (!parsed.success) throw new AdportError('INVALID_INPUT', 'Product fields do not match the selected catalog type. Read tiktok_catalog_product_schema for the native structural schema.');\n return parsed.data;\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { TikTokClient } from './client.js';\nimport { catalogId, catalogInput } from './catalog-schema.js';\nimport { creationScope, requireCatalogCreationAccess, requireCatalogAccess, type TikTokCatalogAccessStore } from './catalog-access.js';\n\nconst hash = z.string().regex(/^[a-f0-9]{64}$/), region = z.string().regex(/^[A-Z]{2}$/), currency = z.string().regex(/^[A-Z]{3}$/);\nconst types = ['ECOM', 'HOTEL', 'FLIGHT', 'DESTINATION', 'ENTERTAINMENT', 'AUTO_VEHICLE', 'AUTO_MODEL', 'MINI_SERIES', 'GENERIC', 'ONLINE_TO_OFFLINE'] as const;\nexport const catalogCreationInput = z.object({ account_id: catalogId, bc_id: catalogId }).strict();\nconst conf = z.object({ currency, region_code: region.optional(), is_multi_country: z.boolean().optional(), channel: z.enum(['PARTNER', 'CLIENT']).optional(), additional_config_list: z.array(z.object({ region_code: region, currency }).strict()).min(1).max(100).optional() }).strict();\nexport const catalogCreate = z.object({ bc_id: catalogId, name: z.string().trim().min(1).max(128), catalog_type: z.enum(types), catalog_conf: conf, expected_creation_access_hash: hash, expected_regions_hash: hash, acknowledge_new_catalog_management: z.literal(true) }).strict().superRefine((input, ctx) => {\n const c = input.catalog_conf;\n if (['ECOM', 'HOTEL', 'FLIGHT', 'DESTINATION'].includes(input.catalog_type) && c.is_multi_country === undefined) ctx.addIssue({ code: 'custom', path: ['catalog_conf', 'is_multi_country'], message: 'Adport requires an explicit immutable is_multi_country choice for this catalog type' });\n if (c.is_multi_country !== undefined && !['ECOM', 'HOTEL', 'FLIGHT', 'DESTINATION'].includes(input.catalog_type)) ctx.addIssue({ code: 'custom', path: ['catalog_conf', 'is_multi_country'], message: 'is_multi_country is documented only for ECOM/HOTEL/FLIGHT/DESTINATION' });\n if (c.is_multi_country ? c.region_code !== undefined : !c.region_code) ctx.addIssue({ code: 'custom', path: ['catalog_conf', 'region_code'], message: 'Choose a primary region for single-country catalogs; omit it for multi-country catalogs' });\n if (c.additional_config_list && (input.catalog_type !== 'MINI_SERIES' || new Set([c.region_code, ...c.additional_config_list.map(row => row.region_code)]).size !== c.additional_config_list.length + 1)) ctx.addIssue({ code: 'custom', path: ['catalog_conf', 'additional_config_list'], message: 'Additional regions are for MINI_SERIES only and cannot duplicate each other or the primary region' });\n});\nexport const catalogDelete = catalogInput.omit({ account_id: true }).extend({ expected_configuration_hash: hash, confirm_catalog_name: z.string().min(1).max(128), acknowledge_shared_effects: z.literal(true), acknowledge_delete_products_and_feeds: z.literal(true) }).strict();\ntype Scope = z.infer<typeof catalogInput>;\ntype Catalog = { catalog_id: string; catalog_name: string; catalog_type: string; catalog_conf: Record<string, unknown>; bc_info: { bc_id: string; bc_name?: string } };\ntype Parent = Catalog & { configuration_hash: string };\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<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 digest = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex');\nconst additional = (value: unknown) => canonical(z.array(z.object({ region_code: region, currency }).strict()).parse(value).sort((a, b) => a.region_code.localeCompare(b.region_code)));\nconst failure = (error: unknown, message: string, ids?: string[]) => {\n const details = error instanceof AdportError && error.details && typeof error.details === 'object' ? error.details as Record<string, unknown> : {};\n return new AdportError('PROVIDER_ERROR', message + ' Native bodies stay hidden; no write was retried.', { ...(Number.isSafeInteger(details.code) ? { provider_code: details.code } : {}), ...(typeof details.request_id === 'string' && /^[a-zA-Z0-9_-]{1,128}$/.test(details.request_id) ? { request_id: details.request_id } : {}), ...(ids ? { resourceIds: ids } : {}) });\n};\n\n/** Create delegation covers only exact new receipts, never existing Business Center catalogs. */\nexport class TikTokCatalogLifecycle {\n constructor(private readonly client: Pick<TikTokClient, 'get' | 'post'>, private readonly store: TikTokCatalogAccessStore | undefined, private readonly parent: (scope: Scope, write?: boolean) => Promise<Parent>, private readonly lookup: (scope: Scope) => Promise<Catalog | undefined>) {}\n async availableCountries(bcId: string) {\n catalogId.parse(bcId);let raw;\n try { raw = await this.client.get('catalog/available_country/get', { bc_id: bcId }); } catch (error) { throw failure(error, 'Native catalog-region lookup failed. Check the exact Business Center and token.'); }\n const parsed = z.object({ region_codes: z.array(region).max(500), bc_id: catalogId.optional() }).safeParse(raw);\n if (!parsed.success || parsed.data.bc_id !== undefined && parsed.data.bc_id !== bcId || new Set(parsed.data.region_codes).size !== parsed.data.region_codes.length) throw new AdportError('PROVIDER_ERROR', 'Catalog region response scope or shape could not be verified.');\n return parsed.data.region_codes.sort();\n }\n async context(value: unknown) {\n const input = catalogCreationInput.parse(value), grant = await requireCatalogCreationAccess(this.store, creationScope(input.account_id, input.bc_id)), regions = await this.availableCountries(input.bc_id);\n return { expected_creation_access_hash: grant.hash, expected_regions_hash: digest({ ...input, regions }), available_region_codes: regions, catalog_types: [...types], records: [{ id: input.bc_id, name: 'Catalog creation', business_center_id: input.bc_id, access: 'Create and manage new catalogs', available_region_count: regions.length }], complete: true, truncated: false,\n notes: ['Owner delegation covers creation in this exact Business Center and management of successfully verified new catalog IDs. It grants no access to existing catalogs.', 'Region discovery does not certify catalog-type/currency combinations or native creation eligibility. Entertainment, mini-series and some multi-country types need native allowlisting.', 'Catalog type, region, currency, channel and additional regions are immutable configuration. Creation adds no products, ads, spend or events.'] };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n if (op.provider !== 'tiktok') throw new AdportError('INVALID_INPUT', 'Catalog lifecycle provider differs.');\n if (op.tool === 'tiktok_create_catalog' && op.kind === 'create') {\n const input = catalogCreate.parse(op.payload), selection = { account_id: op.accountId, bc_id: input.bc_id }, store = this.store;\n if (!store?.adoptCreated) throw new AdportError('NOT_CONNECTED', 'This runtime cannot adopt independently verified new catalogs. No native create was submitted.');\n const prepare = async () => {\n await requireCatalogCreationAccess(store, creationScope(op.accountId, input.bc_id), true);const current = await this.context(selection);\n if (current.expected_creation_access_hash !== input.expected_creation_access_hash || current.expected_regions_hash !== input.expected_regions_hash) throw new AdportError('PENDING_MISMATCH', 'Creation delegation or available regions changed. Read context and request a new preview.');\n const requested = [input.catalog_conf.region_code, ...input.catalog_conf.additional_config_list?.map(row => row.region_code) ?? []].filter((code): code is string => !!code);\n if (requested.some(code => !current.available_region_codes.includes(code))) throw new AdportError('INVALID_INPUT', 'A selected region is not available in this Business Center.');\n };\n await prepare();const c = input.catalog_conf, notes = ['Local preview only. Native creation eligibility, allowlists and supported type/currency/region combinations are checked on apply.', 'Creates an empty Business Center catalog. No products, ads, budgets, tracking or events are created.', 'The owner delegated read/write management of this successfully created, independently verified catalog ID only. Existing catalogs are not adopted or enumerated.', 'Type, region, currency, channel and additional targeting configuration cannot be edited later. Uncertain creation or access adoption retains known IDs; reconcile before another create.'];\n return { summary: `Create TikTok catalog \"${input.name}\"`, changes: [`+ ${input.catalog_type} catalog ${input.name} in Business Center ${input.bc_id}`, `+ Immutable catalog configuration ${canonical(c)}`, '+ Project read/write grant for the independently verified new catalog ID only'], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'tiktok', accountId: op.accountId, kind: 'create', title: 'Create catalog', subject: input.name, fields: [{ label: 'Business Center', after: input.bc_id }, { label: 'Catalog type', after: input.catalog_type }, { label: 'Primary region', after: c.region_code ?? 'Multi-country' }, { label: 'Currency', after: c.currency }, { label: 'Multi-country', after: c.is_multi_country ?? false }, { label: 'Channel', after: c.channel ?? 'Native default' }, { label: 'Additional regions', after: c.additional_config_list?.map(row => row.region_code + ':' + row.currency).join(', ') || 'None' }, { label: 'New catalog project access', after: 'Read and write' }], notices: notes },\n execute: async () => {\n await prepare();let id: string | undefined;\n try {\n const receipt = z.object({ catalog_id: catalogId }).parse(await this.client.post('catalog/create', { bc_id: input.bc_id, name: input.name, catalog_type: input.catalog_type, catalog_conf: c }));id = receipt.catalog_id;\n await requireCatalogCreationAccess(store, creationScope(op.accountId, input.bc_id), true);const scope: Scope = { ...selection, catalog_id: id }, actual = await this.lookup(scope);\n if (!actual || actual.catalog_name !== input.name || actual.catalog_type !== input.catalog_type || actual.catalog_conf.currency !== c.currency || c.region_code !== undefined && actual.catalog_conf.country !== c.region_code || c.is_multi_country !== undefined && actual.catalog_conf.is_multi_country !== c.is_multi_country || c.channel !== undefined && actual.catalog_conf.channel !== c.channel || c.additional_config_list !== undefined && additional(actual.catalog_conf.additional_config_list) !== additional(c.additional_config_list)) throw new Error('Created catalog configuration differs');\n const adopted = await store.adoptCreated!({ accountId: op.accountId, businessId: input.bc_id, resourceId: id, kind: 'catalog' }, input.expected_creation_access_hash);\n if (adopted.scope.accountId !== op.accountId || adopted.scope.businessId !== input.bc_id || adopted.scope.resourceId !== id || adopted.scope.kind !== 'catalog' || adopted.mode !== 'write') throw new Error('Adoption receipt differs');return [id];\n } catch (error) { throw failure(error, 'Catalog creation, configuration readback or project adoption is unconfirmed. Reconcile the known catalog before another create.', id ? [id] : undefined); }\n } };\n }\n if (op.tool === 'tiktok_delete_catalog' && op.kind === 'remove') {\n const input = catalogDelete.parse(op.payload), scope: Scope = { account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id };\n const prepare = async () => { const current = await this.parent(scope, true);if (current.configuration_hash !== input.expected_configuration_hash || current.catalog_name !== input.confirm_catalog_name) throw new AdportError('PENDING_MISMATCH', 'Catalog configuration/name changed. Read it and request a fresh deletion preview.');return current; };\n const current = await prepare(), notes = ['Permanently deletes the entire shared catalog, including its current products and feeds. Existing ads or other accounts may be affected. No restore endpoint or global/atomic usage guarantee is available.', 'Dependent contents are not enumerated or frozen by this configuration snapshot. Deletion applies to the entire catalog and its contents at apply time.', 'Native deletion receipt and filtered catalog absence are checked independently. Provider errors are not absence; uncertain results are never replayed.', 'Adport access grants remain separate owner settings; revocation is available without native catalog access.'];\n return { summary: `Permanently delete TikTok catalog \"${current.catalog_name}\"`, changes: [`- Entire catalog ${input.catalog_id} and its current products/feeds`, '- Catalog availability to existing shared consumers'], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'tiktok', accountId: op.accountId, kind: 'remove', title: 'Delete catalog permanently', subject: current.catalog_name, fields: [{ label: 'Catalog', after: input.catalog_id }, { label: 'Business Center', after: input.bc_id }, { label: 'Catalog type', after: current.catalog_type }, { label: 'Contents affected', after: 'All current products and feeds; not enumerated or frozen' }], notices: notes },\n execute: async () => { await prepare();try {\n const receipt = z.object({ catalog_id: catalogId }).parse(await this.client.post('catalog/delete', { bc_id: input.bc_id, catalog_id: input.catalog_id }));if (receipt.catalog_id !== input.catalog_id) throw new Error('Deletion receipt differs');\n await requireCatalogAccess(this.store, { accountId: op.accountId, businessId: input.bc_id, resourceId: input.catalog_id, kind: 'catalog' }, true);if (await this.lookup(scope)) throw new Error('Catalog remains visible');return [input.catalog_id];\n } catch (error) { throw failure(error, 'Catalog deletion or filtered-view absence is unconfirmed. Inspect the known catalog before another deletion.', [input.catalog_id]); } } };\n }\n throw new AdportError('INVALID_INPUT', 'Unsupported catalog lifecycle operation or kind.');\n }\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport { constants, promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { AdportError, adportHome } from '@adport/core';\nimport { z } from 'zod';\n\nexport const catalogScope = z.object({ accountId: z.string().regex(/^\\d{1,30}$/), businessId: z.string().regex(/^\\d{1,30}$/), resourceId: z.string().regex(/^\\d{1,30}$/), kind: z.enum(['catalog', 'catalog_creation']) }).strict();\nexport type TikTokCatalogScope = z.infer<typeof catalogScope>;\nexport const catalogAccessMode = z.enum(['none', 'read', 'write', 'create']);\nexport type TikTokCatalogAccessMode = z.infer<typeof catalogAccessMode>;\nexport interface TikTokCatalogGrant { scope: TikTokCatalogScope; mode: TikTokCatalogAccessMode; revision: number; hash: string }\nexport interface TikTokCatalogAccessStore {\n readonly canManage: boolean;\n readonly canWrite: boolean;\n get(scope: TikTokCatalogScope): Promise<TikTokCatalogGrant>;\n /** Recheck active account/principal scope before native resource access. */\n authorize(scope: TikTokCatalogScope, write: boolean): Promise<TikTokCatalogGrant>;\n list(accountId: string): Promise<TikTokCatalogGrant[]>;\n /** Only the local owner or authenticated dashboard owner/admin may change access. */\n compareAndSet(scope: TikTokCatalogScope, expectedHash: string, mode: TikTokCatalogAccessMode): Promise<TikTokCatalogGrant>;\n /** Internal creation receipt: adopt only a freshly created, independently verified native catalog. */\n adoptCreated?(scope: TikTokCatalogScope, expectedCreationHash: string): Promise<TikTokCatalogGrant>;\n}\nexport function catalogGrant(scope: TikTokCatalogScope, mode: TikTokCatalogAccessMode = 'none', revision = 0): TikTokCatalogGrant {\n const parsed = catalogScope.parse(scope);catalogAccessMode.parse(mode);\n if (!Number.isSafeInteger(revision) || revision < 0 || parsed.kind === 'catalog_creation' && (parsed.resourceId !== parsed.businessId || !['none', 'create'].includes(mode)) || parsed.kind === 'catalog' && mode === 'create') throw new AdportError('INVALID_INPUT', 'Invalid TikTok catalog access configuration.');\n return { scope: parsed, mode, revision, hash: createHash('sha256').update(JSON.stringify([parsed.accountId, parsed.businessId, parsed.kind, parsed.resourceId, mode, revision])).digest('hex') };\n}\nexport function catalogScopeKey(scope: TikTokCatalogScope) { return catalogGrant(scope).hash; }\nexport async function requireCatalogAccess(store: TikTokCatalogAccessStore | undefined, scope: TikTokCatalogScope, write = false) {\n if (!store) throw new AdportError('POLICY_VIOLATION', 'Catalog access has not been selected for this project. An owner or admin must grant the exact Business Center/catalog in Accounts.');\n if (write && !store.canWrite) throw new AdportError('POLICY_VIOLATION', 'This connection cannot modify TikTok catalogs.');\n const grant = await store.authorize(scope, write);\n if (catalogScopeKey(grant.scope) !== catalogScopeKey(scope)) throw new AdportError('POLICY_VIOLATION', 'Catalog grant scope does not match the requested resource.');\n if (!(write ? grant.mode === 'write' : grant.mode === 'read' || grant.mode === 'write')) throw new AdportError('POLICY_VIOLATION', `This project does not have ${write ? 'write' : 'read'} access to the selected TikTok catalog. Ask an owner or admin to review catalog access in Accounts.`);\n return grant;\n}\n\nexport const creationScope = (accountId: string, businessId: string): TikTokCatalogScope => catalogScope.parse({ accountId, businessId, resourceId: businessId, kind: 'catalog_creation' });\nexport async function requireCatalogCreationAccess(store: TikTokCatalogAccessStore | undefined, scope: TikTokCatalogScope, write = false) {\n if (!store || scope.kind !== 'catalog_creation' || scope.resourceId !== scope.businessId || write && !store.canWrite) throw new AdportError('POLICY_VIOLATION', 'Catalog creation requires owner-delegated creation access and a writable connection.');\n const grant = await store.authorize(scope, write);\n if (catalogScopeKey(grant.scope) !== catalogScopeKey(scope) || grant.mode !== 'create') throw new AdportError('POLICY_VIOLATION', 'An owner must delegate catalog creation for this exact advertiser and Business Center. Existing catalog grants do not grant creation access.');\n return grant;\n}\n\n/** Local-owner scope, separate from OAuth secrets. No default Business Center wildcard. */\nexport class FileTikTokCatalogAccessStore implements TikTokCatalogAccessStore {\n readonly canManage = true;\n readonly canWrite = true;\n constructor(private readonly dir = path.join(adportHome(), 'catalog-access', 'tiktok')) {}\n private file(scope: TikTokCatalogScope) { return path.join(this.dir, catalogScopeKey(scope) + '.json'); }\n async authorize(scope: TikTokCatalogScope, _write: boolean) { return this.get(scope); }\n async get(scope: TikTokCatalogScope): Promise<TikTokCatalogGrant> {\n const absent = catalogGrant(scope);let handle;\n try {\n handle = await fs.open(this.file(scope), constants.O_RDONLY | constants.O_NOFOLLOW);await handle.chmod(0o600);\n if ((await handle.stat()).size > 65536) throw new Error('size');\n const value = JSON.parse(await handle.readFile('utf8')) as { scope: TikTokCatalogScope; mode: TikTokCatalogAccessMode; revision: number };\n const grant = catalogGrant(value.scope, value.mode, value.revision);\n if (catalogScopeKey(grant.scope) !== catalogScopeKey(scope)) throw new Error('scope');\n return grant;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return absent;\n throw new AdportError('POLICY_VIOLATION', 'Local TikTok catalog access could not be verified.');\n } finally { await handle?.close(); }\n }\n async list(accountId: string): Promise<TikTokCatalogGrant[]> {\n if (!/^\\d{1,30}$/.test(accountId)) throw new AdportError('INVALID_INPUT', 'Invalid advertiser ID.');\n let files: string[];\n try { files = await fs.readdir(this.dir); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];throw error; }\n const names = files.filter(value => /^[a-f0-9]{64}\\.json$/.test(value));\n if (names.length > 5000) throw new AdportError('POLICY_VIOLATION', 'Local catalog access inventory exceeds its verification bound.');\n const rows: TikTokCatalogGrant[] = [];\n for (const name of names) {\n let handle;\n try {\n handle = await fs.open(path.join(this.dir, name), constants.O_RDONLY | constants.O_NOFOLLOW);\n await handle.chmod(0o600);\n if ((await handle.stat()).size > 65536) throw new Error('size');\n const value = JSON.parse(await handle.readFile('utf8')) as { scope: TikTokCatalogScope; mode: TikTokCatalogAccessMode; revision: number };\n const grant = catalogGrant(value.scope, value.mode, value.revision);\n if (catalogScopeKey(grant.scope) + '.json' !== name) throw new Error('scope');\n if (grant.scope.accountId === accountId && grant.mode !== 'none') rows.push(grant);\n } catch { throw new AdportError('POLICY_VIOLATION', 'Local TikTok catalog access inventory could not be verified.'); }\n finally { await handle?.close(); }\n }\n return rows;\n }\n async adoptCreated(value: TikTokCatalogScope, expectedCreationHash: string) {\n const scope = catalogScope.parse(value);if (scope.kind !== 'catalog') throw new AdportError('POLICY_VIOLATION', 'Only a new exact catalog can be adopted.');\n const parent = creationScope(scope.accountId, scope.businessId);await fs.mkdir(this.dir, { recursive: true, mode: 0o700 });await fs.chmod(this.dir, 0o700);\n const lock = path.join(this.dir, catalogScopeKey(parent) + '.lock');\n try { await fs.mkdir(lock, { mode: 0o700 }); } catch { throw new AdportError('POLICY_VIOLATION', 'Catalog creation access is changing. Reconcile the known catalog before retrying.'); }\n try {\n const grant = await requireCatalogCreationAccess(this, parent, true);if (grant.hash !== expectedCreationHash) throw new AdportError('POLICY_VIOLATION', 'Creation delegation changed. The created catalog was not adopted.');\n return await this.compareAndSet(scope, catalogGrant(scope).hash, 'write');\n } finally { await fs.rmdir(lock); }\n }\n async compareAndSet(scope: TikTokCatalogScope, expectedHash: string, mode: TikTokCatalogAccessMode) {\n catalogGrant(scope, mode);if (!/^[a-f0-9]{64}$/.test(expectedHash)) throw new AdportError('INVALID_INPUT', 'Read the current catalog access hash first.');\n await fs.mkdir(this.dir, { recursive: true, mode: 0o700 });await fs.chmod(this.dir, 0o700);\n const lock = path.join(this.dir, catalogScopeKey(scope) + '.lock');\n try { await fs.mkdir(lock, { mode: 0o700 }); } catch { throw new AdportError('POLICY_VIOLATION', 'Catalog access is being changed by another local operation. Inspect it before retrying.'); }\n const temporary = path.join(this.dir, randomUUID() + '.tmp');\n try {\n const current = await this.get(scope);\n if (current.hash !== expectedHash) throw new AdportError('POLICY_VIOLATION', 'Catalog access changed. Read and review it again.');\n const next = catalogGrant(scope, mode, current.revision + 1), handle = await fs.open(temporary, 'wx', 0o600);\n try { await handle.writeFile(JSON.stringify(next) + '\\n');await handle.sync(); } finally { await handle.close(); }\n await fs.rename(temporary, this.file(scope));return next;\n } finally {\n await fs.unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; });await fs.rmdir(lock);\n }\n }\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { TikTokClient } from './client.js';\nimport { catalogId, catalogInput } from './catalog-schema.js';\n\nconst hash = z.string().regex(/^[a-f0-9]{64}$/), nativeId = z.union([catalogId, z.number().int().positive().safe()]).transform(String);\nconst code = z.string().min(1).max(256).regex(/^[^\\u0000-\\u0020\\u007f]+$/), text = z.string().max(4000);\nconst selectedFields = { app_id: catalogId.optional(), pixel_code: code.optional() };\nconst hasSource = (value: { app_id?: string | null; pixel_code?: string | null }) => !!(value.app_id || value.pixel_code);\nconst paging = { cursor: z.string().min(1).max(512).optional(), page_size: z.number().int().min(1).max(100).default(30) };\nexport const catalogEventList = catalogInput.extend(paging).strict();\nexport const catalogEventApps = catalogInput.extend({ ...paging, app_platform_ids: z.array(z.string().min(1).max(1000)).min(1).max(100).refine(ids => new Set(ids).size === ids.length, 'Platform IDs must be unique').optional() }).strict();\nexport const catalogEventContext = catalogInput.extend({ ...selectedFields, purpose: z.enum(['bind', 'unbind']).default('bind') }).strict().refine(hasSource, 'Select an app_id, pixel_code or both');\nexport const catalogEventChange = catalogInput.omit({ account_id: true }).extend({ ...selectedFields, expected_catalog_hash: hash, expected_bindings_hash: hash, expected_sources_hash: hash, acknowledge_shared_effects: z.literal(true), acknowledge_measurement_effects: z.literal(true) }).strict().refine(hasSource, 'Select an app_id, pixel_code or both; an empty selector cannot unbind all sources');\ntype Scope = z.infer<typeof catalogInput>;\ntype Selector = { app_id?: string; pixel_code?: string };\ntype Parent = { configuration_hash: string; can_write: boolean };\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]> };\ntype Member = { type: 'APP' | 'PIXEL'; id: string; name: 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 digest = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex');\nconst key = (value: Pick<Member, 'type' | 'id'>) => value.type + ':' + value.id;\nconst identities = (rows: Member[]) => rows.map(({ type, id }) => ({ type, id })).sort((a, b) => key(a).localeCompare(key(b)));\nconst invalid = () => new AdportError('PROVIDER_ERROR', 'TikTok catalog event-source scope, identifiers or response shape could not be verified.');\nconst failure = (error: unknown, message: string, ids?: string[]) => {\n const details = error instanceof AdportError && error.details && typeof error.details === 'object' ? error.details as Record<string, unknown> : {};\n return new AdportError('PROVIDER_ERROR', message + ' Provider bodies stay hidden; no request was retried.', { ...(Number.isSafeInteger(details.code) ? { provider_code: details.code } : {}), ...(typeof details.request_id === 'string' && /^[a-zA-Z0-9_-]{1,128}$/.test(details.request_id) ? { request_id: details.request_id } : {}), ...(ids ? { resourceIds: ids } : {}) });\n};\nconst nativeApp = z.object({ advertiser_id: nativeId, app_id: nativeId, app_name: text, app_platform_id: z.string().min(1).max(1000), platform: z.enum(['ANDROID', 'IOS']).optional(), package_name: text.optional(), self_attribution_enabled: z.boolean().optional(), skan_allowed: z.enum(['ALLOWED', 'NOT_ALLOWED']).optional(), advanced_dedicated_campaign_allowed: z.boolean().optional(), is_attribution_flex_enable: z.boolean().optional() });\nconst matching = z.object({ email: z.boolean().optional(), phone_number: z.boolean().optional(), name: z.boolean().optional(), address: z.boolean().optional(), external_id: z.boolean().optional() });\nconst nativePixel = z.object({ pixel_id: nativeId, pixel_code: code, pixel_name: text, advertiser_id: nativeId.optional(), asset_ownership: z.object({ asset_relation_status: z.string().nullable().optional(), ownership_status: z.boolean().optional(), owner_bc_id: nativeId.nullable().optional() }).optional(), advanced_matching_fields: matching.optional(), automatic_advanced_matching_fields: matching.optional(), enable_first_party_cookies: z.boolean().optional(), enable_expanded_data_sharing: z.boolean().optional() });\nfunction page<T>(scope: unknown, rows: T[], cursor: string | undefined, size: number) {\n const snapshot = digest({ scope, rows });let index = 0;\n if (cursor) {\n try { const parsed = z.object({ h: hash, i: z.number().int().positive().safe() }).strict().parse(JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')));if (parsed.h !== snapshot || parsed.i >= rows.length) throw new Error();index = parsed.i; }\n catch { throw new AdportError('INVALID_INPUT', 'The source inventory, selection or cursor changed. Read the first page again.'); }\n }\n const selected = rows.slice(index, index + size), next = index + selected.length;\n return { selected, complete: next === rows.length, truncated: next < rows.length, ...(next < rows.length ? { next_cursor: Buffer.from(JSON.stringify({ h: snapshot, i: next })).toString('base64url') } : {}) };\n}\n\n/** Native catalog event-source bindings, not event ingestion. Official contracts refreshed 2026-11-05. */\nexport class TikTokCatalogEventSources {\n constructor(private readonly client: Pick<TikTokClient, 'get' | 'post'>, private readonly parent: (scope: Scope, write?: boolean) => Promise<Parent>) {}\n private async get(path: string, params: Record<string, unknown>) {\n try { return await this.client.get(path, params, { jsonContentType: true }); } catch (error) { throw failure(error, 'Catalog event-source read failed. Check native source/catalog access.'); }\n }\n private async bindings(scope: Scope) {\n const response = z.object({ catalog_id: nativeId, bc_id: nativeId.optional(), event_sources: z.array(z.object({ event_source_name: text.nullable().optional(), app_id: nativeId.nullable().optional(), pixel_code: code.nullable().optional() }).refine(hasSource)).max(5000) }).safeParse(await this.get('catalog/eventsource_bind/get', { bc_id: scope.bc_id, catalog_id: scope.catalog_id }));\n if (!response.success || response.data.catalog_id !== scope.catalog_id || response.data.bc_id !== undefined && response.data.bc_id !== scope.bc_id) throw invalid();\n const rows: Member[] = response.data.event_sources.flatMap(row => [...(row.app_id ? [{ type: 'APP' as const, id: row.app_id, name: row.event_source_name ?? 'App event source' }] : []), ...(row.pixel_code ? [{ type: 'PIXEL' as const, id: row.pixel_code, name: row.event_source_name ?? 'Web Pixel' }] : [])]);\n if (rows.length > 5000 || new Set(rows.map(key)).size !== rows.length) throw invalid();\n rows.sort((a, b) => key(a).localeCompare(key(b)));return { rows, hash: digest({ ...scope, bindings: identities(rows) }) };\n }\n async list(value: unknown) {\n const input = catalogEventList.parse(value), scope = catalogInput.parse({ account_id: input.account_id, bc_id: input.bc_id, catalog_id: input.catalog_id }), parent = await this.parent(scope), native = await this.bindings(scope), result = page({ ...scope, kind: 'bindings' }, native.rows, input.cursor, input.page_size);\n return { event_sources: result.selected, records: result.selected.map(row => ({ id: key(row), name: row.name, type: row.type, source_id: row.id })), configuration_hash: native.hash, expected_catalog_hash: parent.configuration_hash, total_in_response: native.rows.length, complete: result.complete, truncated: result.truncated, ...('next_cursor' in result ? { next_cursor: result.next_cursor } : {}), notes: ['Catalog-level bindings may be shared across advertisers. This list does not establish that every source belongs to the selected advertiser.', 'Native endpoint is unpaged; Adport snapshot-pages a bounded response locally. Source IDs/hashes are configuration, not event history or event-ingestion credentials.'] };\n }\n async apps(value: unknown) {\n const input = catalogEventApps.parse(value), scope = catalogInput.parse({ account_id: input.account_id, bc_id: input.bc_id, catalog_id: input.catalog_id });await this.parent(scope);\n const response = z.object({ apps: z.array(nativeApp).max(5000) }).safeParse(await this.get('app/list', { advertiser_id: scope.account_id, ...(input.app_platform_ids ? { app_platform_ids: input.app_platform_ids } : {}) }));\n if (!response.success || response.data.apps.some(row => row.advertiser_id !== scope.account_id || input.app_platform_ids && !input.app_platform_ids.includes(row.app_platform_id)) || new Set(response.data.apps.map(row => row.app_id)).size !== response.data.apps.length) throw invalid();\n const rows = response.data.apps.sort((a, b) => a.app_id.localeCompare(b.app_id)), result = page({ ...scope, kind: 'apps', app_platform_ids: input.app_platform_ids ?? null }, rows, input.cursor, input.page_size);\n return { apps: result.selected, records: result.selected.map(row => ({ id: row.app_id, name: row.app_name, platform: row.platform ?? 'Not reported', app_platform_id: row.app_platform_id, skan_allowed: row.skan_allowed ?? 'Not reported' })), total_in_response: rows.length, complete: result.complete, truncated: result.truncated, ...('next_cursor' in result ? { next_cursor: result.next_cursor } : {}), notes: ['Advertiser app discovery, not a guarantee of catalog binding eligibility. Use the native app_id for event-source binding; app_platform_id and tiktok_app_id are different identifiers.', 'Native endpoint is unpaged; Adport snapshot-pages at most 5,000 apps, up to 100 per local page. Tracking URLs, partner tokens, raw icons and other private fields are omitted.'] };\n }\n private async selected(scope: Scope, input: Selector, purpose: 'bind' | 'unbind') {\n const sources: Array<Record<string, unknown> & Member> = [];\n if (input.app_id) {\n const response = z.object({ app: nativeApp }).safeParse(await this.get('app/info', { advertiser_id: scope.account_id, app_id: input.app_id }));\n if (!response.success || response.data.app.advertiser_id !== scope.account_id || response.data.app.app_id !== input.app_id) throw invalid();\n const app = response.data.app;sources.push({ type: 'APP', id: app.app_id, name: app.app_name, ...app });\n }\n if (input.pixel_code) {\n const response = z.object({ pixels: z.array(nativePixel).max(20), page_info: z.object({ page: z.literal(1), page_size: z.literal(20), total_page: z.number().int().nonnegative().safe().optional(), total_number: z.number().int().nonnegative().safe().optional() }).optional() }).safeParse(await this.get('pixel/list', { advertiser_id: scope.account_id, code: input.pixel_code, page: 1, page_size: 20, ...(purpose === 'bind' ? { filtering: { available_for_catalog_only: true } } : {}) }));\n if (!response.success || response.data.pixels.length !== 1 || (response.data.page_info?.total_page ?? 1) !== 1 || response.data.page_info?.total_number !== undefined && response.data.page_info.total_number !== 1) throw invalid();\n const pixel = response.data.pixels[0]!;if (pixel.pixel_code !== input.pixel_code || pixel.advertiser_id !== undefined && pixel.advertiser_id !== scope.account_id || pixel.asset_ownership?.asset_relation_status === 'UNBOUND') throw invalid();\n sources.push({ type: 'PIXEL', id: pixel.pixel_code, name: pixel.pixel_name, ...pixel });\n }\n return { sources, hash: digest({ ...scope, purpose, sources }) };\n }\n private async contextFor(scope: Scope, input: Selector, purpose: 'bind' | 'unbind', write = false) {\n const parent = await this.parent(scope, write), bindings = await this.bindings(scope), selected = await this.selected(scope, input, purpose);\n const keys = new Set(bindings.rows.map(key));if (selected.sources.some(row => purpose === 'bind' ? keys.has(key(row)) : !keys.has(key(row)))) throw new AdportError('INVALID_INPUT', purpose === 'bind' ? 'A selected source is already bound. Select only new bindings, or split the change.' : 'Every selected source must already be bound. No unbind-all operation is inferred.');\n return { parent, bindings, selected };\n }\n async context(value: unknown) {\n const input = catalogEventContext.parse(value), scope = catalogInput.parse({ account_id: input.account_id, bc_id: input.bc_id, catalog_id: input.catalog_id }), current = await this.contextFor(scope, input, input.purpose);\n return { expected_catalog_hash: current.parent.configuration_hash, expected_bindings_hash: current.bindings.hash, expected_sources_hash: current.selected.hash, purpose: input.purpose, selected_sources: current.selected.sources, records: current.selected.sources.map(row => ({ id: key(row), name: row.name, type: row.type, source_id: row.id, change: input.purpose === 'bind' ? 'Bind to catalog' : 'Unbind from catalog' })), binding_count: current.bindings.rows.length, complete: true, truncated: false, notes: ['Selected sources were verified through the selected advertiser’s native app/Pixel endpoints. The catalog is a separately granted shared Business Center asset.', 'Binding changes can affect product/event matching, retargeting, measurement and existing catalog ads. No tracking is installed and no events are sent.', 'Snapshots are rechecked at apply; there is no native atomic cross-resource guarantee. Unselected binding identities must survive readback.'] };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n const bind = op.tool === 'tiktok_bind_catalog_event_sources';if (op.provider !== 'tiktok' || !(bind && op.kind === 'update' || op.tool === 'tiktok_unbind_catalog_event_sources' && op.kind === 'remove')) throw new AdportError('INVALID_INPUT', 'Unsupported catalog event-source operation or kind.');\n const input = catalogEventChange.parse(op.payload), scope = catalogInput.parse({ account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id }), purpose = bind ? 'bind' : 'unbind';\n const prepare = async () => { const current = await this.contextFor(scope, input, purpose, true);if (current.parent.configuration_hash !== input.expected_catalog_hash || current.bindings.hash !== input.expected_bindings_hash || current.selected.hash !== input.expected_sources_hash) throw new AdportError('PENDING_MISMATCH', 'Catalog, bindings or selected sources changed. Read context and request a new preview.');return current; };\n const current = await prepare(), selected = current.selected.sources, title = bind ? 'Bind catalog event sources' : 'Unbind catalog event sources';\n const notes = ['Local preview only. Changes shared catalog product/event matching and may affect measurement, retargeting and existing ads.', 'No tracking installation, event ingestion, budget or ad-status change. Source access and native catalog eligibility remain authoritative.', 'All unselected binding identities are checked after the write. There is no atomic cross-resource guarantee; uncertain or partial results are never replayed.'];\n return { summary: title + ' · catalog ' + input.catalog_id, changes: selected.map(row => `${bind ? '+' : '-'} ${row.type} ${row.name} (${row.id})`), coercions: [], budgetDeltas: [], notes,\n review: { provider: 'tiktok', accountId: scope.account_id, kind: bind ? 'update' : 'remove', title, subject: input.catalog_id, fields: [{ label: 'Catalog', after: input.catalog_id }, ...selected.map(row => ({ label: row.type === 'APP' ? 'App event source' : 'Web Pixel', before: bind ? 'Not bound' : row.name + ' (' + row.id + ')', after: bind ? row.name + ' (' + row.id + ')' : 'Unbound' })), { label: 'Other bindings preserved', after: String(current.bindings.rows.length - (bind ? 0 : selected.length)) }], notices: notes },\n execute: async () => {\n const fresh = await prepare(), selectedKeys = new Set(selected.map(key)), expected = bind ? [...fresh.bindings.rows, ...selected] : fresh.bindings.rows.filter(row => !selectedKeys.has(key(row)));\n try {\n const receipt = await this.client.post<unknown>('catalog/eventsource/' + purpose, { advertiser_id: scope.account_id, bc_id: input.bc_id, catalog_id: input.catalog_id, ...(input.app_id ? { app_id: input.app_id } : {}), ...(input.pixel_code ? { pixel_code: input.pixel_code } : {}) });\n if (receipt === null || typeof receipt !== 'object' || Array.isArray(receipt)) throw new Error('Unexpected acknowledgement');await this.parent(scope, true);const actual = await this.bindings(scope);\n if (canonical(identities(actual.rows)) !== canonical(identities(expected))) throw new Error('Binding readback differs');return [scope.catalog_id, ...selected.map(row => row.id)];\n } catch (error) { throw failure(error, 'Catalog binding change or preservation readback is unconfirmed. Inspect known catalog/source IDs before another change.', [scope.catalog_id, ...selected.map(row => row.id)]); }\n } };\n }\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, csvRows, MAX_PROJECT_MEDIA_BYTES, verifyMedia, type Creative, type MediaResolver, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { TikTokClient } from './client.js';\nimport { catalogId, catalogInput } from './catalog-schema.js';\nimport { nativeListComplete } from './pagination.js';\n\ntype Row = Record<string, unknown>;\ntype Selection = z.infer<typeof catalogInput>;\ntype Parent = { configuration_hash: string; catalog_type: string; catalog_conf: Row; can_write: boolean };\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]> };\nconst hash = z.string().regex(/^[a-f0-9]{64}$/), count = z.number().int().nonnegative().safe();\nconst nativeId = z.union([catalogId, z.number().int().positive().safe()]).transform(String);\nconst videoId = z.string().min(1).max(1024).regex(/^[^\\u0000-\\u0020\\u007f]+$/);\nconst time = z.string().max(40).regex(/^[0-9TZ :.+-]*$/);\nconst text = z.string().max(256 * 1024).nullable().optional();\nconst metadata = { category: text, brand: text, creator: text, video_type: text, description: text, landing_page_url: text, custom_label_0: text, custom_label_1: text, custom_label_2: text, custom_label_3: text, custom_label_4: text };\nconst metadataKeys = Object.keys(metadata) as Array<keyof typeof metadata>;\nconst nativeVideo = z.object({ ...metadata, catalog_video_id: videoId, video_name: z.string().max(4000), video_link: z.string().max(256 * 1024).optional(), sku_id_list: z.array(z.string().max(100)).max(20).optional(),\n video_id: videoId.nullable().optional(), video_signature: z.string().max(128).nullable().optional(), status: z.enum(['PENDING', 'SUCCESS', 'FAILED']), active_status: z.enum(['ACTIVATED', 'DEACTIVATED']).optional(), create_time: time.optional(), preview_url: z.string().max(16384).nullable().optional(),\n catalog_id: nativeId.optional(), bc_id: nativeId.optional(),\n});\ntype Video = z.infer<typeof nativeVideo>;\nconst displayMetadata = (row: Video): Partial<Pick<Video, Exclude<keyof typeof metadata, 'landing_page_url'>>> => Object.fromEntries(metadataKeys.filter(key => key !== 'landing_page_url' && row[key] !== undefined).map(key => [key, typeof row[key] === 'string' ? row[key].slice(0, 1000) : row[key]]));\nconst source = catalogInput.extend({ media_id: z.string().uuid(), expected_sha256: hash }).strict();\nexport const catalogVideoImportContext = source;\nexport const catalogVideoList = catalogInput.extend({ catalog_video_ids: z.array(videoId).min(1).max(50).refine(ids => new Set(ids).size === ids.length, 'Video IDs must be unique').optional(), page: z.number().int().positive().safe().default(1), page_size: z.number().int().min(1).max(50).default(20) }).strict();\nexport const catalogVideoLog = catalogInput.extend({ feed_log_id: catalogId }).strict();\nexport const catalogVideoUpload = source.omit({ account_id: true }).extend({ expected_catalog_hash: hash, expected_associations_hash: hash, sync_to_selected_account: z.boolean().default(false), acknowledge_account_copy: z.literal(true).optional(), acknowledge_shared_effects: z.literal(true), acknowledge_possible_delivery: z.literal(true), acknowledge_async_processing: z.literal(true) }).strict().refine(value => !value.sync_to_selected_account || value.acknowledge_account_copy === true, 'Syncing creates separate advertiser-library copies; acknowledge_account_copy is required');\nexport const catalogVideoDelete = catalogInput.omit({ account_id: true }).extend({ catalog_video_id: videoId, expected_configuration_hash: hash, acknowledge_shared_effects: z.literal(true) }).strict();\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 digest = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex');\nconst object = (value: unknown): Row => value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};\nconst safeUrl = (value: unknown, httpsOnly = true): string | undefined => {\n if (typeof value !== 'string' || /[\\u0000-\\u0020\\u007f]/.test(value)) return;\n try { const url = new URL(value);return (httpsOnly ? url.protocol === 'https:' : ['http:', 'https:'].includes(url.protocol)) && !url.username && !url.password ? url.href : undefined; } catch { return; }\n};\nconst sourceInfo = (value?: string) => { try { const url = new URL(value ?? '');return { origin: url.origin, sha256: digest(value) }; } catch { return undefined; } };\nconst config = (row: Video) => ({ ...Object.fromEntries(metadataKeys.filter(key => row[key] !== undefined).map(key => [key, row[key]])), catalog_video_id: row.catalog_video_id, video_name: row.video_name, video_link: row.video_link, sku_id_list: row.sku_id_list, active_status: row.active_status });\nconst configurationHash = (scope: Selection, row: Video) => digest({ ...scope, configuration: config(row) });\nconst invalid = () => new AdportError('PROVIDER_ERROR', 'TikTok returned an unexpected catalog-video scope, identifier or shape. No request was retried.');\nconst failure = (error: unknown, message: string, ids?: string[]) => {\n const details = object(error instanceof AdportError ? error.details : undefined);\n return new AdportError('PROVIDER_ERROR', `${message} Provider bodies and source URLs stay hidden; no request was retried.`, { ...(Number.isSafeInteger(details.code) ? { provider_code: details.code } : {}), ...(typeof details.request_id === 'string' && /^[a-zA-Z0-9_-]{1,128}$/.test(details.request_id) ? { request_id: details.request_id } : {}), ...(ids ? { resourceIds: ids } : {}) });\n};\nconst columns = ['video_name', 'video_link', 'sku_id_list', 'category', 'brand', 'creator', 'video_type', 'description', 'landing_page_url', 'custom_label_0', 'custom_label_1', 'custom_label_2', 'custom_label_3', 'custom_label_4'];\n\n/** Official catalog/video file/log/get/delete contracts refreshed 2026-11-05. */\nexport class TikTokCatalogVideos {\n constructor(private readonly client: Pick<TikTokClient, 'get' | 'post'>, private readonly authorizeParent: (scope: Selection, write?: boolean) => Promise<Parent>, private readonly media?: MediaResolver) {}\n private async parent(scope: Selection, write = false) {\n const parent = await this.authorizeParent(scope, write);\n if (parent.catalog_type !== 'ECOM' || parent.catalog_conf.is_multi_country === true) throw new AdportError('INVALID_INPUT', 'Catalog videos require a single-country E-commerce catalog.');\n return parent;\n }\n private async request(path: string, args: Row) {\n try { return await this.client.get(path, args, { jsonContentType: true }); } catch (error) { throw failure(error, 'TikTok catalog-video read failed. Check native permissions and the selected catalog/job.'); }\n }\n private async native(scope: Selection, ids?: string[], page = 1, size = 20) {\n const result = z.object({ videos: z.array(nativeVideo).max(ids ? ids.length : size), page_info: z.unknown().optional() }).safeParse(await this.request('catalog/video/get', { bc_id: scope.bc_id, catalog_id: scope.catalog_id, ...(ids ? { catalog_video_ids: ids } : { page, page_size: size }) }));\n if (!result.success) throw invalid();\n const pageInfo = ids || result.data.page_info === undefined ? undefined : z.object({ page: z.number().int().positive().safe(), page_size: z.number().int().positive().max(50), total_page: count.optional(), total_number: count.optional() }).safeParse(result.data.page_info);\n if (pageInfo && !pageInfo.success) throw invalid();\n const rows = result.data.videos, info = pageInfo?.data;\n if (new Set(rows.map(row => row.catalog_video_id)).size !== rows.length || rows.some(row => ids && !ids.includes(row.catalog_video_id) || row.catalog_id !== undefined && row.catalog_id !== scope.catalog_id || row.bc_id !== undefined && row.bc_id !== scope.bc_id) || !ids && info && (info.page !== page || info.page_size !== size)) throw invalid();\n return { rows, page_info: info, complete: ids ? true : nativeListComplete(info, rows.length) };\n }\n async list(value: unknown) {\n const input = catalogVideoList.parse(value), scope = catalogInput.parse({ account_id: input.account_id, bc_id: input.bc_id, catalog_id: input.catalog_id }), parent = await this.parent(scope), result = await this.native(scope, input.catalog_video_ids, input.page, input.page_size);\n const videos = result.rows.map(row => ({ catalog_video_id: row.catalog_video_id, video_name: row.video_name, sku_id_list: row.sku_id_list, status: row.status, active_status: row.active_status, video_id: row.video_id, create_time: row.create_time,\n ...displayMetadata(row), source: sourceInfo(row.video_link), landing_page: sourceInfo(typeof row.landing_page_url === 'string' ? row.landing_page_url : undefined),\n metadata_truncated_fields: metadataKeys.filter(key => key !== 'landing_page_url' && typeof row[key] === 'string' && row[key].length > 1000),\n ...(row.video_signature && /^[a-f0-9]{32}$/i.test(row.video_signature) ? { video_signature: row.video_signature } : {}), preview_url: row.status === 'SUCCESS' ? safeUrl(row.preview_url) : undefined, configuration_hash: configurationHash(scope, row) }));\n const creatives: Creative[] = videos.map(row => ({ id: row.catalog_video_id, provider: 'tiktok', account_id: input.account_id, type: 'catalog_video', name: row.video_name, status: row.status + (row.active_status ? ` · ${row.active_status}` : ''), headlines: [], descriptions: typeof row.description === 'string' ? [row.description] : [], landing_urls: [],\n media: row.preview_url ? [{ type: 'video', url: row.preview_url, open_url: row.preview_url, alt: row.video_name }] : [],\n actions: parent.can_write ? [{ label: 'Remove from catalog', tool: 'tiktok_delete_catalog_video', arguments: { ...scope, catalog_video_id: row.catalog_video_id, expected_configuration_hash: row.configuration_hash, acknowledge_shared_effects: true }, fields: [] }] : [],\n }));\n return { videos, creatives, complete: result.complete, truncated: result.complete !== true, ...(result.complete === false && Number.isSafeInteger(input.page + 1) ? { next_page: input.page + 1 } : {}), ...(result.page_info && !input.catalog_video_ids ? { page_info: result.page_info } : {}),\n ...(input.catalog_video_ids ? { missing_ids: input.catalog_video_ids.filter(id => !videos.some(row => row.catalog_video_id === id)) } : {}),\n notes: ['Filtered video IDs ignore pagination and return a complete filtered view, not a complete catalog inventory.', 'Extraction status and activation status are separate. Native preview links last six hours; refresh to renew them.', 'Text metadata is clipped at 1,000 characters with explicit field flags; configuration hashes bind full native values.', 'Deleting a catalog video can affect catalog ads; copies already synced to advertiser libraries are not removed.', ...(parent.catalog_conf.is_multi_country === undefined ? ['The catalog did not report its multi-country flag; native endpoint eligibility remains authoritative.'] : []), ...(result.complete === null ? ['Native pagination is absent or contradictory; completeness is unknown.'] : [])],\n };\n }\n async log(value: unknown) {\n const input = catalogVideoLog.parse(value), scope = catalogInput.parse({ account_id: input.account_id, bc_id: input.bc_id, catalog_id: input.catalog_id });await this.parent(scope);\n const issue = z.object({ field: z.string().max(256 * 1024).optional(), affected_video_count: count });\n const result = z.object({ video_feed_log: z.object({ catalog_id: nativeId, bc_id: nativeId.optional(), feed_log_id: nativeId.optional(), feed_id: nativeId.optional(), add_count: count.optional(), update_count: count.optional(), delete_count: count.optional(), error_count: count.optional(), warn_count: count.optional(), process_status: z.enum(['PROCESSING', 'SUCCESS', 'FAILED', 'WAITING']), start_time: time.optional(), end_time: time.optional() }),\n feed_log_data: z.object({ error_affected_videos: z.array(issue).max(1000).nullable().optional(), warn_affected_videos: z.array(issue).max(1000).nullable().optional() }).nullable().optional(),\n }).safeParse(await this.request('catalog/video/log', { bc_id: input.bc_id, catalog_id: input.catalog_id, feed_log_id: input.feed_log_id, language: 'en' }));\n if (!result.success) throw invalid();const row = result.data.video_feed_log;\n if (row.catalog_id !== input.catalog_id || row.bc_id !== undefined && row.bc_id !== input.bc_id || row.feed_log_id !== undefined && row.feed_log_id !== input.feed_log_id) throw invalid();\n const summarize = (rows: z.infer<typeof issue>[]) => rows.slice(0, 50).map(row => ({ field: row.field && row.field.length <= 128 && /^[a-zA-Z0-9_.\\[\\]-]+$/.test(row.field) ? row.field : 'Unrecognized field', affected_video_count: row.affected_video_count }));\n const diagnostics = result.data.feed_log_data, log = { ...row, feed_log_id: input.feed_log_id, ...(diagnostics?.error_affected_videos ? { error_fields: summarize(diagnostics.error_affected_videos) } : {}), ...(diagnostics?.warn_affected_videos ? { warning_fields: summarize(diagnostics.warn_affected_videos) } : {}), diagnostic_fields_truncated: (diagnostics?.error_affected_videos?.length ?? 0) > 50 || (diagnostics?.warn_affected_videos?.length ?? 0) > 50 };\n return { log, records: [{ id: input.feed_log_id, name: 'Catalog video import', status: row.process_status, added: row.add_count, removed: row.delete_count, errors: row.error_count, warnings: row.warn_count }], processing_complete: ['SUCCESS', 'FAILED'].includes(row.process_status), has_item_errors: row.error_count === undefined ? null : row.error_count > 0, complete: true, truncated: false,\n notes: ['These are native task states/counts. Missing counts remain unavailable. Processing completion does not establish extraction, ad eligibility or advertiser-library sync.', 'Diagnostic field counts are bounded. Original video links, downloads, free-form errors and sample rows are omitted.'],\n };\n }\n private async source(scope: Selection, mediaId: string, sha: string, write = false) {\n const parent = await this.parent(scope, write), media = this.media;\n if (!media) throw new AdportError('NOT_CONNECTED', 'Catalog-video imports require a CSV staged through Adport agent, widget, dashboard or cloud CLI media tools.');\n let raw;\n try { raw = await media.read({ media_id: mediaId, expected_sha256: sha }, { maxBytes: MAX_PROJECT_MEDIA_BYTES, contentTypes: ['text/csv'] }); } catch { throw new AdportError('INVALID_INPUT', 'Catalog-video CSV bytes/checksum could not be verified. Refresh the immutable media reference.'); }\n const file = verifyMedia(raw.bytes, raw.name, sha, { maxBytes: MAX_PROJECT_MEDIA_BYTES, contentTypes: ['text/csv'] }), rows = csvRows(file.bytes, { maxRows: 5001, maxColumns: columns.length }), first = rows.next();\n if (first.done || new Set(first.value).size !== first.value.length || first.value.some(key => !columns.includes(key)) || columns.slice(0, 3).some(key => !first.value.includes(key))) throw new AdportError('INVALID_INPUT', 'Use the documented catalog-video CSV headers: video_name, video_link, sku_id_list and optional native metadata columns.');\n const previews: Row[] = [], allSkus = new Set<string>();let rowCount = 0;\n for (const fields of rows) {\n const row = Object.fromEntries(first.value.map((key, i) => [key, fields[i]!]));\n if (!row.video_name?.trim() || row.video_name.length > 500 || !safeUrl(row.video_link, false) || row.landing_page_url && !safeUrl(row.landing_page_url, false) || ['category', 'brand', 'creator', 'video_type', 'description'].some(key => (row[key]?.length ?? 0) > 500)) throw new AdportError('INVALID_INPUT', 'Each catalog-video row needs a nonempty name up to 500 characters and a valid HTTP(S) video URL. Optional metadata up to 500 characters; native would null longer values.');\n const skus = row.sku_id_list!.split(',');\n if (!skus.length || skus.length > 20 || skus.some(sku => !sku || sku !== sku.trim() || sku.length > 100 || /[\\u0000-\\u001f\\u007f]/.test(sku)) || new Set(skus).size !== skus.length) throw new AdportError('INVALID_INPUT', 'Each video needs 1–20 distinct exact SKU IDs, comma-separated without surrounding whitespace. Quote the CSV field when it contains commas.');\n for (const sku of skus) allSkus.add(sku);\n if (allSkus.size > 5000) throw new AdportError('INVALID_INPUT', 'Adport verifies at most 5,000 distinct SKU associations per import. Use smaller CSV batches.');\n if (previews.length < 20) previews.push({ row: rowCount + 2, name: row.video_name, sku_ids: skus, source: sourceInfo(row.video_link) });rowCount++;\n }\n if (!rowCount) throw new AdportError('INVALID_INPUT', 'The catalog-video CSV needs at least one data row.');\n const skuIds = [...allSkus].sort(), found = new Map<string, { sku_id: string; product_id: string; ad_creation_eligible: string }>();\n for (let start = 0; start < skuIds.length; start += 1000) {\n const selected = skuIds.slice(start, start + 1000);\n for (let page = 1; page <= 2; page++) {\n const result = z.object({ list: z.array(z.object({ sku_id: z.string().min(1).max(100), product_id: nativeId, ad_creation_eligible: z.string(), catalog_id: nativeId.optional(), bc_id: nativeId.optional() })).max(500), page_info: z.object({ page: z.number().int().positive(), page_size: z.number().int().positive(), total_page: count.optional(), total_number: count.optional() }).optional() }).safeParse(await this.request('catalog/product/get', { bc_id: scope.bc_id, catalog_id: scope.catalog_id, sku_ids: selected, page, page_size: 500 }));\n if (!result.success || result.data.page_info && (result.data.page_info.page !== page || result.data.page_info.page_size !== 500)) throw invalid();\n for (const row of result.data.list) {\n if (!selected.includes(row.sku_id) || found.has(row.sku_id) || row.catalog_id !== undefined && row.catalog_id !== scope.catalog_id || row.bc_id !== undefined && row.bc_id !== scope.bc_id) throw invalid();\n if (row.ad_creation_eligible !== 'AVAILABLE') throw new AdportError('INVALID_INPUT', 'Every associated SKU must be natively AVAILABLE for ad creation. No import was submitted.');\n found.set(row.sku_id, { sku_id: row.sku_id, product_id: row.product_id, ad_creation_eligible: row.ad_creation_eligible });\n }\n if (selected.every(sku => found.has(sku))) break;\n if (!result.data.list.length || !result.data.page_info || result.data.page_info.total_page === undefined || page >= result.data.page_info.total_page) break;\n }\n if (!selected.every(sku => found.has(sku))) throw new AdportError('INVALID_INPUT', 'Not every selected SKU association could be verified in the catalog. No import was submitted.');\n }\n const associations = [...found.values()].sort((a, b) => a.sku_id.localeCompare(b.sku_id));\n return { parent, file, rowCount, skuCount: skuIds.length, previews, associations_hash: digest({ ...scope, sha256: file.sha256, associations }) };\n }\n async importContext(value: unknown) {\n const input = catalogVideoImportContext.parse(value), scope = catalogInput.parse({ account_id: input.account_id, bc_id: input.bc_id, catalog_id: input.catalog_id }), current = await this.source(scope, input.media_id, input.expected_sha256);\n return { expected_catalog_hash: current.parent.configuration_hash, expected_associations_hash: current.associations_hash, source_media_id: input.media_id, source_sha256: input.expected_sha256, video_rows: current.rowCount, unique_skus: current.skuCount, records: current.previews, complete: true, truncated: current.rowCount > current.previews.length,\n notes: ['Every referenced SKU was found and natively AVAILABLE for ad creation. This is not media ingestion or full catalog verification.', 'Only 20 safe row summaries are displayed. Original video URLs stay private; uploaded CSV bytes are not changed.', 'The CSV parameter structure follows the current official field table. Native media accessibility, dimensions, duration, bitrate and template eligibility are checked asynchronously.'],\n };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n if (op.provider !== 'tiktok') throw new AdportError('INVALID_INPUT', 'TikTok catalog-video provider differs.');\n if (op.tool === 'tiktok_upload_catalog_videos' && op.kind === 'create') {\n const input = catalogVideoUpload.parse(op.payload), scope = catalogInput.parse({ account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id }), media = this.media, providerUrl = media?.providerUrl?.bind(media);\n if (!providerUrl) throw new AdportError('NOT_CONNECTED', 'Catalog-video CSV imports require the hosted project media library to create a private download grant.');\n const prepare = async () => {\n const result = await this.source(scope, input.media_id, input.expected_sha256, true);\n if (result.parent.configuration_hash !== input.expected_catalog_hash || result.associations_hash !== input.expected_associations_hash) throw new AdportError('PENDING_MISMATCH', 'Catalog configuration or SKU associations changed. Read import context and request a fresh preview.');return result;\n };\n const initial = await prepare(), notes = ['Local preview only. This adds catalog videos asynchronously and may make them available to existing Video Shopping Ads using the associated products. Ad statuses and budgets are not changed.', 'Only one catalog-video file task can run at a time. Wait for prior tasks; uncertain/failed submissions are never automatically retried.', 'Native video extraction, media eligibility and any advertiser-library sync remain separate from task acceptance.', input.sync_to_selected_account ? `Requests a separate video copy in the selected advertiser ${scope.account_id}. TikTok ignores ineligible accounts; this request does not confirm sync. Catalog deletion does not delete advertiser copies.` : 'No advertiser-library sync is requested.'];\n return { summary: `Upload ${initial.rowCount} catalog videos`, changes: [`+ ${initial.rowCount} video rows and ${initial.skuCount} distinct SKU associations in catalog ${input.catalog_id}.`, `CSV SHA-256 ${input.expected_sha256}; selected advertiser sync requested: ${input.sync_to_selected_account}.`], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'tiktok', accountId: scope.account_id, kind: 'create', title: 'Upload catalog videos', subject: initial.file.name, fields: [{ label: 'Catalog', after: input.catalog_id }, { label: 'Video rows', after: initial.rowCount }, { label: 'Associated SKUs', after: initial.skuCount }, { label: 'Ad-account copy requested', after: input.sync_to_selected_account ? scope.account_id : 'No' }, { label: 'CSV SHA-256', after: input.expected_sha256 }, { label: 'SKU association snapshot', after: input.expected_associations_hash }], notices: notes },\n execute: async () => {\n await prepare();let grant;\n try { grant = await providerUrl({ media_id: input.media_id, expected_sha256: input.expected_sha256 }, { maxBytes: MAX_PROJECT_MEDIA_BYTES, contentTypes: ['text/csv'] }); } catch { throw new AdportError('PROVIDER_ERROR', 'Private CSV staging failed. No native catalog-video upload was submitted.'); }\n if (grant.sha256 !== input.expected_sha256 || !safeUrl(grant.url) || !(Date.parse(grant.expires_at) > Date.now() + 10 * 60_000)) throw new AdportError('PROVIDER_ERROR', 'The private CSV grant could not be verified. No catalog-video upload was submitted.');\n let job: string | undefined;\n try {\n const result = z.object({ feed_log_id: nativeId }).parse(await this.client.post('catalog/video/file', { bc_id: input.bc_id, catalog_id: input.catalog_id, file_url: grant.url, ...(input.sync_to_selected_account ? { advertiser_ids: [scope.account_id] } : {}) }));job = result.feed_log_id;\n const actual = await this.log({ ...scope, feed_log_id: job });if (actual.log.process_status === 'FAILED' || (actual.log.error_count ?? 0) > 0) throw new Error('Native task failed or has item errors');return [job];\n } catch (error) { throw failure(error, 'Catalog-video upload failed, has item errors or is unconfirmed. Reconcile the known job or native task history before another preview.', job ? [job] : undefined); }\n } };\n }\n if (op.tool === 'tiktok_delete_catalog_video' && op.kind === 'remove') {\n const input = catalogVideoDelete.parse(op.payload), scope = catalogInput.parse({ account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id });\n const prepare = async () => {\n await this.parent(scope, true);const result = await this.native(scope, [input.catalog_video_id]);if (result.rows.length !== 1) throw new AdportError('INVALID_INPUT', 'The exact catalog video could not be verified. Refresh the gallery.');\n const row = result.rows[0]!;if (configurationHash(scope, row) !== input.expected_configuration_hash) throw new AdportError('PENDING_MISMATCH', 'The catalog video changed. Read its configuration and request a fresh preview.');return row;\n };\n const current = await prepare(), notes = ['Local preview only. Removes one catalog video and its product associations; existing catalog ads may be affected.', 'Video copies already synced into advertiser creative libraries are not removed. No global/atomic usage guarantee or restore endpoint is available.'];\n return { summary: `Remove catalog video \"${current.video_name}\"`, changes: [`- Catalog video ${input.catalog_video_id} and its catalog SKU associations.`, 'Advertiser-library copies may remain.'], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'tiktok', accountId: scope.account_id, kind: 'remove', title: 'Remove from catalog', subject: current.video_name, fields: [{ label: 'Catalog video', after: input.catalog_video_id }, { label: 'Associated SKUs', after: current.sku_id_list ?? 'Not reported' }, { label: 'Extraction', after: current.status }, { label: 'Activation', after: current.active_status ?? 'Not reported' }], notices: notes },\n execute: async () => {\n await prepare();\n try {\n const receipt = await this.client.post<unknown>('catalog/video/delete', { bc_id: input.bc_id, catalog_id: input.catalog_id, catalog_video_ids: [input.catalog_video_id] });\n if (receipt === null || typeof receipt !== 'object' || Array.isArray(receipt)) throw new Error('Unexpected native acknowledgement');\n if ((await this.native(scope, [input.catalog_video_id])).rows.length) throw new Error('Video remains visible');return [input.catalog_video_id];\n } catch (error) { throw failure(error, 'Catalog-video removal or filtered-view absence is unconfirmed. Inspect the selected video before any new deletion.', [input.catalog_video_id]); }\n } };\n }\n throw new AdportError('INVALID_INPUT', 'Unsupported TikTok catalog-video operation or kind.');\n }\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport { z } from 'zod';\nimport type { TikTokClient } from './client.js';\nimport { audienceNativeId } from './custom-audience-schemas.js';\nimport { TikTokCustomAudiences, customAudienceConfiguration } from './custom-audiences.js';\nimport { audienceSharesRead, audienceSharingContext, shareAudiences, unshareAudience } from './audience-sharing-schemas.js';\nimport { nativeListComplete } from './pagination.js';\n\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<WriteResult> };\ntype Audience = Awaited<ReturnType<TikTokCustomAudiences['inspect']>>[number];\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 nativeShare = z.object({ custom_audience_id: audienceNativeId, shared_advertiser_id: audienceNativeId, shared_advertiser_name: z.string().max(4096), status: z.string().max(128) });\ntype Share = z.infer<typeof nativeShare>;\nconst asset = z.object({ asset_id: audienceNativeId, asset_type: z.literal('ADVERTISER'), asset_name: z.string().max(4096), advertiser_role: z.string().max(128) });\nconst pageInfo = z.object({ page: z.number().int().positive().safe(), page_size: z.number().int().min(1).max(50), total_page: z.number().int().nonnegative().safe().optional(), total_number: z.number().int().nonnegative().safe().optional() });\nconst supported = new Set(['Customer File Audience', 'Engagement Audience', 'App Activity Audience', 'Website Audience', 'Lookalike Audience']);\nconst notices = ['This changes audience access for the selected destination advertisers. Revocation can affect ads already targeting a shared audience. No ad, budget or delivery status is changed.', 'Business Center membership and source role are checked from the authorized user’s native asset view. Native eligibility, account ownership requirements, quotas and concurrent operations remain authoritative.', 'Sharing-log presence and native audience status are separate from matching, targetability or delivery. No conditional-write, atomic batch or automatic replay is available.'];\nconst invalid = () => new AdportError('PROVIDER_ERROR', 'TikTok sharing scope, native representation or inventory completeness could not be verified.');\nconst preserved = (row: Audience) => { const { shared: _shared, ...configuration } = customAudienceConfiguration(row);return configuration; };\n\n/** Official SDK f809c396 and current published share/cancel/log/BC-asset docs, checked2026-11-06. */\nexport class TikTokAudienceSharing {\n constructor(private readonly client: TikTokClient, private readonly audiences: TikTokCustomAudiences, private readonly authorizeAccounts: (ids: string[]) => Promise<void>) {}\n private async get(path: string, input: Record<string, unknown>) {\n try { return await this.client.get<unknown>(path, input); } catch (error) { const details = error instanceof AdportError && error.details && typeof error.details === 'object' ? error.details as Record<string, unknown> : {};throw new AdportError('PROVIDER_ERROR', 'TikTok audience sharing read failed. Check existing native permissions; no access was changed.', { ...(Number.isSafeInteger(details.code) ? { native_code: details.code } : {}) }); }\n }\n private owned(account: string, row: Audience, share: boolean) {\n if (row.is_creator !== true || row.owner_id !== account) throw new AdportError('POLICY_VIOLATION', 'Audience sharing requires explicit selected-advertiser ownership; recipient access is insufficient.');\n if (share && (!supported.has(row.type.trim()) || row.is_valid !== true || row.is_expiring !== false || row.native_error_reported)) throw new AdportError('INVALID_INPUT', 'Only a documented shareable, available, non-expiring audience without a native error can be shared.');\n }\n private async log(account: string, audience: string): Promise<Share[]> {\n const parsed = z.object({ list: z.array(nativeShare).max(5000) }).safeParse(await this.get('dmp/custom_audience/share/log', { advertiser_id: account, custom_audience_id: audience }));\n if (!parsed.success || parsed.data.list.some(row => row.custom_audience_id !== audience) || new Set(parsed.data.list.map(row => row.shared_advertiser_id)).size !== parsed.data.list.length) throw invalid();\n return parsed.data.list.sort((a, b) => a.shared_advertiser_id.localeCompare(b.shared_advertiser_id));\n }\n private async logs(account: string, ids: string[]) { const rows = new Map<string, Share[]>();for (const id of ids) rows.set(id, await this.log(account, id));return rows; }\n private selection(account: string, targets: string[]) { if (targets.includes(account)) throw new AdportError('INVALID_INPUT', 'Choose destination advertisers other than the source.'); }\n private view(logs: Map<string, Share[]>, targets: string[]) { return [...logs.values()].flat().filter(row => targets.includes(row.shared_advertiser_id)); }\n async read(value: unknown) {\n const input = audienceSharesRead.parse(value);this.selection(input.account_id, input.shared_advertiser_ids);await this.authorizeAccounts([input.account_id, ...input.shared_advertiser_ids]);\n const audiences = await this.audiences.inspect(input.account_id, input.custom_audience_ids);audiences.forEach(row => this.owned(input.account_id, row, false));const logs = await this.logs(input.account_id, input.custom_audience_ids), selected = this.view(logs, input.shared_advertiser_ids);\n return { records: selected, shares: selected, audiences: audiences.map(row => ({ id: row.audience_id, name: row.name, snapshot_hash: row.snapshot_hash })), other_recipient_count: [...logs.values()].flat().length - selected.length, complete: true, truncated: false, notes: notices };\n }\n private async businessAccounts(bc: string, source: string, targets: string[]) {\n const wanted = new Set([source, ...targets]), found = new Map<string, z.infer<typeof asset>>(), seen = new Set<string>();let complete = false;\n for (let page = 1; page <= 100; page++) {\n const parsed = z.object({ list: z.array(asset).max(50), page_info: pageInfo.optional() }).safeParse(await this.get('bc/asset/get', { bc_id: bc, asset_type: 'ADVERTISER', page, page_size: 50 }));\n if (!parsed.success || parsed.data.page_info && (parsed.data.page_info.page !== page || parsed.data.page_info.page_size !== 50)) throw invalid();\n const info = parsed.data.page_info;\n if (info && (info.total_page !== undefined && info.total_page < page && parsed.data.list.length > 0 || info.total_number !== undefined && (parsed.data.list.length !== Math.max(0, Math.min(50, info.total_number - (page - 1) * 50)) || info.total_page !== undefined && (info.total_number === 0 ? info.total_page > 1 : info.total_page !== Math.ceil(info.total_number / 50))))) throw invalid();\n for (const row of parsed.data.list) { if (seen.has(row.asset_id)) throw invalid();seen.add(row.asset_id);if (wanted.has(row.asset_id)) found.set(row.asset_id, row); }\n if (found.size === wanted.size) break;\n const end = nativeListComplete(parsed.data.page_info, parsed.data.list.length);if (end !== false) { complete = end === true;break; }\n }\n if (found.size !== wanted.size) throw new AdportError('INVALID_INPUT', complete ? 'Selected source/destination accounts are not all accessible in this Business Center.' : 'Business Center membership is unconfirmed; inventory is incomplete.');\n if (!['ADMIN', 'OPERATOR'].includes(found.get(source)!.advertiser_role)) throw new AdportError('POLICY_VIOLATION', 'Audience sharing requires the authorized user to be Admin or Operator on the source advertiser.');\n return [...found.values()].sort((a, b) => a.asset_id.localeCompare(b.asset_id));\n }\n private async prepare(value: unknown) {\n const input = audienceSharingContext.parse(value);this.selection(input.account_id, input.shared_advertiser_ids);await this.authorizeAccounts([input.account_id, ...input.shared_advertiser_ids]);\n const accounts = await this.businessAccounts(input.bc_id, input.account_id, input.shared_advertiser_ids), audiences = await this.audiences.inspect(input.account_id, input.custom_audience_ids);audiences.forEach(row => this.owned(input.account_id, row, input.action === 'SHARE'));const logs = await this.logs(input.account_id, input.custom_audience_ids);\n const fingerprint = { input, accounts, audiences: audiences.map(row => ({ snapshot_hash: row.snapshot_hash, configuration: preserved(row) })), logs: [...logs].map(([id, rows]) => [id, rows.map(({ shared_advertiser_name: _name, ...row }) => row)]) };\n return { input, accounts, audiences, logs, context_hash: hash(fingerprint) };\n }\n async context(value: unknown) {\n const current = await this.prepare(value), selected = this.view(current.logs, current.input.shared_advertiser_ids);\n return { context_hash: current.context_hash, action: current.input.action, bc_id: current.input.bc_id, accounts: current.accounts, audiences: current.audiences, existing_pairs: selected, records: current.audiences.flatMap(row => current.input.shared_advertiser_ids.map(id => ({ custom_audience_id: row.audience_id, audience_name: row.name, recipient_advertiser_id: id, shared: selected.some(pair => pair.custom_audience_id === row.audience_id && pair.shared_advertiser_id === id) }))), notes: notices };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n const share = op.tool === 'tiktok_share_custom_audiences';if (op.provider !== 'tiktok' || op.kind !== 'update' || !share && op.tool !== 'tiktok_unshare_custom_audience') throw new AdportError('INVALID_INPUT', 'Unsupported audience-sharing operation/provider kind.');\n const selected = share ? shareAudiences.parse(op.payload) : unshareAudience.parse(op.payload), input = share ? { account_id: op.accountId, ...shareAudiences.parse(selected), action: 'SHARE' as const } : { account_id: op.accountId, bc_id: selected.bc_id, custom_audience_ids: [unshareAudience.parse(selected).custom_audience_id], shared_advertiser_ids: [unshareAudience.parse(selected).shared_advertiser_id], action: 'UNSHARE' as const };\n const selection = audienceSharingContext.parse(Object.fromEntries(Object.entries(input).filter(([key]) => !['expected_context_hash', 'acknowledge_recipient_access'].includes(key))));\n if (canonical([...new Set(op.affectedAccountIds ?? [])].sort()) !== canonical([...selection.shared_advertiser_ids].sort())) throw new AdportError('POLICY_VIOLATION', 'All destination accounts must be bound to the shared policy operation.');\n const current = await this.prepare(selection);if (current.context_hash !== selected.expected_context_hash) throw new AdportError('PENDING_MISMATCH', 'Audience sharing, source configuration or account authority changed; read and preview again.');\n const existing = this.view(current.logs, selection.shared_advertiser_ids);\n if (share ? existing.length > 0 : existing.length !== 1) throw new AdportError('INVALID_INPUT', share ? 'A selected audience/recipient pair already appears in the sharing log. Reconcile partial outcomes and select only intended new pairs; do not replay sharing.' : 'The exact audience/recipient pair is not present in the current explicit sharing log.');\n const title = share ? 'Share custom audiences' : 'Revoke audience sharing';\n return { summary: title, changes: current.audiences.map(row => `${share ? '+' : '-'} ${row.name} · ${selection.shared_advertiser_ids.length} recipient(s)`), coercions: [], budgetDeltas: [], notes: notices, review: { provider: 'tiktok', accountId: op.accountId, kind: 'update', title, fields: [{ label: 'Business Center', after: selection.bc_id }, { label: 'Owned audiences', after: current.audiences.map(row => ({ id: row.audience_id, name: row.name, type: row.type })) }, { label: 'Recipient accounts', after: current.accounts.filter(row => row.asset_id !== op.accountId).map(row => ({ id: row.asset_id, name: row.asset_name })) }, { label: 'Audience access', before: share ? 'Not shared with selected recipients' : 'Shared with selected recipient', after: share ? 'Grant selected recipients access' : 'Revoke selected recipient access' }], notices }, execute: async () => {\n const outcomes: Array<{ custom_audience_id: string; shared_advertiser_id: string; observed: string }> = [];\n try {\n const body = share ? { advertiser_id: op.accountId, custom_audience_ids: selection.custom_audience_ids, shared_advertiser_ids: selection.shared_advertiser_ids } : { advertiser_id: op.accountId, custom_audience_id: selection.custom_audience_ids[0]!, shared_advertiser_id: selection.shared_advertiser_ids[0]! };\n await this.client.post(share ? 'dmp/custom_audience/share' : 'dmp/custom_audience/share/cancel', body);\n for (const audience of selection.custom_audience_ids) {\n const rows = await this.log(op.accountId, audience);\n for (const recipient of selection.shared_advertiser_ids) outcomes.push({ custom_audience_id: audience, shared_advertiser_id: recipient, observed: rows.some(row => row.shared_advertiser_id === recipient) ? 'PRESENT' : 'ABSENT' });\n const others = (values: Share[]) => values.filter(row => !selection.shared_advertiser_ids.includes(row.shared_advertiser_id)).map(row => row.shared_advertiser_id).sort();\n if (canonical(others(rows)) !== canonical(others(current.logs.get(audience)!))) throw invalid();\n }\n if (outcomes.some(row => row.observed !== (share ? 'PRESENT' : 'ABSENT'))) throw invalid();\n const after = await this.audiences.inspect(op.accountId, selection.custom_audience_ids);if (after.some(row => canonical(preserved(row)) !== canonical(preserved(current.audiences.find(before => before.audience_id === row.audience_id)!)))) throw invalid();\n return { applied: true, resourceIds: selection.custom_audience_ids, details: { state: share ? 'RECIPIENT_PAIRS_OBSERVED' : 'RECIPIENT_PAIR_ABSENT', outcomes, audience_configuration_preserved: true, audience_availability_verified: false, ads_changed: false, next_tool: 'tiktok_custom_audience_shares', next_arguments: { account_id: op.accountId, custom_audience_ids: selection.custom_audience_ids, shared_advertiser_ids: selection.shared_advertiser_ids } }, ...(share ? { warnings: ['Recipient pairs are present in the native sharing log. Audience targeting availability remains unverified; inspect native status before use.'] } : {}) };\n } catch (error) {\n const details = error instanceof AdportError && error.details && typeof error.details === 'object' ? error.details as Record<string, unknown> : {};\n throw new AdportError('PROVIDER_ERROR', 'Audience sharing outcome is unconfirmed. Reconcile every selected pair in the sharing log before a new preview. No mutation was retried.', { resourceIds: selection.custom_audience_ids, observed_pairs: outcomes, ...(Number.isSafeInteger(details.code) ? { native_code: details.code } : {}) });\n }\n } };\n }\n}\n","import { z } from 'zod';\nimport { audienceId } from './custom-audience-schemas.js';\n\nconst selectedIds = z.array(audienceId).min(1).max(10).refine(values => new Set(values).size === values.length, 'Use unique IDs');\nexport const sharingSelection = z.object({ custom_audience_ids: selectedIds, shared_advertiser_ids: selectedIds }).strict();\nexport const audienceSharesRead = sharingSelection.safeExtend({ account_id: audienceId });\nexport const audienceSharingContext = audienceSharesRead.safeExtend({ bc_id: audienceId, action: z.enum(['SHARE', 'UNSHARE']).default('SHARE') }).refine(value => value.action !== 'UNSHARE' || value.custom_audience_ids.length === 1 && value.shared_advertiser_ids.length === 1, 'Cancellation selects one audience/recipient pair');\nexport const shareAudiences = sharingSelection.safeExtend({ bc_id: audienceId, expected_context_hash: z.string().regex(/^[a-f0-9]{64}$/), acknowledge_recipient_access: z.literal(true) });\nexport const unshareAudience = z.object({ bc_id: audienceId, custom_audience_id: audienceId, shared_advertiser_id: audienceId, expected_context_hash: z.string().regex(/^[a-f0-9]{64}$/), acknowledge_shared_effects: z.literal(true) }).strict();\nexport const audienceSharingWrites = new Set(['tiktok_share_custom_audiences', 'tiktok_unshare_custom_audience']);\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { TikTokAdsProvider } from './provider.js';\nimport { tiktokCreativeTools } from './creative-tools.js';\nimport { tiktokAudienceTools } from './audiences.js';\nimport { tiktokCustomAudienceTools } from './custom-audience-tools.js';\nimport { tiktokAudienceAuthoringTools } from './audience-authoring-tools.js';\nimport { tiktokAudienceSharingTools } from './audience-sharing-tools.js';\nimport { tiktokMeasurementTools } from './measurement.js';\nimport { tiktokAutomatedRuleTools } from './automated-rules.js';\nimport { tiktokCatalogTools } from './catalog-tools.js';\n\nconst OBJECTIVES = [\n 'REACH',\n 'TRAFFIC',\n 'VIDEO_VIEWS',\n 'LEAD_GENERATION',\n 'ENGAGEMENT',\n 'APP_PROMOTION',\n 'WEB_CONVERSIONS',\n 'PRODUCT_SALES',\n] as const;\n\nconst operationStatusSchema = z.enum(['ENABLE', 'DISABLE']);\n\nexport function tiktokTools(provider: TikTokAdsProvider, options: { catalogAccessManagement?: boolean } = {}): AnyToolDefinition[] {\n return [\n ...tiktokCreativeTools(provider),\n ...tiktokAudienceTools(provider),\n ...tiktokCustomAudienceTools(provider),\n ...tiktokAudienceAuthoringTools(provider),\n ...tiktokAudienceSharingTools(provider),\n ...tiktokMeasurementTools(provider),\n ...tiktokAutomatedRuleTools(provider),\n ...tiktokCatalogTools(provider, options.catalogAccessManagement),\n defineTool({\n name: 'tiktok_api_read',\n namespace: 'tiktok',\n description: 'Call any documented TikTok Business API v1.3 GET endpoint with advertiser scoping and API-shaped parameters.',\n input: z.object({\n account_id: z.string(),\n path: z.string().min(3).describe('Relative endpoint, e.g. adgroup/get, ad/get, creative/report/get'),\n params: z.record(z.string(), z.unknown()).optional(),\n }),\n annotations: { readOnly: true },\n async handler(input) {\n return provider.apiRead(input);\n },\n }),\n defineTool({\n name: 'tiktok_campaigns',\n namespace: 'tiktok',\n description: 'List TikTok campaigns (id, name, operation_status ENABLE/DISABLE, budget, budget_mode, objective).',\n input: z.object({\n account_id: z.string().describe('Advertiser id'),\n campaign_ids: z.array(z.string()).optional(),\n }),\n annotations: { readOnly: true },\n async handler(input) {\n const campaigns = await provider.listCampaigns(input.account_id, input.campaign_ids);\n return { campaigns };\n },\n }),\n defineTool({\n name: 'tiktok_report',\n namespace: 'tiktok',\n description:\n 'Raw TikTok synchronous reporting (report/integrated). Metric values come back as strings; ' +\n 'note total_complete_payment_rate is total purchase VALUE (misleading name), complete_payment_roas is purchase ROAS.',\n input: z.object({\n account_id: z.string(),\n data_level: z.enum(['AUCTION_ADVERTISER', 'AUCTION_CAMPAIGN', 'AUCTION_ADGROUP', 'AUCTION_AD']).default('AUCTION_CAMPAIGN'),\n dimensions: z.array(z.string()).min(1).default(['campaign_id']),\n metrics: z.array(z.string()).min(1).default(['spend', 'impressions', 'clicks', 'conversion']),\n start_date: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/),\n end_date: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/),\n page_size: z.number().int().positive().max(1000).default(200),\n }),\n annotations: { readOnly: true },\n async handler(input) {\n const rows = await provider.rawReport(input);\n return { rows, row_count: rows.length };\n },\n }),\n guardedWriteTool({\n name: 'tiktok_create_campaign',\n namespace: 'tiktok',\n description:\n 'Create a TikTok campaign. Budget is a float in whole account-currency units (min ~20 USD-equivalent for ' +\n 'DAY/TOTAL modes). TikTok has no server-side dry run — the preview is a client-side diff.',\n provider: 'tiktok',\n kind: 'create',\n payload: z.object({\n campaign_name: z.string().min(1).max(512),\n objective_type: z.enum(OBJECTIVES).default('TRAFFIC'),\n budget_mode: z.enum(['BUDGET_MODE_DAY', 'BUDGET_MODE_TOTAL', 'BUDGET_MODE_INFINITE']).default('BUDGET_MODE_DAY'),\n budget: z.number().positive().optional().describe('Whole currency units (float), required unless BUDGET_MODE_INFINITE'),\n operation_status: operationStatusSchema.optional(),\n }),\n }),\n guardedWriteTool({\n name: 'tiktok_set_campaign_status',\n namespace: 'tiktok',\n description: 'Enable or pause (DISABLE) up to 20 TikTok campaigns.',\n provider: 'tiktok',\n kind: 'update',\n payload: z.object({\n campaign_ids: z.array(z.string()).min(1).max(20),\n operation_status: operationStatusSchema,\n }),\n }),\n guardedWriteTool({\n name: 'tiktok_set_budget',\n namespace: 'tiktok',\n description:\n \"Change a TikTok campaign's budget (whole currency units). TikTok rejects new budgets below 105% of current spend.\",\n provider: 'tiktok',\n kind: 'update',\n payload: z.object({\n campaign_id: z.string(),\n budget: z.number().positive(),\n }),\n }),\n guardedWriteTool({\n name: 'tiktok_api_create',\n namespace: 'tiktok',\n description:\n 'Create through any documented TikTok Business API v1.3 /create endpoint. The advertiser is forced to account_id, campaign creation is paused, and budget fields are policy-checked.',\n provider: 'tiktok',\n kind: 'create',\n payload: z.object({ path: z.string().min(3), body: z.record(z.string(), z.unknown()) }),\n }),\n guardedWriteTool({\n name: 'tiktok_api_update',\n namespace: 'tiktok',\n description: 'Update non-budget/non-bid fields through any documented TikTok Business API v1.3 /update endpoint. Monetary and target-ROAS edits require typed tools.',\n provider: 'tiktok',\n kind: 'update',\n payload: z.object({ path: z.string().min(3), body: z.record(z.string(), z.unknown()) }),\n }),\n guardedWriteTool({\n name: 'tiktok_api_delete',\n namespace: 'tiktok',\n description: 'Permanently delete through any documented TikTok Business API v1.3 /delete endpoint.',\n provider: 'tiktok',\n kind: 'remove',\n destructive: true,\n payload: z.object({ path: z.string().min(3), body: z.record(z.string(), z.unknown()) }),\n }),\n ];\n}\n","import { creativesOutput, defineTool, guardedWriteTool, mediaSourceFields, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { TikTokAdsProvider } from './provider.js';\n\nconst id = z.string().regex(/^\\d+$/);\nconst status = z.enum(['ENABLE', 'DISABLE']);\nconst page = { page: z.number().int().positive().default(1), page_size: z.number().int().positive().max(1000).default(100) };\nconst url = z.string().url().refine(value => { const u = new URL(value); return ['https:', 'http:'].includes(u.protocol) && !u.username && !u.password; });\nconst strings = z.array(z.string().min(1));\nconst targetingShape = { location_ids: strings.optional(), zipcode_ids: strings.optional(), age_groups: strings.optional(), gender: z.string().min(1).optional(), languages: strings.optional(), operating_systems: strings.optional(), interest_category_ids: strings.optional(), interest_keyword_ids: strings.optional(), audience_ids: strings.optional(), excluded_audience_ids: strings.optional(), network_types: strings.optional(), device_model_ids: strings.optional(), dayparting: z.string().regex(/^[01]{336}$/).optional(), smart_audience_enabled: z.boolean().optional(), smart_interest_behavior_enabled: z.boolean().optional() };\nconst targeting = z.object(targetingShape).strict();\nexport const groupPayload = z.object({ campaign_id: id, adgroup_name: z.string().trim().min(1).max(512), promotion_type: z.string().min(1), placement_type: z.enum(['PLACEMENT_TYPE_AUTOMATIC', 'PLACEMENT_TYPE_NORMAL']), placements: strings.min(1).optional(), budget_mode: z.enum(['BUDGET_MODE_DAY', 'BUDGET_MODE_TOTAL']), budget: z.number().positive(), optimization_goal: z.string().min(1), billing_event: z.string().min(1), bid_type: z.enum(['BID_TYPE_CUSTOM', 'BID_TYPE_NO_BID']), bid_price: z.number().positive().optional(), conversion_bid_price: z.number().positive().optional(), pacing: z.enum(['PACING_MODE_SMOOTH', 'PACING_MODE_FAST']), schedule_type: z.enum(['SCHEDULE_FROM_NOW', 'SCHEDULE_START_END']), schedule_start_time: z.string().regex(/^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/), schedule_end_time: z.string().regex(/^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/).optional(), pixel_id: id.optional(), optimization_event: z.string().min(1).optional(), app_id: z.string().min(1).optional(), targeting, operation_status: status.default('DISABLE') }).refine(value => value.placement_type !== 'PLACEMENT_TYPE_NORMAL' || Boolean(value.placements?.length), 'Manual placement requires placements').refine(value => value.schedule_type !== 'SCHEDULE_START_END' || Boolean(value.schedule_end_time && value.schedule_end_time > value.schedule_start_time), 'Scheduled end must be after start');\nconst creative = z.object({ ad_name: z.string().trim().min(1).max(512), ad_format: z.enum(['SINGLE_VIDEO', 'SINGLE_IMAGE', 'CAROUSEL_ADS']), ad_text: z.string().min(1).max(100).optional(), identity_type: z.string().min(1), identity_id: z.string().min(1), identity_authorized_bc_id: id.optional(), video_id: z.string().min(1).optional(), image_ids: strings.min(1).optional(), tiktok_item_id: id.optional(), landing_page_url: url.optional(), call_to_action: z.string().min(1).optional(), display_name: z.string().min(1).optional(), operation_status: status.default('DISABLE') }).refine(value => value.ad_format !== 'SINGLE_VIDEO' || Boolean(value.video_id || value.tiktok_item_id), 'Video ads require video_id or an authorized tiktok_item_id').refine(value => value.ad_format === 'SINGLE_VIDEO' || Boolean(value.image_ids?.length), 'Image/carousel ads require image_ids').refine(value => !(value.video_id && value.tiktok_item_id), 'Choose video_id or tiktok_item_id').refine(value => Boolean(value.tiktok_item_id || value.ad_text), 'Non-Spark ads require ad_text');\n\nexport function tiktokCreativeTools(provider: TikTokAdsProvider): 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: 'tiktok', description, input, annotations: { readOnly: true }, handler });\n const write = (name: string, description: string, payload: z.ZodObject, kind: 'create' | 'update' = 'update') => guardedWriteTool({ name, namespace: 'tiktok', provider: 'tiktok', description, payload, kind });\n return [\n read('tiktok_ad_groups', 'Read native ad-group targeting, budgets, bidding, schedules and statuses with pagination.', z.object({ account_id: id, campaign_ids: z.array(id).optional(), ad_group_ids: z.array(id).optional(), ...page }), input => provider.creatives.groups(input)),\n defineTool({ name: 'tiktok_ads', namespace: 'tiktok', description: 'Read native TikTok ad configuration and copy with guarded text/status edit actions. Media previews use URLs returned by TikTok.', input: z.object({ account_id: id, ad_group_ids: z.array(id).optional(), ad_ids: z.array(id).optional(), ...page }), output: creativesOutput.extend({ ads: z.array(z.record(z.string(), z.unknown())), page_info: z.unknown().optional() }), presentation: 'creatives', annotations: { readOnly: true }, handler: input => provider.creatives.ads(input) }),\n read('tiktok_videos', 'Search the advertiser video library with native filtering and pagination.', z.object({ account_id: id, filtering: z.record(z.string(), z.unknown()).optional(), ...page }), input => provider.creatives.read('file/video/ad/search', input)),\n read('tiktok_image_info', 'Read advertiser image IDs, dimensions and returned preview URLs.', z.object({ account_id: id, image_ids: strings.min(1).max(100) }), input => provider.creatives.read('file/image/ad/info', input)),\n read('tiktok_video_info', 'Read advertiser video IDs, processing metadata and returned playback/cover URLs.', z.object({ account_id: id, video_ids: strings.min(1).max(100) }), input => provider.creatives.read('file/video/ad/info', input)),\n read('tiktok_search_targeting', 'Search location/zip targeting tags using TikTok’s read-only POST endpoint. Targeting eligibility depends on objective, placement and promotion type.', z.object({ account_id: id, keywords: strings.min(1).max(1000), search_type: z.enum(['FUZZY_SEARCH', 'BATCH_REGION_SEARCH', 'BATCH_ZIPCODE_SEARCH']).default('FUZZY_SEARCH'), objective_type: z.string().min(1), promotion_type: z.string().min(1).optional(), placements: strings.min(1), region_codes: strings.optional(), geo_types: strings.optional() }).refine(value => value.search_type !== 'FUZZY_SEARCH' || value.keywords.length === 1, 'Fuzzy search takes one keyword'), input => provider.creatives.read('tool/targeting/search', input, true)),\n write('tiktok_create_ad_group', 'Create an advertiser-owned ad group with explicit objective-dependent settings. Budgets/bids are whole currency units; schedules use advertiser time. Policy may force DISABLE.', groupPayload, 'create'),\n write('tiktok_create_ads', 'Create up to 20 standard or Spark ads in an account-owned ad group. Use existing authorized identity and media IDs. Policy may force every creative to DISABLE.', z.object({ ad_group_id: id, creatives: z.array(creative).min(1).max(20) }), 'create'),\n ...(['ad_group', 'ad'] as const).map(entity => write(`tiktok_set_${entity}_status`, 'Enable or pause verified advertiser-owned child entities. Parent serving settings remain independent.', z.object({ [entity === 'ad_group' ? 'ad_group_ids' : 'ad_ids']: z.array(id).min(1).max(20).refine(value => new Set(value).size === value.length, 'IDs must be unique'), operation_status: status }))),\n write('tiktok_update_ad', 'Patch supplied ad text/name, landing page or media IDs in its verified ad group. Uses patch_update=true; serving status and omitted creative fields are preserved.', z.object({ ad_group_id: id, ad_id: id, ad_name: z.string().min(1).max(512).optional(), ad_text: z.string().min(1).max(100).optional(), landing_page_url: url.optional(), video_id: z.string().min(1).optional(), image_ids: strings.min(1).optional() }).refine(value => ['ad_name', 'ad_text', 'landing_page_url', 'video_id', 'image_ids'].some(key => value[key as keyof typeof value] !== undefined), 'Provide a creative field')),\n write('tiktok_update_targeting', 'Replace only supplied ad-group targeting dimensions. Omitted targeting and serving settings remain unchanged; supplied arrays replace existing lists.', z.object({ ad_group_id: id, targeting: targeting.refine(value => Object.keys(value).length > 0, 'Provide a targeting dimension') })),\n write('tiktok_set_ad_group_budget', 'Change a verified ad-group budget in whole account-currency units. Current/proposed amounts are policy-checked; TikTok also enforces spend-based minimums.', z.object({ ad_group_id: id, budget: z.number().positive() })),\n write('tiktok_set_ad_group_bidding', 'Edit supplied ad-group bids and target ROAS. Monetary bids use whole account-currency units and current-value policy checks. Serving status remains unchanged.', z.object({ ad_group_id: id, bid_price: z.number().positive().optional(), conversion_bid_price: z.number().positive().optional(), roas_bid: z.number().positive().optional() }).refine(value => ['bid_price', 'conversion_bid_price', 'roas_bid'].some(key => value[key as keyof typeof value] !== undefined), 'Provide a bid field')),\n ...(['image', 'video'] as const).map(type => write(`tiktok_upload_${type}`, `Upload advertiser ${type} bytes with SHA-256-bound approval and TikTok MD5 signature. Hosted calls require media_id; file_path is local-only. Adport limits: images10MiB, videos100MiB.`, z.object({ ...mediaSourceFields }).refine(value => Number(Boolean(value.file_path)) + Number(Boolean(value.media_id)) === 1, 'Choose media_id or file_path'), 'create')),\n ];\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport type { TikTokAdsProvider } from './provider.js';\nimport { audienceFileUpload, customAudienceList, customAudienceGet, customerAudienceCreate, customerAudienceUpdate, customAudienceRename, customAudiencesDelete } from './custom-audience-schemas.js';\n\nexport function tiktokCustomAudienceTools(provider: TikTokAdsProvider): AnyToolDefinition[] {\n const catalog = { category: 'audiences' as const, exposure: 'specialist' as const }, write = { namespace: 'tiktok', provider: 'tiktok', catalog };\n return [\n defineTool({ name: 'tiktok_custom_audiences', namespace: 'tiktok', catalog, input: customAudienceList, presentation: 'records', pagination: { cursorInput: 'page', cursorOutput: 'next_page' }, annotations: { readOnly: true }, description: 'Page custom audiences, matched coverage and native availability. Supports up to100 exact ID filters. Explicit native pagination distinguishes missing completeness from absence; saved targeting templates are separate.', handler: input => provider.customAudiences.list(input) }),\n defineTool({ name: 'tiktok_get_custom_audience', namespace: 'tiktok', catalog, input: customAudienceGet, presentation: 'records', annotations: { readOnly: true }, description: 'Read exact audience ownership, configuration, availability, expiry and snapshot_hash. Missing native status remains unavailable. Customer identifiers and raw provider error/history messages are excluded.', handler: input => provider.customAudiences.get(input) }),\n guardedWriteTool({ ...write, name: 'tiktok_upload_audience_file', kind: 'create', destructive: false, sensitiveInputs: ['file_path'], payload: audienceFileUpload, description: 'Upload a checksum-bound private CSV/TXT of hashed identifiers from project media or local CLI. Validates the declared hash format and native multipart MD5. Returns a credential/advertiser-bound24-hour receipt; creates no audience and never retries uncertain uploads.' }),\n guardedWriteTool({ ...write, name: 'tiktok_create_customer_audience', kind: 'create', destructive: false, payload: customerAudienceCreate, description: 'Create an audience from1–49 distinct approved upload receipts of one encryption type. Enhancement is disabled. Verifies owned ID/name/type metadata, returns processing pending, and claims no individual membership or delivery change.' }),\n guardedWriteTool({ ...write, name: 'tiktok_update_customer_audience_users', kind: 'update', destructive: true, payload: customerAudienceUpdate, description: 'APPEND, REMOVE or REPLACE an owned available Customer File Audience using current snapshot_hash and matching upload receipts. Requires explicit shared-effects acknowledgement. Native membership processing/size/quota remain authoritative; accepted is not processed.' }),\n guardedWriteTool({ ...write, name: 'tiktok_rename_custom_audience', kind: 'update', destructive: false, payload: customAudienceRename, description: 'Rename an owned available non-expiring custom audience with current snapshot_hash. Independently checks preserved known configuration; sends no file paths or subtype conversion. Native expiry may reset.' }),\n guardedWriteTool({ ...write, name: 'tiktok_delete_custom_audiences', kind: 'remove', destructive: true, payload: customAudiencesDelete, description: 'Permanently delete1–100 owned audiences with exact names/hashes and explicit acknowledgements. Shared-recipient access is not ownership. Requires complete filtered absence readback; no restore, usage freeze or automatic replay.' }),\n ];\n}\n","import { z } from 'zod';\nimport { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport type { TikTokAdsProvider } from './provider.js';\nimport { audienceIdentityList, audienceSourceList, audienceRuleContext, ruleAudienceCreate, lookalikeAudienceCreate, lookalikeAudiencesRefresh } from './audience-authoring-schemas.js';\n\nexport function tiktokAudienceAuthoringTools(provider: TikTokAdsProvider): AnyToolDefinition[] {\n const catalog = { category: 'audiences' as const, exposure: 'specialist' as const }, read = { namespace: 'tiktok', catalog, presentation: 'records' as const, annotations: { readOnly: true }, output: z.looseObject({ records: z.array(z.record(z.string(), z.unknown())) }) }, write = { namespace: 'tiktok', provider: 'tiktok', catalog };\n return [\n defineTool({ ...read, name: 'tiktok_identities', description: 'Page identities already linked to the advertiser. Preserves native identity/BC references and availability; BC queries may include other linked identities. Creates no identity or permissions. Exact video source use rechecks identity/info.', input: audienceIdentityList, pagination: { cursorInput: 'page', cursorOutput: 'next_page' }, handler: input => provider.audienceSources.identities(input) }),\n defineTool({ ...read, name: 'tiktok_audience_sources', description: 'Discover advertiser-scoped event sources for all nine rule-audience families. Pages apps, pixels, ad groups, stores, offline sets and exact-identity videos. Source filters and cursors stay bound; organic history has a native 500-post window.', input: audienceSourceList, pagination: { cursorInput: 'cursor' }, handler: input => provider.audienceSources.list(input) }),\n defineTool({ ...read, name: 'tiktok_rule_audience_context', description: 'Validate exact inclusion/exclusion rules, nested URL/web-parameter filters and each source or explicit all-advertiser scope. Returns context_hash for creation. Does not freeze events, future sources or matched users.', input: audienceRuleContext, handler: input => provider.audienceAuthoring.context(input) }),\n guardedWriteTool({ ...write, name: 'tiktok_create_rule_audience', kind: 'create', destructive: false, payload: ruleAudienceCreate, description: 'Create a rule audience with fresh source context_hash and explicit automatic refresh. Rechecks all source access, disables enhancement and independently verifies owned ID/name metadata. Native event names/rule representation remain authoritative; returns processing pending.' }),\n guardedWriteTool({ ...write, name: 'tiktok_create_lookalike_audience', kind: 'create', destructive: false, payload: lookalikeAudienceCreate, description: 'Create a lookalike from an available non-lookalike seed with at least 100 native matched users and fresh source snapshot_hash. Uses modern native fields, explicit seed inclusion/OS/placements/locations/breadth and processing-pending metadata readback.' }),\n guardedWriteTool({ ...write, name: 'tiktok_refresh_lookalike_audiences', kind: 'update', destructive: true, payload: lookalikeAudiencesRefresh, description: 'Refresh 1–100 owned available lookalikes using each current snapshot_hash and shared-effects acknowledgement. Rechecks all targets before one native batch and preserves known metadata. Processing/membership is not confirmed; no automatic retry.' }),\n ];\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { TikTokAdsProvider } from './provider.js';\nimport { audienceSharesRead, audienceSharingContext, shareAudiences, unshareAudience } from './audience-sharing-schemas.js';\n\nexport function tiktokAudienceSharingTools(provider: TikTokAdsProvider): AnyToolDefinition[] {\n const shared = { namespace: 'tiktok', catalog: { category: 'audiences' as const, exposure: 'specialist' as const } }, read = { ...shared, output: z.looseObject({ records: z.array(z.record(z.string(), z.unknown())) }), presentation: 'records' as const, annotations: { readOnly: true }, additionalAccountInputs: ['shared_advertiser_ids'] }, write = { ...shared, provider: 'tiktok', kind: 'update' as const, destructive: true };\n return [\n defineTool({ ...read, name: 'tiktok_custom_audience_shares', description: 'Read owned audience sharing logs for explicit destination accounts. Hosted scope requires source and destinations enabled in this project. Other recipient names/IDs stay hidden. Native status is preserved; missing list data does not prove absence.', input: audienceSharesRead, handler: input => provider.audienceSharing.read(input) }),\n defineTool({ ...read, name: 'tiktok_audience_sharing_context', description: 'Check selected owned audiences, native authorization, source Admin/Operator role and selected accounts in one Business Center. Returns context_hash for SHARE or singular UNSHARE, with exact existing pairs. No access is changed.', input: audienceSharingContext, handler: input => provider.audienceSharing.context(input) }),\n guardedWriteTool({ ...write, name: 'tiktok_share_custom_audiences', payload: shareAudiences, additionalAccountInputs: ['shared_advertiser_ids'], description: 'Share1–10 eligible owned audiences with1–10 selected accounts in the same Business Center after current context and recipient-access acknowledgement. All affected accounts obey project/protected-account policy. Independent pair readback; accepted sharing does not certify audience availability or delivery.' }),\n guardedWriteTool({ ...write, name: 'tiktok_unshare_custom_audience', payload: unshareAudience, additionalAccountInputs: ['shared_advertiser_id'], description: 'Revoke sharing for one exact audience/recipient pair after context and shared-effects acknowledgement. Can affect destination ad targeting. Preserves the source audience; verifies explicit log absence. Does not delete customer data or pause ads.' }),\n ];\n}\n","import type { CredentialStore, ProviderModule } from '@adport/core';\nimport { TikTokClient, type TikTokCredentials } from './client.js';\nimport { TikTokAdsProvider } from './provider.js';\nimport { tiktokTools } from './tools.js';\nimport { FileTikTokCatalogAccessStore } from './catalog-access.js';\nimport { LocalMediaResolver } from '@adport/core';\n\nexport { TikTokClient, TIKTOK_API_VERSION, type TikTokCredentials } from './client.js';\nexport { TikTokAdsProvider, UNITS_TO_MICROS } from './provider.js';\nexport { tiktokTools } from './tools.js';\nexport { TikTokCatalogService } from './catalogs.js';\nexport { tiktokCatalogTools } from './catalog-tools.js';\nexport { FileTikTokCatalogAccessStore, catalogGrant, catalogScope, catalogScopeKey, creationScope, requireCatalogCreationAccess, requireCatalogAccess, type TikTokCatalogAccessMode, type TikTokCatalogAccessStore, type TikTokCatalogGrant, type TikTokCatalogScope } from './catalog-access.js';\n\nexport async function resolveTikTokCredentials(\n store: CredentialStore,\n): Promise<(TikTokCredentials & { appId: string; secret: string }) | undefined> {\n const record = await store.get('tiktok');\n if (record?.data.access_token && record.data.app_id && record.data.secret) {\n return {\n accessToken: record.data.access_token,\n appId: record.data.app_id,\n secret: record.data.secret,\n sandbox: record.data.sandbox === 'true',\n };\n }\n const env = process.env;\n if (env.TIKTOK_ACCESS_TOKEN && env.TIKTOK_APP_ID && env.TIKTOK_APP_SECRET) {\n return {\n accessToken: env.TIKTOK_ACCESS_TOKEN,\n appId: env.TIKTOK_APP_ID,\n secret: env.TIKTOK_APP_SECRET,\n sandbox: env.TIKTOK_SANDBOX === 'true',\n };\n }\n return undefined;\n}\n\nexport async function createTikTokModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveTikTokCredentials(store);\n if (!credentials) return undefined;\n const provider = new TikTokAdsProvider(new TikTokClient(credentials), {\n appId: credentials.appId,\n secret: credentials.secret,\n }, new LocalMediaResolver(), new FileTikTokCatalogAccessStore());\n return { provider, tools: tiktokTools(provider, { catalogAccessManagement: true }) };\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;AAC5B,SAAS,YAAY,uBAAuB;AAWrC,IAAM,qBAAqB;AAClC,IAAM,YAAY;AAClB,IAAM,eAAe;AAGrB,IAAM,aAAqC;AAAA,EACzC,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AACT;AAQO,IAAM,eAAN,MAAmB;AAAA,EAGxB,YACmB,aACA,YAA0B,OAC3C;AAFiB;AACA;AAEjB,SAAK,UAAU,GAAG,YAAY,UAAU,eAAe,SAAS,IAAI,kBAAkB;AAAA,EACxF;AAAA,EAJmB;AAAA,EACA;AAAA,EAJV;AAAA,EAST,MAAM,IAAOA,OAAc,SAAkC,CAAC,GAAG,UAAyC,CAAC,GAAe;AACxH,UAAM,SAAS,IAAI,gBAAgB;AACnC,eAAW,CAACC,MAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AACjD,UAAI,UAAU,OAAW;AACzB,aAAO,IAAIA,MAAK,OAAO,UAAU,WAAW,KAAK,UAAU,KAAK,IAAI,OAAO,KAAK,CAAC;AAAA,IACnF;AACA,UAAM,QAAQ,OAAO,OAAO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AyB,KAAK;AACxD,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,WAAW,IAAI,kBAAkB,IAAI,aAAa,WAAW,GAAG;AAAA,IACpE,OAAO,YAAY;AAAA,IACnB,QAAQ,YAAY;AAAA,EACtB,GAAG,IAAID,oBAAmB,GAAG,IAAI,6BAA6B,CAAC;AAC/D,SAAO,EAAE,UAAU,OAAO,YAAY,UAAU,EAAE,yBAAyB,KAAK,CAAC,EAAE;AACrF;","names":["path","key","payload","receipt","invalid","url","response","AdportError","AdportError","path","row","id","status","url","ids","key","targeting","creative","kind","createHash","AdportError","page","count","createHash","AdportError","page","audienceId","input","key","audienceIds","selected","createHash","z","AdportError","AdportError","invalid","count","row","z","ids","z","pageInfo","canonical","digest","createHash","row","snapshot","AdportError","ids","notes","AdportError","z","pageInfo","page","row","notes","ids","receipts","receipt","snapshot","canonical","source","createHash","count","digest","id","target","createHash","z","AdportError","z","z","ids","hash","filters","row","z","pageInfo","canonical","digest","createHash","invalid","AdportError","path","row","key","page","identity","count","ids","selected","id","z","AdportError","canonical","notes","invalid","AdportError","row","key","value","condition","id","name","source","z","ids","target","actual","createHash","AdportError","defineTool","guardedWriteTool","z","id","z","nativeId","name","row","pageInfo","canonical","configuration","key","hash","createHash","notes","AdportError","page","input","receipt","defineTool","guardedWriteTool","AdportError","defineTool","z","id","z","nativeId","rule","pageInfo","notes","key","AdportError","identity","target","path","page","row","defineTool","createHash","AdportError","z","defineTool","guardedWriteTool","z","z","createHash","AdportError","csvRows","mediaSourceFields","z","z","text","key","row","z","nativeId","selected","mediaSourceFields","row","name","canonical","digest","createHash","configuration","hash","invalid","AdportError","path","snapshot","notes","receipt","source","csvRows","target","ids","id","createHash","AdportError","z","hash","z","nativeId","count","selected","canonical","digest","createHash","invalid","AdportError","source","text","time","path","row","snapshot","status","title","fields","notes","name","body","receipt","AdportError","csvRows","MAX_PROJECT_MEDIA_BYTES","verifyMedia","z","count","z","nativeId","hash","invalid","AdportError","url","path","page","row","feed","source","MAX_PROJECT_MEDIA_BYTES","verifyMedia","csvRows","notes","receipt","createHash","AdportError","MAX_PROJECT_MEDIA_BYTES","verifyMedia","z","AdportError","z","kind","key","path","object","z","name","AdportError","hash","z","nativeId","selected","payload","object","canonical","digest","createHash","AdportError","key","url","id","path","asset","row","MAX_PROJECT_MEDIA_BYTES","source","verifyMedia","ids","page","config","feed","count","notes","result","createHash","AdportError","z","createHash","AdportError","z","mode","name","hash","z","row","canonical","digest","createHash","failure","ids","AdportError","code","notes","id","receipt","current","createHash","AdportError","z","hash","z","nativeId","text","paging","ids","canonical","digest","createHash","id","invalid","AdportError","failure","matching","snapshot","selected","path","response","row","native","current","notes","receipt","createHash","AdportError","csvRows","MAX_PROJECT_MEDIA_BYTES","verifyMedia","z","hash","z","count","nativeId","text","row","key","ids","canonical","digest","createHash","object","safeUrl","url","config","configurationHash","invalid","AdportError","failure","path","page","pageInfo","id","MAX_PROJECT_MEDIA_BYTES","verifyMedia","csvRows","selected","notes","receipt","hash","z","defineTool","guardedWriteTool","id","z","canonical","config","configurationHash","createHash","AdportError","row","input","scope","current","notes","source","createHash","AdportError","z","z","z","canonical","hash","createHash","z","pageInfo","invalid","AdportError","row","configuration","path","ids","id","selected","source","page","key","ids","row","id","AdportError","key","path","resourceIds","payload","creative","campaign","kind","defineTool","guardedWriteTool","z","creativesOutput","defineTool","guardedWriteTool","mediaSourceFields","z","id","status","page","strings","name","payload","kind","key","defineTool","guardedWriteTool","defineTool","guardedWriteTool","z","defineTool","guardedWriteTool","z","defineTool","guardedWriteTool","defineTool","guardedWriteTool","z","z","defineTool","guardedWriteTool","z","defineTool","guardedWriteTool","LocalMediaResolver","record"]}
|