@adport/mcp 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../package.json","../src/media-library-ui.ts","../src/media-upload-ui.ts","../src/trend-ui.ts","../src/record-ui.ts","../src/receipt-ui.ts","../src/insight-ui.ts","../src/creative-ui.ts","../src/provider-gallery-ui.ts","../src/provider-logos.ts","../src/operation-reconciliation-ui.ts","../src/operation-ui.ts","../src/apple-report-ui.ts","../src/native-report-ui.ts","../src/report-chart-ui.ts","../src/ui.ts"],"sourcesContent":["import { McpServer } from '@modelcontextprotocol/server';\nimport { serveStdio } from '@modelcontextprotocol/server/stdio';\nimport { z } from 'zod';\nimport { registerAppResource, registerAppTool, RESOURCE_MIME_TYPE } from '@modelcontextprotocol/ext-apps/server';\nimport { AdportError, CredentialStore, createContext, selectRuntimeCatalog, nextPageArguments, writeOutput, type ToolSelection, type AdportRuntime, type ProviderModule } from '@adport/core';\nimport { createGa4Module, createGscModule } from '@adport/provider-analytics';\nimport { createGtmModule } from '@adport/provider-gtm';\nimport { createGoogleModule } from '@adport/provider-google';\nimport { createMetaModule } from '@adport/provider-meta';\nimport { createTikTokModule } from '@adport/provider-tiktok';\nimport { createAppleModule } from '@adport/provider-apple';\nimport { createMicrosoftModule } from '@adport/provider-microsoft';\nimport { createRedditModule } from '@adport/provider-reddit';\nimport { createSnapchatModule } from '@adport/provider-snapchat';\nimport { createSpotifyModule } from '@adport/provider-spotify';\nimport { createPinterestModule } from '@adport/provider-pinterest';\nimport { createLinkedInModule } from '@adport/provider-linkedin';\nimport { createXModule } from '@adport/provider-x';\nimport { createOpenAIModule } from '@adport/provider-openai';\nimport packageJson from '../package.json';\nimport {\n ADPORT_SUMMARY_UI_URI,\n ADPORT_UI_HTML,\n ADPORT_UI_DOMAIN,\n ADPORT_UI_RESOURCE_DOMAINS,\n ADPORT_UI_URI,\n structuredResult,\n toolInvocationLabels,\n toolTitle,\n viewForTool,\n} from './ui.js';\n\nexport const PROVIDER_IDS = ['ga4', 'gsc', 'gtm', 'google', 'meta', 'tiktok', 'apple', 'microsoft', 'reddit', 'snapchat', 'spotify', 'pinterest', 'linkedin', 'x', 'openai'] as const;\nexport { ADPORT_UI_RESOURCE_DOMAINS };\nexport const ADPORT_UI_RESOURCE_URIS: readonly string[] = [ADPORT_UI_URI, 'ui://adport/insight-card-v30.html', 'ui://adport/insight-card-v29.html', 'ui://adport/insight-card-v28.html', 'ui://adport/insight-card-v27.html', 'ui://adport/insight-card-v26.html', 'ui://adport/insight-card-v25.html', 'ui://adport/insight-card-v24.html', 'ui://adport/insight-card-v23.html', 'ui://adport/insight-card-v22.html', 'ui://adport/insight-card-v21.html', 'ui://adport/insight-card-v20.html', 'ui://adport/insight-card-v19.html', 'ui://adport/insight-card-v18.html', 'ui://adport/insight-card-v17.html', 'ui://adport/insight-card-v16.html', 'ui://adport/insight-card-v15.html', 'ui://adport/insight-card-v14.html', 'ui://adport/insight-card-v13.html', 'ui://adport/insight-card-v12.html', 'ui://adport/insight-card-v11.html', 'ui://adport/insight-card-v10.html', 'ui://adport/insight-card-v9.html', 'ui://adport/insight-card-v8.html', 'ui://adport/insight-card-v7.html', 'ui://adport/insight-card-v6.html', 'ui://adport/insight-card-v5.html', 'ui://adport/insight-card-v4.html', 'ui://adport/insight-card-v3.html', 'ui://adport/insight-card-v2.html', ADPORT_SUMMARY_UI_URI];\n\nconst DEFAULT_MCP_ICONS = [{\n src: 'https://app.adport.dev/icon.svg?brand=orange-dot-v2',\n mimeType: 'image/svg+xml',\n sizes: ['any'],\n}];\n\n/**\n * Standard runtime assembly: real providers whose credentials exist. Mock data\n * is opt-in so a live runtime never silently substitutes synthetic accounts.\n */\nexport interface AssembleRuntimeOptions {\n includeMock?: boolean;\n includeRawTools?: boolean;\n}\n\nexport async function assembleRuntime(options: AssembleRuntimeOptions = {}): Promise<AdportRuntime> {\n const store = new CredentialStore();\n const modules: ProviderModule[] = [];\n const includeMock = options.includeMock ?? process.env.ADPORT_DEMO === 'true';\n if (!includeMock) {\n for (const factory of [createGa4Module, createGscModule, createGtmModule, createGoogleModule, createMetaModule, createTikTokModule, createAppleModule, createMicrosoftModule, createRedditModule, createSnapchatModule, createSpotifyModule, createPinterestModule, createLinkedInModule, createXModule, createOpenAIModule]) {\n const module = await factory(store);\n if (module) modules.push(module);\n }\n }\n const runtime = await createContext({ providerModules: modules, includeMock });\n return selectRuntimeCatalog(runtime, { profile: 'full', providers: null }, options.includeRawTools ?? false);\n}\n\nexport interface CreateServerOptions {\n runtime: AdportRuntime;\n catalog?: ToolSelection;\n /** Explicit local opt-in; production connectors always reject raw tools. */\n includeRawTools?: boolean;\n /** Transport-specific context, without redefining any provider tool. */\n instructions?: string;\n name?: string;\n version?: string;\n /** Brand icons advertised to MCP clients during initialization. */\n icons?: Array<{ src: string; mimeType?: string; sizes?: string[] }>;\n /** When set by a remote transport, only register tools authorized by this key. */\n scopes?: readonly string[];\n /**\n * Register tools blocked by a dynamic entitlement and return this structured\n * error when called. Missing credential scopes without a denial stay hidden.\n */\n scopeDenials?: Readonly<Record<string, ToolScopeDenial | undefined>>;\n /** Hosted transports can replace local CLI setup guidance, without changing the error code. */\n notConnectedMessage?: string;\n /** Hosted production must never serve synthetic results or demo tool definitions. */\n productionOnly?: boolean;\n /** Host-specific sandbox domain; null lets the host choose its default origin. */\n uiDomain?: string | null;\n uiResourceDomains?: readonly string[];\n /** Exact private-storage origins used by in-widget signed uploads. */\n uiConnectDomains?: readonly string[];\n}\n\nexport interface ToolScopeDenial {\n code: string;\n message: string;\n data?: Record<string, unknown>;\n}\n\ntype UiServerOptions = Pick<CreateServerOptions, 'name' | 'version' | 'icons' | 'uiDomain' | 'uiResourceDomains' | 'uiConnectDomains'>;\n\n/** Static resources only. Business requests must use the normal registry server. */\nexport function createMcpUiServer({ name = 'adport', version = packageJson.version, icons = DEFAULT_MCP_ICONS, uiDomain = ADPORT_UI_DOMAIN, uiResourceDomains = ADPORT_UI_RESOURCE_DOMAINS, uiConnectDomains = [] }: UiServerOptions = {}): McpServer {\n const server = new McpServer({ name, version, ...(icons ? { icons } : {}) });\n registerUiResources(server, uiDomain, uiResourceDomains, uiConnectDomains);\n return server;\n}\n\nfunction registerUiResources(server: McpServer, uiDomain: string | null, uiResourceDomains: readonly string[], uiConnectDomains: readonly string[]): void {\n // Only creative galleries make direct upload requests or render provider media.\n // Summary cards can still display project logos from the hosted storage origin.\n const summaryDomains = uiResourceDomains.filter(domain => domain === ADPORT_UI_DOMAIN || uiConnectDomains.includes(domain));\n for (const uri of ADPORT_UI_RESOURCE_URIS) {\n const summary = uri === ADPORT_SUMMARY_UI_URI;\n const resourceMeta = {\n ui: {\n ...(uiDomain ? { domain: uiDomain } : {}),\n prefersBorder: false,\n csp: { connectDomains: summary ? [] : [...uiConnectDomains], resourceDomains: summary ? summaryDomains : [...uiResourceDomains] },\n },\n ...(uiDomain?.startsWith('https://') ? { 'openai/widgetDomain': uiDomain } : {}),\n };\n const title = uri === ADPORT_UI_URI ? 'Adport insight card' : 'Adport insight card (previous URI)';\n registerAppResource(\n server, summary ? 'Adport summary card' : title, uri,\n { description: summary ? 'Adport results.' : 'Adport cards and creative previews.', _meta: resourceMeta },\n async () => ({ contents: [{ uri, mimeType: RESOURCE_MIME_TYPE, text: ADPORT_UI_HTML, _meta: resourceMeta }] }),\n );\n }\n}\n\n// Describe the fields needed to distinguish preview from apply. The full\n// provider result and widget payload still travel in structuredContent.\nconst hostedWriteOutput = z.looseObject({\n status: writeOutput.shape.status,\n applied: writeOutput.shape.applied,\n preview: z.looseObject(writeOutput.shape.preview.pick({ summary: true, serverValidated: true }).shape),\n pending_operation_id: z.string().optional(),\n expires_at: writeOutput.shape.expires_at.describe('Preview expiration.'),\n result: z.looseObject({}).optional(),\n});\n\n// Preserve the title and widget visibility fields on previously reviewed definitions.\n// Other hosted tools use annotation titles and default visibility to fit the catalog budget.\nconst explicitHostedTitle = new Set([\n 'meta_create_campaign',\n 'google_create_performance_max_campaign',\n]);\nconst explicitHostedUiVisibility = new Set([\n ...explicitHostedTitle,\n 'linkedin_get_sponsored_post',\n]);\n\n/**\n * Thin adapter: every tool in the shared registry becomes an MCP tool.\n * No tool logic lives here — see the \"one tool-definition layer\" principle.\n */\nexport function createMcpServer({ runtime, catalog = { profile: 'full', providers: null }, includeRawTools = false, instructions, name = 'adport', version = packageJson.version, icons = DEFAULT_MCP_ICONS, scopes, scopeDenials, notConnectedMessage, productionOnly = false, uiDomain = ADPORT_UI_DOMAIN, uiResourceDomains = ADPORT_UI_RESOURCE_DOMAINS, uiConnectDomains = [] }: CreateServerOptions): McpServer {\n if (productionOnly && (runtime.dataSource === 'synthetic'\n || runtime.ctx.providers.list().some(provider => !PROVIDER_IDS.includes(provider.id as typeof PROVIDER_IDS[number]))\n || runtime.registry.list().some(tool => /^(demo|mock|synthetic)(_|$)/.test(tool.name) || /^(demo|mock|synthetic)$/.test(tool.namespace)))) {\n throw new AdportError('POLICY_VIOLATION', 'Demo tools and synthetic runtimes are not available on the production connector.');\n }\n runtime = selectRuntimeCatalog(runtime, catalog, includeRawTools && !productionOnly);\n const provenance = (value: unknown): unknown => runtime.dataSource === 'synthetic'\n ? { ...(value && typeof value === 'object' && !Array.isArray(value) ? value : { value }), data_source: 'synthetic' }\n : value;\n const server = new McpServer({ name, version, ...(icons ? { icons } : {}) }, { instructions });\n registerUiResources(server, uiDomain, uiResourceDomains, uiConnectDomains);\n const widgetArguments = z.object({ arguments: z.record(z.string(), z.unknown()) }).optional();\n for (const tool of runtime.registry.list()) {\n // Hosted directory tools must expose each operation explicitly. Keep generic\n // dispatchers in the local CLI/stdio registry, never as a hosted escape hatch.\n if (productionOnly && (tool.name === 'recommendation_apply' || /_api_(read|create|update|delete|remove)$/.test(tool.name))) continue;\n const requiredScope = tool.annotations.readOnly ? 'tools:read' : 'tools:write';\n const scopeDenial = scopes && !scopes.includes(requiredScope) ? scopeDenials?.[requiredScope] : undefined;\n if (scopes && !scopes.includes(requiredScope) && !scopeDenial) continue;\n const view = tool.presentation ?? viewForTool(tool.name, tool.annotations.readOnly ?? false);\n const resourceUri = productionOnly && view !== 'creatives' ? ADPORT_SUMMARY_UI_URI : ADPORT_UI_URI;\n const canRefresh = (view === 'creatives' || view === 'records') && tool.annotations.readOnly;\n const canPage = canRefresh && tool.pagination !== undefined;\n // MCP structuredContent must be an object. Preserve legacy raw arrays in\n // text/CLI results, exposing their declared schema under a value envelope.\n const wrapOutput = !!tool.output && !(tool.output instanceof z.ZodObject);\n const output = productionOnly && tool.output === writeOutput ? hostedWriteOutput : tool.output;\n const objectOutput = output\n ? output instanceof z.ZodObject ? output : z.object({ value: output })\n : undefined;\n const definition = productionOnly ? tool.hosted ?? tool : tool;\n const title = toolTitle(tool.name);\n const config = {\n ...(!productionOnly || explicitHostedTitle.has(tool.name) ? { title } : {}),\n description: scopeDenial\n ? `${definition.description}\\n\\nUnavailable on the current plan: ${scopeDenial.message}`\n : definition.description,\n inputSchema: definition.input,\n ...(objectOutput ? { outputSchema: objectOutput.extend({\n ...(view ? { _adport: productionOnly ? z.looseObject({}) : z.object({\n tool: z.literal(tool.name), view: z.literal(view), providerNames: z.record(z.string(), z.string()),\n provider: z.string().optional(), accountId: z.string().optional(),\n ...(tool.pagination ? { pagination: z.object({ cursorInput: z.string() }).optional() } : {}),\n ...(view === 'operation' ? { approval: widgetArguments } : {}),\n context: z.object({ project_id: z.string() }).optional(),\n capabilities: z.object({ can_write: z.boolean() }).optional(),\n ...(canRefresh ? { refresh: widgetArguments } : {}),\n ...(canPage ? { next: widgetArguments } : {}),\n }) } : {}),\n ...(runtime.dataSource === 'synthetic' ? { data_source: z.literal('synthetic') } : {}),\n }) } : {}),\n annotations: {\n title,\n readOnlyHint: tool.annotations.readOnly ?? false,\n destructiveHint: tool.annotations.destructive ?? false,\n openWorldHint: tool.annotations.openWorld ?? false,\n },\n _meta: {\n ...(!productionOnly ? { 'adport/catalog': tool.catalog ?? {} } : {}),\n ...(tool.fileInputs?.length ? { 'openai/fileParams': [...tool.fileInputs] } : {}),\n },\n };\n const callback = async (args: Record<string, unknown>) => {\n const descriptor = {\n ...(PROVIDER_IDS.includes(tool.namespace as typeof PROVIDER_IDS[number]) ? { provider: tool.namespace } : {}),\n ...(typeof args.account_id === 'string' ? { accountId: args.account_id } : {}),\n ...(tool.pagination ? { pagination: { cursorInput: tool.pagination.cursorInput } } : {}),\n };\n if (scopeDenial) {\n const payload = provenance({\n error: scopeDenial.code,\n code: scopeDenial.code,\n message: scopeDenial.message,\n ...scopeDenial.data,\n });\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify(payload, null, 2),\n }],\n // SDK clients validate structuredContent even on isError responses.\n // Errors use JSON text (also consumed by the widget), never a fake\n // success object to satisfy the advertised output schema.\n isError: true,\n _meta: { adport: { tool: tool.name, view, ...descriptor } },\n };\n }\n try {\n const rawResult = await runtime.registry.call(tool.name, args, runtime.ctx);\n const result = provenance(rawResult);\n const structured = provenance(wrapOutput ? { value: rawResult } : rawResult);\n const rawObject = rawResult && typeof rawResult === 'object' && !Array.isArray(rawResult)\n ? rawResult as Record<string, unknown> : {};\n const nestedResult = rawObject.result && typeof rawObject.result === 'object' && !Array.isArray(rawObject.result)\n ? rawObject.result as Record<string, unknown> : {};\n const pending = rawObject.pending_operation_id ?? nestedResult.pending_operation_id;\n const privateArguments = [...(tool.sensitiveInputs ?? []), ...(tool.fileInputs ?? [])].some(path => {\n let current: unknown = args;\n for (const key of path.split('.')) {\n if (!current || typeof current !== 'object' || !Object.hasOwn(current, key)) return false;\n current = (current as Record<string, unknown>)[key];\n }\n return current !== undefined;\n });\n const approval = view === 'operation' && typeof pending === 'string' && !args.pending_operation_id && !privateArguments\n ? { arguments: { ...args } }\n : undefined;\n const nextArgs = !privateArguments && canPage ? nextPageArguments(tool, args, rawObject) : undefined;\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],\n ...(view ? { structuredContent: structuredResult(tool.name, view, structured, approval, typeof args.project_id === 'string' ? { project_id: args.project_id } : undefined, { can_write: !scopes || scopes.includes('tools:write') }, !privateArguments && canRefresh ? { arguments: Object.fromEntries(Object.entries(args).filter(([key]) => key !== 'pending_operation_id')) } : undefined, nextArgs ? { arguments: nextArgs } : undefined, descriptor) }\n : tool.output ? { structuredContent: structured as Record<string, unknown> } : {}),\n };\n } catch (err) {\n const planLimit = err instanceof AdportError && err.code === 'PLAN_LIMIT'\n && err.details && typeof err.details === 'object' && 'planLimit' in err.details\n ? err.details.planLimit : undefined;\n const payload = provenance(\n err instanceof AdportError\n ? { ...err.toJSON(), ...(planLimit ? { code: 'PLAN_LIMIT', planLimit } : {}), ...(err.code === 'NOT_CONNECTED' && notConnectedMessage && !(err.details && typeof err.details === 'object' && 'connection_recovery' in err.details) ? { message: notConnectedMessage } : {}) }\n : {\n error: 'INTERNAL',\n // Unexpected exceptions can contain credentials or private paths.\n // Do not imply that a failed response means a write was not applied.\n message: 'Adport could not complete this request. If this was a write, check its status before retrying. Contact support if the problem persists.',\n });\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(payload, null, 2) }],\n isError: true,\n _meta: { adport: { tool: tool.name, view, ...descriptor } },\n };\n }\n };\n if (view) {\n const labels = toolInvocationLabels(view);\n registerAppTool(server, tool.name, {\n ...config,\n _meta: {\n ...config._meta,\n ui: !productionOnly || explicitHostedUiVisibility.has(tool.name)\n ? { resourceUri, visibility: ['model', 'app'] }\n : { resourceUri },\n 'openai/widgetAccessible': true,\n 'openai/outputTemplate': resourceUri,\n ...(!productionOnly ? {\n 'openai/toolInvocation/invoking': labels.invoking,\n 'openai/toolInvocation/invoked': labels.invoked,\n } : {}),\n },\n }, callback);\n } else {\n server.registerTool(tool.name, config, callback);\n }\n }\n return server;\n}\n\nexport async function runStdioServer(runtime: AdportRuntime, version?: string, includeRawTools = false): Promise<void> {\n serveStdio(() => createMcpServer({ runtime, version, includeRawTools }));\n // stdout is the protocol channel; stderr is for humans.\n console.error(`adport MCP server on stdio (${runtime.registry.list().length} tools, policy: ${runtime.policySource})`);\n if (runtime.ctx.providers.list().length === 0) {\n console.error('No ad providers connected. Run `adport connect <provider>` or restart with `--demo` for synthetic mock data.');\n }\n}\n","{\n \"name\": \"@adport/mcp\",\n \"version\": \"0.11.0\",\n \"description\": \"adport MCP server — the open control plane for paid media\",\n \"license\": \"Apache-2.0\",\n \"type\": \"module\",\n \"main\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n }\n },\n \"bin\": {\n \"adport-mcp\": \"./dist/bin.js\"\n },\n \"files\": [\n \"dist\"\n ],\n \"scripts\": {\n \"build\": \"tsup src/index.ts src/bin.ts --format esm --dts --sourcemap --clean\",\n \"render:submission-previews\": \"node scripts/render-submission-previews.mjs\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc --noEmit\",\n \"clean\": \"rm -rf dist\"\n },\n \"dependencies\": {\n \"@adport/core\": \"workspace:*\",\n \"@adport/provider-apple\": \"workspace:*\",\n \"@adport/provider-google\": \"workspace:*\",\n \"@adport/provider-linkedin\": \"workspace:*\",\n \"@adport/provider-meta\": \"workspace:*\",\n \"@adport/provider-microsoft\": \"workspace:*\",\n \"@adport/provider-pinterest\": \"workspace:*\",\n \"@adport/provider-reddit\": \"workspace:*\",\n \"@adport/provider-snapchat\": \"workspace:*\",\n \"@adport/provider-spotify\": \"workspace:*\",\n \"@adport/provider-tiktok\": \"workspace:*\",\n \"@adport/provider-openai\": \"workspace:*\",\n \"@adport/provider-x\": \"workspace:*\",\n \"@modelcontextprotocol/ext-apps\": \"^2.0.4\",\n \"zod\": \"^4.6.7\",\n \"@modelcontextprotocol/server\": \"^2.4.0\",\n \"@adport/provider-gtm\": \"workspace:*\",\n \"@adport/provider-analytics\": \"workspace:*\"\n },\n \"devDependencies\": {\n \"@types/jsdom\": \"^21.1.7\",\n \"@types/node\": \"^26.6.6\",\n \"jsdom\": \"26.1.0\",\n \"tsup\": \"^8.3.0\",\n \"typescript\": \"^5.8.0\",\n \"vitest\": \"^4.1.10\",\n \"@modelcontextprotocol/client\": \"^2.4.0\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/ynnickw/adport.git\",\n \"directory\": \"packages/mcp\"\n },\n \"homepage\": \"https://github.com/ynnickw/adport#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/ynnickw/adport/issues\"\n },\n \"engines\": {\n \"node\": \">=22.13\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n","export const MEDIA_LIBRARY_STYLES = String.raw`\n .media-library { position:relative }\n .media-toolbar,.widget-upload-actions { display:flex; align-items:center; justify-content:space-between; gap:10px; margin-bottom:10px }\n .media-toolbar h2 { margin:0; font-size:13px; font-weight:600; letter-spacing:-.015em }\n .media-toolbar small { color:var(--muted); font-size:11px; font-weight:400; margin-left:7px }\n .media-button { display:inline-flex; align-items:center; justify-content:center; gap:5px; min-height:34px; padding:7px 12px; border:1px solid var(--line); border-radius:999px; background:var(--paper); color:var(--ink); font-size:12px; cursor:pointer; flex-shrink:0 }\n .media-button.primary { border-color:transparent; background:var(--orange); color:#171717; font-weight:600 }\n .media-button:active { opacity:.75 }\n .media-button:disabled,.media-button[aria-disabled=\"true\"] { opacity:.5; cursor:default }\n .media-file-label { position:relative; overflow:hidden }\n .media-file-label:focus-within { outline:2px solid var(--orange); outline-offset:2px }\n .media-file-label input { position:absolute; inset:0; width:100%; height:100%; opacity:0; cursor:pointer }\n .media-library.dragging::after { content:'Drop files to upload'; position:absolute; inset:0; z-index:2; display:grid; place-items:center; border:2px dashed var(--orange); border-radius:12px; background:var(--paper); color:var(--ink); font-size:14px; pointer-events:none }\n .widget-upload-queue { display:grid; gap:8px; max-height:220px; overflow:auto; margin-bottom:10px; scrollbar-width:thin }\n .widget-upload-row { display:grid; grid-template-columns:minmax(0,1fr) auto auto; gap:4px 9px; align-items:center; padding:8px 10px; background:var(--soft); border-radius:9px }\n .widget-upload-row strong { display:block; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; font-size:11px; font-weight:500 }\n .widget-upload-row small,.widget-upload-status { color:var(--muted); font-size:10px }\n .widget-upload-row progress { grid-column:1/-1; width:100%; height:4px; accent-color:var(--orange) }\n .widget-upload-row p { grid-column:1/-1; margin:2px 0; color:var(--red); font-size:11px; line-height:1.4; overflow-wrap:anywhere }\n .widget-upload-row .media-button { min-height:28px; padding:4px 8px; font-size:10px }\n .widget-upload-actions { justify-content:flex-end; margin-top:6px }\n .widget-upload-summary { margin-right:auto; color:var(--muted); font-size:11px }\n .media-pages { display:flex; justify-content:center; margin-top:10px }\n .media-message { margin:8px 0; color:var(--muted); font-size:11px; line-height:1.4 }\n @media (pointer:coarse) { .media-button,.widget-upload-row .media-button { min-height:44px } }\n`;\n\n/** Central library only. Pagination and queue updates retain existing media nodes. */\nexport const MEDIA_LIBRARY_UI = String.raw`\n let mediaLibrary=null;\n const libraryPreviewReads=new Map();\n function mediaLibraryProject(data,meta) {\n const project=meta.context?.project_id || data.upload_config?.project_id;\n return uploadUuid(project) && (!data.upload_config?.project_id || data.upload_config.project_id===project)?project:null;\n }\n function libraryFilterKey(meta) {\n const args={...meta.refresh?.arguments};delete args.cursor;delete args.pending_operation_id;\n return JSON.stringify(Object.keys(args).sort().map(key=>[key,args[key]]));\n }\n function mediaUploadMarkup(context) {\n if(!context) return '';\n return '<label class=\"media-button primary media-file-label\" title=\"Choose, drop or paste files\">Upload files<input type=\"file\" multiple data-upload-files aria-label=\"Upload files\" accept=\"'+esc(context.config.content_types.join(','))+'\"></label>';\n }\n function renderMediaLibrary(data,meta) {\n const project=mediaLibraryProject(data,meta),key=libraryFilterKey(meta);\n const retain=mediaLibrary?.project===project && mediaLibrary.key===key && app.querySelector('[data-media-gallery]');\n mediaLibrary={project,key,data,meta,loading:false,seen:retain?mediaLibrary.seen:new Set(),previews:retain?mediaLibrary.previews:new Map()};\n if(!retain) app.innerHTML=chrome('<div class=\"media-library\" data-upload-drop><div class=\"media-toolbar\"><h2>Media library<small data-library-count></small></h2><div data-upload-picker></div></div><section data-upload-panel aria-label=\"Upload queue\"></section><div data-library-notes></div><div class=\"creative-grid\" data-media-gallery role=\"region\" aria-label=\"Creative previews\" tabindex=\"0\"></div><div data-library-pages></div></div>','');\n app.querySelector('[data-library-count]').textContent=arr(data.creatives).length+' files';\n app.querySelector('[data-upload-picker]').innerHTML=mediaUploadMarkup(uploadContext(data,meta));\n app.querySelector('[data-library-notes]').innerHTML=notices({...data,truncated:false});\n const gallery=app.querySelector('[data-media-gallery]'),existing=new Map([...gallery.querySelectorAll('article')].map(card=>[card.dataset.mediaId,card]));\n const template=document.createElement('template');template.innerHTML=creativeCards(arr(data.creatives));\n const keep=new Set();\n for(const card of [...template.content.children]) {\n const old=existing.get(card.dataset.mediaId);keep.add(card.dataset.mediaId);\n if(old) {\n // Signed URLs renew independently; keep healthy players and their playback state.\n for(const selector of ['.creative-heading','.creative-copy','.creative-footer']) old.querySelector(selector)?.replaceChildren(...card.querySelector(selector).childNodes);\n if(!old.querySelector('img,video,audio') && !old.querySelector('[data-preview-retry]') && card.querySelector('.creative-media')) {const media=card.querySelector('.creative-media');if(old.querySelector('.creative-media')) old.querySelector('.creative-media').replaceWith(media);else old.querySelector('.creative-copy').before(media);bindLibraryPreviews(old);}\n } else {gallery.append(card);bindLibraryPreviews(card);}\n }\n for(const [id,card] of existing) if(!keep.has(id)) card.remove();\n gallery.querySelector('.empty')?.remove();\n if(!keep.size) gallery.innerHTML='<div class=\"empty\">'+(uploadContext(data,meta)?'Drop files here or choose Upload files.':'No files to preview.')+'</div>';\n renderLibraryPages();uploadDraw();bindWidgetUpload(uploadContext(data,meta));\n }\n function bindLibraryPreviews(root) {bindCreativeErrors(root,recoverLibraryPreview);}\n function libraryPreviewActive(scope,card,asset) {\n const current=arr(mediaLibrary?.data.assets).find(item=>item.id===asset.id);\n return mediaLibrary?.previews===scope && app.contains(card) && current?.sha256===asset.sha256 && current.status==='READY';\n }\n function libraryPreviewMessage(card,entry,loading=false) {\n const item=card.querySelector('.creative-media-item');if(!item) return;\n const message=document.createElement('span');message.className='creative-placeholder';message.setAttribute('role','status');message.textContent=loading?'Refreshing preview…':'Preview unavailable';\n // An expired image's anchor must not remain an active stale download link.\n const holder=document.createElement('div');holder.className='creative-media-item';holder.append(message);item.replaceWith(holder);\n if(!loading) {const retry=document.createElement('button');retry.className='media-button';retry.type='button';retry.dataset.previewRetry='true';retry.textContent='Retry';retry.setAttribute('aria-label','Retry preview: '+entry.asset.name);retry.addEventListener('click',()=>renewLibraryPreview(card,entry));holder.append(retry);}\n }\n function recoverLibraryPreview(media) {\n const card=media.closest('article'),asset=arr(mediaLibrary?.data.assets).find(item=>item.id===card?.dataset.mediaId);\n if(!card || !uploadUuid(asset?.id) || !/^[a-f0-9]{64}$/i.test(asset.sha256 || '') || asset.status!=='READY') return false;\n const scope=mediaLibrary.previews,key=asset.id+':'+asset.sha256;\n let entry=scope.get(key);\n if(!entry) {entry={asset,scope,project:mediaLibrary.project,pending:false};scope.set(key,entry);renewLibraryPreview(card,entry);}\n else libraryPreviewMessage(card,entry,entry.pending);\n return true;\n }\n async function renewLibraryPreview(card,entry) {\n const {asset,scope,project}=entry;if(entry.pending || !libraryPreviewActive(scope,card,asset)) return;\n entry.pending=true;libraryPreviewMessage(card,entry,true);\n libraryPreviewReads.set(project+':'+asset.id,entry);\n try {\n const response=await callTool('media_get',{media_id:asset.id,project_id:project},60000),value=resultData(response),fresh=value.asset;\n if(response?.isError || value.error || value._adport?.tool!=='media_get' || value._adport?.context?.project_id!==project || fresh?.id!==asset.id || fresh.sha256!==asset.sha256 || fresh.byte_length!==asset.byte_length || fresh.content_type!==asset.content_type || fresh.status!=='READY') throw new Error('Preview could not be confirmed.');\n if(!libraryPreviewActive(scope,card,asset)) return;\n const creative=arr(mediaLibrary.data.creatives).find(item=>item.id===asset.id),kind=fresh.content_type.split('/')[0];\n const media=fresh.preview_cover_url && fresh.preview_url?[{type:'image',url:fresh.preview_cover_url,open_url:fresh.preview_url,alt:creative.name+' — first page'}]:fresh.preview_url && ['image','video','audio'].includes(kind)?[{type:kind,url:fresh.preview_url,alt:creative.name}]:[];\n const updated={...creative,media},template=document.createElement('template');template.innerHTML=creativeCards([updated]);\n const preview=template.content.querySelector('.creative-media');if(!preview || !preview.querySelector('img,video,audio')) throw new Error('Preview unavailable.');\n card.querySelector('.creative-media').replaceWith(preview);bindLibraryPreviews(card);\n const data={...mediaLibrary.data,assets:arr(mediaLibrary.data.assets).map(item=>item.id===asset.id?fresh:item),creatives:arr(mediaLibrary.data.creatives).map(item=>item.id===asset.id?updated:item)};\n mediaLibrary.data=data;state.hasLocalResult=true;state.result={structuredContent:{...data,_adport:mediaLibrary.meta}};\n } catch {if(libraryPreviewActive(scope,card,asset)) libraryPreviewMessage(card,entry);}\n finally {\n entry.pending=false;\n // Keep every in-flight echo bound, even when a large page expires together.\n for(const [key,read] of libraryPreviewReads) {if(libraryPreviewReads.size<=32) break;if(!read.pending) libraryPreviewReads.delete(key);}\n }\n }\n function mediaLibraryIgnoreEcho(data) {\n return !!app.querySelector('[data-media-gallery]') && data?._adport?.tool==='media_get' && [...libraryPreviewReads.values()].some(entry=>data._adport.context?.project_id===entry.project && (entry.asset.id===data.asset?.id || entry.pending && !data.asset));\n }\n function renderLibraryPages(message='') {\n if(!mediaLibrary || !app.querySelector('[data-library-pages]')) return;\n const focused=app.querySelector('[data-library-more]')===document.activeElement;\n const {data,meta,loading}=mediaLibrary,next=meta.next?.arguments;\n app.querySelector('[data-library-pages]').innerHTML=(message?'<p class=\"media-message\" role=\"status\">'+esc(message)+'</p>':'')+(next?'<div class=\"media-pages\"><button class=\"media-button\" data-library-more aria-disabled=\"'+loading+'\">'+(loading?'Loading…':'Load more')+'</button></div>':data.truncated?'<p class=\"media-message\">More files may exist. Ask your assistant for the next page.</p>':'');\n const button=app.querySelector('[data-library-more]');button?.addEventListener('click',loadLibraryPage);\n if(focused) (button || app.querySelector('[data-media-gallery]'))?.focus({preventScroll:true});\n }\n async function loadLibraryPage() {\n const library=mediaLibrary;if(!library || library.loading || !library.meta.next?.arguments) return;\n const args={...library.meta.next.arguments,project_id:library.project};\n if(!uploadUuid(args.cursor) || library.seen.has(args.cursor)) {library.meta={...library.meta,next:undefined};renderLibraryPages('No new page was returned.');return;}\n library.loading=true;renderLibraryPages();\n try {\n const response=await callTool('media_list',args,60000),value=resultData(response);\n if(response?.isError || value.error || !Array.isArray(value.creatives) || value._adport?.tool!=='media_list' || mediaLibraryProject(value,value._adport)!==library.project) throw new Error('The next page could not be confirmed. Try Load more again.');\n if(mediaLibrary!==library) return;\n // A host can deliver a nested page again after the bridge has resolved.\n rememberHostResult(JSON.stringify(value));\n library.seen.add(args.cursor);\n const byId=new Map(arr(library.data.creatives).map(item=>[item.id,item]));\n for(const item of value.creatives) byId.set(item.id,item);\n const assets=new Map(arr(library.data.assets).map(item=>[item.id,item]));for(const item of arr(value.assets)) assets.set(item.id,item);\n const next=value._adport.next?.arguments;\n const meta={...library.meta,next:next && next.cursor!==args.cursor && !library.seen.has(next.cursor)?{arguments:next}:undefined};\n const data={...library.data,...value,assets:[...assets.values()],creatives:[...byId.values()],_adport:meta};\n acceptResult({structuredContent:data},true);\n } catch(error) {if(mediaLibrary===library) renderLibraryPages(error?.message || 'Could not load more files.');}\n finally {if(mediaLibrary===library) {library.loading=false;const more=app.querySelector('[data-library-more]');if(more) {more.setAttribute('aria-disabled','false');more.textContent='Load more';}}}\n }\n function showUploadedAsset(item,asset) {\n if(!mediaLibrary || mediaLibrary.project!==item.context.project) return;\n const args=mediaLibrary.meta.refresh?.arguments || {},kind=['application/pdf','text/csv'].includes(asset.content_type)?'document':asset.content_type.split('/')[0];\n if(args.kind && args.kind!==kind || args.query && !asset.name.toLowerCase().includes(args.query.toLowerCase()) || args.tag && !arr(asset.tags).includes(args.tag) || args.platform && !arr(asset.platforms).includes(args.platform)) return;\n const creative={id:asset.id,name:asset.name,provider:'media',type:asset.content_type,status:asset.status,headlines:[],descriptions:[uploadBytes(asset.byte_length)],media:asset.preview_cover_url && asset.preview_url?[{type:'image',url:asset.preview_cover_url,open_url:asset.preview_url,alt:asset.name+' — first page'}]:asset.preview_url && ['image','video','audio'].includes(kind)?[{type:kind,url:asset.preview_url,alt:asset.name}]:[]};\n const data={...mediaLibrary.data,creatives:[creative,...arr(mediaLibrary.data.creatives).filter(value=>value.id!==asset.id)],assets:[asset,...arr(mediaLibrary.data.assets).filter(value=>value.id!==asset.id)]};\n const gallery=app.querySelector('[data-media-gallery]'),template=document.createElement('template');template.innerHTML=creativeCards([creative]);\n gallery.querySelector('.empty')?.remove();\n const existing=[...gallery.querySelectorAll('article')].find(card=>card.dataset.mediaId===asset.id);\n if(!existing) {gallery.prepend(template.content);bindLibraryPreviews(gallery);}\n else if(!existing.querySelector('img,video,audio') && template.content.querySelector('.creative-media')) {existing.querySelector('.creative-media')?.remove();existing.querySelector('.creative-copy').before(template.content.querySelector('.creative-media'));bindLibraryPreviews(existing);}\n mediaLibrary.data=data;state.hasLocalResult=true;state.result={structuredContent:{...data,_adport:mediaLibrary.meta}};\n app.querySelector('[data-library-count]').textContent=data.creatives.length+' files';\n }\n`;\n","/** Embedded in the MCP App; all library mutations use the existing host tool bridge. */\nexport const MEDIA_UPLOAD_UI = String.raw`\n const uploads={project:null,items:[],running:false,sequence:0,error:''};\n const uploadUuid=value=>typeof value==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value);\n const uploadBytes=value=>value>=1048576?(value/1048576).toFixed(1)+' MB':Math.max(1,Math.ceil(value/1024))+' KB';\n function uploadContext(data,meta) {\n const config=data.upload_config,project=config?.project_id;\n if (meta.tool!=='media_list'||meta.capabilities?.can_write!==true||!uploadUuid(project)||meta.context?.project_id&&meta.context.project_id!==project) return null;\n try {\n const origin=new URL(config.storage_origin);\n if (origin.protocol!=='https:'||origin.origin!==config.storage_origin||!Number.isInteger(config.max_bytes)||config.max_bytes<1||config.max_bytes>52428800||!Array.isArray(config.content_types)) return null;\n return {project,config};\n } catch {return null;}\n }\n function uploadDraw() {\n const panel=app.querySelector('[data-upload-panel]');if(!panel || !mediaLibrary) return;\n const context=uploadContext(mediaLibrary.data,mediaLibrary.meta),items=uploads.project===mediaLibrary.project?uploads.items:[];\n if(!context) {panel.replaceChildren();return;}\n const queued=items.filter(item=>item.status==='Queued').length,ready=items.filter(item=>item.status==='Ready').length;\n panel.innerHTML=(items.length?'<div class=\"widget-upload-queue\" data-upload-queue>'+items.map(item=>'<div class=\"widget-upload-row\" data-upload-key=\"'+item.key+'\"><div><strong title=\"'+esc(item.file.name)+'\">'+esc(item.file.name)+'</strong><small>'+uploadBytes(item.file.size)+'</small></div><span class=\"widget-upload-status\" role=\"status\">'+esc(item.status)+(item.status==='Uploading'?' '+item.percent+'%':'')+'</span>'+(['Queued','Needs review'].includes(item.status)&&!item.mediaId?'<button class=\"media-button\" type=\"button\" data-upload-remove=\"'+item.key+'\" aria-label=\"Remove '+esc(item.file.name)+' from queue\" '+(uploads.running?'disabled':'')+'>×</button>':'')+(item.status==='Needs review'&&item.mediaId?'<button class=\"media-button\" type=\"button\" data-upload-verify=\"'+item.key+'\" '+(uploads.running?'disabled':'')+'>Verify upload</button>':'')+(item.status==='Uploading'?'<progress max=\"100\" value=\"'+item.percent+'\" aria-label=\"Upload progress for '+esc(item.file.name)+'\"></progress>':'')+(item.message?'<p role=\"alert\">'+esc(item.message)+'</p>':'')+'</div>').join('')+'</div>':'')+(uploads.error?'<p class=\"media-message\" role=\"alert\">'+esc(uploads.error)+'</p>':'')+(items.length?'<div class=\"widget-upload-actions\">'+(ready?'<span class=\"widget-upload-summary\" role=\"status\">'+ready+' saved to your library</span><button class=\"media-button\" data-upload-clear '+(uploads.running?'disabled':'')+'>Clear completed</button>':'')+(queued?'<button class=\"media-button primary\" data-upload-start '+(uploads.running?'disabled':'')+'>Upload '+queued+' file'+(queued===1?'':'s')+'</button>':'')+'</div>':'');\n const input=app.querySelector('[data-upload-files]');if(input) input.disabled=uploads.running;\n panel.querySelectorAll('[data-upload-remove]').forEach(button=>button.addEventListener('click',()=>{if(uploads.running)return;uploads.items=uploads.items.filter(item=>item.key!==Number(button.dataset.uploadRemove));uploadDraw();}));\n panel.querySelector('[data-upload-clear]')?.addEventListener('click',()=>{if(uploads.running)return;uploads.items=uploads.items.filter(item=>item.status!=='Ready');uploadDraw();});\n panel.querySelector('[data-upload-start]')?.addEventListener('click',()=>startWidgetUploads(context));\n panel.querySelectorAll('[data-upload-verify]').forEach(button=>button.addEventListener('click',()=>verifyWidgetUpload(Number(button.dataset.uploadVerify))));\n }\n function uploadType(file) {\n const ext={png:'image/png',jpg:'image/jpeg',jpeg:'image/jpeg',webp:'image/webp',heic:'image/heic',gif:'image/gif',mp4:'video/mp4',mov:'video/quicktime',webm:'video/webm',mp3:'audio/mpeg',wav:'audio/wav',ogg:'audio/ogg',pdf:'application/pdf',csv:'text/csv'};\n if(/\\.csv$/i.test(file.name)&&['','application/octet-stream','text/plain','application/vnd.ms-excel','application/csv','text/comma-separated-values'].includes(file.type))return 'text/csv';\n return ['audio/x-wav','audio/vnd.wave','audio/wave'].includes(file.type)?'audio/wav':file.type&&file.type!=='application/octet-stream'?file.type:ext[file.name.split('.').pop().toLowerCase()]||'';\n }\n function queueWidgetFiles(files,context) {\n if (uploads.running) return;\n if (uploads.project!==context.project) {uploads.project=context.project;uploads.items=[];}\n uploads.error='';\n for (const file of Array.from(files||[])) {\n if (uploads.items.length>=50) {uploads.error='Choose up to 50 files in one batch.';break;}\n const contentType=uploadType(file),valid=file.size>0&&file.size<=context.config.max_bytes&&context.config.content_types.includes(contentType)&&file.name.trim().length>0&&file.name.trim().length<=240;\n uploads.items.push({key:++uploads.sequence,file,contentType,context,status:valid?'Queued':'Needs review',percent:0,message:valid?'':'Choose a supported, non-empty file with a name up to 240 characters and within the size limit.'});\n }\n uploadDraw();\n }\n async function uploadCall(tool,args) {\n const response=await callTool(tool,args,180000),value=resultData(response);\n if (response?.isError||value?.error) throw new Error('The library request was not confirmed. Check the result in chat before trying again.');\n return value;\n }\n async function uploadChange(tool,args) {\n const preview=await uploadCall(tool,args);\n if (preview?.status!=='pending_validation'||preview.applied!==false||typeof preview.pending_operation_id!=='string') throw new Error('The library did not return an upload preview.');\n // No apply retry: each approval is consumed by one call, including unknown outcomes.\n const applied=await uploadCall(tool,{...args,pending_operation_id:preview.pending_operation_id});\n if (applied?.status!=='applied'||applied.applied!==true) throw new Error('The library did not confirm this upload operation.');\n return applied.result;\n }\n async function widgetHash(bytes) {\n const digest=await crypto.subtle.digest('SHA-256',bytes);\n return Array.from(new Uint8Array(digest),byte=>byte.toString(16).padStart(2,'0')).join('');\n }\n async function finalizeWidgetFile(item) {\n item.status='Verifying';item.message='';item.finalizeAttempted=true;uploadDraw();\n const result=await uploadChange('media_finalize_upload',{media_id:item.mediaId,expected_sha256:item.sha256,project_id:item.context.project});\n const asset=result?.details?.asset;\n if (!exactWidgetAsset(item,asset)||asset.status!=='READY') throw new Error('The library has not confirmed the exact file is ready. Verify this upload.');\n markWidgetFileReady(item,asset);\n // The apply receipt intentionally omits signed previews; the read can hydrate this one card.\n try {const value=await uploadCall('media_get',{media_id:item.mediaId,project_id:item.context.project});if(exactWidgetAsset(item,value?.asset)&&value.asset.status==='READY') showUploadedAsset(item,value.asset);} catch {}\n }\n const exactWidgetAsset=(item,asset)=>asset?.id===item.mediaId&&asset.sha256===item.sha256&&asset.byte_length===item.file.size&&asset.content_type===item.contentType;\n function markWidgetFileReady(item,asset) {\n item.status='Ready';item.assetName=asset.name;item.percent=100;item.message='';showUploadedAsset(item,asset);uploadDraw();\n }\n function shareWidgetUploads() {\n const facts={project_id:uploads.project,files:uploads.items.filter(item=>item.mediaId).map(item=>({media_id:item.mediaId,name:item.assetName||item.file.name,byte_length:item.file.size,sha256:item.sha256,status:item.status==='Ready'?'READY':'UNCONFIRMED'}))};\n const context={adport_uploads:facts};\n send({jsonrpc:'2.0',id:id++,method:'ui/update-model-context',params:{content:[{type:'text',text:JSON.stringify(context)}],structuredContent:context}});\n if(typeof window.openai?.setWidgetState==='function') Promise.resolve().then(()=>window.openai.setWidgetState({...context,modelContent:context})).catch(()=>{});\n }\n async function transferWidgetFile(item) {\n try {\n item.status='Checking';uploadDraw();\n const bytes=await item.file.arrayBuffer();item.sha256=await widgetHash(bytes);\n const result=await uploadChange('media_prepare_upload',{name:item.file.name.trim(),content_type:item.contentType,byte_length:item.file.size,sha256:item.sha256,project_id:item.context.project});\n const grant=result?.details;\n if (uploadUuid(grant?.media_id)) item.mediaId=grant.media_id;\n const destination=new URL(grant?.upload_url);\n if (!item.mediaId||grant.method!=='PUT'||destination.origin!==item.context.config.storage_origin||destination.username||destination.password||destination.hash||destination.pathname!=='/storage/v1/object/upload/sign/creative-media/'+item.context.project+'/'+item.mediaId||!destination.searchParams.get('token')) throw new Error('The private upload destination could not be verified. No bytes were sent.');\n item.status='Uploading';uploadDraw();\n await new Promise((resolve,reject)=>{\n const xhr=new XMLHttpRequest();xhr.open('PUT',destination.href);xhr.timeout=300000;xhr.withCredentials=false;\n xhr.setRequestHeader('content-type',item.contentType);xhr.setRequestHeader('x-upsert','false');xhr.setRequestHeader('cache-control','max-age=0');\n xhr.upload.onprogress=event=>{if (event.lengthComputable) {item.percent=Math.round(event.loaded/event.total*100);const row=app.querySelector('[data-upload-queue]');if(row) {const element=row.querySelector('[data-upload-key=\"'+item.key+'\"]');if(element) {element.querySelector('progress')?.setAttribute('value',String(item.percent));element.querySelector('.widget-upload-status').textContent='Uploading '+item.percent+'%';}}}};\n xhr.onload=()=>xhr.status>=200&&xhr.status<300?resolve():reject(new Error('Transfer was not confirmed. Use Verify upload before sending the file again.'));\n xhr.onerror=xhr.ontimeout=xhr.onabort=()=>reject(new Error('Transfer was interrupted. Use Verify upload before sending the file again.'));\n xhr.send(bytes);\n });\n await finalizeWidgetFile(item);\n } catch(error) {item.status='Needs review';item.message=error?.message||'Upload was not confirmed. Check the result in chat.';uploadDraw();}\n }\n async function startWidgetUploads(context) {\n if(uploads.running || uploads.project!==context.project || !uploads.items.some(item=>item.status==='Queued')) return;\n uploads.running=true;uploads.error='';const waiting=uploads.items.filter(item=>item.status==='Queued');uploadDraw();\n const worker=async()=>{let item;while((item=waiting.shift())) await transferWidgetFile(item);};\n try {await Promise.all([worker(),worker()]);} finally {uploads.running=false;shareWidgetUploads();uploadDraw();}\n }\n async function verifyWidgetUpload(key) {\n if(uploads.running) return;const item=uploads.items.find(value=>value.key===key);if(!item?.mediaId) return;\n uploads.running=true;item.status='Verifying';item.message='';uploadDraw();\n try {\n const value=await uploadCall('media_get',{media_id:item.mediaId,project_id:item.context.project}),asset=value?.asset;\n if(!exactWidgetAsset(item,asset)) throw new Error('The file reference could not be verified. Check the result in chat.');\n if(asset.status==='READY') markWidgetFileReady(item,asset);\n else if(asset.status==='PROCESSING' && !item.finalizeAttempted) await finalizeWidgetFile(item);\n else throw new Error('The file is not ready yet. No bytes were resent. Check again later.');\n } catch(error) {item.status='Needs review';item.message=error?.message||'The upload could not be verified. No bytes were resent.';}\n finally {uploads.running=false;shareWidgetUploads();uploadDraw();}\n }\n function bindWidgetUpload(context) {\n const input=app.querySelector('[data-upload-files]');\n if(input) input.onchange=event=>{queueWidgetFiles(event.target.files,context);input.value='';};\n const drop=app.querySelector('[data-upload-drop]');if(!drop) return;\n drop.onpaste=event=>{\n if(!context || uploads.running || event.defaultPrevented || event.target?.closest?.('textarea,input:not([type=\"file\"]),[contenteditable]:not([contenteditable=\"false\"])')) return;\n const files=Array.from(event.clipboardData?.files || []);if(!files.length) return;\n event.preventDefault();queueWidgetFiles(files,context);\n };\n let depth=0;\n const hasFiles=event=>Array.from(event.dataTransfer?.types || []).includes('Files');\n drop.ondragenter=event=>{if(!context||!hasFiles(event))return;event.preventDefault();depth++;if(!uploads.running)drop.classList.add('dragging');};\n drop.ondragover=event=>{if(!context||!hasFiles(event))return;event.preventDefault();event.dataTransfer.dropEffect=uploads.running?'none':'copy';};\n drop.ondragleave=()=>{if(--depth<=0){depth=0;drop.classList.remove('dragging');}};\n drop.ondrop=event=>{if(!context)return;event.preventDefault();depth=0;drop.classList.remove('dragging');queueWidgetFiles(event.dataTransfer?.files,context);};\n }\n`;\n","export const TREND_UI_STYLES = String.raw`\n .report-trend { min-width:0; margin:12px 0 0 }\n [data-report-trend] svg { display:block; width:100%; overflow:visible }\n [data-report-trend] text { fill:var(--muted); font-family:var(--sans); font-size:11px }\n [data-report-trend] .trend-line { fill:none; stroke:var(--orange); stroke-width:2; stroke-linejoin:round }\n [data-report-trend] circle { fill:var(--orange) }\n [data-report-trend] .trend-grid { stroke:var(--line); stroke-width:1 }\n`;\n\nexport const TREND_UI_SCRIPT = String.raw`\n let trendResize;\n function dailyObservations(rows,metric,errors) {\n const dates=[...new Set(rows.map(row=>row.date).filter(date=>typeof date==='string'&&/^\\d{4}-\\d{2}-\\d{2}$/.test(date)&&Number.isFinite(Date.parse(date))&&new Date(date).toISOString().slice(0,10)===date))].sort();\n return dates.map(date=>{\n const selected=rows.filter(row=>row.date===date);\n let value=null;\n if(!arr(errors).some(error=>error.date===date && (!error.provider || rows.some(row=>row.provider===error.provider)))) {\n if(metric==='roas') {\n const spend=total(selected,'spend'),returns=selected.map(rowReturn);\n if(spend>0&&returns.every(available))value=returns.reduce((sum,item)=>sum+item,0)/spend;\n } else value=total(selected,metric);\n }\n return {date,value};\n });\n }\n function mountReportTrend(rows,metric,currency,data) {\n const element=app.querySelector('[data-report-trend]');if(!element)return;\n const observations=dailyObservations(rows,metric,data.errors),valid=observations.filter(item=>available(item.value));\n const draw=()=>{\n if(!valid.length){element.innerHTML='<p class=\"operation-note\">No complete dated values were returned for this metric.</p>';return;}\n const width=Math.max(240,Math.floor(element.getBoundingClientRect?.().width || 480)),height=166,left=54,right=16,top=12,bottom=35;\n const start=Date.parse(data.resolved_date_range?.start || observations[0].date),end=Date.parse(data.resolved_date_range?.end || observations.at(-1).date),span=Math.max(86400000,end-start);\n const max=Math.max(1,...valid.map(item=>item.value)),min=Math.min(0,...valid.map(item=>item.value)),range=max-min || 1;\n const x=date=>left+(Date.parse(date)-start)/span*(width-left-right),y=value=>top+(max-value)/range*(height-top-bottom);\n const format=value=>metric==='spend'?money(value,currency):metric==='roas'?value.toFixed(2)+'×':compact(value);\n const axisFormat=value=>Math.abs(value)<1000?format(value):new Intl.NumberFormat(state.host.locale||undefined,{notation:'compact',maximumFractionDigits:1}).format(value);\n let line='',previous;\n for(const point of observations) {\n if(!available(point.value)){previous=undefined;continue;}\n const contiguous=previous&&Date.parse(point.date)-Date.parse(previous.date)===86400000;\n line+=(contiguous?' L':' M')+x(point.date).toFixed(2)+' '+y(point.value).toFixed(2);previous=point;\n }\n const ticks=[...new Set([observations[0].date,observations[Math.floor((observations.length-1)/2)].date,observations.at(-1).date])];\n const labels=ticks.map((date,index)=>'<text x=\"'+x(date)+'\" y=\"'+(height-9)+'\" text-anchor=\"'+(index===0?'start':index===ticks.length-1?'end':'middle')+'\">'+esc(new Intl.DateTimeFormat(state.host.locale||undefined,{month:'short',day:'numeric',timeZone:'UTC'}).format(new Date(date+'T00:00:00Z')))+'</text>').join('');\n const summary=valid.map(point=>point.date+': '+format(point.value)).join('; ');\n element.innerHTML='<svg viewBox=\"0 0 '+width+' '+height+'\" role=\"img\" aria-label=\"Daily '+esc(metric)+'; '+esc(summary)+'\"><line class=\"trend-grid\" x1=\"'+left+'\" x2=\"'+(width-right)+'\" y1=\"'+(height-bottom)+'\" y2=\"'+(height-bottom)+'\"/><text x=\"'+(left-7)+'\" y=\"'+(top+4)+'\" text-anchor=\"end\">'+esc(axisFormat(max))+'</text><text x=\"'+(left-7)+'\" y=\"'+(height-bottom)+'\" text-anchor=\"end\">'+esc(axisFormat(min))+'</text><path class=\"trend-line\" d=\"'+line+'\"/>'+valid.map(point=>'<circle cx=\"'+x(point.date)+'\" cy=\"'+y(point.value)+'\" r=\"3\"><title>'+esc(point.date+' · '+format(point.value))+'</title></circle>').join('')+labels+'</svg>';\n };\n draw();\n if(typeof ResizeObserver!=='undefined'){trendResize=new ResizeObserver(draw);trendResize.observe(element);}\n }\n`;\n","export const RECORD_UI_STYLES = String.raw`\n .record-list { display:grid; max-height:400px; overflow:auto; scrollbar-width:thin }\n .record-row { min-width:0; padding:10px 0; border-bottom:1px solid var(--line) }\n .record-heading { display:flex; align-items:baseline; justify-content:space-between; gap:10px; min-width:0 }\n .record-heading strong { font-size:12px; line-height:1.5; overflow-wrap:anywhere }\n .record-heading > span { color:var(--muted); font-size:10px; white-space:nowrap }\n .record-name { display:flex; align-items:center; gap:8px; min-width:0 }\n .record-name .logo { width:23px; height:23px; padding:4px; border-radius:6px }\n .record-fields { display:flex; flex-wrap:wrap; gap:5px 16px; margin:6px 0 0; font-size:11px; line-height:1.5 }\n .record-fields > div { min-width:0; overflow-wrap:anywhere }\n .record-fields dt { display:inline; color:var(--muted); margin-right:5px }\n .record-fields dd { display:inline; margin:0 }\n .record-notes { max-height:140px; overflow:auto; scrollbar-width:thin }\n .record-providers { display:flex; flex-wrap:wrap; align-items:center; gap:6px; min-width:0 }\n .record-provider { display:inline-flex }\n .record-provider .logo { width:26px; height:26px; padding:5px; border-radius:7px }\n .record-provider-name { color:var(--muted); font-size:11px; overflow-wrap:anywhere }\n .project-row { display:grid; grid-template-columns:34px minmax(0,1fr); gap:7px 10px; padding:12px 0; border-bottom:1px solid var(--line) }\n .project-logo { display:grid; place-items:center; width:34px; height:34px; border:1px solid var(--line); border-radius:9px; background:var(--paper); color:var(--muted); font-size:14px; font-weight:600; overflow:hidden }\n .project-logo img { display:block; width:100%; height:100%; object-fit:contain }\n .project-copy { align-self:center; min-width:0 }\n .project-copy strong { font-size:12px; line-height:1.5; overflow-wrap:anywhere }\n .project-copy p { margin:3px 0 0; color:var(--muted); font-size:11px; line-height:1.5; overflow-wrap:anywhere }\n .project-platforms-empty { margin:0; color:var(--muted); font-size:11px }\n .project-row .record-providers { grid-column:2 }\n @media(min-width:600px) {\n .project-row { grid-template-columns:34px minmax(0,1fr) minmax(0,50%) }\n .project-row .record-providers { grid-column:3; grid-row:1; justify-content:flex-end; align-self:center }\n }\n`;\n\nexport const RECORD_UI_SCRIPT = String.raw`\n let recordPages=null;\n function recordPagesIgnoreEcho(data) {\n return !!recordPages?.busy && data?._adport?.view==='records' && galleryMatches(data._adport,recordPages.meta) && galleryScope(data._adport)===recordPages.scope;\n }\n function providerMarks(values,meta,label='Platforms') {\n const providers=[...new Set(arr(values).filter(value=>typeof value==='string'&&value))];\n return providers.length?'<div class=\"record-providers\" role=\"group\" aria-label=\"'+esc(label)+'\">'+providers.map(provider=>{\n const name=providerName(provider,meta.providerNames||{});\n return providerSvg[provider]?'<span class=\"record-provider\" role=\"img\" aria-label=\"'+esc(name)+'\" title=\"'+esc(name)+'\">'+logo(provider)+'</span>':'<span class=\"record-provider-name\">'+esc(name)+'</span>';\n }).join('')+'</div>':'';\n }\n function renderProjects(data,meta) {\n const projects=arr(data.projects),rows=projects.slice(0,1000).map(project=>{\n const name=String(project.name||'Untitled project'),initial=[...name.trim()][0]?.toUpperCase()||'?';\n const organization=typeof project.organization_name==='string'&&project.organization_name.trim().toLowerCase()!==name.trim().toLowerCase()?project.organization_name:'';\n const subtitle=[organization,project.role?human(String(project.role)):null].filter(Boolean).join(' · ');\n let url;try { const value=new URL(project.logo_url);if(value.protocol==='https:'&&!value.username&&!value.password)url=value.href; }catch {}\n return '<article class=\"project-row\"><span class=\"project-logo\" aria-hidden=\"true\" data-project-initial=\"'+esc(initial)+'\">'+(url?'<img src=\"'+esc(url)+'\" alt=\"\" referrerpolicy=\"no-referrer\">':esc(initial))+'</span><div class=\"project-copy\"><strong>'+esc(name)+'</strong>'+(subtitle?'<p>'+esc(subtitle)+'</p>':'')+'</div>'+(providerMarks(project.providers,meta,'Connected platforms')||'<p class=\"record-providers project-platforms-empty\">No connected platforms</p>')+'</article>';\n }).join('');\n const clean={...data};delete clean._adport;\n app.innerHTML=chrome(operationHeader('Projects','')+notices(data)+(projects.length?'<div class=\"record-list\" role=\"region\" aria-label=\"Authorized projects\" tabindex=\"0\">'+rows+'</div>':'<p class=\"operation-note\">No accessible projects were returned.</p>')+(projects.length>1000?'<p class=\"operation-note\">Showing 1,000 of '+projects.length+' projects. The full response is in Details.</p>':'')+'<details><summary>Details</summary><pre>'+esc(JSON.stringify(clean,null,2))+'</pre></details>',projects.length+' project'+(projects.length===1?'':'s'));\n app.querySelectorAll('.project-logo img').forEach(image=>image.addEventListener('error',()=>{const parent=image.parentElement;parent.textContent=parent.dataset.projectInitial;},{once:true}));\n }\n function recordPayload(data) {\n if(object(data)&&Array.isArray(data.records))return {records:data.records};\n const value=data.value ?? data.data ?? data.result ?? data;\n if(!object(value))return value;\n for(const key of ['keyword','audience','pixel','capi_integration','mobile_app','dataset','board','campaign','ad_group','ad','asset','customer_list'])if(object(value[key]))return value[key];\n return value;\n }\n function recordEntries(payload) {\n if(Array.isArray(payload))return payload;\n if(!object(payload))return null;\n if(['name','value','title','id','saved_audience_name','saved_audience_id','pixel_name','pixel_id','capi_connection_id'].some(key=>Object.hasOwn(payload,key)&&!object(payload[key])&&!Array.isArray(payload[key])))return null;\n const ignored=/^(_adport|notes|warnings|errors|actions|creatives|fields|media|resourceIds|resource_ids)$/;\n const keys=['items','results','records','campaigns','ad_groups','ad_sets','ads','keywords','audiences','accounts','projects','assets','data'];\n const key=keys.find(key=>Array.isArray(payload[key])) ?? Object.keys(payload).find(key=>!ignored.test(key)&&Array.isArray(payload[key]));\n return key?payload[key]:null;\n }\n function recordValue(value,key,currency) {\n if(typeof value==='number'&&Number.isFinite(value)&&/micros$|cents$/i.test(key))return esc(money(value/(/cents$/i.test(key)?100:1e6),currency,6));\n return valueHTML(value,true);\n }\n function recordRow(value,index,meta) {\n if(!object(value))return '<article class=\"record-row\">'+valueHTML(value,true)+'</article>';\n const fields=dataFields(value).filter(field=>!/(?:hash|token|secret|password|authorization|pending operation|snapshot)/i.test(field.label));\n const name=fields.find(field=>/^(name|display name|title|value|keyword|keyword text|campaign name|ad group name|ad name|creative name|account name|audience name|saved audience name|pixel name)$/i.test(field.label));\n const id=fields.find(field=>/^(id|resource name|saved audience id|pixel id|capi connection id)$/i.test(field.label));\n const status=fields.find(field=>/^(status|state|delivery status|archived)$/i.test(field.label));\n const currency=currencyOf(value)||(/^[A-Z]{3}$/.test(value.currency_code||'')?value.currency_code:currencyOf(meta));\n const chosen=fields.filter(field=>!/^note$|^notes$|^actions$|preview url|preview cover url|logo url/i.test(field.label)&&field!==name&&field!==status&&!/^(id|saved audience id|pixel id|pixel code|capi connection id|account id|provider|resource name|currency|currency code)$/i.test(field.label));\n chosen.sort((a,b)=>{const priority=field=>/match type|scope|budget|bid|size|type|rule|frequency/i.test(field.label)?0:1;return priority(a)-priority(b);});\n const label=name?.after ?? id?.after ?? 'Record '+(index+1);\n const nativeProvider=typeof value.provider==='string'?value.provider:typeof value.platform==='string'&&providerSvg[value.platform]?value.platform:undefined;\n const provider=nativeProvider!==meta.provider?nativeProvider:undefined;\n return '<article class=\"record-row\"><div class=\"record-heading\"><div class=\"record-name\">'+(provider?'<span role=\"img\" aria-label=\"'+esc(providerName(provider,meta.providerNames||{}))+'\">'+logo(provider)+'</span>':'')+'<strong>'+esc(label)+'</strong></div>'+(status?'<span>'+esc(status.label==='Archived'&&typeof status.after==='boolean'?(status.after?'Archived':'Unarchived'):status.after)+'</span>':'')+'</div>'+(chosen.length?'<dl class=\"record-fields\">'+chosen.slice(0,4).map(field=>/^(providers|platforms)$/i.test(field.label)&&Array.isArray(field.after)?'<div><dd>'+providerMarks(field.after,meta)+'</dd></div>':'<div><dt>'+esc(/micros$|cents$/i.test(field.label)?field.label.replace(/ (?:micros|cents)$/i,'')+' · '+(currency||'account units'):field.label)+'</dt><dd>'+recordValue(field.after,field.label.replaceAll(' ','_'),currency)+'</dd></div>').join('')+'</dl>':'')+'</article>';\n }\n function renderRecordPages(message='') {\n const pages=recordPages,area=app.querySelector('[data-record-pages]');if(!pages||!area)return;\n const next=pages.rows.length<1000 && galleryNext(pages.meta);\n let status=area.querySelector('[role=\"status\"]');if(!status){status=document.createElement('p');status.className='operation-note';status.setAttribute('role','status');area.prepend(status);}status.textContent=message;status.hidden=!message;\n let button=area.querySelector('[data-record-more]');\n if(next){if(!button){button=document.createElement('button');button.type='button';button.className='media-button';button.dataset.recordMore='';button.addEventListener('click',loadRecordPage);area.append(button);}button.textContent=pages.busy?'Loading…':'Load more';button.setAttribute('aria-disabled',String(!!pages.busy));}\n else if(button){const focused=button===document.activeElement;button.remove();if(focused)app.querySelector('[data-record-list]')?.focus({preventScroll:true});}\n }\n async function loadRecordPage() {\n const pages=recordPages,args=pages && galleryNext(pages.meta);if(!pages||pages.busy||!args||pages.rows.length>=1000)return;\n const key=galleryStable(args);if(pages.seen.has(key)){pages.meta={...pages.meta,next:undefined};renderRecordPages('No new page was returned.');return;}\n pages.busy=true;state.hasLocalResult=true;renderRecordPages();\n try {\n const response=await callTool(pages.meta.tool,args,60000),value=resultData(response),meta=value?._adport,rows=recordEntries(recordPayload(value));\n hostResults.add(JSON.stringify(value));if(hostResults.size>16)hostResults.delete(hostResults.values().next().value);\n if(recordPages!==pages){state.hasLocalResult=true;return;}\n if(response?.isError||value?.error||!Array.isArray(rows)||!meta||meta.view!=='records'||!galleryMatches(meta,pages.meta)||galleryScope(meta)!==pages.scope||!object(meta.refresh?.arguments)||galleryStable(meta.refresh.arguments)!==key||!rows.length&&(value.truncated!==false||galleryNext(meta)))throw new Error('The next page could not be confirmed.');\n const root=app.querySelector('[data-record-list]');if(!root)return;\n let added=0;\n rows.forEach((row,index)=>{\n const identity=object(row)&&(typeof row.id==='string'&&row.id||typeof row.id==='number'&&Number.isSafeInteger(row.id))?'id:'+String(row.id):key+':'+index;\n const previous=pages.items.get(identity);\n if(previous){if(galleryStable(previous.row)!==galleryStable(row)){const template=document.createElement('template');template.innerHTML=recordRow(row,previous.index,meta);const node=template.content.firstElementChild;previous.node.replaceWith(node);previous.node=node;previous.row=row;pages.rows[previous.index]=row;}return;}\n if(pages.rows.length>=1000)return;\n const template=document.createElement('template');template.innerHTML=recordRow(row,pages.rows.length,meta);const node=template.content.firstElementChild;\n pages.items.set(identity,{row,index:pages.rows.length,node});pages.rows.push(row);root.append(node);added++;\n });\n pages.seen.add(key);pages.meta={...meta,...(!added||pages.rows.length>=1000?{next:undefined}:{})};pages.data=value;\n state.hasLocalResult=true;state.result={structuredContent:{...value,records:pages.rows.slice(),_adport:pages.meta}};\n const notes=app.querySelector('.record-notes');if(notes)notes.innerHTML=notices(value);\n const details=app.querySelector('[data-record-details]');if(details){details.querySelector('summary').textContent='Details · '+pages.rows.length+' loaded';details.querySelector('pre').textContent=JSON.stringify({loaded_records:pages.rows,latest_page:Object.fromEntries(Object.entries(value).filter(([field])=>field!=='_adport'))},null,2);}\n pages.busy=false;renderRecordPages(pages.rows.length>=1000?'Showing 1,000 records. Ask your assistant if you need more results.':!added&&rows.length?'No new records were returned. Ask your assistant for a fresh view.':'');\n }catch(error){if(recordPages===pages){pages.busy=false;renderRecordPages(error?.message||'Could not load more records.');}}\n }\n function renderRecords(data,meta) {\n if(meta.tool==='projects_list')return renderProjects(data,meta);\n if(meta.tool==='apple_report')return renderAppleReport(data,meta);\n if(nativeReportTools.has(meta.tool)&&(meta.tool!=='google_gaql'||arr(recordPayload(data)?.rows).some(row=>object(row?.metrics)&&Object.keys(row.metrics).length)))return renderNativeReport(data,meta);\n const payload=recordPayload(data),entries=recordEntries(payload),rows=entries ?? [payload];\n const title=human(String(meta.tool||'Results').replace(/^(?:google|meta|tiktok|apple|microsoft|reddit|snapchat|spotify|pinterest|linkedin|x)_/,'').replace(/^(?:list|get)_/,'').replace(/_(?:list|get)$/,'').replaceAll('_',' '));\n const parent=object(data.parent)?Object.entries(data.parent).filter(([key])=>/_id$/.test(key)).map(([key,value])=>human(key.replace(/_id$/,''))+' '+value).join(' · '):'';\n const scope=[parent,typeof data.parent_id==='string'&&!parent?data.parent_id:'',meta.accountId].filter(Boolean).join(' · ');\n const clean=object(data)?Object.fromEntries(Object.entries(data).filter(([key])=>key!=='_adport'&&!(key==='creatives'&&meta.view==='records'))):data;\n const content=rows.length?'<div class=\"record-list\" data-record-list role=\"region\" aria-label=\"Returned records\" tabindex=\"0\">'+rows.slice(0,1000).map((row,index)=>recordRow(row,index,meta)).join('')+'</div>':'<p class=\"operation-note\">No results returned.</p>';\n app.innerHTML=chrome(operationHeader(title,scope,meta.provider)+'<div class=\"record-notes\">'+notices(data)+'</div>'+content+(rows.length>1000?'<p class=\"operation-note\">Showing 1,000 of '+rows.length+' records. The full response is in Details.</p>':'')+'<div data-record-pages></div><details data-record-details><summary>Details'+(entries?' · '+entries.length+' results':'')+'</summary><pre>'+esc(JSON.stringify(clean,null,2))+'</pre></details>','');\n if(meta.view==='records'&&Array.isArray(entries)&&rows.length&&galleryNext(meta)){\n recordPages={scope:galleryScope(meta),meta,data,rows:rows.slice(0,1000),items:new Map(),seen:new Set([galleryStable(meta.refresh.arguments)]),busy:false};\n const nodes=app.querySelectorAll('[data-record-list]>article');recordPages.rows.forEach((row,index)=>{const identity=object(row)&&(typeof row.id==='string'&&row.id||typeof row.id==='number'&&Number.isSafeInteger(row.id))?'id:'+String(row.id):galleryStable(meta.refresh.arguments)+':'+index;recordPages.items.set(identity,{row,index,node:nodes[index]});});\n renderRecordPages();\n }\n }\n function renderData(data,meta) {\n const payload=recordPayload(data);\n const receipt=receiptInfo(payload),named=object(payload)&&['name','title'].some(key=>typeof payload[key]==='string');\n if(receipt.exists&&!named&&(!recordEntries(payload)||receipt.items.length&&/(status|processing|operation|diagnostic|job|receipt)/i.test(meta.tool||'')))return renderReceipt(data,meta);\n return renderRecords(data,meta);\n }\n`;\n","export const RECEIPT_UI_STYLES = String.raw`\n .receipt { margin:12px 0; min-width:0 }\n .receipt-state { margin:0 0 8px; font-size:12px; font-weight:600 }\n .receipt-counts { display:flex; flex-wrap:wrap; gap:14px; margin:8px 0 }\n .receipt-counts div { display:grid; gap:3px }\n .receipt-counts dt { color:var(--muted); font-size:11px }\n .receipt-counts dd { margin:0; font-size:15px; font-variant-numeric:tabular-nums }\n .receipt-progress { display:block; width:100%; height:5px; margin:10px 0; accent-color:var(--orange) }\n .receipt-items { display:grid; max-height:240px; overflow:auto; scrollbar-width:thin }\n .receipt-item { display:flex; align-items:baseline; justify-content:space-between; gap:12px; padding:8px 0; border-top:1px solid var(--line); font-size:11px; overflow-wrap:anywhere }\n .receipt-item p { margin:3px 0 0; color:var(--muted); line-height:1.5 }\n .receipt-item > span { flex-shrink:0; color:var(--muted) }\n`;\n\nexport const RECEIPT_UI_SCRIPT = String.raw`\n function receiptInfo(input) {\n const root=object(input)?input:{},result=object(root.result)?root.result:root;\n const source=object(result.details)?result.details:result,base=object(source.native)?{...source.native,...source}:source,detail=object(base.processing_info)?{...base,...base.processing_info}:base;\n const numeric=value=>(typeof value==='number'||typeof value==='string'&&/^[0-9]+$/.test(value))&&Number.isSafeInteger(Number(value))&&Number(value)>=0;\n const definitions=[['Total',['total_count','totalCount','total','expected_event_count']],['Accepted',['accepted_count','acceptedCount','accepted']],['Reported records',['record_count']],['Processed',['processed_count','processedCount','processed']],['Succeeded',['succeeded_count','success_count','successful_count','succeeded']],['Failed',['failed_count','error_count','failed','errors_count']],['Warnings',['warning_count','warnings_count']]];\n const counts=[];\n for(const [label,keys] of definitions) {\n const source=[detail.counts,detail,root.counts,root].find(source=>object(source)&&keys.some(key=>numeric(source[key])));\n const key=source&&keys.find(key=>numeric(source[key]));if(key)counts.push({label,value:Number(source[key])});\n }\n const native=String(detail.processing_status ?? detail.media_status ?? detail.state ?? detail.status ?? root.processing_status ?? root.state ?? root.status ?? '');\n const pending=/^(ACCEPTED(?:_FOR_PROCESSING)?|QUEUED|PENDING|PROCESSING|IN_PROGRESS|UPLOADING|TRANSCODING|TRANSCODE_PENDING|TRANSCODE_IN_PROGRESS|RUNNING|STARTED)$/i.test(native) || detail.processed===false;\n const complete=!pending && /^(SUCCEEDED|SUCCESS|COMPLETED|COMPLETE|READY|PROCESSED|FINISHED|TRANSCODE_COMPLETED)$/i.test(native);\n const failed=/^(FAILED|ERROR|REJECTED|TRANSCODE_FAILED)$/i.test(native),partial=/^(PARTIAL|PARTIALLY_APPLIED|PARTIAL_SUCCESS)$/i.test(native);\n const collection=[detail.results,detail.items,detail.operation_results,root.results].find(Array.isArray) || [];\n const items=collection.filter(item=>object(item) && (item.status!==undefined || item.state!==undefined || item.error!==undefined || item.success!==undefined)).map((item,index)=>{\n const error=object(item.error)?item.error.message:typeof item.error==='string'?item.error:undefined;\n return {label:String(item.id ?? item.resource_id ?? item.resourceId ?? (item.index!==undefined?'Row '+item.index:'Item '+(index+1))),status:String(item.status ?? item.state ?? (item.success===true?'Succeeded':item.success===false?'Failed':'Unconfirmed')),message:typeof error==='string'?error:typeof item.message==='string'?item.message:''};\n });\n const diagnostics=[...arr(detail.errors).map(item=>({...item,kind:'Error'})),...arr(detail.warnings).map(item=>({...item,kind:'Warning'}))].filter(item=>object(item)&&typeof item.reason==='string').map(item=>({label:item.kind,status:numeric(item.record_count)?String(item.record_count)+' records':'',message:item.reason}));\n items.push(...diagnostics);\n const percent=numeric(detail.progress_percent)&&Number(detail.progress_percent)<=100?Number(detail.progress_percent):undefined;\n const state=failed?'Failed':partial?'Partially completed':pending?'Processing pending':complete?'Completed':native&&!/^(applied|pending_validation)$/i.test(native)?human(native):'';\n return {counts,items,state,native,percent,pending:pending&&!failed&&!partial,complete,exists:counts.some(item=>item.label!=='Total') || items.length>0 || pending || failed || partial || complete || /^(UNKNOWN|REQUEST_STATUS_UNKNOWN)$/i.test(native)&&typeof detail.request_id==='string'};\n }\n function receiptMarkup(input,showState=true) {\n const receipt=receiptInfo(input);if(!receipt.exists)return '';\n const total=receipt.counts.find(item=>item.label==='Total')?.value,processed=receipt.counts.find(item=>item.label==='Processed')?.value;\n const progress=typeof total==='number'&&total>0&&typeof processed==='number'&&processed<=total?'<progress class=\"receipt-progress\" max=\"'+total+'\" value=\"'+processed+'\" aria-label=\"Reported processed items\"></progress>':typeof receipt.percent==='number'?'<p class=\"operation-note\">'+receipt.percent+'% processed</p><progress class=\"receipt-progress\" max=\"100\" value=\"'+receipt.percent+'\" aria-label=\"Provider-reported progress\"></progress>':'';\n return '<section class=\"receipt\" aria-label=\"Operation receipt\">'+(showState&&receipt.state?'<p class=\"receipt-state\" role=\"status\">'+esc(receipt.state)+'</p>':'')+(receipt.counts.length?'<dl class=\"receipt-counts\">'+receipt.counts.map(item=>'<div><dt>'+esc(item.label)+'</dt><dd>'+esc(item.value)+'</dd></div>').join('')+'</dl>':'')+progress+(showState&&receipt.pending?'<p class=\"operation-note\">Accepted work is not confirmed as processed.</p>':'')+(receipt.items.length?'<div class=\"receipt-items\" role=\"region\" aria-label=\"Individual results\" tabindex=\"0\">'+receipt.items.map(item=>'<div class=\"receipt-item\"><div>'+esc(item.label)+(item.message?'<p>'+esc(item.message)+'</p>':'')+'</div><span>'+esc(item.status)+'</span></div>').join('')+'</div>':'')+'</section>';\n }\n function renderReceipt(data,meta) {\n const value=data.value ?? data.data ?? data;\n app.innerHTML=chrome(operationHeader(human(String(meta.tool||'Processing status').replace(/^[a-z]+_/,'').replaceAll('_',' ')),meta.accountId,meta.provider)+notices({...data,errors:arr(data.errors).filter(item=>typeof item==='string'||typeof item?.message==='string'),warnings:arr(data.warnings).filter(item=>typeof item==='string'||typeof item?.message==='string')})+(receiptMarkup(value)||'<p class=\"operation-note\">No processing outcome was reported.</p>')+'<details><summary>Details</summary><pre>'+esc(JSON.stringify(value,null,2))+'</pre></details>','');\n }\n`;\n","export const INSIGHT_UI_STYLES = String.raw`\n .insight-list { display:grid; max-height:430px; overflow:auto; scrollbar-width:thin }\n .insight { padding:12px 0; border-bottom:1px solid var(--line); min-width:0 }\n .insight-heading { display:flex; align-items:center; gap:8px; min-width:0 }\n .insight-heading .logo { width:23px; height:23px; padding:4px; flex-shrink:0 }\n .insight-heading strong { flex:1; font-size:12px; line-height:1.5; overflow-wrap:anywhere }\n .insight p { margin:7px 0 0; font-size:12px; line-height:1.55; overflow-wrap:anywhere }\n .insight-reason { color:var(--muted) }\n .insight-action span { color:var(--muted); margin-right:5px }\n`;\n\nexport const INSIGHT_UI_SCRIPT = String.raw`\n function renderInsights(data) {\n const items=data.finding?[data.finding]:arr(data.findings||data.recommendations||data.results||data.entries);\n const body=notices(data)+(items.length?'<div class=\"insight-list\" role=\"region\" aria-label=\"Recommendations\" tabindex=\"0\">'+items.map(item=>{\n const reason=typeof item.detail==='string'?item.detail:typeof item.description==='string'?item.description:'';\n const suggestion=typeof item.recommendation==='string'?item.recommendation:'';\n const status=item.status&&item.status!=='open'?item.status:item.severity||item.status||'';\n return '<article class=\"insight\"><div class=\"insight-heading\">'+(item.provider?logo(item.provider):'')+'<strong>'+esc(item.title||item.summary||item.rule||'Finding')+'</strong>'+(status?'<span class=\"pill '+(/critical|high/i.test(status)?'danger':'neutral')+'\">'+esc(status)+'</span>':'')+'</div>'+(reason?'<p class=\"insight-reason\">'+esc(reason)+'</p>':'')+(suggestion?'<p class=\"insight-action\"><span>Suggested</span>'+esc(suggestion)+'</p>':'')+'</article>';\n }).join('')+'</div><details><summary>Details · '+items.length+' findings</summary><pre>'+esc(JSON.stringify(items,null,2))+'</pre></details>':'<div class=\"empty\">No recommendations were returned.</div>');\n app.innerHTML=chrome(body,items.length+' recommendation'+(items.length===1?'':'s'));\n }\n`;\n","export const CREATIVE_UI_STYLES = String.raw`\n .shell:has(.creative-grid-single) { max-width:320px }\n .creative-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(min(100%,200px),1fr)); gap:10px; max-height:430px; overflow:auto; overscroll-behavior:contain; align-items:start; scrollbar-width:thin }\n .creative-grid:focus-visible { outline:2px solid var(--orange); outline-offset:3px; border-radius:10px }\n .creative-grid-single { grid-template-columns:minmax(0,280px); max-height:none }\n .creative-card { min-width:0; padding:10px; border:1px solid var(--line); border-radius:12px }\n .creative-heading { display:flex; align-items:center; gap:6px; min-width:0; margin-bottom:8px }\n .creative-heading .logo { width:18px; height:18px; padding:2px; border:0; border-radius:4px; background:transparent }\n .creative-name { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:11px; font-weight:600 }\n .creative-media { display:flex; overflow-x:auto; gap:6px; scroll-snap-type:x mandatory; scrollbar-width:thin; margin:0 0 8px; border-radius:7px; background:var(--soft) }\n .creative-media-item { display:grid; place-items:center; flex:0 0 100%; min-width:0; height:128px; scroll-snap-align:start; color:var(--muted); text-decoration:none }\n .creative-media img,.creative-media video { display:block; width:100%; height:128px; object-fit:contain }\n .creative-media audio { width:100%; max-width:100% }\n .creative-placeholder { color:var(--muted); font:500 10px/1.5 var(--sans) }\n .creative-copy { display:grid; gap:4px; overflow-wrap:anywhere }\n .creative-copy strong,.creative-copy p { display:-webkit-box; -webkit-box-orient:vertical; overflow:hidden; margin:0; font-size:12px; line-height:1.45; white-space:pre-wrap }\n .creative-copy strong { -webkit-line-clamp:2; font-weight:600 }\n .creative-copy p { -webkit-line-clamp:3; color:var(--muted) }\n .creative-footer { display:flex; align-items:center; justify-content:space-between; gap:8px; margin-top:8px; color:var(--muted); font-size:10px; line-height:1.4 }\n .creative-status { display:flex; align-items:center; gap:4px; white-space:nowrap }\n .creative-status::before { content:''; width:4px; height:4px; border-radius:50%; background:var(--faint) }\n .creative-status-active::before { background:var(--green) }\n .creative-destination { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; color:var(--muted); text-decoration:none }\n .creative-destination:hover { text-decoration:underline }\n`;\n\n/** Media rendering is shared; scoped controls live in the provider gallery or central library. */\nexport const CREATIVE_UI_SCRIPT = String.raw`\n function creativeCards(creatives,menuFor) {\n const safeUrl=(value,media=false)=>{try {const url=new URL(value);return (media?url.protocol==='https:':['https:','http:'].includes(url.protocol))&&!url.username&&!url.password?url:null;} catch {return null;}};\n const mediaView=creative=>{\n const items=arr(creative.media).map(media=>{\n const url=safeUrl(media.url,true);if (!url) return '';\n const src=esc(url.href),open=safeUrl(media.open_url,true)||url,poster=safeUrl(media.poster_url,true),name=esc(media.alt || creative.name || 'Creative');\n if (media.type==='image') return '<a class=\"creative-media-item\" href=\"'+esc(open.href)+'\" target=\"_blank\" rel=\"noopener noreferrer\" aria-label=\"'+(creative.type==='application/pdf'?'Open document: ':'View image: ')+name+'\"><img src=\"'+src+'\" alt=\"'+name+'\" loading=\"lazy\" referrerpolicy=\"no-referrer\"></a>';\n if (media.type==='video') return '<div class=\"creative-media-item\"><video src=\"'+src+'\" data-open-url=\"'+esc(open.href)+'\" controls preload=\"metadata\" '+(poster?'poster=\"'+esc(poster.href)+'\"':'data-first-frame')+' playsinline aria-label=\"'+name+'\"></video></div>';\n if (media.type==='audio') return '<div class=\"creative-media-item\"><audio src=\"'+src+'\" data-open-url=\"'+esc(open.href)+'\" controls preload=\"none\" aria-label=\"'+name+'\"></audio></div>';\n return '';\n }).join('');\n if (items) return '<div class=\"creative-media\">'+items+'</div>';\n return /pdf|document/i.test(creative.type || '')?'<div class=\"creative-media\"><div class=\"creative-media-item\"><span class=\"creative-placeholder\">Document preview unavailable</span></div></div>':'';\n };\n const unique=values=>[...new Set(arr(values).filter(value=>typeof value==='string'&&value.trim()))];\n return creatives.map(creative=>{\n const name=creative.name || 'Untitled creative',status=statusOf(creative.status);\n const destination=arr(creative.landing_urls).map(value=>safeUrl(value)).find(Boolean);\n const headline=unique(creative.headlines).filter(text=>text!==name).join(' · '),copy=unique(creative.descriptions).filter(text=>text!==name&&text!==headline).join('\\n');\n const active=/^(active|enabled|ready|approved)$/i.test(creative.status || '');\n return '<article class=\"creative-card\" data-media-id=\"'+esc(creative.id)+'\"><div class=\"creative-heading\">'+(providerSvg[creative.provider]?logo(creative.provider):'')+'<span class=\"creative-name\" title=\"'+esc(name)+'\">'+esc(name)+'</span>'+(menuFor?menuFor(creative):'')+'</div>'+mediaView(creative)+'<div class=\"creative-copy\">'+(headline?'<strong title=\"'+esc(headline)+'\">'+esc(headline)+'</strong>':'')+(copy?'<p title=\"'+esc(copy)+'\">'+esc(copy)+'</p>':'')+'</div><div class=\"creative-footer\"><span class=\"creative-status'+(active?' creative-status-active':'')+'\">'+esc(status.label)+'</span>'+(destination?'<a class=\"creative-destination\" href=\"'+esc(destination.href)+'\" target=\"_blank\" rel=\"noopener noreferrer\">'+esc(destination.hostname.replace(/^www\\./,''))+'</a>':'')+'</div></article>';\n }).join('');\n }\n function bindCreativeErrors(root,recover) {\n root.querySelectorAll('.creative-media img,.creative-media video,.creative-media audio').forEach(media=>{\n if(media.dataset.previewBound) return;media.dataset.previewBound='true';\n if(media.matches('video[data-first-frame]')) media.addEventListener('loadedmetadata',()=>{if(Number.isFinite(media.duration)&&media.duration>0)media.currentTime=Math.min(.1,media.duration/2);},{once:true});\n media.addEventListener('error',()=>{\n if(recover?.(media)) return;\n const item=media.closest('.creative-media-item');\n const openUrl=media.dataset.openUrl;\n const placeholder=document.createElement(openUrl?'a':'span');\n placeholder.className='creative-placeholder';\n placeholder.textContent=openUrl || item.matches('a[href]')?'Open preview':'Preview unavailable';\n if(openUrl){placeholder.href=openUrl;placeholder.target='_blank';placeholder.rel='noopener noreferrer';}\n item.replaceChildren(placeholder);\n },{once:true});\n });\n }\n function renderCreatives(data,meta) {\n if(meta.tool==='media_list' && mediaLibraryProject(data,meta)) return renderMediaLibrary(data,meta);\n return renderProviderGallery(data,meta);\n }\n`;\n","export const PROVIDER_GALLERY_STYLES = String.raw`\n .creative-heading .creative-name { flex:1 }\n .creative-menu { position:relative; margin-left:auto; flex:none }\n .creative-menu>summary { display:grid; place-items:center; width:30px; min-height:30px; border-radius:7px; cursor:pointer; list-style:none; font-size:17px; color:var(--muted) }\n .creative-menu>summary::-webkit-details-marker { display:none }\n .creative-menu>summary:hover,.creative-menu>summary:active { background:var(--soft); color:var(--ink) }\n .creative-menu>summary:focus-visible,.creative-menu button:focus-visible,.creative-editor input:focus-visible,.creative-editor textarea:focus-visible,.creative-editor select:focus-visible { outline:2px solid var(--orange); outline-offset:2px }\n .creative-menu-items { position:absolute; top:100%; right:0; z-index:3; width:max-content; max-width:210px; padding:4px; border:1px solid var(--line); border-radius:9px; background:var(--paper); box-shadow:0 6px 20px rgba(0,0,0,.12) }\n .creative-menu-items button { display:block; width:100%; min-height:32px; padding:6px 9px; border:0; border-radius:5px; background:none; color:var(--ink); font:inherit; font-size:11px; text-align:left; cursor:pointer }\n .creative-menu-items button:hover,.creative-menu-items button:active { background:var(--soft) }\n .creative-editor { display:grid; gap:8px; padding-top:10px; margin-top:10px; border-top:1px solid var(--line) }\n .creative-editor label { display:grid; gap:4px; color:var(--muted); font-size:11px }\n .creative-editor input,.creative-editor textarea,.creative-editor select { box-sizing:border-box; width:100%; min-width:0; padding:7px 8px; border:1px solid var(--line); border-radius:7px; background:var(--paper); color:var(--ink); font:12px/1.45 var(--sans) }\n .creative-editor textarea { resize:vertical; min-height:66px }\n .creative-editor-actions { display:flex; flex-wrap:wrap; justify-content:flex-end; gap:6px }\n .provider-pages { display:flex; justify-content:center; margin-top:10px }\n .provider-message { margin:8px 0; color:var(--muted); font-size:11px; line-height:1.4 }\n @media (pointer:coarse) { .creative-menu>summary,.creative-menu-items button { min-height:44px } }\n`;\n\n/** Provider controls invoke the registry; the central upload library remains separate. */\nexport const PROVIDER_GALLERY_UI = String.raw`\n let providerGallery=null;\n const galleryStable=value=>JSON.stringify((function sort(v){return Array.isArray(v)?v.map(sort):object(v)?Object.fromEntries(Object.entries(v).sort(([a],[b])=>a.localeCompare(b)).map(([k,item])=>[k,sort(item)])):v;})(value));\n const galleryItemKey=item=>[item.provider,item.account_id,item.id].join(':');\n function galleryScope(meta) {\n const args={...meta.refresh?.arguments};delete args[meta.pagination?.cursorInput];\n return galleryStable({tool:meta.tool,provider:meta.provider,account:meta.accountId,project:meta.context?.project_id,filters:args});\n }\n function galleryMatches(meta,expected) {return meta.tool===expected.tool && meta.provider===expected.provider && meta.accountId===expected.accountId && meta.context?.project_id===expected.context?.project_id;}\n function galleryArgsMatchScope(args,meta) {return object(args) && args.account_id===meta.accountId && args.project_id===meta.context?.project_id && !Object.hasOwn(args,'pending_operation_id');}\n function galleryActions(creative,meta) {\n if(meta.capabilities?.can_write!==true || !meta.provider || !meta.accountId || creative.provider!==meta.provider || creative.account_id!==meta.accountId) return [];\n return arr(creative.actions).filter(action=>object(action) && typeof action.tool==='string' && action.tool.startsWith(meta.provider+'_') && object(action.arguments) && action.arguments.account_id===creative.account_id && !Object.hasOwn(action.arguments,'pending_operation_id') && (!action.arguments.project_id || action.arguments.project_id===meta.context?.project_id) && Array.isArray(action.fields) && action.fields.every(field=>object(field) && typeof field.key==='string' && /^[a-z][a-z0-9_]*$/.test(field.key) && !['account_id','project_id','pending_operation_id','constructor','prototype','__proto__'].includes(field.key) && !Object.hasOwn(action.arguments,field.key) && ['text','text_list','url_list','select'].includes(field.type) && (typeof field.value==='string' || Array.isArray(field.value) && field.value.every(v=>typeof v==='string'))) && new Set(action.fields.map(field=>field.key)).size===action.fields.length).slice(0,8);\n }\n function galleryMenu(creative) {\n const actions=galleryActions(creative,providerGallery.meta);\n return actions.length?'<details class=\"creative-menu\"><summary aria-label=\"Actions for '+esc(creative.name || 'creative')+'\">⋯</summary><div class=\"creative-menu-items\">'+actions.map((action,index)=>'<button type=\"button\" data-creative-action=\"'+index+'\">'+esc(action.label || 'Edit creative')+'</button>').join('')+'</div></details>':'';\n }\n function galleryNext(meta) {\n const args=meta.next?.arguments,key=meta.pagination?.cursorInput,base=meta.refresh?.arguments;\n if(typeof key!=='string' || !/^[a-z][a-z0-9_]*$/.test(key) || ['account_id','project_id','pending_operation_id','constructor','prototype'].includes(key) || !galleryArgsMatchScope(args,meta) || !object(base)) return null;\n const immutable=value=>Object.fromEntries(Object.entries(value).filter(([field])=>field!==key));\n if(galleryStable(immutable(args))!==galleryStable(immutable(base)) || galleryStable(args[key])===galleryStable(base[key]) || !(typeof args[key]==='string' && args[key] || typeof args[key]==='number' && Number.isSafeInteger(args[key]) && args[key]>=0)) return null;\n return {...args};\n }\n function galleryPageValue(response,gallery,args) {\n const value=resultData(response),meta=value?._adport;\n if(response?.isError || value?.error || !Array.isArray(value?.creatives) || !meta || !galleryMatches(meta,gallery.meta) || !galleryArgsMatchScope(args,meta) || !object(meta.refresh?.arguments) || galleryStable(meta.refresh.arguments)!==galleryStable(args) || value.creatives.some(item=>item.provider!==meta.provider || item.account_id!==meta.accountId)) throw new Error('The gallery response could not be confirmed.');\n return value;\n }\n function updateGalleryCard(card,old,item,gallery) {\n const template=document.createElement('template');template.innerHTML=creativeCards([item],galleryMenu);const fresh=template.content.firstElementChild;\n for(const selector of ['.creative-heading','.creative-copy','.creative-footer']) card.querySelector(selector)?.replaceChildren(...fresh.querySelector(selector).childNodes);\n const mediaKey=items=>galleryStable(arr(items).map(media=>{const path=value=>{try {const url=new URL(value);return url.origin+url.pathname;} catch {return value;}};return {type:media.type,url:path(media.url),poster:path(media.poster_url)};}));\n if(mediaKey(old.media)!==mediaKey(item.media)) {card.querySelector('.creative-media')?.remove();const media=fresh.querySelector('.creative-media');if(media) card.querySelector('.creative-copy').before(media);bindCreativeErrors(card);}\n else {\n const links=card.querySelectorAll('.creative-media a'),next=fresh.querySelectorAll('.creative-media a');links.forEach((link,index)=>{if(next[index]) link.href=next[index].href;});\n const labels=card.querySelectorAll('.creative-media [aria-label],.creative-media img'),freshLabels=fresh.querySelectorAll('.creative-media [aria-label],.creative-media img');labels.forEach((node,index)=>{const label=freshLabels[index];if(label) for(const key of ['aria-label','alt']) {if(label.hasAttribute(key)) node.setAttribute(key,label.getAttribute(key));else node.removeAttribute(key);}});\n }\n bindGalleryCard(card,gallery);\n }\n function renderProviderGallery(data,meta) {\n const previous=providerGallery,previousWrite=previous?.meta.capabilities?.can_write,retain=previous && previous.scope===galleryScope(meta) && app.querySelector('[data-provider-gallery]');\n if(!retain) providerGallery={scope:galleryScope(meta),data,meta,items:new Map(),sources:new Map(),seen:new Set(),busy:null,review:null};\n const gallery=providerGallery;gallery.data=data;gallery.meta=meta;\n if(!retain) app.innerHTML=chrome('<div data-provider-notes></div><div class=\"creative-grid\" data-provider-gallery role=\"region\" aria-label=\"Creative previews\" tabindex=\"0\"></div><div data-provider-pages></div>','');\n const root=app.querySelector('[data-provider-gallery]');\n for(const item of arr(data.creatives)) {\n const key=galleryItemKey(item);gallery.sources.set(key,meta.refresh?.arguments);if(gallery.items.has(key)) {const old=gallery.items.get(key);if(galleryStable(old)!==galleryStable(item) || previousWrite!==meta.capabilities?.can_write) {const card=[...root.querySelectorAll('[data-creative-key]')].find(node=>node.dataset.creativeKey===key);gallery.items.set(key,item);if(card) {if(meta.capabilities?.can_write!==true) card.querySelector('[data-creative-editor]')?.remove();updateGalleryCard(card,old,item,gallery);}}continue;}\n gallery.items.set(key,item);\n const template=document.createElement('template');template.innerHTML=creativeCards([item],galleryMenu);const card=template.content.firstElementChild;card.dataset.creativeKey=key;root.append(card);bindGalleryCard(card,gallery);bindCreativeErrors(card);\n }\n root.querySelector('.empty')?.remove();if(!gallery.items.size) root.innerHTML='<div class=\"empty\">No creatives to preview.</div>';\n root.classList.toggle('creative-grid-single',gallery.items.size===1);\n app.querySelector('[data-provider-notes]').innerHTML=notices({...data,truncated:false});\n state.result={structuredContent:{...data,creatives:[...gallery.items.values()],_adport:meta}};renderProviderPages();\n }\n function renderProviderPages(message='') {\n const gallery=providerGallery,area=app.querySelector('[data-provider-pages]');if(!gallery || !area) return;\n const next=galleryNext(gallery.meta),focused=area.querySelector('button')===document.activeElement;\n area.innerHTML=(message?'<p class=\"provider-message\" role=\"status\">'+esc(message)+'</p>':'')+(next?'<div class=\"provider-pages\"><button class=\"media-button\" type=\"button\" data-provider-more aria-disabled=\"'+!!gallery.busy+'\">'+(gallery.busy?.kind==='page'?'Loading…':'Load more')+'</button></div>':gallery.data.truncated?'<p class=\"provider-message\">More creatives may exist. Ask your assistant for the next page.</p>':'');\n area.querySelector('[data-provider-more]')?.addEventListener('click',loadProviderPage);\n if(focused) (area.querySelector('button') || app.querySelector('[data-provider-gallery]'))?.focus({preventScroll:true});\n }\n async function loadProviderPage() {\n const gallery=providerGallery,args=gallery && galleryNext(gallery.meta);if(!gallery || gallery.busy || !args) return;\n const fingerprint=galleryStable(args);if(gallery.seen.has(fingerprint)) {gallery.meta={...gallery.meta,next:undefined};renderProviderPages('No new page was returned.');return;}\n gallery.busy={kind:'page',tool:gallery.meta.tool,args};renderProviderPages();\n try {\n const response=await callTool(gallery.meta.tool,args,60000),value=galleryPageValue(response,gallery,args);if(providerGallery!==gallery) return;\n gallery.seen.add(fingerprint);state.hasLocalResult=true;hostResults.add(JSON.stringify(value));\n const next=galleryNext(value._adport),meta={...value._adport,...(next && !gallery.seen.has(galleryStable(next))?{}:{next:undefined})};\n gallery.busy=null;renderProviderGallery(value,meta);\n } catch(error) {if(providerGallery===gallery) renderProviderPages(error?.message || 'Could not load more creatives.');}\n finally {if(providerGallery===gallery) {gallery.busy=null;const button=app.querySelector('[data-provider-more]');if(button) {button.setAttribute('aria-disabled','false');button.textContent='Load more';}}}\n }\n function bindGalleryCard(card,gallery) {\n card.querySelectorAll('[data-creative-action]').forEach(button=>button.addEventListener('click',()=>{\n if(providerGallery!==gallery || gallery.busy) return;\n const item=gallery.items.get(card.dataset.creativeKey),action=galleryActions(item,gallery.meta)[Number(button.dataset.creativeAction)];if(!action) return;\n card.querySelectorAll('.creative-menu').forEach(menu=>{menu.open=false;});openGalleryEditor(card,item,action,gallery);\n }));\n card.querySelector('.creative-menu')?.addEventListener('keydown',event=>{if(event.key==='Escape') {event.currentTarget.open=false;event.currentTarget.querySelector('summary').focus();}});\n card.querySelector('.creative-menu')?.addEventListener('toggle',event=>{if(event.currentTarget.open) app.querySelectorAll('.creative-menu[open]').forEach(menu=>{if(menu!==event.currentTarget) menu.open=false;});});\n }\n function openGalleryEditor(card,item,action,gallery) {\n card.querySelector('[data-creative-editor]')?.remove();const form=document.createElement('form');form.className='creative-editor';form.dataset.creativeEditor='';form.setAttribute('aria-label',action.label || 'Edit creative');\n form.innerHTML=action.fields.map((field,index)=>{const value=Array.isArray(field.value)?field.value.join('\\n'):field.value;\n const input=field.type==='select'?'<select data-field=\"'+index+'\">'+arr(field.options).filter(option=>typeof option.value==='string').map(option=>'<option value=\"'+esc(option.value)+'\" '+(option.value===value?'selected':'')+'>'+esc(option.label || option.value)+'</option>').join('')+'</select>':field.type!=='text' || value.includes('\\n') || value.length>120?'<textarea data-field=\"'+index+'\" rows=\"3\">'+esc(value)+'</textarea>':'<input data-field=\"'+index+'\" value=\"'+esc(value)+'\">';\n return '<label>'+esc(field.label || field.key)+input+'</label>';}).join('')+'<p class=\"provider-message\" role=\"alert\" data-editor-error hidden></p><div class=\"creative-editor-actions\"><button class=\"media-button\" type=\"button\" data-editor-cancel>Cancel</button><button class=\"media-button primary\" type=\"submit\">Preview changes</button></div>';\n card.append(form);form.querySelector('[data-field],[type=\"submit\"]')?.focus({preventScroll:true});form.scrollIntoView?.({block:'nearest'});\n form.querySelector('[data-editor-cancel]').addEventListener('click',()=>{if(!gallery.busy) {form.remove();card.querySelector('.creative-menu>summary')?.focus({preventScroll:true});}});\n form.addEventListener('submit',async event=>{\n event.preventDefault();if(providerGallery!==gallery || gallery.busy) return;\n const error=form.querySelector('[data-editor-error]'),args={...action.arguments,...(gallery.meta.context?.project_id?{project_id:gallery.meta.context.project_id}:{})};error.hidden=true;\n try {\n action.fields.forEach((field,index)=>{const raw=form.querySelector('[data-field=\"'+index+'\"]').value,value=['text_list','url_list'].includes(field.type)?raw.split(/\\r?\\n/).map(v=>v.trim()).filter(Boolean):raw;\n if(field.max_length && (Array.isArray(value)?value:[value]).some(v=>v.length>field.max_length)) throw new Error((field.label || field.key)+' is too long.');\n if(field.type==='select' && !arr(field.options).some(option=>option.value===value)) throw new Error('Choose a listed option.');args[field.key]=value;});\n gallery.busy={kind:'preview',tool:action.tool,args};form.querySelectorAll('button,input,textarea,select').forEach(node=>{node.disabled=true;});form.querySelector('[type=\"submit\"]').textContent='Preparing preview…';\n const response=await callTool(action.tool,args,180000),value=resultData(response);if(providerGallery!==gallery) return;\n if(response?.isError || value?.error || value.status!=='pending_validation' || value.applied!==false || typeof value.pending_operation_id!=='string' || value._adport?.tool!==action.tool || value._adport?.accountId!==item.account_id || value._adport?.context?.project_id!==gallery.meta.context?.project_id) throw new Error('The preview could not be confirmed. Check the tool result before trying again.');\n const fragment=document.createDocumentFragment(),root=app.querySelector('[data-provider-gallery]');gallery.review={fragment,key:galleryItemKey(item),tool:action.tool,pending:value.pending_operation_id,kind:value.preview?.review?.kind,scroll:root.scrollTop};while(app.firstChild) fragment.append(app.firstChild);\n gallery.busy=null;acceptResult(response,true);\n } catch(problem) {if(providerGallery===gallery) {error.textContent=problem?.message || 'The preview could not be confirmed.';error.hidden=false;}}\n finally {if(providerGallery===gallery) {gallery.busy=null;form.querySelectorAll('button,input,textarea,select').forEach(node=>{node.disabled=false;});form.querySelector('[type=\"submit\"]').textContent='Preview changes';}}\n });\n if(!action.fields.length) form.requestSubmit();\n }\n function providerGalleryIgnoreEcho(data) {\n const busy=providerGallery?.busy,meta=data?._adport;\n return !!busy && meta?.tool===busy.tool && (!meta.accountId || meta.accountId===providerGallery.meta.accountId) && (!meta.context?.project_id || meta.context.project_id===providerGallery.meta.context?.project_id);\n }\n function providerGalleryReviewControls(data,meta) {\n const gallery=providerGallery,review=gallery?.review;if(!review) return;\n if(meta.tool!==review.tool || meta.accountId!==gallery.meta.accountId || meta.context?.project_id!==gallery.meta.context?.project_id) {providerGallery=null;return;}\n const footer=app.querySelector('.operation-footer');if(!footer) return;\n const back=document.createElement('button');back.type='button';back.className='media-button';back.textContent='Back';back.setAttribute('aria-label','Back to creatives');back.disabled=attempts.get(review.pending)?.phase==='applying';footer.prepend(back);\n back.addEventListener('click',async()=>{\n if(providerGallery!==gallery || attempts.get(review.pending)?.phase==='applying') return;\n cancelHold();clearTimeout(expiryTimer);const phase=attempts.get(review.pending)?.phase;app.replaceChildren(review.fragment);gallery.review=null;\n const root=app.querySelector('[data-provider-gallery]');root.scrollTop=review.scroll;state.result={structuredContent:{...gallery.data,creatives:[...gallery.items.values()],_adport:gallery.meta}};\n const card=[...root.querySelectorAll('[data-creative-key]')].find(node=>node.dataset.creativeKey===review.key);card?.querySelector('.creative-menu>summary')?.focus({preventScroll:true});\n if(!['applied','unconfirmed','partial'].includes(phase)) return;\n card?.querySelector('[data-creative-editor]')?.remove();const args=gallery.sources.get(review.key);\n if(!galleryArgsMatchScope(args,gallery.meta)) {renderProviderPages('Ask your assistant for a fresh view before editing again.');return;}\n gallery.busy={kind:'refresh',tool:gallery.meta.tool,args};renderProviderPages();\n try {\n const response=await callTool(gallery.meta.tool,args,60000),value=galleryPageValue(response,gallery,args);if(providerGallery!==gallery) return;\n const updated=value.creatives.find(item=>galleryItemKey(item)===review.key);\n if(!updated && !(phase==='applied' && review.kind==='remove')) throw new Error('The edited creative is outside this page. Ask your assistant for a fresh view.');\n if(!updated) {\n gallery.items.delete(review.key);gallery.sources.delete(review.key);card?.remove();gallery.seen.clear();\n renderProviderGallery(value,value._adport);root.scrollTop=review.scroll;root.focus({preventScroll:true});\n } else {\n const old=gallery.items.get(review.key);gallery.items.set(review.key,updated);if(card) updateGalleryCard(card,old,updated,gallery);\n state.result={structuredContent:{...gallery.data,creatives:[...gallery.items.values()],_adport:gallery.meta}};\n }\n state.hasLocalResult=true;\n } catch(problem) {if(providerGallery===gallery) {card?.querySelector('.creative-menu')?.remove();renderProviderPages(problem?.message || 'The updated creative could not be read. Ask your assistant for a fresh view.');}}\n finally {if(providerGallery===gallery) {gallery.busy=null;const more=app.querySelector('[data-provider-more]');more?.setAttribute('aria-disabled','false');}}\n });\n }\n`;\n","// Provider brand marks reused from the cloud UI; embedded to keep the iframe offline.\nexport const PROVIDER_LOGOS: Record<string, string> = {\n \"ga4\": \"<svg stroke=\\\"currentColor\\\" fill=\\\"currentColor\\\" stroke-width=\\\"0\\\" role=\\\"img\\\" viewBox=\\\"0 0 24 24\\\" color=\\\"#e37400\\\" style=\\\"color:#e37400\\\" height=\\\"1em\\\" width=\\\"1em\\\"><path d=\\\"M22.84 2.9982v17.9987c.0086 1.6473-1.3197 2.9897-2.967 2.9984a2.9808 2.9808 0 01-.3677-.0208c-1.528-.226-2.6477-1.5558-2.6105-3.1V3.1204c-.0369-1.5458 1.0856-2.8762 2.6157-3.1 1.6361-.1915 3.1178.9796 3.3093 2.6158.014.1201.0208.241.0202.3619zM4.1326 18.0548c-1.6417 0-2.9726 1.331-2.9726 2.9726C1.16 22.6691 2.4909 24 4.1326 24s2.9726-1.3309 2.9726-2.9726-1.331-2.9726-2.9726-2.9726zm7.8728-9.0098c-.0171 0-.0342 0-.0513.0003-1.6495.0904-2.9293 1.474-2.891 3.1256v7.9846c0 2.167.9535 3.4825 2.3505 3.763 1.6118.3266 3.1832-.7152 3.5098-2.327.04-.1974.06-.3983.0593-.5998v-8.9585c.003-1.6474-1.33-2.9852-2.9773-2.9882z\\\"></path></svg>\",\n \"gsc\": \"<svg stroke=\\\"currentColor\\\" fill=\\\"currentColor\\\" stroke-width=\\\"0\\\" role=\\\"img\\\" viewBox=\\\"0 0 24 24\\\" color=\\\"#4285f4\\\" style=\\\"color:#4285f4\\\" height=\\\"1em\\\" width=\\\"1em\\\"><path d=\\\"M8.548 1.156L6.832 2.872v1.682h1.716zm0 3.398v.035H6.832v-.035H3.386L0 7.844v3.577h2.826V8.94c0-.525.429-.954.954-.954h16.476c.525 0 .954.43.954.954v2.48h2.754V7.844l-3.386-3.29H17.3v.035h-1.717v-.035zm7.035 0H17.3V2.872l-1.717-1.716zM8.679 1.188V2.84h6.773V1.188zm11.471 7.07a.834.834 0 00-.132.01l-.543.002c-5.216.014-10.432-.008-15.648.01-.435-.063-.794.436-.716.883v2.264h17.812c-.016-.888.045-1.782-.034-2.666-.104-.342-.427-.502-.739-.502zm-15.422.634a.689.698 0 01.689.698.689.698 0 01-.689.697.689.698 0 01-.688-.697.689.698 0 01.688-.698zm2.134 0a.689.698 0 01.689.698.689.698 0 01-.689.697.689.698 0 01-.688-.697.689.698 0 01.688-.698zM.036 11.645v9.156c0 1.05.858 1.908 1.907 1.908h.883V11.645zm21.174 0v11.064h.882c1.05 0 1.908-.858 1.908-1.908v-9.156zM4.057 13.133v6.85h6.137v-6.85zm13.243.021v3.777l-1.708.977-1.708-.977v-3.758a4.006 4.006 0 000 7.23v2.441h3.457v-2.442a4.006 4.006 0 00-.041-7.248zm-13.243 8.26v1.43h7.925v-1.43z\\\"></path></svg>\",\n \"gtm\": \"<svg stroke=\\\"currentColor\\\" fill=\\\"currentColor\\\" stroke-width=\\\"0\\\" role=\\\"img\\\" viewBox=\\\"0 0 24 24\\\" color=\\\"#4285f4\\\" style=\\\"color:#4285f4\\\" height=\\\"1em\\\" width=\\\"1em\\\"><path d=\\\"M12.003 0a3 3 0 0 0-2.121 5.121l6.865 6.865-4.446 4.541 1.745 1.836a3.432 3.432 0 0 1 .7.739l.012.011-.001.002a3.432 3.432 0 0 1 .609 1.953 3.432 3.432 0 0 1-.09.78l7.75-7.647c.031-.029.067-.05.098-.08.023-.023.038-.052.06-.076a2.994 2.994 0 0 0-.06-4.166l-9-9A2.99 2.99 0 0 0 12.003 0zM8.63 2.133L.88 9.809a2.998 2.998 0 0 0 0 4.238l7.7 7.75a3.432 3.432 0 0 1-.077-.729 3.432 3.432 0 0 1 3.431-3.431 3.432 3.432 0 0 1 .826.101l-5.523-5.81 4.371-4.373-2.08-2.08c-.903-.904-1.193-2.183-.898-3.342zm3.304 16.004a2.932 2.932 0 0 0-2.931 2.931A2.932 2.932 0 0 0 11.934 24a2.932 2.932 0 0 0 2.932-2.932 2.932 2.932 0 0 0-2.932-2.931z\\\"></path></svg>\",\n \"snapchat\": \"<svg viewBox=\\\"0 0 1024 1024\\\" aria-hidden=\\\"true\\\"> <path fill=\\\"#fff\\\" d=\\\"M992.5,756.3c-4.2-13.9-24.3-23.7-24.3-23.7l0,0c-1.9-1-3.6-1.9-5-2.6c-33.5-16.2-63.2-35.7-88.2-57.8 c-20.1-17.8-37.3-37.4-51.1-58.2c-16.9-25.4-24.8-46.6-28.2-58.1c-1.9-7.5-1.6-10.5,0-14.4c1.3-3.3,5.2-6.4,7-7.9 c11.3-8,29.5-19.8,40.7-27c9.7-6.3,18-11.7,22.9-15.1c15.7-11,26.5-22.2,32.8-34.3c8.2-15.6,9.2-32.8,2.8-49.7 c-8.6-22.8-29.9-36.4-57-36.4c-6,0-12.2,0.7-18.4,2c-15.5,3.4-30.2,8.9-42.5,13.7c-0.9,0.4-1.9-0.3-1.8-1.3 c1.3-30.5,2.8-71.5-0.6-110.4c-3-35.2-10.3-64.9-22.1-90.8c-11.9-26-27.4-45.2-39.5-59.1C708.5,112,688.2,92.5,657.6,75 C614.6,50.4,565.6,37.9,512,37.9c-53.5,0-102.4,12.5-145.5,37.1c-32.4,18.5-53.1,39.4-62.5,50.2c-12.1,13.9-27.6,33.1-39.5,59.1 c-11.9,25.9-19.1,55.5-22.1,90.8c-3.4,39.1-2,76.8-0.6,110.4c0,1-0.9,1.7-1.9,1.3c-12.3-4.8-27-10.3-42.5-13.7 c-6.1-1.3-12.3-2-18.4-2c-27,0-48.3,13.6-57,36.4c-6.4,16.9-5.4,34.1,2.8,49.7c6.4,12.1,17.1,23.3,32.8,34.3 c4.8,3.4,13.2,8.8,22.9,15.1c10.9,7.1,28.6,18.6,40,26.5c1.4,1,6.2,4.6,7.7,8.4c1.6,4,1.9,7-0.2,15c-3.5,11.6-11.4,32.6-28,57.5 c-13.8,20.9-31,40.4-51.1,58.2c-25,22.1-54.7,41.6-88.2,57.8c-1.6,0.8-3.5,1.7-5.5,2.9l0,0c0,0-20,10.2-23.8,23.4 c-5.6,19.5,9.3,37.8,24.4,47.6c24.8,16,55,24.6,72.5,29.3c4.9,1.3,9.3,2.5,13.3,3.7c2.5,0.8,8.8,3.2,11.5,6.7 c3.4,4.4,3.8,9.8,5,15.9v0c1.9,10.3,6.2,23,18.9,31.8c14,9.6,31.7,10.3,54.2,11.2c23.5,0.9,52.7,2,86.2,13.1 c15.5,5.1,29.6,13.8,45.8,23.8c34,20.9,76.3,46.9,148.5,46.9c72.3,0,114.9-26.1,149.1-47.1c16.2-9.9,30.1-18.5,45.3-23.5 c33.5-11.1,62.7-12.2,86.2-13.1c22.5-0.9,40.2-1.5,54.2-11.2c13.6-9.4,17.5-23.4,19.3-33.9c1-5.2,1.6-9.9,4.6-13.7 c2.6-3.3,8.4-5.6,11.1-6.5c4.1-1.3,8.7-2.5,13.8-3.9c17.5-4.7,39.5-10.2,66.2-25.3C993.7,789.8,995.9,767.4,992.5,756.3z\\\" /> <path fill=\\\"#000\\\" d=\\\"M1020.3,745.5c-7.1-19.4-20.7-29.7-36.1-38.3c-2.9-1.7-5.6-3.1-7.8-4.1c-4.6-2.4-9.3-4.7-14-7.1 c-48.1-25.5-85.7-57.7-111.7-95.8c-8.8-12.9-14.9-24.5-19.2-34c-2.2-6.4-2.1-10-0.5-13.3c1.2-2.5,4.4-5.1,6.2-6.4 c8.3-5.5,16.8-11,22.6-14.7c10.3-6.7,18.5-12,23.7-15.6c19.8-13.8,33.6-28.5,42.2-44.9c12.2-23.1,13.7-49.5,4.3-74.3 c-13-34.4-45.6-55.8-85-55.8c-8.2,0-16.5,0.9-24.7,2.7c-2.2,0.5-4.3,1-6.4,1.5c0.4-23.4-0.2-48.4-2.3-72.8 c-7.4-86-37.5-131.1-68.9-167c-13.1-15-35.9-36.9-70.1-56.5C624.9,21.7,570.9,7.9,512,7.9c-58.7,0-112.7,13.8-160.4,41.1 c-34.4,19.6-57.2,41.6-70.2,56.5c-31.4,35.9-61.5,81-68.9,167c-2.1,24.4-2.6,49.4-2.3,72.8c-2.1-0.5-4.3-1-6.4-1.5 c-8.2-1.8-16.6-2.7-24.7-2.7c-39.4,0-72,21.4-85,55.8c-9.4,24.8-7.9,51.2,4.3,74.3c8.6,16.4,22.5,31.1,42.2,44.9 c5.3,3.7,13.4,9,23.7,15.6c5.6,3.6,13.7,8.9,21.7,14.2c1.2,0.8,5.5,4,7,7c1.7,3.4,1.7,7.1-0.8,13.9c-4.2,9.3-10.3,20.7-18.9,33.3 c-25.5,37.3-62,68.9-108.5,94.1c-24.7,13.1-50.3,21.8-61.1,51.2c-8.2,22.2-2.8,47.5,17.9,68.8l0,0c6.8,7.3,15.4,13.8,26.2,19.8 c25.4,14,47,20.9,64,25.6c3,0.9,9.9,3.1,12.9,5.8c7.6,6.6,6.5,16.6,16.6,31.2c6.1,9.1,13.1,15.3,18.9,19.3 c21.1,14.6,44.9,15.5,70.1,16.5c22.7,0.9,48.5,1.9,77.9,11.6c12.2,4,24.9,11.8,39.5,20.8c35.2,21.7,83.5,51.3,164.2,51.3 c80.8,0,129.3-29.8,164.8-51.5c14.6-8.9,27.2-16.7,39-20.6c29.4-9.7,55.2-10.7,77.9-11.6c25.2-1,48.9-1.9,70.1-16.5 c6.6-4.6,15-12.1,21.6-23.5c7.2-12.3,7.1-21,13.9-26.9c2.8-2.4,8.9-4.5,12.2-5.5c17.1-4.7,39-11.6,64.9-25.9 c11.5-6.3,20.4-13.2,27.5-21.1c0.1-0.1,0.2-0.2,0.3-0.3C1023.4,791.7,1028.3,767.2,1020.3,745.5z M948.6,784 c-43.8,24.2-72.9,21.6-95.5,36.1c-19.2,12.4-7.9,39.1-21.8,48.7c-17.2,11.9-67.9-0.8-133.4,20.8c-54,17.9-88.5,69.2-185.8,69.2 c-97.5,0-131-51.1-185.8-69.2c-65.5-21.6-116.3-8.9-133.4-20.8c-13.9-9.6-2.6-36.3-21.8-48.7c-22.6-14.6-51.7-12-95.5-36.1 c-27.9-15.4-12.1-24.9-2.8-29.4c158.6-76.7,183.8-195.3,185-204.2c1.4-10.6,2.9-19-8.8-29.9c-11.3-10.5-61.6-41.6-75.5-51.3 c-23.1-16.1-33.2-32.2-25.7-52c5.2-13.7,18-18.8,31.5-18.8c4.2,0,8.5,0.5,12.6,1.4c25.3,5.5,49.9,18.2,64.1,21.6 c2,0.5,3.7,0.7,5.2,0.7c7.6,0,10.2-3.8,9.7-12.5c-1.6-27.7-5.6-81.7-1.2-132.2c6-69.4,28.4-103.8,55-134.3 c12.8-14.6,72.8-78,187.5-78c115,0,174.7,63.4,187.5,78c26.6,30.4,49,64.8,55,134.3c4.4,50.5,0.6,104.5-1.2,132.2 c-0.6,9.1,2.2,12.5,9.7,12.5c1.5,0,3.3-0.2,5.2-0.7c14.2-3.4,38.8-16.1,64.1-21.6c4.1-0.9,8.4-1.4,12.6-1.4 c13.5,0,26.3,5.2,31.5,18.8c7.5,19.8-2.7,35.9-25.7,52c-13.9,9.7-64.2,40.8-75.5,51.3c-11.7,10.8-10.2,19.2-8.8,29.9 c1.1,8.9,26.4,127.5,185,204.2C960.6,759.1,976.5,768.6,948.6,784z\\\" /> </svg>\",\n \"google\": \"<svg viewBox=\\\"0 0 24 24\\\"><path fill=\\\"#34a853\\\" d=\\\"M4 22.93a4 4 0 1 1 0-8 4 4 0 0 1 0 8Z\\\"/><path fill=\\\"#4285f4\\\" d=\\\"M23.464 16.929 15.463 3.072A4 4 0 0 0 8.534 7.072l8.001 13.857a4 4 0 0 0 6.929-4Z\\\"/><path fill=\\\"#fbbc04\\\" d=\\\"M7.514 4.844 1.565 15.148A4.5 4.5 0 0 1 4 14.43a4.5 4.5 0 0 1 4.494 4.715l3.217-5.573-3.61-6.25a4 4 0 0 1-.587-2.478Z\\\"/></svg>\",\n \"meta\": \"<svg viewBox=\\\"0 0 24 24\\\"><path fill=\\\"#0866ff\\\" d=\\\"M6.915 4.03C2.484 4.03 0 9.95 0 14.449c0 3.37 1.276 5.521 4.439 5.521 2.93 0 4.146-2.574 6.628-6.764l.942-1.664 2.335 3.895c1.883 3.15 3.38 4.533 5.53 4.533 2.788 0 4.126-1.93 4.126-5.56 0-5.53-2.73-10.38-6.8-10.38-2.04 0-3.835 1.53-5.173 3.348C10.16 5.01 8.593 4.03 6.915 4.03Zm-.04 2.606c1.55 0 2.445 1.193 3.908 3.025l-1.02 1.566c-2.22 3.41-3.576 6.155-5.323 6.155-1.23 0-2.154-1.075-2.154-2.9 0-3.755 2.088-7.846 4.588-7.846Zm10.2-.553c2.488 0 4.639 4.054 4.639 8.4 0 1.547-.368 2.899-1.839 2.899-1.193 0-2.027-1.42-4.496-5.362l-1.872-3.008c1.12-1.814 2.248-2.929 3.559-2.929Z\\\"/></svg>\",\n \"tiktok\": \"<svg class=\\\"tiktok-logo\\\" viewBox=\\\"0 0 58 58\\\" aria-hidden=\\\"true\\\">\\n <path d=\\\"M25.98 0v37.68c0 4.94-3.55 8.11-7.88 8.11-1.43 0-2.79-.33-3.97-.95 1.5 1.91 3.87 3.01 6.47 3.01 4.32 0 7.87-3.17 7.87-8.11V2.06h6.85A20.3 20.3 0 0 1 34.87 0h-8.89ZM20.36 21.91v-1.87a15.6 15.6 0 0 0-2.45-.19C8.16 19.85 0 27.66 0 37.35c0 6.36 3.1 11.79 7.81 15.01a18.09 18.09 0 0 1-5.32-12.96c0-9.67 8.14-17.48 17.87-17.49Zm29-6.56v-1.69a17.4 17.4 0 0 1-7.63-2.55 16.14 16.14 0 0 0 7.63 4.24Z\\\" fill=\\\"#2DCCD3\\\" />\\n <path d=\\\"M41.73 11.11a17.48 17.48 0 0 1-4.37-9.05h-2.04c1.16 4.23 3.56 7.18 6.41 9.05Zm7.63 11.37a19.31 19.31 0 0 1-11-2.97c3.84 3.84 8.5 5.03 13.5 5.03v-8.82a17.4 17.4 0 0 1-2.5-.37v7.13ZM14.13 44.84a8.05 8.05 0 0 1-1.7-5.1c0-5.7 4.47-8.72 10.42-8.09v-9.55a14.98 14.98 0 0 0-2.45-.2h-.04v7.69c-5.95-.62-10.42 2.38-10.42 8.09 0 3.34 1.71 5.87 4.19 7.16Zm21.74-7.78c0 12.03-9.22 18.41-17.91 18.41-3.76 0-7.26-1.14-10.15-3.11a18.12 18.12 0 0 0 12.64 5.17c8.69 0 17.91-6.38 17.91-18.41V19.51a19.9 19.9 0 0 1-2.49-2.06v19.61Z\\\" fill=\\\"#F1204A\\\" />\\n <path d=\\\"M35.32 2.06h-6.85v37.68c0 4.94-3.55 8.11-7.87 8.11-2.6 0-4.97-1.1-6.47-3.01-2.48-1.29-4.19-3.82-4.19-7.16 0-5.71 4.47-8.71 10.42-8.09v-7.68C10.63 21.93 2.49 29.73 2.49 39.4c0 5.16 2.04 9.71 5.32 12.96 2.89 1.97 6.39 3.11 10.15 3.11 8.69 0 17.91-6.38 17.91-18.41V17.45c.8.8 1.63 1.48 2.49 2.06a19.31 19.31 0 0 0 11 2.97v-7.13a16.14 16.14 0 0 1-7.63-4.24c-2.85-1.87-5.25-4.82-6.41-9.05Z\\\" fill=\\\"currentColor\\\" />\\n </svg>\",\n \"apple\": \"<svg viewBox=\\\"0 0 24 24\\\"><path fill=\\\"currentColor\\\" d=\\\"M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09Zm3.377-3.065C16.372 2.819 16.929 1.403 16.774 0c-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.56-1.701Z\\\"/></svg>\",\n \"microsoft\": \"<svg viewBox=\\\"0 0 24 24\\\"><path fill=\\\"#f25022\\\" d=\\\"M0 0h11.4v11.4H0Z\\\"/><path fill=\\\"#7fba00\\\" d=\\\"M12.6 0H24v11.4H12.6Z\\\"/><path fill=\\\"#00a4ef\\\" d=\\\"M0 12.6h11.4V24H0Z\\\"/><path fill=\\\"#ffb900\\\" d=\\\"M12.6 12.6H24V24H12.6Z\\\"/></svg>\",\n \"reddit\": \"<svg stroke=\\\"currentColor\\\" fill=\\\"currentColor\\\" stroke-width=\\\"0\\\" role=\\\"img\\\" viewBox=\\\"0 0 24 24\\\" color=\\\"#fff\\\" style=\\\"color:#fff\\\" height=\\\"1em\\\" width=\\\"1em\\\"><path d=\\\"M12 0C5.373 0 0 5.373 0 12c0 3.314 1.343 6.314 3.515 8.485l-2.286 2.286C.775 23.225 1.097 24 1.738 24H12c6.627 0 12-5.373 12-12S18.627 0 12 0Zm4.388 3.199c1.104 0 1.999.895 1.999 1.999 0 1.105-.895 2-1.999 2-.946 0-1.739-.657-1.947-1.539v.002c-1.147.162-2.032 1.15-2.032 2.341v.007c1.776.067 3.4.567 4.686 1.363.473-.363 1.064-.58 1.707-.58 1.547 0 2.802 1.254 2.802 2.802 0 1.117-.655 2.081-1.601 2.531-.088 3.256-3.637 5.876-7.997 5.876-4.361 0-7.905-2.617-7.998-5.87-.954-.447-1.614-1.415-1.614-2.538 0-1.548 1.255-2.802 2.803-2.802.645 0 1.239.218 1.712.585 1.275-.79 2.881-1.291 4.64-1.365v-.01c0-1.663 1.263-3.034 2.88-3.207.188-.911.993-1.595 1.959-1.595Zm-8.085 8.376c-.784 0-1.459.78-1.506 1.797-.047 1.016.64 1.429 1.426 1.429.786 0 1.371-.369 1.418-1.385.047-1.017-.553-1.841-1.338-1.841Zm7.406 0c-.786 0-1.385.824-1.338 1.841.047 1.017.634 1.385 1.418 1.385.785 0 1.473-.413 1.426-1.429-.046-1.017-.721-1.797-1.506-1.797Zm-3.703 4.013c-.974 0-1.907.048-2.77.135-.147.015-.241.168-.183.305.483 1.154 1.622 1.964 2.953 1.964 1.33 0 2.47-.81 2.953-1.964.057-.137-.037-.29-.184-.305-.863-.087-1.795-.135-2.769-.135Z\\\"></path></svg>\",\n \"x\": \"<svg stroke=\\\"currentColor\\\" fill=\\\"currentColor\\\" stroke-width=\\\"0\\\" role=\\\"img\\\" viewBox=\\\"0 0 24 24\\\" color=\\\"#fff\\\" style=\\\"color:#fff\\\" height=\\\"1em\\\" width=\\\"1em\\\"><path d=\\\"M14.234 10.162 22.977 0h-2.072l-7.591 8.824L7.251 0H.258l9.168 13.343L.258 24H2.33l8.016-9.318L16.749 24h6.993zm-2.837 3.299-.929-1.329L3.076 1.56h3.182l5.965 8.532.929 1.329 7.754 11.09h-3.182z\\\"></path></svg>\",\n \"pinterest\": \"<svg stroke=\\\"currentColor\\\" fill=\\\"currentColor\\\" stroke-width=\\\"0\\\" role=\\\"img\\\" viewBox=\\\"0 0 24 24\\\" color=\\\"#fff\\\" style=\\\"color:#fff\\\" height=\\\"1em\\\" width=\\\"1em\\\"><path d=\\\"M12.017 0C5.396 0 .029 5.367.029 11.987c0 5.079 3.158 9.417 7.618 11.162-.105-.949-.199-2.403.041-3.439.219-.937 1.406-5.957 1.406-5.957s-.359-.72-.359-1.781c0-1.663.967-2.911 2.168-2.911 1.024 0 1.518.769 1.518 1.688 0 1.029-.653 2.567-.992 3.992-.285 1.193.6 2.165 1.775 2.165 2.128 0 3.768-2.245 3.768-5.487 0-2.861-2.063-4.869-5.008-4.869-3.41 0-5.409 2.562-5.409 5.199 0 1.033.394 2.143.889 2.741.099.12.112.225.085.345-.09.375-.293 1.199-.334 1.363-.053.225-.172.271-.401.165-1.495-.69-2.433-2.878-2.433-4.646 0-3.776 2.748-7.252 7.92-7.252 4.158 0 7.392 2.967 7.392 6.923 0 4.135-2.607 7.462-6.233 7.462-1.214 0-2.354-.629-2.758-1.379l-.749 2.848c-.269 1.045-1.004 2.352-1.498 3.146 1.123.345 2.306.535 3.55.535 6.607 0 11.985-5.365 11.985-11.987C23.97 5.39 18.592.026 11.985.026L12.017 0z\\\"></path></svg>\",\n \"spotify\": \"<svg stroke=\\\"currentColor\\\" fill=\\\"currentColor\\\" stroke-width=\\\"0\\\" role=\\\"img\\\" viewBox=\\\"0 0 24 24\\\" color=\\\"#111\\\" style=\\\"color:#111\\\" height=\\\"1em\\\" width=\\\"1em\\\"><path d=\\\"M12 0C5.4 0 0 5.4 0 12s5.4 12 12 12 12-5.4 12-12S18.66 0 12 0zm5.521 17.34c-.24.359-.66.48-1.021.24-2.82-1.74-6.36-2.101-10.561-1.141-.418.122-.779-.179-.899-.539-.12-.421.18-.78.54-.9 4.56-1.021 8.52-.6 11.64 1.32.42.18.479.659.301 1.02zm1.44-3.3c-.301.42-.841.6-1.262.3-3.239-1.98-8.159-2.58-11.939-1.38-.479.12-1.02-.12-1.14-.6-.12-.48.12-1.021.6-1.141C9.6 9.9 15 10.561 18.72 12.84c.361.181.54.78.241 1.2zm.12-3.36C15.24 8.4 8.82 8.16 5.16 9.301c-.6.179-1.2-.181-1.38-.721-.18-.601.18-1.2.72-1.381 4.26-1.26 11.28-1.02 15.721 1.621.539.3.719 1.02.419 1.56-.299.421-1.02.599-1.559.3z\\\"></path></svg>\",\n \"linkedin\": \"<svg stroke=\\\"currentColor\\\" fill=\\\"currentColor\\\" stroke-width=\\\"0\\\" viewBox=\\\"0 0 448 512\\\" color=\\\"#fff\\\" style=\\\"color:#fff\\\" height=\\\"1em\\\" width=\\\"1em\\\"><path d=\\\"M416 32H31.9C14.3 32 0 46.5 0 64.3v383.4C0 465.5 14.3 480 31.9 480H416c17.6 0 32-14.5 32-32.3V64.3c0-17.8-14.4-32.3-32-32.3zM135.4 416H69V202.2h66.5V416zm-33.2-243c-21.3 0-38.5-17.3-38.5-38.5S80.9 96 102.2 96c21.2 0 38.5 17.3 38.5 38.5 0 21.3-17.2 38.5-38.5 38.5zm282.1 243h-66.4V312c0-24.8-.5-56.7-34.5-56.7-34.6 0-39.9 27-39.9 54.9V416h-66.4V202.2h63.7v29.2h.9c8.9-16.8 30.6-34.5 62.9-34.5 67.2 0 79.7 44.3 79.7 101.9V416z\\\"></path></svg>\",\n \"openai\": \"<svg stroke=\\\"currentColor\\\" fill=\\\"currentColor\\\" stroke-width=\\\"0\\\" role=\\\"img\\\" viewBox=\\\"0 0 24 24\\\" color=\\\"#fff\\\" style=\\\"color:#fff\\\" height=\\\"1em\\\" width=\\\"1em\\\"><path d=\\\"M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z\\\"></path></svg>\"\n};\n","/** Only identifiers and explicit per-source states may leave an error receipt. */\nexport const OPERATION_RECONCILIATION_UI = String.raw`\n function reconciliationOf(data,tool,args,applied=false) {\n const details=object(data?.details)?data.details:null;\n if(!details) return null;\n const result={},validId=value=>typeof value==='string' && /^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,199}$/.test(value);\n const reported=arr(details.resource_ids || details.resourceIds).filter(validId),ids=[...new Set(reported)];\n if(ids.length) result.resource_ids=ids.slice(0,100);\n if(ids.length>100) {result.resource_ids_truncated=true;result.total_resource_ids=ids.length;}\n if(tool==='x_create_repost_promotions') {\n const postId=value=>typeof value==='string' && /^[1-9][0-9]{0,24}$/.test(value),associationId=value=>typeof value==='string' && /^[a-z0-9]{1,32}$/.test(value),selected=new Set(arr(args?.tweet_ids).filter(postId));\n const sourceIds=value=>[...new Set(arr(value).filter(id=>postId(id) && selected.has(id)))].slice(0,50);\n const ambiguous=sourceIds(details.ambiguous_source_ids),ambiguousSet=new Set(ambiguous),confirmed=[],seen=new Set();\n for(const row of arr(applied?details.source_copy_mappings:details.confirmed_source_copy_mappings)) {\n if(!object(row) || !selected.has(row.source_tweet_id) || ambiguousSet.has(row.source_tweet_id) || !postId(row.copied_tweet_id) || selected.has(row.copied_tweet_id) || !associationId(row.promoted_tweet_id) || seen.has(row.source_tweet_id)) continue;\n seen.add(row.source_tweet_id);confirmed.push({source_tweet_id:row.source_tweet_id,copied_tweet_id:row.copied_tweet_id,promoted_tweet_id:row.promoted_tweet_id});\n if(confirmed.length===50) break;\n }\n if(confirmed.length) result[applied?'source_copy_mappings':'confirmed_source_copy_mappings']=confirmed;\n if(ambiguous.length) result.ambiguous_source_ids=ambiguous;\n const observed=[...new Set(arr(details.reported_tweet_ids).filter(postId))].slice(0,100),unattempted=sourceIds(details.unattempted_source_ids),outcomes=arr(details.source_outcomes).filter(row=>object(row) && selected.has(row.source_tweet_id) && ['UNCONFIRMED','NOT_STARTED'].includes(row.state)).slice(0,50).map(row=>({source_tweet_id:row.source_tweet_id,state:row.state}));\n if(observed.length) result.reported_tweet_ids=observed;\n if(unattempted.length) result.unattempted_source_ids=unattempted;\n if(outcomes.length) result.source_outcomes=outcomes;\n const next=details.next_arguments;\n if(applied && details.next_tool==='x_promoted_posts' && object(next) && next.account_id===args?.account_id && next.line_item_id===args?.line_item_id && postId(next.user_id) && next.user_id!==args?.user_id) result.next_arguments={...(typeof args.project_id==='string'?{project_id:args.project_id}:{}),account_id:args.account_id,line_item_id:args.line_item_id,user_id:next.user_id};\n }\n return Object.keys(result).length?result:null;\n }\n`;\n","import { OPERATION_RECONCILIATION_UI } from './operation-reconciliation-ui.js';\n\n/** Runs inside the shared, offline iframe closure. */\nexport const OPERATION_UI_SCRIPT = String.raw`\n const attempts = new Map(), pendingRequests = new Map();\n let cancelHold = () => {}, expiryTimer;\n const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);\n ${OPERATION_RECONCILIATION_UI}\n const human = value => String(value).replace(/([a-z])([A-Z])/g,'$1 $2').replace(/[_.]/g,' ').replace(/^./,c=>c.toUpperCase());\n function resultData(result) {\n if (result?.structuredContent && typeof result.structuredContent === 'object') return result.structuredContent;\n for (const item of arr(result?.content)) {\n if (item.type === 'text') { try { const value=JSON.parse(item.text),data=object(value)?value:{value};return result._meta?.adport?{...data,_adport:result._meta.adport}:data; } catch {} }\n }\n return Array.isArray(result)?{value:result}:result || {};\n }\n function dataFields(value, prefix='', depth=0) {\n if (!object(value) || depth>8) return [];\n return Object.entries(value).filter(([key])=>!['_adport','data_source','pending_operation_id'].includes(key)).flatMap(([key,item])=>{\n const path=prefix?prefix+'.'+key:key;\n return object(item)?dataFields(item,path,depth+1):[{label:human(path),after:item}];\n });\n }\n function valueHTML(value,compact=false) {\n if (value===null || value===undefined) return '<span class=\"unavailable\">Not set</span>';\n if (Array.isArray(value)) return value.length?'<ul class=\"review-list\">'+value.slice(0,compact?3:undefined).map(item=>'<li>'+(object(item)?fieldsHTML(dataFields(item),compact):valueHTML(item,compact))+'</li>').join('')+'</ul>'+(compact && value.length>3?'<span class=\"operation-note\">'+(value.length-3)+' more in Details</span>':''):'<span class=\"unavailable\">None</span>';\n if (object(value)) return fieldsHTML(dataFields(value),compact);\n const text=typeof value==='boolean'?(value?'Yes':'No'):String(value);\n return esc(compact && text.length>400?text.slice(0,400)+'… (full value in Details)':text);\n }\n function fieldsHTML(fields,compact=false) {\n return '<dl class=\"review-fields\">'+fields.map(field=>{\n const currency=currencyOf(field), isMoney=field.format==='money';\n const format=value=>isMoney && available(value)?esc(money(value/1e6,currency,6)):valueHTML(value,compact);\n const hasBefore=Object.hasOwn(field,'before') && field.before!==undefined;\n const changed=hasBefore && JSON.stringify(field.before)!==JSON.stringify(field.after);\n let value;\n if (changed && Array.isArray(field.before) && Array.isArray(field.after)) {\n const key=value=>JSON.stringify(value), before=new Set(field.before.map(key)),after=new Set(field.after.map(key));\n value=field.after.filter(v=>!before.has(key(v))).map(v=>'<span class=\"review-added\">+ '+valueHTML(v)+'</span>').concat(field.before.filter(v=>!after.has(key(v))).map(v=>'<span class=\"review-removed\">− '+valueHTML(v)+'</span>')).join(' ');\n if (!value) value=valueHTML(field.after);\n } else value=(changed?'<span class=\"review-before\">'+format(field.before)+'</span><span class=\"review-arrow\" aria-label=\"to\">→</span>':'')+'<span class=\"review-after\">'+format(field.after)+'</span>';\n return '<div class=\"review-field\"><dt>'+esc(field.label)+(isMoney?' · '+esc(currency || 'account units'):'')+'</dt><dd'+(field.format==='text'?' class=\"review-copy\"':isMoney?' class=\"review-money\"':'')+'>'+value+'</dd></div>';\n }).join('')+'</dl>';\n }\n function legacyFields(preview) {\n const fields=arr(preview.budgetDeltas).map(v=>({label:v.target || 'Budget',format:'money',currency:v.currency,...(available(v.fromMicros)?{before:v.fromMicros}:{}),after:v.toMicros}));\n const explicit=arr(preview.fieldChanges);\n if(explicit.length && explicit.every(field=>object(field) && typeof field.field==='string' && typeof field.before==='string' && typeof field.after==='string')) return [...fields,...explicit.map(field=>({label:field.field,before:field.before,after:field.after}))];\n for (const change of arr(preview.changes)) {\n const text=String(change);\n if (/^!/.test(text)) continue;\n if (fields.length && /budget|amount_micros/i.test(text)) continue;\n const match=text.match(/^~\\s+.*?\\b(status|configured_status|bidding_strategy|delivery|bid|name|DailyBudget|value)\\s*:?\\s*(.*?)\\s*→\\s*(.+)$/i);\n if (match) { fields.push({label:human(match[1]),...(match[2].trim()?{before:match[2].trim()}:{}),after:match[3].trim()});continue; }\n const start=text.indexOf('{'),end=text.lastIndexOf('}');\n if (start>=0 && end>start) { try { fields.push(...dataFields(JSON.parse(text.slice(start,end+1))));continue; } catch {} }\n fields.push({label:/^-/.test(text)?'Remove':/^\\+/.test(text)?'Create':'Change',after:text.replace(/^[+~!-]\\s*/, '')});\n }\n return fields;\n }\n function operationOf(data,meta) { return meta?.tool==='recommendation_apply' && object(data.result)?data.result:data; }\n const pendingOf=result=>{const data=resultData(result);return operationOf(data,data._adport).pending_operation_id;};\n function operationHeader(title,subject,provider) {\n return '<div class=\"operation-heading\">'+(provider?logo(provider):'')+'<div><h2>'+esc(title)+'</h2>'+(subject?'<p>'+esc(subject)+'</p>':'')+'</div></div>';\n }\n function samePreviewArguments(left,right) {\n const stable=value=>Array.isArray(value)?value.map(stable):object(value)?Object.fromEntries(Object.keys(value).sort().map(key=>[key,stable(value[key])])):value;\n return JSON.stringify(stable(left))===JSON.stringify(stable(right));\n }\n function connectionRecovery(data,args,meta) {\n const recovery=data.details?.connection_recovery,project=args.project_id || meta.context?.project_id;\n if(data.error!=='NOT_CONNECTED' || data.details?.apply_state!=='NOT_STARTED' || !object(recovery)\n || !['account_selection','connection_changed','reconnect'].includes(recovery.kind)\n || typeof project!=='string' || recovery.project_id!==project\n || recovery.dashboard_url!=='https://app.adport.dev/dashboard/analytics') return null;\n return {kind:recovery.kind,project_id:project,dashboard_url:recovery.dashboard_url};\n }\n async function refreshConnectionPreview(tool,args,pending) {\n const attempt=attempts.get(pending);\n if(!attempt?.recovery || attempt.refreshing || pendingOf(state.result)!==pending) return;\n const previewArgs={...args};delete previewArgs.pending_operation_id;\n attempt.refreshing=true;render(state.result);\n try {\n const result=await callTool(tool,previewArgs),value=resultData(result),meta=value._adport;\n if(result?.isError || value.error) throw new Error(value.message || 'The connection is not ready. Finish account selection before refreshing again.');\n if(value.applied!==false || value.status!=='pending_validation' || typeof value.pending_operation_id!=='string'\n || value.pending_operation_id===pending || meta?.tool!==tool || meta.context?.project_id!==attempt.recovery.project_id\n || !samePreviewArguments(meta.approval?.arguments,previewArgs)) throw new Error('The fresh preview could not be matched to this operation. Ask your assistant for a new preview.');\n if(pendingOf(state.result)===pending) acceptResult(result,true);\n } catch(error) {\n attempt.message=error?.message || 'The preview could not be refreshed. No apply was requested.';\n } finally {\n attempt.refreshing=false;\n if(pendingOf(state.result)===pending) render(state.result);\n }\n }\n function renderOperation(raw,meta) {\n clearTimeout(expiryTimer);\n let data=operationOf(raw,meta), pending=data.pending_operation_id;\n const originalPreview=data.preview || {};\n const attempt=attempts.get(pending);\n if (attempt?.data) data=operationOf(attempt.data,attempt.data._adport || meta);\n const preview={...originalPreview,...data.preview},review=preview.review || {},fields=Array.isArray(review.fields)?review.fields.filter(field=>object(field) && typeof field.label==='string' && Object.hasOwn(field,'after') && field.after!==undefined):legacyFields(preview);\n const provider=providerSvg[review.provider]?review.provider:meta.provider || (providerSvg[String(meta.tool).split('_')[0]]?String(meta.tool).split('_')[0]:null);\n let title=review.title || human(String(meta.tool || 'Review change').replace(/^[a-z]+_/,'').replaceAll('_',' '));\n if (review.kind==='remove' && /permanent/i.test(preview.summary || '') && !/permanent/i.test(title)) title+=' permanently';\n const subject=[review.subject || String(preview.summary || '').match(/\"([^\"]+)\"/)?.[1],review.accountId || meta.accountId].filter(Boolean).join(' · ');\n const applied=data.applied===true && data.status==='applied';\n const accepted=applied && data.result?.details?.status==='ACCEPTED_FOR_PROCESSING' && data.result?.details?.processed===false;\n const warnings=applied?arr(data.result?.warnings).filter(value=>typeof value==='string'):[];\n const partial=['partial','partially_applied'].includes(data.status);\n const expires=Date.parse(data.expires_at), expired=Number.isFinite(expires) && expires<=Date.now();\n const approval=meta.approval, bound=typeof pending==='string' && pending.length>0 && object(approval?.arguments) && typeof meta.tool==='string';\n const concrete=Array.isArray(review.fields) || arr(preview.fieldChanges).length || arr(preview.budgetDeltas).length || arr(preview.changes).some(change=>/^[+~-]\\s/.test(String(change)) || /\\{.+\\}/.test(String(change)));\n const complete=typeof preview.summary==='string' && preview.summary.trim() && fields.length>0 && concrete;\n const canApprove=!applied && !partial && !attempt && !expired && Number.isFinite(expires) && bound && complete && data.status==='pending_validation' && data.applied===false && meta.capabilities?.can_write!==false;\n let phase=accepted?'Processing pending':applied?(warnings.length?'Applied with warnings':'Applied'):partial?'Partially applied':attempt?.phase==='applying'?'Applying…':attempt?.phase==='expired' || expired?'Expired':attempt?.phase==='blocked'?'Blocked':attempt?'Unconfirmed':canApprove?'':pending?'Review required':'Result';\n const action=canApprove?'<button class=\"approve\" data-approve=\"true\" aria-label=\"Hold for 0.9 seconds to apply; release to cancel\"><span>Hold to apply</span></button>':phase==='Applying…'?'<button class=\"approve\" disabled><span>Applying…</span></button>':'<span class=\"operation-status\" role=\"status\">'+esc(phase)+'</span>';\n const validation=preview.serverValidated===true?'Provider validated':preview.serverValidated===false?'Local preview; provider validation runs on apply':'Validation not reported';\n const details='<details><summary>Details</summary><div class=\"operation-details\"><p>'+esc(validation)+'</p>'+(!applied && data.expires_at?'<p>Expires '+esc(data.expires_at)+'</p>':'')+'<p>'+esc(preview.summary || 'No change details returned.')+'</p>'+fieldsHTML(fields)+arr(preview.changes).map(v=>'<p>'+esc(v)+'</p>').join('')+(data.result?'<pre>'+esc(JSON.stringify(data.result,null,2))+'</pre>':'')+(attempt?.reconciliation?'<p>Reconciliation</p><pre>'+esc(JSON.stringify(attempt.reconciliation,null,2))+'</pre>':'')+'<p>'+esc(meta.tool || '')+'</p></div></details>';\n const notes=[...arr(review.notices),...arr(preview.notes),...arr(preview.changes).filter(v=>/^!/.test(String(v))).map(v=>String(v).replace(/^!\\s*/,'')),...arr(preview.coercions),...warnings];\n const message=attempt?.message || (accepted?'Accepted for processing. Processing is not confirmed.':expired?'Request a fresh preview before applying.':partial?'Check each result before retrying.':pending && !canApprove && !applied && !attempt?'Review the tool response in chat before applying.':review.kind==='update' && fields.length && fields.every(field=>!Object.hasOwn(field,'before'))?'Previous values unavailable':'');\n const recovery=attempt?.recovery?'<p class=\"operation-note\"><a href=\"'+esc(attempt.recovery.dashboard_url)+'\" target=\"_blank\" rel=\"noopener noreferrer\">Open analytics connections ↗</a></p><p class=\"operation-note\">After finishing account selection, refresh this preview. Refreshing never applies or publishes.</p><button data-refresh-preview=\"true\" '+(attempt.refreshing?'disabled':'')+'>'+(attempt.refreshing?'Refreshing preview…':'Refresh preview')+'</button>':'';\n const body=operationHeader(title,subject,provider)+(fields.length?fieldsHTML(fields.slice(0,6),true):'<p class=\"operation-note\">No change details were returned.</p>')+(fields.length>6?'<p class=\"operation-note\">'+(fields.length-6)+' more changes in Details</p>':'')+[...new Set(notes)].map(v=>'<p class=\"adjustment\"'+(warnings.includes(v)?' role=\"alert\"':'')+'>'+esc(v)+'</p>').join('')+receiptMarkup(data,false)+(message?'<p class=\"operation-note\" role=\"status\">'+esc(message)+'</p>':'')+recovery+'<div class=\"operation-footer\">'+details+'<div class=\"operation-action\">'+action+'</div></div>';\n app.innerHTML=chrome(body,'');\n app.querySelectorAll('[data-refresh-preview]').forEach(button=>button.addEventListener('click',()=>refreshConnectionPreview(meta.tool,approval.arguments,pending)));\n if (canApprove) {\n const source=state.result;\n app.querySelectorAll('[data-approve]').forEach(button=>{cancelHold=bindHold(button,()=>{if(state.result===source) approve(meta.tool,approval.arguments,pending,expires);});});\n const updateExpiry=()=>{if(state.result===source && !attempts.has(pending)) {if(Date.now()>=expires) render(state.result);else expiryTimer=setTimeout(updateExpiry,Math.min(expires-Date.now()+5,2147483647));}};\n expiryTimer=setTimeout(updateExpiry,Math.min(expires-Date.now()+5,2147483647));\n }\n }\n function bindHold(button,complete) {\n let timer=null,interacted=false;\n const cancel=()=>{clearTimeout(timer);timer=null;button.classList.remove('holding');};\n const begin=event=>{\n if(button.disabled || timer!==null) return;\n if(event.type==='keydown') {if(![' ','Enter'].includes(event.key) || event.repeat) return;event.preventDefault();}\n else {if(event.button!==0) return;button.setPointerCapture?.(event.pointerId);}\n interacted=true;button.classList.add('holding');timer=setTimeout(()=>{cancel();complete();},900);\n };\n button.addEventListener('pointerdown',begin);\n button.addEventListener('keydown',event=>{if(event.key==='Escape') cancel();else begin(event);});\n button.addEventListener('pointermove',event=>{if(timer!==null && button.getBoundingClientRect) {const rect=button.getBoundingClientRect();if(event.clientX<rect.left || event.clientX>rect.right || event.clientY<rect.top || event.clientY>rect.bottom) cancel();}});\n ['pointerup','pointerleave','pointercancel','lostpointercapture','blur'].forEach(name=>button.addEventListener(name,cancel));\n button.addEventListener('keyup',event=>{if([' ','Enter','Escape'].includes(event.key)) cancel();});\n button.addEventListener('contextmenu',event=>event.preventDefault());\n // Assistive-technology activation has no physical press/release sequence.\n button.addEventListener('click',event=>{if(event.detail===0 && !interacted && !button.disabled) complete();});\n return cancel;\n }\n function errorPhase(data) {\n const code=data.code || data.error;\n if (['PENDING_EXPIRED','PENDING_NOT_FOUND','PENDING_MISMATCH'].includes(code)) return 'expired';\n if (['POLICY_VIOLATION','PLAN_LIMIT','NOT_CONNECTED','INVALID_INPUT'].includes(code)) return 'blocked';\n return 'unconfirmed';\n }\n function callHostTool(tool,args) {\n return callTool(tool,args).catch(error=>{throw new Error((error?.message || 'No confirmation arrived.')+' The write may have succeeded; check its status before retrying.');});\n }\n async function approve(tool,args,pending,expires) {\n if(attempts.has(pending) || pendingOf(state.result)!==pending) return;\n if(Date.now()>=expires) {render(state.result);return;}\n const original=resultData(state.result),originalOperation=operationOf(original,original._adport);\n attempts.set(pending,{phase:'applying'});render(state.result);\n try {\n const result=await callHostTool(tool,{...args,pending_operation_id:pending}),value=resultData(result),outcome=operationOf(value,{tool});\n if(!result || result.isError || value.error) {\n const phase=errorPhase(value),message=value.message || 'Adport could not confirm the change.';\n const recovery=connectionRecovery(value,args,original._adport);\n attempts.set(pending,{phase,message:phase==='unconfirmed' && !/before retrying/i.test(message)?message+' Check its status before retrying.':message,reconciliation:reconciliationOf(value,tool,args),...(recovery?{recovery}:{})});\n }\n else if(outcome.applied===true && outcome.status==='applied') {\n const preview={...originalOperation.preview,...outcome.preview};\n const data=tool==='recommendation_apply'?{...value,result:{...outcome,preview}}:{...value,preview};\n attempts.set(pending,{phase:'applied',data});\n }\n else if(['partial','partially_applied'].includes(outcome.status)) attempts.set(pending,{phase:'partial',data:value});\n else attempts.set(pending,{phase:'unconfirmed',message:'The change was not confirmed as applied. Check its status before retrying.'});\n } catch(error) {attempts.set(pending,{phase:'unconfirmed',message:error?.message || 'The change could not be confirmed. Check its status before retrying.'});}\n // A late response belongs to its original review, never a newer preview.\n const attempt=attempts.get(pending),outcome=attempt.data?operationOf(attempt.data,{tool}):null;\n if(pendingOf(state.result)===pending) {\n if(attempt.data) acceptResult({structuredContent:{...attempt.data,_adport:{...original._adport,...attempt.data._adport,approval:undefined}}},true);\n else render(state.result);\n }\n const details=outcome?.result?.details,resources=arr(outcome?.result?.resourceIds).filter(value=>typeof value==='string'),warnings=arr(outcome?.result?.warnings).filter(value=>typeof value==='string');\n const reportedCounts=receiptInfo(outcome||{}).counts;\n const reconciliation=attempt.reconciliation || (tool==='x_create_repost_promotions' && outcome?.applied===true && outcome.status==='applied'?reconciliationOf(outcome.result,tool,args,true):null);\n const facts={tool,status:attempt.phase,...(reportedCounts.length?{counts:Object.fromEntries(reportedCounts.map(item=>[item.label.toLowerCase(),item.value]))}:{}),...(typeof args.project_id==='string'?{project_id:args.project_id}:{}),...(typeof args.account_id==='string'?{account_id:args.account_id}:{}),...(outcome?{resource_ids:resources.slice(0,100),...(resources.length>100?{resource_ids_truncated:true,total_resource_ids:resources.length}:{}),...(details?.status==='ACCEPTED_FOR_PROCESSING' && details?.processed===false?{processing_status:'ACCEPTED_FOR_PROCESSING',processed:false}:{}),...(warnings.length?{warnings:warnings.slice(0,20)}:{}),...(typeof details?.next_tool==='string'?{next_tool:details.next_tool}:{}),...(typeof details?.resource_receipt==='string'?{resource_receipt:details.resource_receipt}:{})}:{message:attempt.message}),...(reconciliation?{reconciliation,...(reconciliation.resource_ids?{resource_ids:reconciliation.resource_ids}:{}),...(reconciliation.resource_ids_truncated?{resource_ids_truncated:true,total_resource_ids:reconciliation.total_resource_ids}:{})}:{})};\n if(typeof window.openai?.setWidgetState==='function') Promise.resolve().then(()=>window.openai.setWidgetState({lastOperation:facts})).catch(()=>{});\n else send({jsonrpc:'2.0',id:id++,method:'ui/update-model-context',params:{structuredContent:{adport_operation:facts}}});\n }\n function renderFailure(data,meta,isWrite) {\n const phase=errorPhase(data),title=phase==='expired'?'Preview expired':phase==='blocked'?'Action blocked':isWrite?'Outcome unconfirmed':'Request failed';\n app.innerHTML=chrome(operationHeader(title,meta.accountId,meta.provider)+'<p class=\"operation-note\" role=\"alert\">'+esc(data.message || (isWrite?'Check the result before retrying.':'See the tool response for details.'))+'</p>'+(!['expired','blocked'].includes(phase) && isWrite?'<p class=\"operation-note\">Check the current state before retrying.</p>':'')+'<details><summary>Details</summary><pre>'+esc(JSON.stringify(data,null,2))+'</pre></details>','');\n }\n`;\n","/** Native Apple report rows retain totals, time buckets and metadata separately. */\nexport const APPLE_REPORT_UI_STYLES = String.raw`\n .apple-report-metrics { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:10px; margin-top:9px }\n .apple-report-metrics dt { display:block; margin:0 0 3px; font-size:10px }\n .apple-report-metrics dd { font-size:12px; font-variant-numeric:tabular-nums }\n .apple-report-total { padding:12px 0 0 }\n .apple-report-total > strong { font-size:11px }\n .apple-report-dimensions { margin:4px 0 0; color:var(--muted); font-size:10px; overflow-wrap:anywhere }\n .apple-report-periods { margin:10px 0 0; padding-top:8px }\n .apple-report-periods summary { font-size:10px }\n .apple-report-period { margin-top:10px }\n .apple-report-period > strong { font-size:10px; font-weight:500 }\n .apple-report-page { margin:10px 0 0; color:var(--muted); font-size:10px }\n`;\n\nexport const APPLE_REPORT_UI_SCRIPT = String.raw`\n function appleReportNumber(value) {\n if(typeof value==='string' && !/^(?:\\d+(?:\\.\\d*)?|\\.\\d+)$/.test(value))return null;\n return (typeof value==='number'||typeof value==='string') && Number.isFinite(Number(value)) && Number(value)>=0?Number(value):null;\n }\n function appleReportMoney(value) {\n const amount=object(value)?appleReportNumber(value.amount):null;\n if(amount===null)return '—';\n const currency=currencyOf(value);\n return currency?money(amount,currency):money(amount,null)+' (currency unavailable)';\n }\n function appleReportMetrics(value) {\n const metrics=object(value)?value:{},taps=appleReportNumber(metrics.taps),installs=appleReportNumber(metrics.totalInstalls);\n // Apple's zero CPI for zero installs is undefined, not a free acquisition.\n const fields=[['Spend',appleReportMoney(metrics.localSpend)],['Taps',taps===null?'—':taps.toLocaleString(state.host.locale||'en')],['Installs',installs===null?'—':installs.toLocaleString(state.host.locale||'en')],['CPI',installs===0?'—':appleReportMoney(metrics.totalAvgCPI)]];\n return '<dl class=\"record-fields apple-report-metrics\">'+fields.map(([label,value])=>'<div><dt>'+esc(label)+'</dt><dd>'+esc(value)+'</dd></div>').join('')+'</dl>';\n }\n function appleReportRow(row,index) {\n const metadata=object(row?.metadata)?row.metadata:{},keyword=object(metadata.keyword)?metadata.keyword:{};\n const name=[metadata.searchTermText,metadata.text,metadata.name,keyword.text].find(value=>typeof value==='string'&&value.trim()) ?? (metadata.id!==undefined?String(metadata.id):'Unnamed result '+(index+1));\n const status=[metadata.displayStatus,metadata.systemStatus,metadata.status].find(value=>typeof value==='string'&&value);\n const dimensions=['countryOrRegion','countryCode','adminArea','locality','deviceClass','ageRange','gender'].flatMap(key=>typeof metadata[key]==='string'&&metadata[key]?[metadata[key]]:[]);\n const matchType=metadata.matchType||keyword.matchType;\n if(typeof matchType==='string')dimensions.push(human(matchType.toLowerCase()));\n const periods=arr(row?.granularMetrics),hasTotals=object(row?.totalMetrics);\n const breakdown=periods.length?'<details class=\"apple-report-periods\"'+(!hasTotals?' open':'')+'><summary>'+periods.length+' reported period'+(periods.length===1?'':'s')+'</summary>'+periods.slice(0,100).map(period=>'<div class=\"apple-report-period\"><strong>'+esc(typeof period?.date==='string'?period.date:'Date unavailable')+'</strong>'+appleReportMetrics(period)+'</div>').join('')+(periods.length>100?'<p class=\"operation-note\">Showing 100 periods. All returned periods are in Details.</p>':'')+'</details>':'';\n return '<article class=\"record-row\"><div class=\"record-heading\"><strong>'+esc(name)+'</strong>'+(status?'<span>'+esc(human(status.toLowerCase()))+'</span>':'')+'</div>'+(dimensions.length?'<p class=\"apple-report-dimensions\">'+dimensions.map(esc).join(' · ')+'</p>':'')+(hasTotals||!periods.length?appleReportMetrics(row?.totalMetrics):'')+breakdown+'</article>';\n }\n function appleChartRecord(row,index,metrics=row?.totalMetrics) {\n const metadata=object(row?.metadata)?row.metadata:{},keyword=object(metadata.keyword)?metadata.keyword:{};\n const name=[metadata.searchTermText,metadata.text,metadata.name,keyword.text].find(value=>typeof value==='string'&&value.trim())??String(metadata.id??'Unnamed result '+(index+1));\n const context=['countryOrRegion','countryCode','deviceClass','ageRange','gender'].flatMap(key=>typeof metadata[key]==='string'?[metadata[key]]:[]);\n const fields=[['spend','Spend',metrics?.localSpend?.amount,appleReportMoney(metrics?.localSpend),currencyOf(metrics?.localSpend||{})||'Account units'],['taps','Taps',metrics?.taps,appleReportNumber(metrics?.taps)===null?'—':String(metrics.taps),''],['installs','Installs',metrics?.totalInstalls,appleReportNumber(metrics?.totalInstalls)===null?'—':String(metrics.totalInstalls),'']].map(([key,label,raw,display,unit])=>({key,label,value:appleReportNumber(raw),display,unit}));\n for(const [key,raw] of Object.entries(metrics||{}))if(!['localSpend','taps','totalInstalls','date'].includes(key)) {\n const monetary=object(raw),value=key==='totalAvgCPI'&&metrics.totalInstalls===0?null:appleReportNumber(monetary?raw.amount:raw);\n fields.push({key,label:key==='totalAvgCPI'?'CPI':human(key),value,display:value===null?'—':monetary?appleReportMoney(raw):String(raw),unit:monetary?currencyOf(raw)||'Account units':''});\n }\n return {name,context:typeof metrics?.date==='string'&&!reportDate(metrics.date)?[...context,metrics.date]:context,series:[name,...context].join(' · '),date:reportDate(metrics?.date),fields};\n }\n function appleReportOverview(metrics) {\n if(!object(metrics))return '';\n const taps=appleReportNumber(metrics.taps),installs=appleReportNumber(metrics.totalInstalls);\n return '<div class=\"report-overview apple-report-total\" aria-label=\"Report total\"><div><small>Total spend</small><strong>'+esc(appleReportMoney(metrics.localSpend))+'</strong></div><dl><div><dt>Taps</dt><dd>'+esc(taps??'—')+'</dd></div><div><dt>Installs</dt><dd>'+esc(installs??'—')+'</dd></div>'+(installs>0&&object(metrics.totalAvgCPI)?'<div><dt>CPI</dt><dd>'+esc(appleReportMoney(metrics.totalAvgCPI))+'</dd></div>':'')+'</dl></div>';\n }\n function renderAppleReport(data,meta) {\n const payload=recordPayload(data),hasRows=object(payload)&&Array.isArray(payload.rows),rows=hasRows?payload.rows:[];\n const content=hasRows?(rows.length?rows.slice(0,1000).map(appleReportRow).join(''):'<p class=\"operation-note\">No report rows returned.</p>'):'<p class=\"operation-note\">Report rows unavailable. The response is in Details.</p>';\n const grandTotal=payload?.summary?.grandTotal;\n // Use Apple's explicit total, which can cover more rows than this page.\n // Never sum breakdowns, average CPIs, or mix currencies in the widget.\n const summary=rows.length?appleReportOverview(grandTotal):'';\n const pagination=data.pagination,offset=pagination?.offset,count=pagination?.totalCount;\n const page=rows.length&&Number.isSafeInteger(offset)&&offset>=0&&Number.isSafeInteger(count)&&count>=offset+rows.length&&(offset>0||count>rows.length)?'<p class=\"apple-report-page\">Showing '+(offset+1)+'–'+(offset+Math.min(rows.length,1000))+' of '+count+' results</p>':'';\n const clean={...data};delete clean._adport;\n const shown=rows.slice(0,1000),periods=shown.flatMap((row,index)=>arr(row?.granularMetrics).map(metrics=>appleChartRecord(row,index,metrics)));\n const dimension=rows.some(row=>row.metadata?.searchTermText)?'search term':rows.some(row=>row.metadata?.text)?'keyword':rows.some(row=>row.metadata?.dailyBudget&&!row.metadata?.campaignId)?'campaign':'result';\n const chart=reportCharts(shown.map((row,index)=>appleChartRecord(row,index)),{dimension,periods});\n app.innerHTML=chrome(operationHeader('Performance','', 'apple')+notices(data)+'<section data-apple-report>'+summary+(rows.length?chart.html:content)+page+(rows.length>1000?'<p class=\"operation-note\">Showing 1,000 returned rows. The full response is in Details.</p>':'')+'<details class=\"report-data\"><summary>Details</summary>'+(rows.length?'<div class=\"record-list\" role=\"region\" aria-label=\"Apple performance data\" tabindex=\"0\">'+content+'</div>':'')+'<pre>'+esc(JSON.stringify(clean,null,2))+'</pre></details></section>','');\n chart.mount();\n }\n`;\n","export const NATIVE_REPORT_TOOLS = [\n 'ga4_report', 'ga4_realtime_report', 'gsc_search_analytics',\n 'google_gaql',\n 'linkedin_demographic_report',\n 'meta_insights', 'tiktok_report', 'reddit_report', 'spotify_insight_report',\n 'microsoft_keyword_report', 'microsoft_search_term_report',\n 'microsoft_offline_conversion_reports', 'microsoft_offline_conversion_goal_report',\n 'apple_impression_share', 'apple_search_term_popularity',\n] as const;\n\nexport const NATIVE_REPORT_UI_STYLES = String.raw`\n .native-report-metrics { grid-template-columns:repeat(auto-fit,minmax(min(110px,100%),1fr)) }\n`;\n\n/** Each native read retains its own metrics, attribution and units. */\nexport const NATIVE_REPORT_UI_SCRIPT = String.raw`\n const nativeReportTools=new Set(${JSON.stringify(NATIVE_REPORT_TOOLS)});\n function nativeReportDecimal(value,scale=0) {\n const text=typeof value==='number'&&Number.isFinite(value)?String(value):typeof value==='string'?value:'';\n if(!/^-?\\d+(?:\\.\\d+)?$/.test(text))return null;\n if(!scale)return text;\n const negative=text.startsWith('-'),[whole,fraction='']=text.replace(/^-/,'').split('.'),digits=whole+fraction,point=whole.length-scale;\n const result=(point>0?digits.slice(0,point)+'.'+digits.slice(point):'0.'+'0'.repeat(-point)+digits).replace(/^0+(?=\\d)/,'').replace(/\\.?0+$/,'');\n return (negative?'-':'')+(result||'0');\n }\n function nativeReportLabel(key) {\n const known={spend:'Spend',costMicros:'Spend',conversionsValue:'Conversion value',impressions:'Impressions',clicks:'Clicks',conversion:'Conversions',conversions:'Conversions',purchases:'Purchases',cpc:'CPC',cpm:'CPM',ctr:'CTR',roas:'ROAS',total_complete_payment_rate:'Purchase value',complete_payment_roas:'Purchase ROAS',lowImpressionShare:'Impression share · lower bound',highImpressionShare:'Impression share · upper bound',searchPopularity1to5:'Popularity · 1–5',searchPopularity1to100:'Popularity · 1–100',searchPopularityInGenre:'Genre popularity · 1–100',rankInGenre:'Genre rank',OverallSuccessRate:'Success rate · ratio',OverallSuccessCount:'Succeeded',SuccessCount:'Succeeded',FailureCount:'Failed',OverallUnattributedCount:'Unattributed'};\n return known[key]||known[key.toLowerCase()]||human(human(key).toLowerCase());\n }\n function nativeReportRatio(key,provider) {return provider==='gsc'&&key==='ctr'||provider==='ga4'&&!key.includes(':')&&/Rate$/.test(key);}\n function nativeReportMetric(key,value,provider,currency,moneyFields=[]) {\n if(key==='costInUsd')currency='USD';\n const lower=key.toLowerCase(),decimal=nativeReportDecimal(value);\n if(value===null||value===undefined||value===''||value==='-'||value==='--')return '—';\n if(provider==='spotify'&&decimal==='-5')return 'Suppressed';\n if(nativeReportRatio(key,provider)&&decimal!==null)return new Intl.NumberFormat(state.host.locale||'en',{style:'percent',maximumFractionDigits:2}).format(Number(decimal));\n const moneyField=nativeReportMoneyField(key,provider,moneyFields);\n if(moneyField) {\n if(decimal===null)return '—';\n const scale=nativeReportScale(key,provider);\n const amount=nativeReportDecimal(value,scale);\n // Decimal shifting is exact even for provider counts/amounts beyond 2^53.\n return amount+' '+(currency||'account units');\n }\n return typeof value==='string'||typeof value==='number'||typeof value==='boolean'?String(value):'—';\n }\n function nativeReportMoneyField(key,provider,moneyFields=[]) {\n return moneyFields.includes(key)||/^(spend|revenue|cpc|cpm|cost_per_conversion|costInLocalCurrency|costInUsd|total_complete_payment_rate|conversion_.*_total_value)$|^(?:action_values|cost_per_action_type) · /i.test(key)||provider==='google'&&(/Micros$/.test(key)||/conversionsValue$/i.test(key));\n }\n function nativeReportScale(key,provider) { return provider==='reddit'?/total_value$/i.test(key)?2:6:provider==='google'&&/Micros$/.test(key)?6:0; }\n function reportBucket(value) {\n if(value==='LESS_THAN_ONE_DAY')return 'Under 1 day';\n const words={ONE:1,TWO:2,THREE:3,FOUR:4,FIVE:5,SIX:6,SEVEN:7,EIGHT:8,NINE:9,TEN:10,ELEVEN:11,TWELVE:12,THIRTEEN:13,FOURTEEN:14,TWENTY_ONE:21,THIRTY:30,FORTY_FIVE:45,SIXTY:60,NINETY:90};\n const match=typeof value==='string'&&value.match(/^(.+)_TO_(.+)_DAYS$/);\n return match&&words[match[1]]!==undefined&&words[match[2]]!==undefined?words[match[1]]+'–'+words[match[2]]+' days':human(String(value).toLowerCase());\n }\n function nativeReportRecord(row,index,meta,payload) {\n if(!object(row))return null;\n const provider=meta.tool.split('_')[0],dimensions=object(row.dimensions)?row.dimensions:provider==='google'&&object(row.segments)?row.segments:{},metrics=['tiktok','google','linkedin','ga4','gsc'].includes(provider)&&object(row.metrics)?row.metrics:row;\n const names=provider==='microsoft'?['SearchQuery','Keyword','ConversionName','UploadDate']:provider==='apple'?['searchTerm','appName']:['ad_name','adgroup_name','adset_name','campaign_name','account_name','advertiser_name','name','entity_name'];\n const ids=['ad_id','adgroup_id','adset_id','campaign_id','advertiser_id','account_id','entity_id','id','GoalId','urn'];\n const first=(keys,sources)=>keys.flatMap(key=>sources.map(source=>source[key])).find(value=>(typeof value==='string'&&value.trim())||typeof value==='number');\n const googleName=provider==='google'?[row.adGroupAd?.ad?.name,row.adGroup?.name,row.campaign?.name,row.customer?.descriptiveName,row.searchTermView?.searchTerm,row.adGroupCriterion?.keyword?.text].find(value=>typeof value==='string'&&value):null;\n const bucket=dimensions.conversionLagBucket??dimensions.conversionOrAdjustmentLagBucket;\n const analyticsName=['ga4','gsc'].includes(provider)?Object.values(dimensions).filter(value=>typeof value==='string'&&value).join(' · '):null;\n const name=bucket?reportBucket(bucket):googleName??analyticsName??first(names,[row,metrics,dimensions]) ?? first(ids,[row,dimensions]) ?? (provider==='google'?'Report':'Result '+(index+1));\n const status=first(['entity_status','status'],[row]);\n const dimensionKeys=['date','day','week','month','stat_time_day','stat_time_hour','country','countryOrRegion','countryCode','country_code','country_id','deviceClass','device_platform','age','gender','platform','placement','insight_value','genre','BidMatchType','match_type','date_start','date_stop','start_time','end_time'];\n const context=[...new Set([...dimensionKeys.flatMap(key=>[row[key],dimensions[key]]),...(provider==='google'?Object.entries(dimensions).filter(([key,value])=>!['conversionLagBucket','conversionOrAdjustmentLagBucket','date'].includes(key)&&typeof value==='string').map(([,value])=>human(value.toLowerCase())):[]),...(bucket&&googleName?[googleName]:[])].filter(value=>typeof value==='string'&&value))];\n const currency=[row.currency,row.account_currency,row.currency_code,row.customer?.currencyCode,metrics.currency,payload.currency,payload.metadata?.currencyCode,meta.currency].find(value=>typeof value==='string'&&/^[A-Z]{3}$/.test(value));\n const ignored=new Set([...names,...ids,...dimensionKeys,'currency','account_currency','currency_code','entity_type','status','entity_status','report_type','FileUrlExpiryTimeUtc','file_available','timezone']);\n let fields=provider==='spotify'?arr(row.stats).filter(stat=>typeof stat?.field_type==='string').map(stat=>[stat.field_type,stat.field_value]):Object.entries(metrics).filter(([key,value])=>!ignored.has(key)&&!/(?:_id$|Id$|hash|token|secret|url|password)/i.test(key)&&!object(value)&&!Array.isArray(value));\n if(meta.tool==='apple_impression_share'&&(Object.hasOwn(row,'lowImpressionShare')||Object.hasOwn(row,'highImpressionShare'))) {\n const bound=value=>typeof value==='number'&&Number.isFinite(value)&&value>=0&&value<=1?new Intl.NumberFormat(state.host.locale||'en',{style:'percent',maximumFractionDigits:2}).format(value):'—';\n const low=bound(row.lowImpressionShare),high=bound(row.highImpressionShare);\n fields=fields.filter(([key])=>!['lowImpressionShare','highImpressionShare'].includes(key));\n fields.unshift(['Impression share',low===high?low:low+'–'+high]);\n }\n if(provider==='meta')for(const key of ['actions','action_values','purchase_roas','cost_per_action_type'])for(const item of arr(row[key]))if(typeof item?.action_type==='string')fields.push([key+' · '+item.action_type,item.value]);\n if(provider==='linkedin'&&row.date_range?.start&&row.date_range?.end){const period=row.date_range.start+' – '+row.date_range.end;context.push(period);fields.push(['period',period]);}\n const priority=key=>/^(spend|impressions|clicks)$/i.test(key)?['spend','impressions','clicks'].indexOf(key.toLowerCase()):/^(conversion|conversions|purchases)$|^actions · purchase$/i.test(key)?3:4;\n fields.sort((a,b)=>priority(a[0])-priority(b[0]));\n const moneyFields=provider==='ga4'?arr(payload.metric_headers).filter(header=>header.type==='TYPE_CURRENCY').map(header=>header.name):[];\n return {name,status,context,currency,moneyFields,provider,fields,native:row,date:reportDate(dimensions.stat_time_day??(provider==='ga4'&&/^\\d{8}$/.test(dimensions.date||'')?dimensions.date.replace(/^(\\d{4})(\\d{2})(\\d{2})$/,'$1-$2-$3'):dimensions.date)??(row.date_start===row.date_stop?row.date_start:null)??(row.date_range?.start===row.date_range?.end?row.date_range?.start:null)),series:googleName||(['ga4','gsc'].includes(provider)?Object.entries(dimensions).filter(([key])=>key!=='date').map(([,value])=>value).join(' · ')||'Website':name)};\n }\n function nativeChartRecord(record) {\n if(!record)return {name:'Unavailable row',context:[],fields:[]};\n const fields=record.fields.map(([key,raw])=>{\n const monetary=nativeReportMoneyField(key,record.provider,record.moneyFields),scaled=nativeReportDecimal(raw,nativeReportScale(key,record.provider));\n const ratio=nativeReportRatio(key,record.provider);\n const value=record.provider==='spotify'&&String(raw)==='-5'?null:reportNumber(monetary?scaled:raw);\n const display=nativeReportMetric(key,raw,record.provider,record.currency,record.moneyFields);\n return {key,label:key==='costInLocalCurrency'?'Spend':key==='costInUsd'?'Spend · USD':nativeReportLabel(key),value:ratio&&value!==null?value*100:value,display,unit:ratio?'%':monetary?key==='costInUsd'?'USD':record.currency||'Account units':''};\n });\n const low=record.native.lowImpressionShare,high=record.native.highImpressionShare;\n const range=record.provider==='apple'&&[low,high].every(value=>typeof value==='number'&&Number.isFinite(value)&&value>=0&&value<=1)&&low<=high?[low,high]:undefined;\n if(range){const field=fields.find(field=>field.key==='Impression share');if(field){field.value=low;field.unit='%';}}\n return {...record,fields,range,series:[record.series,...record.context.filter(value=>!reportDate(value)&&!(/^\\d{8}$/.test(value)&&record.provider==='ga4')&&!/^\\d{4}-\\d{2}-\\d{2} – \\d{4}-\\d{2}-\\d{2}$/.test(value))].join(' · ')};\n }\n function nativeReportRow(row,index,meta,payload) {\n const record=nativeReportRecord(row,index,meta,payload);\n if(!record)return '<article class=\"record-row\"><p class=\"operation-note\">Report row unavailable.</p></article>';\n const {name,status,context,currency,provider,fields,moneyFields}=record;\n const shown=fields.slice(0,4),details=fields.length>4?'<p class=\"apple-report-dimensions\">'+(fields.length-4)+' more metric'+(fields.length===5?'':'s')+' in Details</p>':'';\n return '<article class=\"record-row\"><div class=\"record-heading\"><div class=\"record-name\"><strong>'+esc(name)+'</strong></div>'+(status?'<span>'+esc(status)+'</span>':'')+'</div>'+(context.length?'<p class=\"apple-report-dimensions\">'+context.map(esc).join(' · ')+'</p>':'')+(shown.length?'<dl class=\"record-fields apple-report-metrics native-report-metrics\">'+shown.map(([key,value])=>'<div><dt>'+esc(nativeReportLabel(key))+'</dt><dd>'+esc(nativeReportMetric(key,value,provider,currency,moneyFields))+'</dd></div>').join('')+'</dl>':'<p class=\"operation-note\">No metrics returned for this row.</p>')+details+'</article>';\n }\n function renderNativeReport(data,meta) {\n const payload=meta.tool==='linkedin_demographic_report'?data:recordPayload(data),rows=meta.tool==='reddit_report'?payload?.metrics:payload?.rows;\n const entries=Array.isArray(rows)?rows:[],provider=meta.tool.split('_')[0];\n const title=meta.tool.includes('offline_conversion')?'Upload diagnostics':meta.tool==='apple_impression_share'?'Impression share':meta.tool==='apple_search_term_popularity'?'Search popularity':provider==='ga4'?'Website analytics':provider==='gsc'?'Organic search':'Performance';\n const missing=Array.isArray(rows)?'No report rows returned.':'Report rows unavailable. The response is in Details.';\n const clean={...data};delete clean._adport;\n const errors=arr(data.errors).filter(error=>error?.error_code).map(error=>'<p class=\"notice\">Goal '+esc(error.goal_id||'unavailable')+': '+esc(error.error_code)+'</p>').join('');\n const missingGoals=arr(data.not_returned_goal_ids).filter(id=>!arr(data.errors).some(error=>error?.goal_id===id&&error?.error_code));\n const absent=missingGoals.length?'<p class=\"notice\">No summary returned for goal'+(missingGoals.length===1?'':'s')+' '+missingGoals.map(esc).join(', ')+'.</p>':'';\n const records=entries.slice(0,1000).map((row,index)=>nativeReportRecord(row,index,meta,payload)),delay=provider==='google'&&entries.some(row=>row.segments?.conversionLagBucket||row.segments?.conversionOrAdjustmentLagBucket);\n const pageArgs=['ga4_report','gsc_search_analytics'].includes(meta.tool)?galleryNext(meta):null;\n const chart=reportCharts(records.map(nativeChartRecord),delay?{dimension:'delay',mode:'bars',metric:records.some(record=>record?.fields.some(([key])=>key==='conversions'))?'conversions':undefined}:meta.tool==='apple_impression_share'?{metric:'Impression share',dimension:'search term'}:{});\n app.innerHTML=chrome(operationHeader(delay?'Conversion delay':title,'',provider)+notices({...data,...(meta.tool==='linkedin_demographic_report'?{notes:[]}:{}),errors:arr(data.errors).filter(error=>!error?.error_code)})+errors+absent+'<section data-native-report>'+(entries.length?chart.html:'<p class=\"operation-note\">'+missing+'</p>')+(meta.tool==='linkedin_demographic_report'?'<p class=\"report-chart-foot\">Approximate demographics · privacy thresholds apply</p>':'')+(entries.length>1000?'<p class=\"operation-note\">Showing 1,000 returned rows. The full response is in Details.</p>':'')+(pageArgs?'<div class=\"provider-pages\"><button type=\"button\" class=\"media-button\" data-report-next>Next page</button></div><p class=\"provider-message\" data-report-page-status role=\"status\"></p>':'')+'<details class=\"report-data\"><summary>Details · '+entries.length+' results</summary>'+(entries.length?'<div class=\"record-list\" role=\"region\" aria-label=\"Native report data\" tabindex=\"0\">'+entries.slice(0,1000).map((row,index)=>nativeReportRow(row,index,meta,payload)).join('')+'</div>':'')+'<pre>'+esc(JSON.stringify(clean,null,2))+'</pre></details></section>','');\n chart.mount();\n const snapshot=state.result,button=app.querySelector('[data-report-next]');\n button?.addEventListener('click',async()=>{\n if(button.disabled || state.result!==snapshot)return;\n button.disabled=true;button.textContent='Loading…';\n try {\n const response=await callTool(meta.tool,pageArgs,60000),value=resultData(response),nextMeta=value?._adport;\n if(state.result!==snapshot)return;\n if(response?.isError || value?.error || !nextMeta || !galleryMatches(nextMeta,meta) || galleryStable(nextMeta.refresh?.arguments)!==galleryStable(pageArgs))throw new Error('The report page could not be confirmed.');\n acceptResult(response,true);\n } catch(error) {if(state.result===snapshot) {app.querySelector('[data-report-page-status]').textContent=error?.message||'Could not load the next page.';button.disabled=false;button.textContent='Next page';}}\n });\n }\n`;\n","export const REPORT_CHART_STYLES = String.raw`\n .report-overview { display:flex; align-items:flex-end; gap:26px; margin:4px 0 24px; min-width:0 }\n .report-overview small { display:block; color:var(--muted); font-size:10px; margin-bottom:6px }\n .report-overview strong { font-size:30px; line-height:1; letter-spacing:-.045em; font-weight:650; overflow-wrap:anywhere }\n .report-overview dl { display:flex; flex-wrap:wrap; gap:14px 24px; margin:0 0 1px; min-width:0 }\n .report-overview dt { color:var(--muted); font-size:10px; margin-bottom:5px }\n .report-overview dd { margin:0; font-size:17px; font-variant-numeric:tabular-nums }\n .report-chart { margin:16px 0 4px; min-width:0 }\n .report-chart-head { display:flex; align-items:baseline; justify-content:space-between; gap:12px; margin-bottom:14px; color:var(--muted); font-size:11px }\n .report-chart-head b { color:var(--ink); font-size:11px; font-weight:500 }\n .report-chart-head span { font-size:10px }\n .report-bars { display:grid; gap:14px; list-style:none; padding:0; margin:0 }\n .report-bars li { min-width:0 }\n .report-bar-label { display:flex; align-items:baseline; justify-content:space-between; gap:12px; margin-bottom:6px; font-size:12px }\n .report-bar-label > span { min-width:0; overflow:hidden; white-space:nowrap; text-overflow:ellipsis }\n .report-bar-label strong { flex:0 0 auto; font-size:11px; font-weight:500; font-variant-numeric:tabular-nums }\n .report-bar-track { height:10px; overflow:hidden; border-radius:4px; background:var(--soft); position:relative }\n .report-bar-fill { position:absolute; left:0; top:0; bottom:0; border-radius:4px; background:var(--orange) }\n .report-bar-range { opacity:.5; border-radius:0; border-inline:1px solid var(--orange) }\n .report-bar-zero { position:absolute; top:0; bottom:0; border-left:1px solid var(--muted) }\n .report-chart-foot { margin:10px 0 0; color:var(--muted); font-size:10px; line-height:1.5 }\n [data-native-line] svg { display:block; width:100%; overflow:visible }\n [data-native-line] text { fill:var(--muted); font:10px var(--sans) }\n [data-native-line] .chart-grid { stroke:var(--line); stroke-width:1 }\n [data-native-line] circle:focus { outline:none; stroke:var(--ink); stroke-width:2 }\n .report-legend { display:flex; flex-wrap:wrap; gap:6px 14px; margin:8px 0 0; font-size:10px; color:var(--muted) }\n .report-legend span { display:inline-flex; align-items:center; gap:5px; min-width:0; overflow-wrap:anywhere }\n .report-legend i { display:inline-block; width:12px; border-top:2px solid; flex:0 0 auto }\n .report-data { margin-top:18px }\n .report-data .record-list { margin:12px 0 }\n @media(max-width:380px) { .report-overview { gap:20px }.report-overview dl { gap:12px 18px }.report-overview strong { font-size:27px } }\n`;\n\nexport const REPORT_CHART_SCRIPT = String.raw`\n function reportDate(value) {\n if(typeof value!=='string'||!/^\\d{4}-\\d{2}-\\d{2}$/.test(value))return null;\n const time=Date.parse(value);return Number.isFinite(time)&&new Date(time).toISOString().slice(0,10)===value?value:null;\n }\n function reportNumber(value) {\n const decimal=nativeReportDecimal(value);return decimal!==null&&Number.isFinite(Number(decimal))?Number(decimal):null;\n }\n function reportMetricPriority(key) {\n const value=key.replaceAll('_','').toLowerCase();\n const order=['spend','costmicros','costinlocalcurrency','costinusd','conversions','conversion','totalinstalls','installs','purchases','clicks','taps','impressions','searchpopularity1to100','searchpopularityingenre','searchpopularity1to5','overallsuccesscount','successcount'];\n const rank=order.indexOf(value);return rank<0?100:rank;\n }\n function reportCharts(records,options={}) {\n const all=[...records,...arr(options.periods)],keys=[...new Set(all.flatMap(row=>row.fields.map(field=>field.key)))];\n const key=options.metric||keys.sort((a,b)=>reportMetricPriority(a)-reportMetricPriority(b)).find(key=>all.some(row=>row.fields.some(field=>field.key===key&&available(field.value))))||keys[0];\n if(!key)return {html:'<p class=\"operation-note\">No chartable metrics were returned.</p>',mount:()=>{}};\n const field=all.flatMap(row=>row.fields).find(field=>field.key===key),groups=new Map();\n const seriesPoints=arr(options.periods).length?options.periods:records;\n const points=seriesPoints.map(row=>{const metric=row.fields.find(field=>field.key===key);return {...row,...metric,value:metric?.value??null,display:metric?.display||'—',unit:metric?.unit||field?.unit||''};});\n for(const point of points){const unit=point.unit||'';if(!groups.has(unit))groups.set(unit,[]);groups.get(unit).push(point);}\n const models=[...groups.entries()].slice(0,4).map(([unit,returned])=>{\n const points=returned.slice(0,366);\n const unique=new Set(),dated=points.every(point=>reportDate(point.date)&&!unique.has(JSON.stringify([point.series||point.name,point.date]))&&unique.add(JSON.stringify([point.series||point.name,point.date])));\n const trend=options.mode!=='bars'&&dated&&!points.some(point=>point.range)&&new Set(points.map(point=>point.date)).size>1;\n return {unit,points,trend,returned:returned.length,label:field?.label||human(key)};\n });\n const pretty=value=>String(value).replaceAll('_',' ');\n const html=models.map((model,index)=>{\n const {points,unit,trend,label}=model;\n const title=options.label||label+(trend?' over time':options.dimension?' by '+options.dimension:' by result');\n const shown=points.slice(0,8),valid=shown.filter(point=>available(point.value)),max=Math.max(0,...valid.map(point=>point.value)),min=Math.min(0,...valid.map(point=>point.value)),span=max-min||1;\n const body=trend?'<div data-native-line=\"'+index+'\"></div>':'<ol class=\"report-bars\" aria-label=\"'+esc(title)+'\">'+shown.map(point=>{\n const value=available(point.value)?point.value:null,width=value===null?0:Math.min(100,Math.abs(value)/span*100),left=value===null?0:(Math.min(value,0)-min)/span*100;\n const label=pretty(point.name)+(point.context?.length?' · '+point.context.join(' · '):'');\n const range=point.range&&point.range.every(available)?point.range:null;\n const fill=range?'<span class=\"report-bar-fill report-bar-range\" style=\"left:'+Math.max(0,range[0]*100)+'%;width:'+Math.max(0,(range[1]-range[0])*100)+'%\"></span>':'<span class=\"report-bar-fill\" style=\"left:'+left.toFixed(5)+'%;width:'+width.toFixed(5)+'%\"></span>';\n return '<li data-chart-value=\"'+(value===null?'':value)+'\"><div class=\"report-bar-label\"><span title=\"'+esc(label)+'\">'+esc(label)+'</span><strong>'+esc(point.display)+'</strong></div><div class=\"report-bar-track\" aria-hidden=\"true\">'+fill+(min<0?'<span class=\"report-bar-zero\" style=\"left:'+(-min/span*100).toFixed(5)+'%\"></span>':'')+'</div></li>';\n }).join('')+'</ol>';\n return '<section class=\"report-chart\" data-report-chart><div class=\"report-chart-head\"><b>'+esc(title)+'</b>'+(unit?'<span>'+esc(unit)+'</span>':'')+'</div>'+body+(!trend&&model.returned>shown.length?'<p class=\"report-chart-foot\">'+shown.length+' of '+model.returned+' returned rows · all rows in Details</p>':trend&&model.returned>points.length?'<p class=\"report-chart-foot\">'+points.length+' of '+model.returned+' dated observations · all data in Details</p>':'')+'</section>';\n }).join('')+(groups.size>4?'<p class=\"report-chart-foot\">Showing four units. All returned values are in Details.</p>':'');\n return {html,mount:()=>{\n const elements=[...app.querySelectorAll('[data-native-line]')];\n const draw=()=>elements.forEach(element=>{\n if(element.isConnected===false)return;\n const model=models[Number(element.dataset.nativeLine)];if(!model)return;\n const series=new Map();for(const point of model.points){const name=point.series||point.name;if(!series.has(name))series.set(name,[]);series.get(name).push(point);}\n const chosen=[...series.entries()].slice(0,3),valid=chosen.flatMap(([,points])=>points).filter(point=>available(point.value));\n if(!valid.length){element.innerHTML='<p class=\"operation-note\">No complete dated values were returned.</p>';return;}\n const width=Math.max(240,Math.floor(element.getBoundingClientRect?.().width||480)),height=178,left=46,right=12,top=12,bottom=30;\n const dates=[...new Set(model.points.map(point=>point.date))].sort(),start=Date.parse(dates[0]),end=Date.parse(dates.at(-1)),span=Math.max(86400000,end-start);\n const max=Math.max(1e-100,...valid.map(point=>point.value)),min=Math.min(0,...valid.map(point=>point.value)),range=max-min||1;\n const x=date=>left+(Date.parse(date)-start)/span*(width-left-right),y=value=>top+(max-value)/range*(height-top-bottom);\n const colors=['var(--orange)','var(--ink)','var(--muted)'],dashes=['','5 3','2 3'];\n const ticks=[...new Set([dates[0],dates[Math.floor((dates.length-1)/2)],dates.at(-1)])];\n const labels=ticks.map((date,index)=>'<text x=\"'+x(date)+'\" y=\"'+(height-7)+'\" text-anchor=\"'+(index===0?'start':index===ticks.length-1?'end':'middle')+'\">'+esc(new Intl.DateTimeFormat(state.host.locale||'en',{month:'short',day:'numeric',timeZone:'UTC'}).format(new Date(date)))+'</text>').join('');\n const paths=chosen.map(([name,points],index)=>{\n let line='',previous;const sorted=[...points].sort((a,b)=>a.date.localeCompare(b.date));\n for(const point of sorted){if(!available(point.value)){previous=null;continue;}const adjacent=previous&&Date.parse(point.date)-Date.parse(previous.date)===86400000;line+=(adjacent?' L':' M')+x(point.date).toFixed(2)+' '+y(point.value).toFixed(2);previous=point;}\n return '<path d=\"'+line+'\" fill=\"none\" stroke=\"'+colors[index]+'\" stroke-width=\"2\" stroke-dasharray=\"'+dashes[index]+'\"/>'+sorted.filter(point=>available(point.value)).map(point=>'<circle cx=\"'+x(point.date)+'\" cy=\"'+y(point.value)+'\" r=\"3\" fill=\"'+colors[index]+'\" tabindex=\"0\"><title>'+esc(pretty(name)+' · '+point.date+' · '+point.display)+'</title></circle>').join('');\n }).join('');\n const axis=value=>new Intl.NumberFormat(state.host.locale||'en',{notation:Math.abs(value)>=1000?'compact':'standard',maximumFractionDigits:3}).format(value);\n element.innerHTML='<svg viewBox=\"0 0 '+width+' '+height+'\" role=\"img\" aria-label=\"'+esc(model.label+' over reported dates')+'\"><line class=\"chart-grid\" x1=\"'+left+'\" x2=\"'+(width-right)+'\" y1=\"'+(height-bottom)+'\" y2=\"'+(height-bottom)+'\"/><text x=\"'+(left-8)+'\" y=\"'+(top+4)+'\" text-anchor=\"end\">'+esc(axis(max))+'</text><text x=\"'+(left-8)+'\" y=\"'+(height-bottom)+'\" text-anchor=\"end\">'+esc(axis(min))+'</text>'+paths+labels+'</svg>'+(chosen.length>1?'<div class=\"report-legend\">'+chosen.map(([name],index)=>'<span><i style=\"border-color:'+colors[index]+';border-top-style:'+(index?'dashed':'solid')+'\"></i>'+esc(pretty(name))+'</span>').join('')+'</div>':'')+(series.size>3?'<p class=\"report-chart-foot\">3 of '+series.size+' series · all series in Details</p>':'');\n });\n draw();if(typeof ResizeObserver!=='undefined'&&models.some(model=>model.trend)){trendResize=new ResizeObserver(draw);elements.forEach(element=>trendResize.observe(element));}\n }};\n }\n`;\n","import { MEDIA_LIBRARY_UI, MEDIA_LIBRARY_STYLES } from './media-library-ui.js';\nimport { MEDIA_UPLOAD_UI } from './media-upload-ui.js';\nimport { TREND_UI_SCRIPT, TREND_UI_STYLES } from './trend-ui.js';\nimport { RECORD_UI_SCRIPT, RECORD_UI_STYLES } from './record-ui.js';\nimport { RECEIPT_UI_SCRIPT, RECEIPT_UI_STYLES } from './receipt-ui.js';\nimport { INSIGHT_UI_SCRIPT, INSIGHT_UI_STYLES } from './insight-ui.js';\nimport { CREATIVE_UI_SCRIPT, CREATIVE_UI_STYLES } from './creative-ui.js';\nimport { PROVIDER_GALLERY_UI, PROVIDER_GALLERY_STYLES } from './provider-gallery-ui.js';\nimport { PROVIDER_LOGOS } from './provider-logos.js';\nimport { OPERATION_UI_SCRIPT } from './operation-ui.js';\nimport { APPLE_REPORT_UI_SCRIPT, APPLE_REPORT_UI_STYLES } from './apple-report-ui.js';\nimport { NATIVE_REPORT_UI_SCRIPT, NATIVE_REPORT_UI_STYLES } from './native-report-ui.js';\nimport { REPORT_CHART_SCRIPT, REPORT_CHART_STYLES } from './report-chart-ui.js';\n\nexport const ADPORT_UI_URI = 'ui://adport/insight-card-v31.html';\nexport const ADPORT_SUMMARY_UI_URI = 'ui://adport/summary-card-v30.html';\nexport const ADPORT_UI_DOMAIN = 'https://app.adport.dev';\nexport const ADPORT_UI_RESOURCE_DOMAINS = [\n ADPORT_UI_DOMAIN,\n 'https://scontent.xx.fbcdn.net',\n 'https://video.xx.fbcdn.net',\n 'https://tpc.googlesyndication.com',\n 'https://www.bing.com',\n 'https://i.scdn.co',\n 'https://storage.googleapis.com',\n 'https://i.pinimg.com',\n 'https://i.redd.it',\n 'https://preview.redd.it',\n 'https://v.redd.it',\n 'https://media.licdn.com',\n 'https://dms.licdn.com',\n 'https://pbs.twimg.com',\n 'https://video.twimg.com',\n 'https://ton.twimg.com',\n 'https://p16-sign-sg.tiktokcdn.com',\n 'https://v16-tiktokcdn-com.akamaized.net',\n];\n\nexport type AdportView = 'accounts' | 'report' | 'operation' | 'insights' | 'creatives' | 'planning' | 'data' | 'records' | 'receipt';\n\nconst providerNames: Record<string, string> = {\n ga4: 'Google Analytics 4',\n gsc: 'Google Search Console',\n gtm: 'Google Tag Manager',\n google: 'Google Ads',\n meta: 'Meta Ads',\n tiktok: 'TikTok Ads',\n apple: 'Apple Ads',\n microsoft: 'Microsoft Advertising',\n reddit: 'Reddit Ads',\n snapchat: 'Snapchat Ads',\n spotify: 'Spotify Ads',\n pinterest: 'Pinterest Ads',\n linkedin: 'LinkedIn Ads',\n x: 'X Ads',\n openai: 'OpenAI Ads',\n mock: 'Demo',\n demo: 'Synthetic demo',\n};\n\nexport function viewForTool(name: string, readOnly: boolean): AdportView {\n if (name === 'accounts_list') return 'accounts';\n if (name === 'report') return 'report';\n if (name === 'audit_run' || name === 'recommendation_dismiss') return 'insights';\n if (!readOnly) return 'operation';\n if (name.startsWith('recommendation') || name.startsWith('audit_')) return 'insights';\n if (/(?:_request_status|_upload_status|_experiment_operation|_offline_conversion_diagnostics|_get_media_upload)$/.test(name)) return 'receipt';\n return 'data';\n}\n\nexport function toolTitle(name: string): string {\n if (name === 'accounts_list') return 'Show connected ad accounts';\n if (name === 'report') return 'Show advertising performance';\n return name\n .split('_')\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(' ');\n}\n\nexport function toolInvocationLabels(view: AdportView): { invoking: string; invoked: string } {\n switch (view) {\n case 'accounts': return { invoking: 'Loading ad accounts…', invoked: 'Ad accounts ready' };\n case 'report': return { invoking: 'Analyzing performance…', invoked: 'Performance ready' };\n // Descriptor labels cover both preview and apply; the card shows the actual result.\n case 'operation': return { invoking: 'Processing change…', invoked: 'Change result ready' };\n case 'insights': return { invoking: 'Reviewing opportunities…', invoked: 'Opportunities ready' };\n case 'creatives': return { invoking: 'Loading creatives…', invoked: 'Creatives ready' };\n case 'planning': return { invoking: 'Loading planning estimates…', invoked: 'Planning estimates ready' };\n case 'records': return { invoking: 'Loading records…', invoked: 'Records ready' };\n case 'receipt': return { invoking: 'Checking processing…', invoked: 'Processing status ready' };\n case 'data': return { invoking: 'Loading data…', invoked: 'Data ready' };\n }\n}\n\nexport function structuredResult(tool: string, view: AdportView, result: unknown, approval?: { arguments: Record<string, unknown> }, context?: { project_id: string }, capabilities?: { can_write: boolean }, refresh?: { arguments: Record<string, unknown> }, next?: { arguments: Record<string, unknown> }, descriptor?: { provider?: string; accountId?: string; pagination?: { cursorInput: string } }): Record<string, unknown> {\n const payload = result && typeof result === 'object' && !Array.isArray(result)\n ? result as Record<string, unknown>\n : { value: result };\n return {\n ...payload,\n _adport: {\n tool,\n view,\n providerNames,\n ...descriptor,\n ...(approval ? { approval } : {}),\n ...(context ? { context } : {}),\n ...(capabilities ? { capabilities } : {}),\n ...(refresh ? { refresh } : {}),\n ...(next ? { next } : {}),\n },\n };\n}\n\n/**\n * Self-contained MCP App. It uses the open MCP Apps postMessage protocol and\n * has no external script dependencies. Media uses only the resource CSP supplied\n * by the server; tool invocations always use the host bridge.\n */\nexport const ADPORT_UI_HTML = String.raw`<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />\n <meta name=\"color-scheme\" content=\"light dark\" />\n <title>Adport insight</title>\n <style>\n :root {\n --ink: var(--color-text-primary, #171717);\n --muted: var(--color-text-secondary, #6f6f73);\n --faint: var(--color-text-tertiary, #949499);\n --paper: var(--color-background-primary, #ffffff);\n --soft: var(--color-background-secondary, #f6f6f4);\n --line: var(--color-border-secondary, rgba(23,23,23,.11));\n --orange: #ff6b00;\n --green: #16845b;\n --red: #c8392f;\n --amber: #a86500;\n --radius: var(--border-radius-lg, 18px);\n --sans: var(--font-sans, ui-sans-serif, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif);\n --mono: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);\n }\n * { box-sizing: border-box }\n html, body { margin: 0; min-width: 0; background: transparent; color: var(--ink); font-family: var(--sans) }\n body { padding: 2px; }\n button { font: inherit }\n .shell { overflow: hidden; border: 1px solid var(--line); border-radius: var(--radius); background: var(--paper); box-shadow: 0 10px 32px rgba(20,20,20,.07) }\n .top { display:flex; align-items:center; justify-content:space-between; gap:16px; padding:14px 16px 10px }\n .brand { display:flex; align-items:center; gap:9px; min-width:0 }\n .wordmark-dot { color:#ff6b00; font-size:1.3em; line-height:0 }\n .brand b { font-size:12px; letter-spacing:-.02em }\n .context { color:var(--muted); font-size:11px; text-align:right }\n .content { padding:4px 16px 16px }\n .kpis { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:8px; margin-bottom:15px }\n .kpi { min-width:0; padding:12px; border-radius:13px; background:var(--soft); border:1px solid color-mix(in srgb,var(--line) 70%,transparent) }\n button.kpi { cursor:pointer; color:var(--ink); text-align:left }\n button.kpi[aria-pressed=\"true\"] { border-color:color-mix(in srgb,var(--orange) 65%,var(--line)) }\n .kpi small { display:block; color:var(--faint); font:600 9px/1.2 var(--mono); letter-spacing:.11em; text-transform:uppercase }\n .kpi strong { display:block; overflow:hidden; margin-top:8px; font-size:clamp(17px,3vw,24px); line-height:1; letter-spacing:-.04em; text-overflow:ellipsis }\n .panel { min-width:0; padding:13px; border:1px solid var(--line); border-radius:14px }\n .panel-head { display:flex; align-items:center; justify-content:space-between; gap:12px; margin-bottom:12px }\n .panel-head b { font-size:12px }\n .panel-head span { color:var(--faint); font:500 9px/1 var(--mono); text-transform:uppercase; letter-spacing:.1em }\n .bars { display:grid; gap:9px }\n .bar-row { display:grid; grid-template-columns:minmax(100px,1fr) minmax(60px,2fr) auto; align-items:center; gap:9px; font-size:11px }\n .bar-name { display:flex; align-items:center; gap:7px; min-width:0 }\n .bar-name > span:last-child { overflow:hidden; white-space:nowrap; text-overflow:ellipsis }\n .bar-name .logo { width:22px; height:22px; padding:4px; border-radius:6px }\n .track { height:7px; overflow:hidden; border-radius:99px; background:var(--soft) }\n .fill { height:100%; border-radius:99px; background:linear-gradient(90deg,var(--orange),#ff985e) }\n .tabs { display:flex; gap:6px; overflow:auto; padding-bottom:12px }\n .tabs button { flex:0 0 auto; cursor:pointer; padding:8px 12px; border:1px solid var(--line); border-radius:99px; background:var(--paper); color:var(--muted); font-size:12px }\n .tabs button[aria-pressed=\"true\"] { color:var(--ink); border-color:var(--orange); background:color-mix(in srgb,var(--orange) 8%,var(--paper)) }\n button:focus-visible { outline:2px solid var(--orange); outline-offset:2px }\n .notice { padding:10px 12px; margin:0 0 12px; border-radius:10px; background:var(--soft); color:var(--muted); font-size:12px; line-height:1.45 }\n .bar-value { color:var(--muted); font:600 10px/1 var(--mono); white-space:nowrap }\n .list { display:grid; gap:7px }\n .row { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:10px 11px; border:1px solid var(--line); border-radius:12px }\n .identity { display:flex; align-items:center; gap:10px; min-width:0 }\n .logo { display:grid; place-items:center; flex:0 0 auto; width:29px; height:29px; padding:6px; border:1px solid var(--line); border-radius:9px; color:var(--ink); background:var(--paper); font-weight:800; font-size:10px }\n .logo svg { display:block; width:100%; height:100% }\n .logo.reddit { background:#ff4500 }.logo.linkedin { background:#0a66c2 }.logo.spotify { background:#1db954 }.logo.pinterest { background:#e60023 }.logo.x { background:#111 }.logo.openai { background:#000 }.logo.snapchat { background:#fffc00;color:#111 }\n .identity-copy { min-width:0 }\n .identity-copy b, .identity-copy span { display:block; overflow:hidden; white-space:nowrap; text-overflow:ellipsis }\n .identity-copy b { font-size:12px }.identity-copy span { margin-top:3px; color:var(--muted); font-size:10px }\n .pill { flex:0 0 auto; padding:5px 8px; border-radius:99px; color:var(--green); background:color-mix(in srgb,var(--green) 10%,transparent); font:700 9px/1 var(--mono); letter-spacing:.08em; text-transform:uppercase }\n .pill.warn { color:var(--amber); background:color-mix(in srgb,var(--amber) 11%,transparent) }\n .pill.danger { color:var(--red); background:color-mix(in srgb,var(--red) 10%,transparent) }\n .pill.neutral { color:var(--muted); background:var(--soft) }\n .operation-name { margin:2px 0 16px; font-size:14px; line-height:1.4; font-weight:600; overflow-wrap:anywhere }\n .comparison { width:100%; border-collapse:collapse; table-layout:fixed; margin-bottom:12px }\n .comparison th { padding:0 8px 8px; color:var(--muted); font-size:10px; font-weight:500; text-align:left }\n .comparison td { border-top:1px solid var(--line); padding:12px 8px; font-size:14px; overflow-wrap:anywhere }\n .comparison td:first-child { color:var(--muted); font-size:11px }\n .comparison td:last-child { font-weight:600 }\n .comparison .changed { color:var(--orange) }\n .planning-scroll { max-height:440px; overflow:auto; margin-bottom:12px }\n .planning-table { width:100%; border-collapse:collapse; font-size:11px }\n .planning-table th { position:sticky; top:0; background:var(--paper); padding:8px; text-align:left; color:var(--muted) }\n .planning-table td { border-top:1px solid var(--line); padding:9px 8px; overflow-wrap:anywhere }\n .planning-pages { display:flex; align-items:center; justify-content:space-between; gap:8px; margin-bottom:12px }\n .planning-pages button { cursor:pointer; padding:7px 10px; border:1px solid var(--line); border-radius:9px; color:var(--ink); background:var(--paper) }\n .planning-pages button:disabled { cursor:default; opacity:.45 }\n .adjustment { margin:8px 0; color:var(--amber); font-size:11px; line-height:1.4 }\n .approval { display:flex; align-items:center; gap:10px; flex-wrap:wrap; margin:12px 0 }\n .approve { cursor:pointer; min-width:145px; padding:11px 19px 10px; border:0; border-radius:999px; background:var(--orange); color:#1d1d1f; font-size:13px; font-weight:750 }\n .approve:disabled { cursor:default; opacity:.55 }\n .approve { position:relative; overflow:hidden; touch-action:none; user-select:none }\n .approve::before { content:''; position:absolute; inset:0; background:#1d1d1f26; transform:scaleX(0); transform-origin:left }\n .approve > span { position:relative }\n @media (hover:hover) { .approve:not(:disabled):hover { background:#f26100 } }\n .approve.holding::before { transform:scaleX(1); transition:transform .9s linear }\n .approve:focus-visible { outline:2px solid var(--orange); outline-offset:3px }\n @media (prefers-reduced-motion:reduce) { .approve.holding::before { transition:none } }\n details { border-top:1px solid var(--line); padding-top:10px; color:var(--muted); font-size:11px; line-height:1.5 }\n summary { cursor:pointer; width:fit-content; padding:3px 0 }\n summary:focus-visible { outline:2px solid var(--orange); outline-offset:3px }\n details p { margin:8px 0; overflow-wrap:anywhere }\n .empty { padding:26px 12px; text-align:center; color:var(--muted); font-size:12px }\n .operation-heading { display:flex; align-items:center; gap:11px; margin:8px 0 22px; min-width:0 }\n .operation-heading h2 { margin:0; font-size:15px; line-height:1.4; font-weight:650; letter-spacing:-.015em }\n .operation-heading p { margin:3px 0 0; color:var(--muted); font-size:12px; overflow-wrap:anywhere }\n .review-fields { margin:0; display:grid; gap:12px }\n .review-field { display:grid; grid-template-columns:minmax(90px,.8fr) minmax(0,2fr); gap:12px; align-items:baseline }\n .review-field dt { font-size:12px; color:var(--muted); overflow-wrap:anywhere }\n .review-field dd { display:flex; flex-wrap:wrap; align-items:baseline; gap:5px 9px; margin:0; min-width:0; font-size:14px; overflow-wrap:anywhere }\n .review-before,.review-arrow,.unavailable { color:var(--muted) }\n .review-after { font-weight:500; min-width:0 }\n .review-copy { font-size:16px!important; line-height:1.6 }\n .review-money { font-size:20px!important; font-variant-numeric:tabular-nums }\n .review-list { margin:0; padding-left:17px; display:grid; gap:5px }\n .review-added,.review-removed { padding:3px 7px; border-radius:5px; font-size:13px }\n .review-added { color:var(--green); background:color-mix(in srgb,var(--green) 10%,var(--paper)) }\n .review-removed { color:var(--red); background:color-mix(in srgb,var(--red) 10%,var(--paper)) }\n .operation-note { margin:10px 0; color:var(--muted); font-size:12px; line-height:1.5; overflow-wrap:anywhere }\n .operation-footer { position:relative; border-top:1px solid var(--line); margin-top:21px; padding-top:14px; min-height:55px }\n .operation-footer > details { border:0; padding:0 }\n .operation-footer summary { display:flex; align-items:center; min-height:40px; max-width:calc(100% - 160px); padding:0 }\n .operation-footer summary::after { content:'⌄'; margin-left:5px }\n .operation-action { position:absolute; top:14px; right:0 }\n .operation-status { display:block; padding:11px 0; font-size:13px }\n .operation-details { padding-top:12px }\n .operation-details .review-fields { margin:14px 0 }\n pre { font:11px/1.5 var(--mono); white-space:pre-wrap; overflow-wrap:anywhere; margin:12px 0 0 }\n .data-record { padding:12px 0; border-top:1px solid var(--line) }\n @media (max-width:420px) { .review-field { grid-template-columns:1fr; gap:5px } }\n @media (pointer:coarse) { .approve,.operation-footer summary { min-height:44px } }\n @media (max-width:620px) { .kpis { grid-template-columns:repeat(2,minmax(0,1fr)) }.top,.content { padding-left:12px; padding-right:12px } }\n @media (max-width:420px) { .bar-row { grid-template-columns:minmax(0,1fr) auto; gap:5px }.bar-name { grid-column:1/-1 }.bar-name > span:last-child { white-space:normal }.bars { gap:12px } }\n${CREATIVE_UI_STYLES}\n${PROVIDER_GALLERY_STYLES}\n${MEDIA_LIBRARY_STYLES}\n${RECORD_UI_STYLES}\n${APPLE_REPORT_UI_STYLES}\n${NATIVE_REPORT_UI_STYLES}\n${REPORT_CHART_STYLES}\n${RECEIPT_UI_STYLES}\n${INSIGHT_UI_STYLES}\n${TREND_UI_STYLES}\n @media (prefers-reduced-motion:reduce) { * { animation:none!important; transition:none!important } }\n :root[data-theme=\"dark\"] { --ink:#f5f5f3;--muted:#aaa9ad;--faint:#a09fa5;--paper:#171717;--soft:#222220;--line:rgba(255,255,255,.11) }\n @media (prefers-color-scheme:dark) { :root:not([data-theme=\"light\"]) { --ink:#f5f5f3;--muted:#aaa9ad;--faint:#a09fa5;--paper:#171717;--soft:#222220;--line:rgba(255,255,255,.11) } }\n </style>\n</head>\n<body>\n <main id=\"app\" class=\"shell\" aria-live=\"polite\">\n <header class=\"top\"><div class=\"brand\"><b>adport<span class=\"wordmark-dot\" aria-hidden=\"true\">.</span></b></div></header>\n <section class=\"content\"><div class=\"empty\">Loading…</div></section>\n </main>\n <script>\n (() => {\n const app = document.getElementById('app');\n const state = { host: {}, result: null, reportGroup: null, reportMetric: 'spend', planningPage: 0, hasLocalResult: false };\n const hostResults=new Set();\n const esc = (value) => String(value ?? '').replace(/[&<>\"']/g, (c) => ({'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;',\"'\":'&#39;'}[c]));\n const arr = (value) => Array.isArray(value) ? value : [];\n const num = (value) => Number.isFinite(Number(value)) ? Number(value) : 0;\n const money = (value, currency, maximumFractionDigits=2) => currency\n ? new Intl.NumberFormat(state.host.locale || 'en', { style:'currency', currency, maximumFractionDigits }).format(num(value))\n : new Intl.NumberFormat(state.host.locale || 'en', { maximumFractionDigits }).format(num(value));\n const compact = (value) => new Intl.NumberFormat(state.host.locale || 'en', { notation:'compact', maximumFractionDigits:1 }).format(num(value));\n const available = (value) => typeof value === 'number' && Number.isFinite(value);\n const total = (rows, key) => rows.length && rows.every(r => available(r.metrics?.[key])) ? rows.reduce((sum,r) => sum+r.metrics[key],0) : null;\n const rowReturn = (row) => {\n const m=row.metrics || {};\n if (available(m.conversion_value)) return m.conversion_value;\n // A report can request ROAS without conversion_value. Weight reported\n // ratios by spend; never average campaign ratios or infer missing revenue.\n const value=available(m.spend) && m.spend>0 && available(m.roas) ? m.spend*m.roas : null;\n return available(value) ? value : null;\n };\n const currencyOf = (row) => typeof row.currency === 'string' && /^[A-Z]{3}$/.test(row.currency) ? row.currency : null;\n const statusOf = (status) => !status || /unknown|unspecified/i.test(status) ? {label:'Status unavailable',tone:'neutral'} : /disabled|removed|inactive|closed|suspended/i.test(status) ? {label:status,tone:'danger'} : /paused|disable$/i.test(status) ? {label:status,tone:'warn'} : /^(enabled|active|approved|ready)$/i.test(status) ? {label:status,tone:''} : {label:status,tone:'neutral'};\n const noticeText=(value,fallback)=>typeof value==='string'?value:typeof value?.message==='string'?value.message:typeof value?.reason==='string'?value.reason:fallback;\n const notices = data => [...arr(data.errors).map(error=>(error?.provider || 'Provider')+': '+noticeText(error,'Read failed')), ...arr(data.warnings).map(warning=>noticeText(warning,'Some metadata is unavailable')), ...arr(data.notes).filter(note=>typeof note==='string'), ...(typeof data.note==='string'?[data.note]:[]), ...(data.truncated ? ['Partial result: row limit reached. Totals and charts cover returned rows only.'] : [])].map(text => '<p class=\"notice\">'+esc(text)+'</p>').join('');\n const providerName = (id, names) => names?.[id] || String(id || 'Provider');\n const initials = (id) => ({snapchat:'S',spotify:'S',pinterest:'P',linkedin:'in',x:'X',openai:'AI'}[id] || String(id || '?').slice(0,2).toUpperCase());\n const providerSvg = ${JSON.stringify(PROVIDER_LOGOS)};\n const logo = (id) => '<span class=\"logo '+esc(id)+'\" aria-hidden=\"true\">'+(providerSvg[id] || esc(initials(id)))+'</span>';\n let syntheticResult = false;\n const chrome = (body, context) => '<header class=\"top\"><div class=\"brand\"><b>adport<span class=\"wordmark-dot\" aria-hidden=\"true\">.</span></b></div><span class=\"context\">'+(syntheticResult?'Synthetic demo · ':'')+esc(context || '')+'</span></header><section class=\"content\">'+body+'</section>';\n function renderAccounts(data, meta) {\n const accounts = arr(data.accounts), errors = arr(data.errors), names = meta.providerNames || {};\n const body = notices(data)+(accounts.length ? '<div class=\"list\">'+accounts.map(a => { const status=statusOf(a.status); return '<div class=\"row\"><div class=\"identity\">'+logo(a.provider)+'<div class=\"identity-copy\"><b>'+esc(a.name || 'Ad account')+'</b><span>'+esc(providerName(a.provider,names))+' · '+esc(a.id)+(a.currency ? ' · '+esc(a.currency) : '')+'</span></div></div><span class=\"pill '+status.tone+'\">'+esc(status.label)+'</span></div>'; }).join('')+'</div>' : '<div class=\"empty\">'+(errors.length ? 'Account inventory could not be fully loaded.' : 'No accessible ad accounts were returned.')+'</div>');\n app.innerHTML = chrome(body, accounts.length+' account'+(accounts.length===1?'':'s'));\n }\n function renderReport(data,meta) {\n const groups = new Map();\n for (const row of arr(data.rows)) {\n const currency=currencyOf(row), key=currency || JSON.stringify([row.provider,row.accountId]);\n if (!groups.has(key)) groups.set(key,{key,currency,label:currency || (row.provider+' · '+row.accountId),rows:[]});\n groups.get(key).rows.push(row);\n }\n const choices=[...groups.values()];\n const selected=groups.get(state.reportGroup) || choices[0];\n const rows=selected?.rows || [], currency=selected?.currency;\n state.reportGroup=selected?.key;\n const tabs=choices.length>1 ? '<div class=\"tabs\" role=\"group\" aria-label=\"Report currency or account\">'+choices.map((g,i)=>'<button data-group=\"'+i+'\" aria-pressed=\"'+(g===selected)+'\">'+esc(g.label)+'</button>').join('')+'</div>' : '';\n const summary=arr(data.summary?.groups).find(group=>group.key===selected?.key)?.metrics;\n const aggregate=key=>summary ? (available(summary[key])?summary[key]:null) : total(rows,key);\n const spend=aggregate('spend'), returns=rows.map(rowReturn);\n const value=returns.length && returns.every(available) ? returns.reduce((sum,value)=>sum+value,0) : null;\n const ratio=summary ? summary.roas : spend>0 && value!==null ? value/spend : null;\n const roas=available(ratio) ? ratio.toFixed(2)+'×' : '—';\n const metric=state.reportMetric, labels={spend:'Spend',clicks:'Clicks',conversions:'Conversions',roas:'ROAS'};\n const metricValue=r=>metric==='roas' ? (available(r.metrics?.conversion_value) && r.metrics?.spend>0 ? r.metrics.conversion_value/r.metrics.spend : r.metrics?.roas) : r.metrics?.[metric];\n const format=value=>metric==='spend'?money(value,currency):metric==='roas'?value.toFixed(2)+'×':compact(value);\n const ranked=[...rows].filter(r=>available(metricValue(r))).sort((a,b)=>metricValue(b)-metricValue(a)).slice(0,6), max=Math.max(1,...ranked.map(metricValue));\n const bars=ranked.length ? ranked.map(r=>'<div class=\"bar-row\"><span class=\"bar-name\" title=\"'+esc(r.entity?.name || r.entity?.id)+'\">'+logo(r.provider)+'<span>'+esc(r.entity?.name || r.entity?.id || 'Entity')+'</span></span><span class=\"track\" aria-hidden=\"true\"><span class=\"fill\" style=\"display:block;width:'+Math.max(0,metricValue(r)/max*100).toFixed(1)+'%\"></span></span><span class=\"bar-value\">'+esc(format(metricValue(r)))+'</span></div>').join('') : '<div class=\"empty\">No '+esc(labels[metric])+' values were returned.</div>';\n const kpi=(key,label,value)=>'<button class=\"kpi\" data-metric=\"'+key+'\" aria-pressed=\"'+(metric===key)+'\" aria-label=\"Chart '+esc(label)+'\"><small>'+esc(label)+'</small><strong>'+esc(value)+'</strong></button>';\n const period=typeof data.date_range==='string' ? data.date_range.replaceAll('_',' ') : data.date_range ? data.date_range.start+' – '+data.date_range.end : 'Selected period';\n const dated=rows.some(row=>typeof row.date==='string');\n const chart=dated?'<div class=\"report-trend\"><div class=\"panel-head\"><b>Daily '+esc(labels[metric].toLowerCase())+'</b>'+providerMarks(rows.map(row=>row.provider),meta,'Report platforms')+'</div><div data-report-trend></div><p class=\"operation-note\">Missing or unavailable days remain gaps.</p></div>':'<div class=\"panel\"><div class=\"panel-head\"><b>'+esc(labels[metric])+'</b><span>Top '+ranked.length+' of '+rows.length+' rows</span></div><div class=\"bars\">'+bars+'</div></div>';\n const body=notices(data)+tabs+(rows.length ? (!currency?'<p class=\"notice\">Currency unavailable. These values belong to this account only; no cross-account money total is calculated.</p>':'')+'<div class=\"kpis\" role=\"group\" aria-label=\"Chart metric\">'+kpi('spend','Spend',spend===null?'—':money(spend,currency))+kpi('clicks','Clicks',total(rows,'clicks')===null?'—':compact(total(rows,'clicks')))+kpi('conversions','Conversions',total(rows,'conversions')===null?'—':compact(total(rows,'conversions')))+kpi('roas','ROAS',roas)+'</div>'+chart : '<div class=\"empty\">'+(arr(data.errors).length?'Report unavailable for the requested providers.':'No rows returned for this period.')+'</div>');\n trendResize?.disconnect();\n app.innerHTML=chrome(body,period+(currency?' · '+currency:''));\n if(dated)mountReportTrend(rows,metric,currency,data);\n app.querySelectorAll('[data-group]').forEach(button=>button.addEventListener('click',()=>{state.reportGroup=choices[Number(button.dataset.group)].key;renderReport(data,meta);}));\n app.querySelectorAll('[data-metric]').forEach(button=>button.addEventListener('click',()=>{state.reportMetric=button.dataset.metric;renderReport(data,meta);}));\n }\n${OPERATION_UI_SCRIPT}\n${RECEIPT_UI_SCRIPT}\n${RECORD_UI_SCRIPT}\n${APPLE_REPORT_UI_SCRIPT}\n${NATIVE_REPORT_UI_SCRIPT}\n${REPORT_CHART_SCRIPT}\n${INSIGHT_UI_SCRIPT}\n${TREND_UI_SCRIPT}\n async function callTool(tool,parameters,timeoutMs=30000) {\n const requestId=id++;\n return new Promise((resolve,reject)=>{\n const timer=setTimeout(()=>{pendingRequests.delete(requestId);reject(new Error('The request could not be confirmed. Check the result in chat before retrying.'));},timeoutMs);\n pendingRequests.set(requestId,{resolve,reject,timer});\n if (typeof window.openai?.callTool==='function') {\n Promise.resolve().then(()=>window.openai.callTool(tool,parameters)).then(result=>{\n const request=pendingRequests.get(requestId);if (request) {clearTimeout(request.timer);pendingRequests.delete(requestId);request.resolve(result);}\n },error=>{const request=pendingRequests.get(requestId);if (request) {clearTimeout(request.timer);pendingRequests.delete(requestId);request.reject(error);}});\n } else send({jsonrpc:'2.0',id:requestId,method:'tools/call',params:{name:tool,arguments:parameters}});\n });\n }\n${MEDIA_UPLOAD_UI}\n${MEDIA_LIBRARY_UI}\n${CREATIVE_UI_SCRIPT}\n${PROVIDER_GALLERY_UI}\n function renderPlanning(data,meta) {\n const planning=data.planning || {}, columns=arr(planning.columns).filter(v=>typeof v?.key==='string'&&typeof v?.label==='string').slice(0,12), rows=arr(planning.rows), pageSize=100, pages=Math.max(1,Math.ceil(rows.length/pageSize));\n state.planningPage=Math.max(0,Math.min(state.planningPage,pages-1));\n const start=state.planningPage*pageSize, shown=rows.slice(start,start+pageSize);\n const notes=arr(planning.notes).filter(v=>typeof v==='string').map(v=>'<p class=\"notice\">'+esc(v)+'</p>').join('');\n const table=columns.length&&shown.length?'<div class=\"planning-scroll\" tabindex=\"0\" role=\"region\" aria-label=\"Planning estimate table\"><table class=\"planning-table\"><thead><tr>'+columns.map(v=>'<th scope=\"col\">'+esc(v.label)+'</th>').join('')+'</tr></thead><tbody>'+shown.map(row=>'<tr>'+columns.map(column=>{const value=row&&Object.hasOwn(row,column.key)?row[column.key]:null;return '<td>'+esc(value==null?'—':value)+'</td>';}).join('')+'</tr>').join('')+'</tbody></table></div>':'<div class=\"empty\">No planning values were returned for this selection.</div>';\n const controls=pages>1?'<div class=\"planning-pages\"><button type=\"button\" data-planning-page=\"previous\" '+(state.planningPage===0?'disabled':'')+'>Previous rows</button><span class=\"context\">Rows '+(start+1)+'–'+(start+shown.length)+' of '+rows.length+'</span><button type=\"button\" data-planning-page=\"next\" '+(state.planningPage===pages-1?'disabled':'')+'>Next rows</button></div>':'';\n app.innerHTML=chrome(operationHeader(planning.title || 'Planning estimates','',meta.provider)+table+controls+(data.truncated?'<p class=\"notice\">Partial native response. More estimates may exist.</p>':'')+notes,'Read-only estimates');\n app.querySelectorAll('[data-planning-page]').forEach(button=>button.addEventListener('click',()=>{if(button.disabled)return;state.planningPage+=button.dataset.planningPage==='next'?1:-1;renderPlanning(data,meta);}));\n }\n function render(result) {\n cancelHold();clearTimeout(expiryTimer);trendResize?.disconnect();\n let data=resultData(result);\n if (!object(data)) data={value:data};\n const meta = data._adport || {};\n recordPages=null;\n if(providerGallery && meta.view!=='creatives' && (!providerGallery.review || meta.view!=='operation' || meta.tool!==providerGallery.review.tool || meta.accountId!==providerGallery.meta.accountId || meta.context?.project_id!==providerGallery.meta.context?.project_id)) providerGallery=null;\n syntheticResult = data.data_source === 'synthetic';\n if (data.cancelled) {\n app.innerHTML=chrome('<p class=\"notice\">'+esc(data.message || 'The host interrupted this request. Check the tool response before retrying.')+'</p>','Request interrupted');\n return;\n }\n if (result?.isError || data.error) {\n renderFailure(data,meta,meta.view==='operation');\n return;\n }\n if (meta.view === 'accounts') return renderAccounts(data,meta);\n if (meta.view === 'report') return renderReport(data,meta);\n if (meta.view === 'operation') {renderOperation(data,meta);providerGalleryReviewControls(data,meta);return;}\n if (meta.view === 'records') return renderRecords(data,meta);\n if (meta.view === 'receipt') return renderReceipt(data,meta);\n if (meta.view === 'creatives') return renderCreatives(data,meta);\n if (meta.view === 'planning') return renderPlanning(data,meta);\n if (meta.view === 'insights') return renderInsights(data,meta);\n return renderData(data,meta);\n }\n function rememberHostResult(fingerprint) {\n hostResults.add(fingerprint);\n if (hostResults.size>16) hostResults.delete(hostResults.values().next().value);\n }\n function acceptResult(result,local=false) {\n if (!result || typeof result !== 'object') return;\n const incoming=resultData(result);\n if(!local && (providerGalleryIgnoreEcho(incoming) || mediaLibraryIgnoreEcho(incoming) || recordPagesIgnoreEcho(incoming))) return;\n if(!local && (app.querySelector('[data-media-gallery]') && uploads.items.length>0 && ['media_prepare_upload','media_finalize_upload','media_get'].includes(incoming?._adport?.tool || result._meta?.adport?.tool) || mediaLibrary?.loading && incoming?._adport?.tool==='media_list' && mediaLibraryProject(incoming,incoming._adport)===mediaLibrary.project)) return;\n const fingerprint=JSON.stringify(incoming);\n // Host state updates can echo an old tool result after a local edit/apply.\n if (!local && state.hasLocalResult && hostResults.has(fingerprint)) return;\n if (local) state.hasLocalResult=true;\n else rememberHostResult(fingerprint);\n clearTimeout(resultWait);\n // ChatGPT can deliver the same result through both supported bridges.\n // Do not reset an open disclosure when the second copy arrives.\n if (state.result && JSON.stringify(state.result) === JSON.stringify(result)) return;\n state.planningPage=0;\n state.result = result;\n render(result);\n }\n function receiveGlobals(globals) {\n if (!globals) return;\n const metadata = globals.toolResponseMetadata;\n const envelope = metadata?.mcp_tool_result || metadata?.call_tool_result;\n if (envelope && typeof envelope === 'object') return acceptResult(envelope);\n if (globals.toolOutput && typeof globals.toolOutput === 'object') acceptResult({structuredContent:{...globals.toolOutput,...(metadata?.adport?{_adport:metadata.adport}:{})}});\n }\n // Some hosts mount an error result's resource but never relay its payload.\n // This is a delivery fallback, not a claim about tool execution or success.\n const resultWait = setTimeout(() => {\n if (!state.result) app.innerHTML=chrome('<p class=\"notice\">The host has not provided a result to this view. Check the tool response in the conversation. This card will update if a result arrives.</p>','Result not received');\n }, 15000);\n const send = (message) => window.parent.postMessage(message,'*');\n const resize = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(() => {\n send({jsonrpc:'2.0',method:'ui/notifications/size-changed',params:{height:Math.ceil(document.body.getBoundingClientRect().height)}});\n });\n let id = 1;\n window.addEventListener('message', (event) => {\n if (event.source !== window.parent) return;\n const message = event.data;\n if (!message || message.jsonrpc !== '2.0') return;\n if (message.id !== undefined && pendingRequests.has(message.id)) {\n const request=pendingRequests.get(message.id);\n pendingRequests.delete(message.id);\n clearTimeout(request.timer);\n if (message.error) request.reject(message.error);\n else request.resolve(message.result);\n return;\n }\n if (message.id === 1 && message.result) {\n state.host = message.result.hostContext || {};\n document.documentElement.dataset.theme = state.host.theme || '';\n send({jsonrpc:'2.0',method:'ui/notifications/initialized'});\n resize?.observe(document.body);\n if (state.result) render(state.result);\n }\n if (message.method === 'ui/notifications/tool-result') acceptResult(message.params);\n if (message.method === 'ui/notifications/tool-cancelled') acceptResult({structuredContent:{cancelled:true,message:message.params?.reason}});\n if (message.method === 'ui/notifications/host-context-changed') {\n const previousLocale = state.host.locale;\n state.host = {...state.host,...message.params};\n document.documentElement.dataset.theme = state.host.theme || '';\n // Size/theme updates must not rebuild the DOM: opening Details changes\n // the iframe height, which some hosts echo back as a context update.\n if (state.result && previousLocale !== state.host.locale) {\n const expanded = app.querySelector('details')?.open || false;\n render(state.result);\n const details = app.querySelector('details');\n if (details) details.open = expanded;\n }\n }\n });\n // The compatibility bridge can hydrate after the iframe has mounted,\n // including full error envelopes in toolResponseMetadata.\n window.addEventListener('openai:set_globals', event => receiveGlobals(event.detail?.globals));\n send({jsonrpc:'2.0',id:id++,method:'ui/initialize',params:{appInfo:{name:'Adport Insight',version:'1.0.0'},appCapabilities:{},protocolVersion:'2026-01-26'}});\n receiveGlobals(window.openai);\n })();\n </script>\n</body>\n</html>`;\n"],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,SAAS,kBAAkB;AAC3B,SAAS,SAAS;AAClB,SAAS,qBAAqB,iBAAiB,0BAA0B;AACzE,SAAS,aAAa,iBAAiB,eAAe,sBAAsB,mBAAmB,mBAAgF;AAC/K,SAAS,iBAAiB,uBAAuB;AACjD,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AACnC,SAAS,wBAAwB;AACjC,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;AAClC,SAAS,6BAA6B;AACtC,SAAS,0BAA0B;AACnC,SAAS,4BAA4B;AACrC,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AACtC,SAAS,4BAA4B;AACrC,SAAS,qBAAqB;AAC9B,SAAS,0BAA0B;;;AClBnC;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,SAAW;AAAA,EACX,MAAQ;AAAA,EACR,MAAQ;AAAA,EACR,OAAS;AAAA,EACT,SAAW;AAAA,IACT,KAAK;AAAA,MACH,OAAS;AAAA,MACT,QAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA,KAAO;AAAA,IACL,cAAc;AAAA,EAChB;AAAA,EACA,OAAS;AAAA,IACP;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,OAAS;AAAA,IACT,8BAA8B;AAAA,IAC9B,MAAQ;AAAA,IACR,WAAa;AAAA,IACb,OAAS;AAAA,EACX;AAAA,EACA,cAAgB;AAAA,IACd,gBAAgB;AAAA,IAChB,0BAA0B;AAAA,IAC1B,2BAA2B;AAAA,IAC3B,6BAA6B;AAAA,IAC7B,yBAAyB;AAAA,IACzB,8BAA8B;AAAA,IAC9B,8BAA8B;AAAA,IAC9B,2BAA2B;AAAA,IAC3B,6BAA6B;AAAA,IAC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