@adport/mcp 0.11.1 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +1 -1
- package/dist/{chunk-FVSA7WDE.js → chunk-RE4ZCAVJ.js} +757 -53
- package/dist/chunk-RE4ZCAVJ.js.map +1 -0
- package/dist/index.js +1 -1
- package/package.json +16 -16
- package/dist/chunk-FVSA7WDE.js.map +0 -1
|
@@ -22,7 +22,7 @@ import { createOpenAIModule } from "@adport/provider-openai";
|
|
|
22
22
|
// package.json
|
|
23
23
|
var package_default = {
|
|
24
24
|
name: "@adport/mcp",
|
|
25
|
-
version: "0.
|
|
25
|
+
version: "0.12.1",
|
|
26
26
|
description: "adport MCP server \u2014 the open control plane for paid media",
|
|
27
27
|
license: "Apache-2.0",
|
|
28
28
|
type: "module",
|
|
@@ -472,7 +472,7 @@ var RECORD_UI_STYLES = String.raw`
|
|
|
472
472
|
var RECORD_UI_SCRIPT = String.raw`
|
|
473
473
|
let recordPages=null;
|
|
474
474
|
function recordPagesIgnoreEcho(data) {
|
|
475
|
-
return !!recordPages?.busy && data?._adport?.view===
|
|
475
|
+
return !!recordPages?.busy && data?._adport?.view===recordPages.meta.view && galleryMatches(data._adport,recordPages.meta) && galleryScope(data._adport)===recordPages.scope;
|
|
476
476
|
}
|
|
477
477
|
function providerMarks(values,meta,label='Platforms') {
|
|
478
478
|
const providers=[...new Set(arr(values).filter(value=>typeof value==='string'&&value))];
|
|
@@ -527,13 +527,46 @@ var RECORD_UI_SCRIPT = String.raw`
|
|
|
527
527
|
const provider=nativeProvider!==meta.provider?nativeProvider:undefined;
|
|
528
528
|
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>';
|
|
529
529
|
}
|
|
530
|
+
function entityRecordTable(tool) {
|
|
531
|
+
return /^(?:google|meta|apple|microsoft|tiktok|linkedin|pinterest|reddit|snapchat|spotify|openai|x)_(?:list_)?(?:campaigns|campaign_groups|adgroups|ad_groups|ad_sets|adsets|line_items|adsquads)$/.test(tool||'');
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
function entityFields(row,meta) {
|
|
535
|
+
const item=object(row?.campaign)?row.campaign:object(row?.ad_group)?row.ad_group:row||{};
|
|
536
|
+
const name=item.name??item.Name??item.campaign_name??item.adgroup_name??item.id??item.Id;
|
|
537
|
+
const status=item.effective_status??item.status??item.Status??item.delivery_status??item.configured_status??
|
|
538
|
+
item.displayStatus??item.systemStatus??item.secondary_status??item.operation_status??item.entity_status;
|
|
539
|
+
const scope=/(?:campaigns|campaign_groups)$/.test(meta.tool)?item.account_id??item.ad_account_id??item.advertiser_id??meta.accountId:
|
|
540
|
+
item.campaign_name??item.campaign_id??item.campaignId??item.CampaignId??item.parent_id??meta.accountId;
|
|
541
|
+
const native=item.dailyBudget??item.DailyBudget??item.daily_budget??(meta.provider==='tiktok'?item.budget:undefined);
|
|
542
|
+
const daily=object(native?.value)?native.value:native;
|
|
543
|
+
const minor=meta.provider==='meta'?2:0;
|
|
544
|
+
const currency=currencyOf(item)||currencyOf({currency:item.currency_code??item.currencyCode??meta.currency});
|
|
545
|
+
const moneyField=(value,scale)=> {
|
|
546
|
+
const amount=nativeReportDecimal(object(value)?value.amount??value.Amount??value.value:value,scale);
|
|
547
|
+
return amount===null?null:amount+' '+(currencyOf(object(value)?value:{})||currency||'account units');
|
|
548
|
+
};
|
|
549
|
+
const dailyMicros=item.daily_budget_micros??item.daily_budget_amount_local_micro??item.daily_spend_cap??item.budget?.daily_spend_limit_micros;
|
|
550
|
+
const totalMicros=item.lifetime_budget_micros??item.total_budget_amount_local_micro??item.lifetime_spend_cap??item.budget?.lifetime_spend_limit_micros;
|
|
551
|
+
const value=moneyField(dailyMicros,6)??moneyField(daily,minor)??moneyField(totalMicros,6)??moneyField(item.lifetime_budget,minor)??
|
|
552
|
+
moneyField(item.bid_micros??item.bid_amount_local_micro,6)??moneyField(item.bidAmount??item.bid??item.bid_amount,minor);
|
|
553
|
+
return [name,workflowLabel(status),scope,value];
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
const entityHeaders=['Name','Status','Scope','Budget or bid'];
|
|
557
|
+
function recordEntryMarkup(row,index,meta,table) {
|
|
558
|
+
if(!table)return recordRow(row,index,meta);
|
|
559
|
+
return '<tr role="row">'+entityFields(row,meta).map((value,i)=>
|
|
560
|
+
workflowCell(entityHeaders[i],esc(workflowText(value)||(i===0?'Record '+(index+1):'—')),i===0)).join('')+'</tr>';
|
|
561
|
+
}
|
|
562
|
+
|
|
530
563
|
function renderRecordPages(message='') {
|
|
531
564
|
const pages=recordPages,area=app.querySelector('[data-record-pages]');if(!pages||!area)return;
|
|
532
565
|
const next=pages.rows.length<1000 && galleryNext(pages.meta);
|
|
533
566
|
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;
|
|
534
567
|
let button=area.querySelector('[data-record-more]');
|
|
535
568
|
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));}
|
|
536
|
-
else if(button){const focused=button===document.activeElement;button.remove();if(focused)app.querySelector('[data-record-list]')?.focus({preventScroll:true});}
|
|
569
|
+
else if(button){const focused=button===document.activeElement;button.remove();if(focused)(app.querySelector('[data-record-list]')?.closest('[role=region]'))?.focus({preventScroll:true});}
|
|
537
570
|
}
|
|
538
571
|
async function loadRecordPage() {
|
|
539
572
|
const pages=recordPages,args=pages && galleryNext(pages.meta);if(!pages||pages.busy||!args||pages.rows.length>=1000)return;
|
|
@@ -543,15 +576,16 @@ var RECORD_UI_SCRIPT = String.raw`
|
|
|
543
576
|
const response=await callTool(pages.meta.tool,args,60000),value=resultData(response),meta=value?._adport,rows=recordEntries(recordPayload(value));
|
|
544
577
|
hostResults.add(JSON.stringify(value));if(hostResults.size>16)hostResults.delete(hostResults.values().next().value);
|
|
545
578
|
if(recordPages!==pages){state.hasLocalResult=true;return;}
|
|
546
|
-
if(response?.isError||value?.error||!Array.isArray(rows)||!meta||meta.view!==
|
|
579
|
+
if(response?.isError||value?.error||!Array.isArray(rows)||!meta||meta.view!==pages.meta.view||!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.');
|
|
547
580
|
const root=app.querySelector('[data-record-list]');if(!root)return;
|
|
581
|
+
const displayMeta=currencyOf(value)?{...meta,currency:currencyOf(value)}:meta;
|
|
548
582
|
let added=0;
|
|
549
583
|
rows.forEach((row,index)=>{
|
|
550
584
|
const identity=object(row)&&(typeof row.id==='string'&&row.id||typeof row.id==='number'&&Number.isSafeInteger(row.id))?'id:'+String(row.id):key+':'+index;
|
|
551
585
|
const previous=pages.items.get(identity);
|
|
552
|
-
if(previous){if(galleryStable(previous.row)!==galleryStable(row)){const template=document.createElement('template');template.innerHTML=
|
|
586
|
+
if(previous){if(galleryStable(previous.row)!==galleryStable(row)){const template=document.createElement('template');template.innerHTML=recordEntryMarkup(row,previous.index,displayMeta,pages.table);const node=template.content.firstElementChild;previous.node.replaceWith(node);previous.node=node;previous.row=row;pages.rows[previous.index]=row;}return;}
|
|
553
587
|
if(pages.rows.length>=1000)return;
|
|
554
|
-
const template=document.createElement('template');template.innerHTML=
|
|
588
|
+
const template=document.createElement('template');template.innerHTML=recordEntryMarkup(row,pages.rows.length,displayMeta,pages.table);const node=template.content.firstElementChild;
|
|
555
589
|
pages.items.set(identity,{row,index:pages.rows.length,node});pages.rows.push(row);root.append(node);added++;
|
|
556
590
|
});
|
|
557
591
|
pages.seen.add(key);pages.meta={...meta,...(!added||pages.rows.length>=1000?{next:undefined}:{})};pages.data=value;
|
|
@@ -570,11 +604,16 @@ var RECORD_UI_SCRIPT = String.raw`
|
|
|
570
604
|
const parent=object(data.parent)?Object.entries(data.parent).filter(([key])=>/_id$/.test(key)).map(([key,value])=>human(key.replace(/_id$/,''))+' '+value).join(' · '):'';
|
|
571
605
|
const scope=[parent,typeof data.parent_id==='string'&&!parent?data.parent_id:'',meta.accountId].filter(Boolean).join(' · ');
|
|
572
606
|
const clean=object(data)?Object.fromEntries(Object.entries(data).filter(([key])=>key!=='_adport'&&!(key==='creatives'&&meta.view==='records'))):data;
|
|
573
|
-
const
|
|
607
|
+
const table=Array.isArray(entries)&&entityRecordTable(meta.tool)&&rows.every(object);
|
|
608
|
+
const displayMeta=currencyOf(data)?{...meta,currency:currencyOf(data)}:meta;
|
|
609
|
+
const markup=rows.slice(0,1000).map((row,index)=>recordEntryMarkup(row,index,displayMeta,table)).join('');
|
|
610
|
+
const content=rows.length?table?'<div class="workflow-scroll" role="region" aria-label="Returned records" tabindex="0"><table class="workflow-table workflow-stack" role="table">'+workflowHeader(entityHeaders)+
|
|
611
|
+
'<tbody data-record-list role="rowgroup">'+markup+'</tbody></table></div>':
|
|
612
|
+
'<div class="record-list" data-record-list role="region" aria-label="Returned records" tabindex="0">'+markup+'</div>':'<p class="operation-note">No results returned.</p>';
|
|
574
613
|
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>','');
|
|
575
|
-
if(
|
|
576
|
-
recordPages={scope:galleryScope(meta),meta,data,rows:rows.slice(0,1000),items:new Map(),seen:new Set([galleryStable(meta.refresh.arguments)]),busy:false};
|
|
577
|
-
const nodes=app.querySelectorAll('[data-record-list]
|
|
614
|
+
if(Array.isArray(entries)&&rows.length&&galleryNext(meta)){
|
|
615
|
+
recordPages={scope:galleryScope(meta),meta,data,table,rows:rows.slice(0,1000),items:new Map(),seen:new Set([galleryStable(meta.refresh.arguments)]),busy:false};
|
|
616
|
+
const nodes=app.querySelectorAll('[data-record-list]>*');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]});});
|
|
578
617
|
renderRecordPages();
|
|
579
618
|
}
|
|
580
619
|
}
|
|
@@ -650,15 +689,41 @@ var INSIGHT_UI_STYLES = String.raw`
|
|
|
650
689
|
.insight-action span { color:var(--muted); margin-right:5px }
|
|
651
690
|
`;
|
|
652
691
|
var INSIGHT_UI_SCRIPT = String.raw`
|
|
653
|
-
function
|
|
654
|
-
const
|
|
655
|
-
|
|
692
|
+
function appleRecommendationMoney(value) {
|
|
693
|
+
const amount=nativeReportDecimal(value?.amount),currency=currencyOf(value||{});
|
|
694
|
+
return amount===null?null:amount+' '+(currency||'account units');
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
function renderAppleRecommendations(data,meta) {
|
|
698
|
+
const items=workflowRows(data.result);
|
|
699
|
+
const recommendations=items.map(item=>{
|
|
700
|
+
const budget=item.suggestedDailyBudgetAmount!=null;
|
|
701
|
+
const current=appleRecommendationMoney(budget?item.dailyBudget:item.bidStrategy?.bidAmount);
|
|
702
|
+
const proposed=appleRecommendationMoney(budget?item.suggestedDailyBudgetAmount:item.recommendedTargetCPA);
|
|
703
|
+
const entity=item.campaignName?item.campaignName:item.campaignId!=null?'Campaign '+item.campaignId:'Apple Ads recommendation';
|
|
704
|
+
const label=budget?'Daily budget':item.recommendedTargetCPA!=null?'Target CPA':'Native recommendation';
|
|
705
|
+
return {provider:'apple',title:entity+' · '+label,detail:current?'Current '+current:'',recommendation:proposed||''};
|
|
706
|
+
});
|
|
707
|
+
const args=readPageArgs(meta,'data-recommendations-next');
|
|
708
|
+
renderInsights({...data,recommendations,truncated:false},data,
|
|
709
|
+
readPageMarkup(args,'data-recommendations-next','data-recommendations-status'));
|
|
710
|
+
bindReadPage(meta,args,'data-recommendations-next','data-recommendations-status',value=>Array.isArray(value.result));
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
function renderInsights(data,native,footer='') {
|
|
714
|
+
const items=data.finding?[data.finding]:workflowRows(data.findings||data.recommendations||data.results||data.entries);
|
|
715
|
+
const coverage=[
|
|
716
|
+
typeof data.evaluatedAccounts==='number'?data.evaluatedAccounts+' evaluated accounts':null,
|
|
717
|
+
data.range?.start&&data.range?.end?data.range.start+' – '+data.range.end:null
|
|
718
|
+
].filter(Boolean).join(' · ');
|
|
719
|
+
const body=notices(data)+workflowNote(coverage)+(items.length?'<div class="insight-list" role="region" aria-label="Recommendations" tabindex="0">'+items.map(item=>{
|
|
656
720
|
const reason=typeof item.detail==='string'?item.detail:typeof item.description==='string'?item.description:'';
|
|
657
721
|
const suggestion=typeof item.recommendation==='string'?item.recommendation:'';
|
|
722
|
+
const scope=item.accountId?'<p>Account '+esc(item.accountId)+'</p>':'';
|
|
658
723
|
const status=item.status&&item.status!=='open'?item.status:item.severity||item.status||'';
|
|
659
|
-
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>';
|
|
660
|
-
}).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>');
|
|
661
|
-
app.innerHTML=chrome(body,items.length+' recommendation'+(items.length===1?'':'s'));
|
|
724
|
+
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>'+scope+(reason?'<p class="insight-reason">'+esc(reason)+'</p>':'')+(suggestion?'<p class="insight-action"><span>Suggested</span>'+esc(suggestion)+'</p>':'')+'</article>';
|
|
725
|
+
}).join('')+'</div><details><summary>Details · '+items.length+' findings</summary><pre>'+esc(JSON.stringify(native||items,null,2))+'</pre></details>':'<div class="empty">No recommendations were returned.</div>');
|
|
726
|
+
app.innerHTML=chrome(body+footer,items.length+' recommendation'+(items.length===1?'':'s'));
|
|
662
727
|
}
|
|
663
728
|
`;
|
|
664
729
|
|
|
@@ -967,7 +1032,7 @@ var OPERATION_UI_SCRIPT = String.raw`
|
|
|
967
1032
|
if (!object(value) || depth>8) return [];
|
|
968
1033
|
return Object.entries(value).filter(([key])=>!['_adport','data_source','pending_operation_id'].includes(key)).flatMap(([key,item])=>{
|
|
969
1034
|
const path=prefix?prefix+'.'+key:key;
|
|
970
|
-
return object(item)?dataFields(item,path,depth+1):[{label:human(path),after:item}];
|
|
1035
|
+
return object(item)?dataFields(item,path,depth+1):[{path,label:human(path),after:item}];
|
|
971
1036
|
});
|
|
972
1037
|
}
|
|
973
1038
|
function valueHTML(value,compact=false) {
|
|
@@ -1224,6 +1289,118 @@ var APPLE_REPORT_UI_SCRIPT = String.raw`
|
|
|
1224
1289
|
}
|
|
1225
1290
|
`;
|
|
1226
1291
|
|
|
1292
|
+
// src/gaql-report-ui.ts
|
|
1293
|
+
var GAQL_REPORT_UI = String.raw`
|
|
1294
|
+
const gaqlEntities = new Map([
|
|
1295
|
+
['searchTermView.searchTerm', 'Search term'], ['campaignSearchTermView.searchTerm', 'Search term'],
|
|
1296
|
+
['adGroupCriterion.keyword.text', 'Keyword'], ['segments.keyword.info.text', 'Keyword'],
|
|
1297
|
+
['adGroupAd.ad.name', 'Ad'], ['adGroupAd.ad.id', 'Ad ID'],
|
|
1298
|
+
['asset.name', 'Asset'], ['asset.id', 'Asset ID'], ['assetGroup.name', 'Asset group'], ['assetGroup.id', 'Asset group ID'],
|
|
1299
|
+
['adGroup.name', 'Ad group'], ['adGroup.id', 'Ad group ID'], ['campaign.name', 'Campaign'], ['campaign.id', 'Campaign ID'],
|
|
1300
|
+
['customer.descriptiveName', 'Account'], ['customer.id', 'Account ID']
|
|
1301
|
+
]);
|
|
1302
|
+
|
|
1303
|
+
function gaqlDimensions(row) {
|
|
1304
|
+
const {metrics, ...dimensions} = row;
|
|
1305
|
+
return new Map(dataFields(dimensions)
|
|
1306
|
+
.filter(({path, after}) => after != null && !Array.isArray(after) && String(after).trim() &&
|
|
1307
|
+
!/(?:currency(?:_?code)?$|token|secret|password|authorization)/i.test(path))
|
|
1308
|
+
.map(({path, after}) => [path, String(after)]));
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
function gaqlDimensionLabel(path) {
|
|
1312
|
+
if (gaqlEntities.has(path)) return gaqlEntities.get(path);
|
|
1313
|
+
if (path.endsWith('.keyword.matchType') || path.endsWith('.keyword.info.matchType')) return 'Match type';
|
|
1314
|
+
return human(human(path.replace(/^segments\./, '')).toLowerCase()).replace(/\bid\b/i, 'ID');
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
const gaqlMoneyFormats = new Map();
|
|
1318
|
+
function gaqlAmount(amount, currency) {
|
|
1319
|
+
const locale = state.host.locale || 'en', key = locale + '/' + (currency || '');
|
|
1320
|
+
if (!gaqlMoneyFormats.has(key)) {
|
|
1321
|
+
const digits = currency ? new Intl.NumberFormat(locale, {style:'currency', currency}).resolvedOptions().maximumFractionDigits : 2;
|
|
1322
|
+
gaqlMoneyFormats.set(key, {
|
|
1323
|
+
format: new Intl.NumberFormat(locale, {minimumFractionDigits:digits, maximumFractionDigits:digits}),
|
|
1324
|
+
unit: 10 ** -digits
|
|
1325
|
+
});
|
|
1326
|
+
}
|
|
1327
|
+
const {format, unit} = gaqlMoneyFormats.get(key);
|
|
1328
|
+
if (Number(amount) !== 0 && Math.abs(Number(amount)) < unit) {
|
|
1329
|
+
return Number(amount) < 0 ? '>' + format.format(-unit) : '<' + format.format(unit);
|
|
1330
|
+
}
|
|
1331
|
+
return format.format(amount);
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
function gaqlHasTrend(points, dimensions, paths) {
|
|
1335
|
+
// A dated series must refer to the same returned entity and breakdown on every date.
|
|
1336
|
+
if (points.length > 366 || new Set(points.map(point => point.date)).size < 2) return false;
|
|
1337
|
+
const series = new Map(), observations = new Set();
|
|
1338
|
+
const seriesPaths = paths.filter(path => path !== 'segments.date');
|
|
1339
|
+
return points.every((point, i) => {
|
|
1340
|
+
if (!point.date) return false;
|
|
1341
|
+
const identity = JSON.stringify(seriesPaths.map(path => dimensions[i].get(path)));
|
|
1342
|
+
const observation = JSON.stringify([point.series, point.date]);
|
|
1343
|
+
if (observations.has(observation) || (series.has(point.series) && series.get(point.series) !== identity)) return false;
|
|
1344
|
+
observations.add(observation);
|
|
1345
|
+
series.set(point.series, identity);
|
|
1346
|
+
return true;
|
|
1347
|
+
}) && series.size <= 3;
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
function gaqlReportTable(records, points) {
|
|
1351
|
+
const dimensions = records.map(record => record?.gaqlDimensions || new Map());
|
|
1352
|
+
const paths = [...new Set(dimensions.flatMap(row => [...row.keys()]))];
|
|
1353
|
+
const fields = [...new Set(points.flatMap(row => row.fields.map(field => field.key)))];
|
|
1354
|
+
const first = records[0];
|
|
1355
|
+
const commonEntity = first?.gaqlEntity && records.every(row => row?.gaqlEntity === first.gaqlEntity);
|
|
1356
|
+
if (points.length <= 8 && fields.length === 1 && commonEntity && !points.some(point => point.date) &&
|
|
1357
|
+
new Set(points.map(point => point.name)).size === points.length) return null;
|
|
1358
|
+
const monetary = fields.some(key => nativeReportMoneyField(key, 'google'));
|
|
1359
|
+
const currencies = new Set(records.map(row => row?.currency || ''));
|
|
1360
|
+
if ((!monetary || currencies.size === 1) && gaqlHasTrend(points, dimensions, paths)) return null;
|
|
1361
|
+
|
|
1362
|
+
const varies = path => dimensions.some(row => row.get(path) !== dimensions[0].get(path));
|
|
1363
|
+
const varying = paths.filter(varies);
|
|
1364
|
+
const identifiers = [...gaqlEntities.keys()].filter(path => varying.includes(path));
|
|
1365
|
+
const names = identifiers.filter(path => !path.endsWith('.id'));
|
|
1366
|
+
const columns = [...new Set([...names, ...identifiers, ...varying])].filter(path => !path.endsWith('.resourceName'));
|
|
1367
|
+
const distinct = keys => new Set(dimensions.map(row => JSON.stringify(keys.map(key => row.get(key))))).size;
|
|
1368
|
+
let identities = distinct(columns);
|
|
1369
|
+
for (const path of varying.filter(path => path.endsWith('.resourceName'))) {
|
|
1370
|
+
const withResource = distinct([...columns, path]);
|
|
1371
|
+
if (withResource > identities) { columns.push(path); identities = withResource; }
|
|
1372
|
+
}
|
|
1373
|
+
const primary = columns.shift() ?? (records.length === 1 ? first?.gaqlEntity : undefined);
|
|
1374
|
+
const metrics = fields.sort((a, b) => reportMetricPriority(a) - reportMetricPriority(b));
|
|
1375
|
+
const mixed = monetary && currencies.size > 1;
|
|
1376
|
+
const currency = currencies.size === 1 ? first?.currency : null;
|
|
1377
|
+
const headers = [primary ? gaqlDimensionLabel(primary) : 'Row', ...metrics.map(key =>
|
|
1378
|
+
nativeReportLabel(key) + (currency && nativeReportMoneyField(key, 'google') ? ' · ' + currency : '')),
|
|
1379
|
+
...(mixed ? ['Currency'] : []), ...columns.map(gaqlDimensionLabel)];
|
|
1380
|
+
const values = points.map((point, i) => [
|
|
1381
|
+
primary ? dimensions[i].get(primary) : i + 1,
|
|
1382
|
+
...metrics.map(key => {
|
|
1383
|
+
const field = point.fields.find(field => field.key === key);
|
|
1384
|
+
return field?.shortDisplay ?? field?.display;
|
|
1385
|
+
}),
|
|
1386
|
+
...(mixed ? [records[i]?.currency] : []), ...columns.map(path => dimensions[i].get(path))
|
|
1387
|
+
]);
|
|
1388
|
+
const scope = paths.filter(path => path !== primary && !varying.includes(path) &&
|
|
1389
|
+
(gaqlEntities.has(path) || path.startsWith('segments.')) &&
|
|
1390
|
+
!(path.endsWith('.id') && paths.includes(path.slice(0, -2) + 'name')))
|
|
1391
|
+
.map(path => gaqlEntities.has(path) && !path.endsWith('.id') ? dimensions[0].get(path) :
|
|
1392
|
+
gaqlDimensionLabel(path) + ' ' + dimensions[0].get(path));
|
|
1393
|
+
if (monetary && currencies.has('')) scope.push('Currency unavailable');
|
|
1394
|
+
return {
|
|
1395
|
+
title: gaqlEntities.has(primary) ? gaqlDimensionLabel(primary).replace(/ ID$/, '') + ' performance' : 'Google Ads query results',
|
|
1396
|
+
subject: [...new Set(scope)].join(' · '),
|
|
1397
|
+
html: (identities < records.length ?
|
|
1398
|
+
workflowNote('Some rows have identical labels. Include a more specific name, ID or segment to distinguish them.') : '') +
|
|
1399
|
+
workflowTable(headers, values, 'Google Ads query results')
|
|
1400
|
+
};
|
|
1401
|
+
}
|
|
1402
|
+
`;
|
|
1403
|
+
|
|
1227
1404
|
// src/native-report-ui.ts
|
|
1228
1405
|
var NATIVE_REPORT_TOOLS = [
|
|
1229
1406
|
"ga4_report",
|
|
@@ -1247,6 +1424,7 @@ var NATIVE_REPORT_UI_STYLES = String.raw`
|
|
|
1247
1424
|
`;
|
|
1248
1425
|
var NATIVE_REPORT_UI_SCRIPT = String.raw`
|
|
1249
1426
|
const nativeReportTools=new Set(${JSON.stringify(NATIVE_REPORT_TOOLS)});
|
|
1427
|
+
${GAQL_REPORT_UI}
|
|
1250
1428
|
function nativeReportDecimal(value,scale=0) {
|
|
1251
1429
|
const text=typeof value==='number'&&Number.isFinite(value)?String(value):typeof value==='string'?value:'';
|
|
1252
1430
|
if(!/^-?\d+(?:\.\d+)?$/.test(text))return null;
|
|
@@ -1259,7 +1437,7 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
|
|
|
1259
1437
|
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'};
|
|
1260
1438
|
return known[key]||known[key.toLowerCase()]||human(human(key).toLowerCase());
|
|
1261
1439
|
}
|
|
1262
|
-
function nativeReportRatio(key,provider) {return provider==='gsc'&&key==='ctr'||provider==='ga4'&&!key.includes(':')&&/Rate$/.test(key);}
|
|
1440
|
+
function nativeReportRatio(key,provider) {return (provider==='gsc'||provider==='google')&&key==='ctr'||provider==='ga4'&&!key.includes(':')&&/Rate$/.test(key);}
|
|
1263
1441
|
function nativeReportMetric(key,value,provider,currency,moneyFields=[]) {
|
|
1264
1442
|
if(key==='costInUsd')currency='USD';
|
|
1265
1443
|
const lower=key.toLowerCase(),decimal=nativeReportDecimal(value);
|
|
@@ -1292,7 +1470,9 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
|
|
|
1292
1470
|
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'];
|
|
1293
1471
|
const ids=['ad_id','adgroup_id','adset_id','campaign_id','advertiser_id','account_id','entity_id','id','GoalId','urn'];
|
|
1294
1472
|
const first=(keys,sources)=>keys.flatMap(key=>sources.map(source=>source[key])).find(value=>(typeof value==='string'&&value.trim())||typeof value==='number');
|
|
1295
|
-
const
|
|
1473
|
+
const googleDimensions=provider==='google'?gaqlDimensions(row):null;
|
|
1474
|
+
const googleEntity=googleDimensions&&[...gaqlEntities.keys()].find(path=>googleDimensions.has(path));
|
|
1475
|
+
const googleName=googleDimensions?.get(googleEntity);
|
|
1296
1476
|
const bucket=dimensions.conversionLagBucket??dimensions.conversionOrAdjustmentLagBucket;
|
|
1297
1477
|
const analyticsName=['ga4','gsc'].includes(provider)?Object.values(dimensions).filter(value=>typeof value==='string'&&value).join(' · '):null;
|
|
1298
1478
|
const name=bucket?reportBucket(bucket):googleName??analyticsName??first(names,[row,metrics,dimensions]) ?? first(ids,[row,dimensions]) ?? (provider==='google'?'Report':'Result '+(index+1));
|
|
@@ -1313,7 +1493,7 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
|
|
|
1313
1493
|
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;
|
|
1314
1494
|
fields.sort((a,b)=>priority(a[0])-priority(b[0]));
|
|
1315
1495
|
const moneyFields=provider==='ga4'?arr(payload.metric_headers).filter(header=>header.type==='TYPE_CURRENCY').map(header=>header.name):[];
|
|
1316
|
-
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)};
|
|
1496
|
+
return {name,status,context,currency,moneyFields,provider,fields,gaqlDimensions:googleDimensions,gaqlEntity:googleEntity,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)};
|
|
1317
1497
|
}
|
|
1318
1498
|
function nativeChartRecord(record) {
|
|
1319
1499
|
if(!record)return {name:'Unavailable row',context:[],fields:[]};
|
|
@@ -1322,7 +1502,9 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
|
|
|
1322
1502
|
const ratio=nativeReportRatio(key,record.provider);
|
|
1323
1503
|
const value=record.provider==='spotify'&&String(raw)==='-5'?null:reportNumber(monetary?scaled:raw);
|
|
1324
1504
|
const display=nativeReportMetric(key,raw,record.provider,record.currency,record.moneyFields);
|
|
1325
|
-
|
|
1505
|
+
const googleMoney=record.provider==='google'&&monetary;
|
|
1506
|
+
const shortDisplay=googleMoney&&scaled!==null?gaqlAmount(scaled,record.currency):undefined;
|
|
1507
|
+
return {key,label:key==='costInLocalCurrency'?'Spend':key==='costInUsd'?'Spend · USD':nativeReportLabel(key),value:ratio&&value!==null?value*100:value,display,shortDisplay,unit:ratio?'%':monetary?key==='costInUsd'?'USD':record.currency||(googleMoney?'Currency unavailable':'Account units'):''};
|
|
1326
1508
|
});
|
|
1327
1509
|
const low=record.native.lowImpressionShare,high=record.native.highImpressionShare;
|
|
1328
1510
|
const range=record.provider==='apple'&&[low,high].every(value=>typeof value==='number'&&Number.isFinite(value)&&value>=0&&value<=1)&&low<=high?[low,high]:undefined;
|
|
@@ -1345,21 +1527,527 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
|
|
|
1345
1527
|
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('');
|
|
1346
1528
|
const missingGoals=arr(data.not_returned_goal_ids).filter(id=>!arr(data.errors).some(error=>error?.goal_id===id&&error?.error_code));
|
|
1347
1529
|
const absent=missingGoals.length?'<p class="notice">No summary returned for goal'+(missingGoals.length===1?'':'s')+' '+missingGoals.map(esc).join(', ')+'.</p>':'';
|
|
1348
|
-
const records=entries.slice(0,1000).map((row,index)=>nativeReportRecord(row,index,meta,payload)),delay=provider==='google'&&entries.some(row=>row
|
|
1349
|
-
const pageArgs=['ga4_report','gsc_search_analytics'].includes(meta.tool)?
|
|
1350
|
-
const
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
const
|
|
1530
|
+
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);
|
|
1531
|
+
const pageArgs=['ga4_report','gsc_search_analytics'].includes(meta.tool)?readPageArgs(meta,'data-report-next'):null;
|
|
1532
|
+
const points=records.map(nativeChartRecord);
|
|
1533
|
+
const table=provider==='google'&&!delay&&entries.length?gaqlReportTable(records,points):null;
|
|
1534
|
+
const entity=records[0]?.gaqlEntity;
|
|
1535
|
+
const dimension=entity&&records.every(row=>row?.gaqlEntity===entity)?gaqlEntities.get(entity).toLowerCase():undefined;
|
|
1536
|
+
const chart=table?null:reportCharts(points,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'}:{dimension});
|
|
1537
|
+
const analytics=['ga4','gsc'].includes(provider),range=payload?.date_range;
|
|
1538
|
+
const period=analytics&&object(range)?[range.start_date??range.start,range.end_date??range.end].filter(workflowText).join(' – '):'';
|
|
1539
|
+
const subject=table?.subject||(analytics?[meta.accountId,period].filter(Boolean).join(' · '):'');
|
|
1540
|
+
const body=table?.html||(entries.length?chart.html:'<p class="operation-note">'+missing+'</p>');
|
|
1541
|
+
app.innerHTML=chrome(operationHeader(table?.title||(delay?'Conversion delay':title),subject,provider)+notices({...data,...(meta.tool==='linkedin_demographic_report'?{notes:[]}:{}),errors:arr(data.errors).filter(error=>!error?.error_code)})+errors+absent+'<section data-native-report data-read-page-focus tabindex="-1">'+body+(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>':'')+readPageMarkup(pageArgs,'data-report-next','data-report-page-status')+'<details class="report-data"><summary>Details · '+entries.length+' results</summary>'+(!table&&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>',table?entries.length+(entries.length===1?' row':' rows'):'');
|
|
1542
|
+
chart?.mount();
|
|
1543
|
+
bindReadPage(meta,pageArgs,'data-report-next','data-report-page-status',value=>Array.isArray(recordPayload(value)?.rows));
|
|
1544
|
+
}
|
|
1545
|
+
`;
|
|
1546
|
+
|
|
1547
|
+
// src/workflow-ui.ts
|
|
1548
|
+
import { MEDIA_PREPARATION_TOOLS, MEDIA_UPLOAD_TOOLS } from "@adport/core";
|
|
1549
|
+
var WORKFLOW_UI_STYLES = String.raw`
|
|
1550
|
+
.workflow-list { display:grid; gap:0; max-height:430px; overflow:auto; scrollbar-width:thin }
|
|
1551
|
+
.workflow-item { min-width:0; padding:10px 0; border-bottom:1px solid var(--line); overflow-wrap:anywhere }
|
|
1552
|
+
.workflow-item h3 { margin:0; font-size:12px }
|
|
1553
|
+
.workflow-heading { display:flex; align-items:baseline; justify-content:space-between; flex-wrap:wrap; gap:8px }
|
|
1554
|
+
.workflow-item p { margin:5px 0 0; color:var(--muted); font-size:11px; line-height:1.55 }
|
|
1555
|
+
.workflow-item .record-fields { margin-top:6px }
|
|
1556
|
+
.workflow-item .media-button { margin-top:8px }
|
|
1557
|
+
.workflow-timeline { list-style:none; padding-left:12px; border-left:1px solid var(--line) }
|
|
1558
|
+
.workflow-arms { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,200px),1fr)); gap:12px }
|
|
1559
|
+
.workflow-scroll { overflow:auto; max-height:430px; scrollbar-width:thin; margin-top:8px }
|
|
1560
|
+
.workflow-table { width:100%; border-collapse:collapse; font-size:11px }
|
|
1561
|
+
.workflow-table th,.workflow-table td { padding:8px; border-bottom:1px solid var(--line); text-align:left; overflow-wrap:anywhere }
|
|
1562
|
+
.workflow-table thead th { position:sticky; top:0; z-index:1; background:var(--paper); color:var(--muted); font-weight:500 }
|
|
1563
|
+
.workflow-table tbody th { font-weight:600 }
|
|
1564
|
+
.workflow-link { color:var(--ink); text-underline-offset:2px }
|
|
1565
|
+
.workflow-cell-label { display:none }
|
|
1566
|
+
:root[data-theme="dark"] .workflow-item .pill:not(.neutral):not(.warn) { color:#70c9a1 }
|
|
1567
|
+
:root[data-theme="dark"] .workflow-item .pill.warn { color:#f0bb67 }
|
|
1568
|
+
@media (max-width:480px) {
|
|
1569
|
+
.workflow-stack,.workflow-stack tbody,.workflow-stack tr { display:block }
|
|
1570
|
+
.workflow-stack thead { position:absolute; width:1px; height:1px; overflow:hidden; clip-path:inset(50%) }
|
|
1571
|
+
.workflow-stack tbody tr { border-bottom:1px solid var(--line); padding:7px 0 }
|
|
1572
|
+
.workflow-stack tbody :is(td,th) { display:grid; grid-template-columns:minmax(88px,2fr) minmax(0,3fr); gap:8px; padding:4px 0; border:0 }
|
|
1573
|
+
.workflow-cell-label { display:block; color:var(--muted); font-weight:400 }
|
|
1574
|
+
.workflow-cell-label::before { content:attr(data-label) }
|
|
1575
|
+
}
|
|
1576
|
+
`;
|
|
1577
|
+
var WORKFLOW_UI = String.raw`
|
|
1578
|
+
const uploadPreviewTools=new Set(${JSON.stringify([...MEDIA_UPLOAD_TOOLS])});
|
|
1579
|
+
const preparePreviewTools=new Set(${JSON.stringify([...MEDIA_PREPARATION_TOOLS])});
|
|
1580
|
+
const workflowRows=value=>arr(value).filter(object);
|
|
1581
|
+
const workflowText=value=>typeof value==='string'&&value.trim()?value:typeof value==='number'&&Number.isFinite(value)?String(value):'';
|
|
1582
|
+
const workflowLabel=value=>workflowText(value)?human(String(value).replace(/^[A-Z][A-Z0-9_]+$/,word=>word.toLowerCase())):'';
|
|
1583
|
+
const workflowNote=value=>workflowText(value)?'<p class="operation-note">'+esc(value)+'</p>':'';
|
|
1584
|
+
const workflowEmpty=value=>'<p class="empty">'+esc(value)+'</p>';
|
|
1585
|
+
const workflowDetails=data=>'<details><summary>Details</summary><pre>'+esc(JSON.stringify(Object.fromEntries(Object.entries(data).filter(([key])=>key!=='_adport')),null,2))+'</pre></details>';
|
|
1586
|
+
|
|
1587
|
+
function workflowFields(pairs) {
|
|
1588
|
+
const fields=pairs.filter(([,value])=>workflowText(value));
|
|
1589
|
+
return fields.length?'<dl class="record-fields">'+fields.map(([label,value])=>'<div><dt>'+esc(label)+'</dt><dd>'+esc(value)+'</dd></div>').join('')+'</dl>':'';
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
function workflowItem(title,status,body,tag='article',tone='neutral') {
|
|
1593
|
+
return '<'+tag+' class="workflow-item"><div class="workflow-heading"><h3><strong>'+esc(title)+'</strong></h3>'+
|
|
1594
|
+
(status?'<span class="pill '+tone+'">'+esc(status)+'</span>':'')+'</div>'+body+'</'+tag+'>';
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
function workflowHeader(labels) {
|
|
1598
|
+
return '<thead role="rowgroup"><tr role="row">'+labels.map(label=>
|
|
1599
|
+
'<th role="columnheader" scope="col">'+esc(label)+'</th>').join('')+'</tr></thead>';
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
function workflowCell(label,html,heading=false) {
|
|
1603
|
+
const tag=heading?'th':'td',role=heading?'rowheader':'cell';
|
|
1604
|
+
return '<'+tag+' role="'+role+'"'+(heading?' scope="row"':'')+'>'+
|
|
1605
|
+
'<span class="workflow-cell-label" aria-hidden="true" data-label="'+esc(label)+'"></span><span>'+html+'</span></'+tag+'>';
|
|
1606
|
+
}
|
|
1607
|
+
|
|
1608
|
+
function workflowTable(labels,rows,description) {
|
|
1609
|
+
if(!rows.length)return '';
|
|
1610
|
+
return '<div class="workflow-scroll" role="region" aria-label="'+esc(description)+'" tabindex="0">'+
|
|
1611
|
+
'<table class="workflow-table workflow-stack" role="table">'+workflowHeader(labels)+'<tbody role="rowgroup">'+
|
|
1612
|
+
rows.map(row=>'<tr role="row">'+row.map((value,i)=>workflowCell(labels[i],esc(workflowText(value)||'—'),i===0)).join('')+'</tr>').join('')+
|
|
1613
|
+
'</tbody></table></div>';
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
function workflowUrl(value) {
|
|
1617
|
+
try {
|
|
1618
|
+
const parsed=new URL(value);
|
|
1619
|
+
return parsed.protocol==='https:'&&!parsed.username&&!parsed.password?parsed.href:null;
|
|
1620
|
+
} catch {return null;}
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
function workflowLink(url,label,attribute='') {
|
|
1624
|
+
return url?'<p class="operation-note"><a class="workflow-link" '+attribute+' href="'+esc(url)+'" target="_blank" rel="noreferrer noopener">'+esc(label)+'</a></p>':'';
|
|
1625
|
+
}
|
|
1626
|
+
|
|
1627
|
+
function workflowList(body,label) {
|
|
1628
|
+
return '<div class="workflow-list" role="region" aria-label="'+esc(label)+'" tabindex="0">'+body+'</div>';
|
|
1629
|
+
}
|
|
1630
|
+
|
|
1631
|
+
function workflowDate(value) {
|
|
1632
|
+
if(typeof value!=='string'||!Number.isFinite(Date.parse(value)))return null;
|
|
1633
|
+
return value;
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
function workflowMillis(value) {
|
|
1637
|
+
return typeof value==='number'&&Number.isFinite(new Date(value).getTime())?new Date(value).toISOString():null;
|
|
1638
|
+
}
|
|
1639
|
+
|
|
1640
|
+
function renderAvailability(data,meta) {
|
|
1641
|
+
const settings=workflowUrl(data.manage_access_url);
|
|
1642
|
+
const access=settings&&new URL(settings).pathname==='/dashboard/agents'?settings:null;
|
|
1643
|
+
const tools=workflowRows(data.tools);
|
|
1644
|
+
const matches=typeof data.total_matches==='number'?data.total_matches:tools.length;
|
|
1645
|
+
const coverage=workflowRows(data.platforms).filter(platform=>platform.selected===true);
|
|
1646
|
+
const rows=tools.map(item=>workflowItem(item.name||'Tool',item.enabled===true?'Ready':item.enabled===false?'Blocked':'Status unavailable',
|
|
1647
|
+
workflowFields([['Platform',providerName(item.provider,meta.providerNames)],['Access',item.read_only===true?'Read-only':item.read_only===false?'Requires write access':null]])+
|
|
1648
|
+
(item.description?'<p>'+esc(item.description)+'</p>':'')+
|
|
1649
|
+
(item.enabled===false?'<p>'+arr(item.blockers).map(workflowLabel).filter(Boolean).map(esc).join(' · ')+'</p>'+
|
|
1650
|
+
arr(item.next_steps).filter(workflowText).map(step=>'<p>'+esc(step)+'</p>').join(''):''),
|
|
1651
|
+
'article',item.enabled===true?'':item.enabled===false?'warn':'neutral')).join('');
|
|
1652
|
+
const total=(data.truncated?tools.length+' of '+matches:matches)+' matching '+(matches===1?'tool':'tools');
|
|
1653
|
+
const platformDetails=coverage.length?'<details><summary>Selected platforms</summary>'+workflowFields(coverage.map(platform=>[providerName(platform.id,meta.providerNames),platform.connected===true?'Connected':platform.connected===false?'Connection required':'Status unavailable']))+'</details>':'';
|
|
1654
|
+
app.innerHTML=chrome(operationHeader('Tool availability','')+(rows?workflowList(rows,'Matching tools'):workflowEmpty('No matching tools were returned.'))+
|
|
1655
|
+
workflowLink(access,'Manage tool access ↗')+workflowNote(data.profile?'Connection profile · '+workflowLabel(data.profile):'')+platformDetails+workflowDetails(data),total);
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1658
|
+
function measurementTable(data,tool) {
|
|
1659
|
+
switch(tool) {
|
|
1660
|
+
case 'reddit_pixel_last_fired': {
|
|
1661
|
+
const pairs=Object.entries(object(data.last_fired_at)?data.last_fired_at:{});
|
|
1662
|
+
return workflowTable(['Event','Last received'],pairs.map(([event,time])=>[workflowLabel(event),workflowDate(time)||'Unavailable']),'Pixel event activity');
|
|
1663
|
+
}
|
|
1664
|
+
case 'pinterest_event_quality':
|
|
1665
|
+
return workflowList(workflowRows(data.items).map(item=>{
|
|
1666
|
+
const components=Object.entries(item.quality_components||{}).flatMap(([component,events])=>
|
|
1667
|
+
Object.entries(events||{}).map(([event,result])=>[
|
|
1668
|
+
workflowLabel(component)+' · '+workflowLabel(event),result?.coverage,result?.overlap,
|
|
1669
|
+
workflowRows(result?.issues).map(issue=>[issue.name,issue.reason].filter(workflowText).join(' · ')).filter(Boolean).join(' | ')
|
|
1670
|
+
]));
|
|
1671
|
+
return workflowItem(workflowLabel(item.source_platform)||'Source',workflowLabel(item.overall_status),
|
|
1672
|
+
workflowFields([['Source',workflowLabel(item.ingestion_source)],['Lookback',item.lookback_period]])+
|
|
1673
|
+
workflowTable(['Component and event','Coverage','Overlap','Issues'],components,'Event quality components'));
|
|
1674
|
+
}).join(''),'Source diagnostics');
|
|
1675
|
+
case 'openai_conversion_events':
|
|
1676
|
+
return workflowTable(['Event','Channel','Event time','Received'],workflowRows(data.events).map(item=>[
|
|
1677
|
+
item.event_type ?? item.event_name,item.api_channel,workflowDate(item.event_time),workflowDate(item.received_at)
|
|
1678
|
+
]),'Sampled events');
|
|
1679
|
+
case 'tiktok_pixel_event_stats':
|
|
1680
|
+
return workflowTable(['Pixel','Event','Reported count','Last activity'],workflowRows(data.list).map(item=>[
|
|
1681
|
+
item.pixel_name ?? item.pixel_id,item.event_name ?? item.event_type ?? item.event,
|
|
1682
|
+
item.event_count ?? item.count,workflowDate(item.last_event_time ?? item.last_fired_at)
|
|
1683
|
+
]),'Pixel observations');
|
|
1684
|
+
case 'spotify_dataset_diagnostics':
|
|
1685
|
+
return workflowList(workflowRows(data.datasources).map(source=>workflowItem(source.datasource_id,workflowLabel(source.datasource_type),
|
|
1686
|
+
workflowFields([['Interval',workflowLabel(source.granularity)]])+
|
|
1687
|
+
workflowTable(['Interval start','Event','Count','Last activity'],workflowRows(source.timeseries).flatMap(bucket=>{
|
|
1688
|
+
const time=workflowMillis(bucket.timestamp);
|
|
1689
|
+
const events=workflowRows(bucket.event_counts);
|
|
1690
|
+
return events.length?events.map(event=>[time,event.name,event.event_count,workflowMillis(event.last_activity_ms)]):[[time,'All reported events',bucket.total,null]];
|
|
1691
|
+
}),'Reported activity')
|
|
1692
|
+
)).join(''),'Dataset sources');
|
|
1693
|
+
default:return '';
|
|
1694
|
+
}
|
|
1695
|
+
}
|
|
1696
|
+
|
|
1697
|
+
function renderMeasurement(data,meta) {
|
|
1698
|
+
const tool=meta.tool,period=data.date_range;
|
|
1699
|
+
const subject=[data.pixel_id?'Pixel '+data.pixel_id:null,data.dataset_id?'Dataset '+data.dataset_id:null,
|
|
1700
|
+
object(period)?[period.start_date??period.start,period.end_date??period.end].filter(workflowText).join(' – '):period].filter(workflowText).join(' · ');
|
|
1701
|
+
let body=measurementTable(data,tool);
|
|
1702
|
+
if(tool==='meta_custom_conversion_stats') {
|
|
1703
|
+
const rows=workflowRows(data.stats).flatMap(bucket=>workflowRows(bucket.data).map(entry=>({
|
|
1704
|
+
date:workflowDate(bucket.timestamp),entry
|
|
1705
|
+
})));
|
|
1706
|
+
// Named, explicitly numeric metrics are charted per native series. Bucket
|
|
1707
|
+
// payloads remain separate even if multiple series report the same date.
|
|
1708
|
+
const records=rows.map(({date,entry},i)=>{
|
|
1709
|
+
const group=Object.entries(entry).filter(([key,value])=>typeof value==='string'&&!/^(count|value)$/i.test(key)&&reportNumber(value)===null).map(([,value])=>value).join(' · ');
|
|
1710
|
+
const measure=entry.count??(/^(?:count|unmatched_count|usd_amount|unmatched_usd_amount)$/.test(data.aggregation)?entry.value:null);
|
|
1711
|
+
const count=reportNumber(measure);
|
|
1712
|
+
const unit=/_usd_amount$|^usd_amount$/.test(data.aggregation)?'USD':'';
|
|
1713
|
+
const label=unit?'Reported amount':data.aggregation==='unmatched_count'?'Unmatched count':'Reported count';
|
|
1714
|
+
return {date:date?.slice(0,10),name:date||'Bucket '+(i+1),series:group||'Reported count',context:group?[group]:[],
|
|
1715
|
+
fields:count===null?[]:[{key:'count',label,unit,value:count,display:String(measure)}]};
|
|
1716
|
+
}).filter(row=>row.fields.length);
|
|
1717
|
+
const periods=new Set(records.map(row=>row.date).filter(Boolean));
|
|
1718
|
+
const chart=periods.size>1&&records.every(row=>row.date)&&
|
|
1719
|
+
new Set(records.map(row=>JSON.stringify([row.date,row.series]))).size===records.length?reportCharts(records,{metric:'count'}):null;
|
|
1720
|
+
const args=readPageArgs(meta,'data-measurement-next');
|
|
1721
|
+
body=(chart?.html||'')+workflowTable(['Timestamp','Native values'],workflowRows(data.stats).map(bucket=>[
|
|
1722
|
+
bucket.timestamp,workflowRows(bucket.data).map(entry=>Object.entries(entry).filter(([,val])=>workflowText(val)).map(([key,val])=>workflowLabel(key)+' '+val).join(' · ')).filter(Boolean).join(' | ')
|
|
1723
|
+
]),'Native conversion buckets')+readPageMarkup(args,'data-measurement-next','data-measurement-status');
|
|
1724
|
+
app.innerHTML=chrome(operationHeader('Conversion statistics',[data.conversion_id?'Conversion '+data.conversion_id:null,workflowLabel(data.aggregation),
|
|
1725
|
+
[meta.refresh?.arguments?.start_time,meta.refresh?.arguments?.end_time].filter(workflowText).join(' – ')].filter(Boolean).join(' · '),meta.provider)+notices(data)+(body||workflowEmpty('No conversion statistics were returned.'))+workflowDetails(data),'');
|
|
1726
|
+
chart?.mount();
|
|
1727
|
+
bindReadPage(meta,args,'data-measurement-next','data-measurement-status',value=>Array.isArray(value.stats));
|
|
1728
|
+
return;
|
|
1729
|
+
}
|
|
1730
|
+
const hasRows=tool==='pinterest_event_quality'?workflowRows(data.items).length:tool==='spotify_dataset_diagnostics'?workflowRows(data.datasources).length:true;
|
|
1731
|
+
app.innerHTML=chrome(operationHeader('Measurement health',subject,meta.provider)+notices(data)+
|
|
1732
|
+
(tool==='openai_conversion_events'?workflowNote('Recent event sample. Counts cover the rows shown. (Sample size: '+arr(data.events).length+')'):'')+
|
|
1733
|
+
(body&&hasRows?body:workflowEmpty('No matching observations were returned.'))+workflowDetails(data),'');
|
|
1734
|
+
}
|
|
1735
|
+
|
|
1736
|
+
function renderHistory(data,meta) {
|
|
1737
|
+
const args=readPageArgs(meta,'data-history-next');
|
|
1738
|
+
const events=workflowRows(Array.isArray(data.result)?data.result:data.events);
|
|
1739
|
+
const ordered=[...events].sort((a,b)=>(Date.parse(b.eventTime)||0)-(Date.parse(a.eventTime)||0));
|
|
1740
|
+
const rows=ordered.slice(0,1000).map(item=>workflowItem([workflowLabel(item.eventType),workflowLabel(item.entityType)].filter(Boolean).join(' · ')||'Change',null,
|
|
1741
|
+
workflowFields([['Time (UTC)',workflowDate(item.eventTime)],['Actor',item.modifiedBy],['Actor type',workflowLabel(item.userType)],['Transaction',item.transactionId],['Changes',item.count]])+
|
|
1742
|
+
(workflowRows(item.metas).length?'<details><summary>Returned entity metadata</summary><pre>'+esc(JSON.stringify(item.metas,null,2))+'</pre></details>':''),'li')).join('');
|
|
1743
|
+
app.innerHTML=chrome(operationHeader('Change history',meta.accountId,meta.provider)+notices(data)+(rows?'<ol class="workflow-list workflow-timeline">'+rows+'</ol>':workflowEmpty('No change summaries were returned.'))+
|
|
1744
|
+
(ordered.length>1000?workflowNote('Showing 1,000 changes. All returned changes are in Details.'):'' )+
|
|
1745
|
+
readPageMarkup(args,'data-history-next','data-history-status')+workflowDetails(data),ordered.length+' returned');
|
|
1746
|
+
bindReadPage(meta,args,'data-history-next','data-history-status',value=>Array.isArray(value.result));
|
|
1747
|
+
}
|
|
1748
|
+
|
|
1749
|
+
function renderExperiment(data,meta) {
|
|
1750
|
+
const experiment=data.experiment,arms=workflowRows(data.arms),campaigns=workflowRows(data.campaigns),currency=currencyOf({currency:data.account?.currencyCode});
|
|
1751
|
+
const comparison=arms.map(arm=>{
|
|
1752
|
+
const linked=[...new Set([...arr(arm.campaigns),...arr(arm.inDesignCampaigns)])];
|
|
1753
|
+
const budgets=linked.map(resource=>{
|
|
1754
|
+
const value=campaigns.find(item=>item.campaign?.resourceName===resource),native=value?.budget;
|
|
1755
|
+
const micros=native?.period==='DAILY'?value.budget_micros:null;
|
|
1756
|
+
return [value?.campaign?.name||resource,workflowLabel(value?.campaign?.status),available(micros)?money(micros/1e6,currency,6):null];
|
|
1757
|
+
});
|
|
1758
|
+
return workflowItem(arm.name||'Arm',arm.control===true?'Control':arm.control===false?'Treatment':'',
|
|
1759
|
+
workflowFields([['Traffic',reportNumber(arm.trafficSplit)===null?null:arm.trafficSplit+'%']])+
|
|
1760
|
+
workflowTable(['Campaign','Status',currency?'Daily budget · '+currency:'Daily budget · account units'],budgets,'Campaigns in this arm'));
|
|
1761
|
+
}).join('');
|
|
1762
|
+
const base=data.base_campaign,daily=base?.budget?.period==='DAILY'?base.budget_micros:null;
|
|
1763
|
+
const content=object(experiment)?workflowFields([['Status',workflowLabel(experiment.status)],['Start',experiment.startDate],['End',experiment.endDate],['Account timezone',data.account?.timeZone]])+
|
|
1764
|
+
(comparison?'<div class="workflow-arms">'+comparison+'</div>':workflowEmpty('No experiment arms were returned.')):
|
|
1765
|
+
object(base)?workflowFields([['Base campaign',base.campaign?.name],['Status',workflowLabel(base.campaign?.status)],['Daily budget',available(daily)?money(daily/1e6,currency,6):null]]):
|
|
1766
|
+
workflowEmpty('No experiment or base campaign was returned.');
|
|
1767
|
+
app.innerHTML=chrome(operationHeader(experiment?.name||'Experiment comparison',meta.accountId,meta.provider)+notices(data)+content+workflowDetails(data),'Configuration');
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
function renderCatalogProcessing(data,meta) {
|
|
1771
|
+
const tool=meta.tool,rows=workflowRows(data.records);
|
|
1772
|
+
const identity=data.batch_id??data.feed_id??data.import_id??data.processing_result_id;
|
|
1773
|
+
let report='';
|
|
1774
|
+
if(tool==='reddit_catalog_import_report') {
|
|
1775
|
+
const expires=workflowDate(data.expires_at),href=data.report_available===true&&expires&&Date.parse(expires)>Date.now()?workflowUrl(data.download_url):null;
|
|
1776
|
+
report=href?workflowLink(href,'Download native report ↗','data-catalog-download')+workflowNote('Expires '+expires):workflowNote('The native report is unavailable or expired.');
|
|
1777
|
+
}
|
|
1778
|
+
const items=rows.map(item=>{
|
|
1779
|
+
const detail=item.message??item.error?.message??item.error??item.reason;
|
|
1780
|
+
const counts=Object.entries(item.product_counts??item.summary??Object.fromEntries(
|
|
1781
|
+
['added','updated','removed','errors','warnings','affected_product_count','affected_video_count'].map(key=>[key,item[key]])
|
|
1782
|
+
)).filter(([,value])=>workflowText(value));
|
|
1783
|
+
const structured=['validation_details','ingestion_details','errors','warnings','issues'].filter(key=>item[key]&&Object.keys(item[key]).length);
|
|
1784
|
+
return workflowItem(item.name||item.source_id||item.item_id||item.id||item.code||'Result',item.status??item.severity,
|
|
1785
|
+
workflowFields([['Store',item.store_code],['Updated',workflowDate(item.updated_at)],['Completed',item.completed_at],
|
|
1786
|
+
['Readback',workflowLabel(item.readback)],['Code',item.code],['Field',item.field],['Line',item.line],['Product',item.product_id],
|
|
1787
|
+
...counts.map(([key,value])=>[workflowLabel(key),value])])+
|
|
1788
|
+
workflowNote(detail)+(structured.length?'<details><summary>Provider diagnostics</summary><pre>'+esc(JSON.stringify(Object.fromEntries(structured.map(key=>[key,item[key]])),null,2))+'</pre></details>':''));
|
|
1789
|
+
}).join('');
|
|
1790
|
+
const args=readPageArgs(meta,'data-catalog-next');
|
|
1791
|
+
const summary=receiptMarkup({status:data.status})+
|
|
1792
|
+
workflowFields([['Submitted',data.submitted_items],['Terminal item outcomes',data.terminal_items]]);
|
|
1793
|
+
app.innerHTML=chrome(operationHeader('Catalog processing',identity,meta.provider)+notices(data)+summary+
|
|
1794
|
+
(data.all_items_native_successful===false?workflowNote('Some item outcomes are unsuccessful or unconfirmed.'):'')+
|
|
1795
|
+
report+(items?workflowList(items,'Catalog outcomes'):report?'':workflowEmpty('No processing records were returned.'))+
|
|
1796
|
+
workflowTable(['Severity','Field','Affected items'],['error_fields','warning_fields'].flatMap(key=>
|
|
1797
|
+
workflowRows(data.log?.[key]).map(row=>[key==='error_fields'?'Error':'Warning',row.field,row.affected_product_count??row.affected_video_count])
|
|
1798
|
+
),'Affected fields')+
|
|
1799
|
+
readPageMarkup(args,'data-catalog-next','data-catalog-status')+workflowDetails(data),'');
|
|
1800
|
+
app.querySelector('[data-catalog-download]')?.addEventListener('click',event=>{
|
|
1801
|
+
if(Date.parse(data.expires_at)>Date.now())return;
|
|
1802
|
+
event.preventDefault();
|
|
1803
|
+
const message=document.createElement('span');
|
|
1804
|
+
message.setAttribute('role','status');
|
|
1805
|
+
message.textContent='This report link expired. Request a fresh report.';
|
|
1806
|
+
event.currentTarget.replaceWith(message);
|
|
1807
|
+
});
|
|
1808
|
+
bindReadPage(meta,args,'data-catalog-next','data-catalog-status',value=>Array.isArray(value.records));
|
|
1809
|
+
}
|
|
1810
|
+
|
|
1811
|
+
function distributionArguments(item,data,meta) {
|
|
1812
|
+
const tools=item.stage==='upload'?uploadPreviewTools:item.stage==='prepare'?preparePreviewTools:null;
|
|
1813
|
+
if(meta.capabilities?.can_write!==true||!meta.context?.project_id||item.ready!==true||item.available!==true||
|
|
1814
|
+
!tools?.has(item.tool)||typeof item.provider!=='string'||!item.tool.startsWith(item.provider+'_')||
|
|
1815
|
+
typeof item.account_id!=='string'||!object(item.arguments)) return null;
|
|
1816
|
+
const args=item.arguments;
|
|
1817
|
+
if(args.account_id!==item.account_id||Object.hasOwn(args,'project_id')&&args.project_id!==meta.context.project_id||
|
|
1818
|
+
Object.hasOwn(args,'pending_operation_id')||Object.hasOwn(args,'file_path')) return null;
|
|
1819
|
+
if(item.stage==='upload'&&(!data.asset?.id||!data.asset?.sha256||args.media_id!==data.asset.id||args.expected_sha256!==data.asset.sha256))return null;
|
|
1820
|
+
return {...args,project_id:meta.context.project_id};
|
|
1821
|
+
}
|
|
1822
|
+
|
|
1823
|
+
let distributionReview=null;
|
|
1824
|
+
function distributionIgnoreEcho(data) {
|
|
1825
|
+
const pending=distributionReview,actual=data?._adport;
|
|
1826
|
+
return !!pending&&actual?.tool===pending.item.tool&&actual.context?.project_id===pending.args.project_id&&
|
|
1827
|
+
actual.accountId===pending.args.account_id&&samePreviewArguments(actual.approval?.arguments,pending.args);
|
|
1828
|
+
}
|
|
1829
|
+
|
|
1830
|
+
function renderDistribution(data,meta) {
|
|
1831
|
+
const plan=meta.tool==='media_distribution_plan',items=workflowRows(plan?data.destinations:data.distributions);
|
|
1832
|
+
const rows=items.map((item,index)=>{
|
|
1833
|
+
const title=[providerName(item.provider,meta.providerNames),item.account_name||item.account_id].filter(Boolean).join(' · ');
|
|
1834
|
+
const status=plan?item.available===false?'Unavailable':item.ready===true?'Ready for review':'Needs input':
|
|
1835
|
+
({ACCEPTED:'Upload accepted',STARTED:'Attempt started',UNCONFIRMED:'Outcome unconfirmed',READY:'Ready'}[item.status]||workflowLabel(item.status));
|
|
1836
|
+
const metadata=plan?workflowFields([['Stage',item.stage==='prepare'?'Prepare an asset container':item.stage==='upload'?'Upload a copy':null]])+
|
|
1837
|
+
workflowNote(item.reason)+workflowNote(item.note)+workflowRows(item.problems).map(problem=>workflowNote([workflowLabel(problem.field),problem.message].filter(Boolean).join(' · '))).join(''):
|
|
1838
|
+
workflowFields([['Updated',workflowDate(item.updated_at)],['Provider resource',arr(item.resource_ids).join(', ')],['Error code',item.error_code]])+
|
|
1839
|
+
(item.status==='ACCEPTED'?workflowNote('Processing readiness is unconfirmed.'):item.status==='UNCONFIRMED'||item.status==='STARTED'?workflowNote('Check the native resource or processing status.'):'' );
|
|
1840
|
+
return workflowItem(title||'Destination',status,metadata+(plan&&distributionArguments(item,data,meta)?
|
|
1841
|
+
'<button type="button" class="media-button" data-distribution-review="'+index+'">Review '+(item.stage==='prepare'?'preparation':'upload')+'</button>':''));
|
|
1842
|
+
}).join('');
|
|
1843
|
+
const details=plan?{...data,destinations:items.map(({arguments:_arguments,fields:_fields,...item})=>item)}:data;
|
|
1844
|
+
app.innerHTML=chrome(operationHeader(plan?'Media distribution plan':'Media distribution status',data.asset?.name)+notices(data)+
|
|
1845
|
+
(rows?workflowList(rows,plan?'Eligible destinations':'Upload attempts'):workflowEmpty(plan?'No matching destinations were returned.':'No upload attempts were returned.'))+
|
|
1846
|
+
'<p class="provider-message" data-distribution-status role="status"></p>'+workflowDetails(details),'');
|
|
1847
|
+
const snapshot=state.result;
|
|
1848
|
+
app.querySelectorAll('[data-distribution-review]').forEach(button=>button.addEventListener('click',async()=>{
|
|
1849
|
+
if(distributionReview?.snapshot===snapshot||state.result!==snapshot)return;
|
|
1850
|
+
const item=items[Number(button.dataset.distributionReview)],args=distributionArguments(item,data,meta);
|
|
1851
|
+
if(!args)return;
|
|
1852
|
+
const pending={snapshot,item,args};distributionReview=pending;button.disabled=true;
|
|
1853
|
+
const indicator=app.querySelector('[data-distribution-status]');indicator.textContent='Preparing review…';
|
|
1854
|
+
try {
|
|
1855
|
+
const response=await callTool(item.tool,args,60000),value=resultData(response),actual=value?._adport;
|
|
1856
|
+
if(state.result!==snapshot){rememberHostResult(JSON.stringify(value));return;}
|
|
1857
|
+
if(response?.isError||value?.error||value.status!=='pending_validation'||value.applied!==false||
|
|
1858
|
+
typeof value.pending_operation_id!=='string'||!value.pending_operation_id||
|
|
1859
|
+
actual?.view!=='operation'||actual.provider!==item.provider||!distributionIgnoreEcho(value)) throw new Error('The upload review could not be confirmed.');
|
|
1860
|
+
rememberHostResult(JSON.stringify(value));
|
|
1861
|
+
acceptResult(response,true);
|
|
1862
|
+
} catch(error) {
|
|
1863
|
+
if(state.result===snapshot)indicator.textContent=error?.message||'Could not prepare the review.';
|
|
1864
|
+
} finally {
|
|
1865
|
+
if(distributionReview===pending)distributionReview=null;
|
|
1866
|
+
if(state.result===snapshot)button.disabled=false;
|
|
1867
|
+
}
|
|
1868
|
+
}));
|
|
1869
|
+
}
|
|
1870
|
+
`;
|
|
1871
|
+
|
|
1872
|
+
// src/planning-ui.ts
|
|
1873
|
+
var PLANNING_UI = String.raw`
|
|
1874
|
+
const forecastNames=new Set(['meta_delivery_estimate','pinterest_audience_estimate','snapchat_audience_size','spotify_audience_estimate','spotify_bid_estimate']);
|
|
1875
|
+
|
|
1876
|
+
function planningMicros(value) {
|
|
1877
|
+
const amount=nativeReportDecimal(value,6);
|
|
1878
|
+
return amount===null?null:amount+' account units';
|
|
1879
|
+
}
|
|
1880
|
+
|
|
1881
|
+
function monthlyHistory(months) {
|
|
1882
|
+
const names=['JANUARY','FEBRUARY','MARCH','APRIL','MAY','JUNE','JULY','AUGUST','SEPTEMBER','OCTOBER','NOVEMBER','DECEMBER'];
|
|
1883
|
+
const points=new Map();
|
|
1884
|
+
for(const row of workflowRows(months)) {
|
|
1885
|
+
const month=names.indexOf(String(row.month).toUpperCase()), year=String(row.year);
|
|
1886
|
+
if(month<0||!/^[1-9]\d{3}$/.test(year))continue;
|
|
1887
|
+
const date=year+'-'+String(month+1).padStart(2,'0'),value=nativeReportDecimal(row.monthlySearches);
|
|
1888
|
+
points.set(date,{date,index:Number(year)*12+month,value});
|
|
1889
|
+
}
|
|
1890
|
+
return [...points.values()].sort((a,b)=>a.index-b.index).slice(-24);
|
|
1891
|
+
}
|
|
1892
|
+
|
|
1893
|
+
function monthlySparkline(points) {
|
|
1894
|
+
const valid=points.filter(point=>point.value!==null && Number.isFinite(Number(point.value)) && Number(point.value)>=0);
|
|
1895
|
+
if(!valid.length)return '—';
|
|
1896
|
+
const width=96,height=22,start=points[0].index,span=Math.max(1,points.at(-1).index-start),max=Math.max(1,...valid.map(point=>Number(point.value)));
|
|
1897
|
+
let path='',previous=null;
|
|
1898
|
+
const dots=[];
|
|
1899
|
+
for(const point of valid) {
|
|
1900
|
+
const x=3+(point.index-start)/span*(width-6),y=height-3-Number(point.value)/max*(height-6);
|
|
1901
|
+
const adjacent=previous===point.index-1;
|
|
1902
|
+
path+=(adjacent?' L':' M')+x.toFixed(2)+' '+y.toFixed(2);
|
|
1903
|
+
dots.push('<circle cx="'+x+'" cy="'+y+'" r="2" fill="var(--orange)"/>');
|
|
1904
|
+
previous=point.index;
|
|
1905
|
+
}
|
|
1906
|
+
const label=points.map(point=>point.date+': '+(point.value??'unavailable')).join(', ');
|
|
1907
|
+
return '<svg width="'+width+'" height="'+height+'" viewBox="0 0 '+width+' '+height+'" role="img" aria-label="'+esc(label)+'"><title>'+esc(label)+'</title>'+
|
|
1908
|
+
'<path d="'+path+'" fill="none" stroke="var(--orange)" stroke-width="1.5"/>'+
|
|
1909
|
+
dots.join('')+'</svg>';
|
|
1910
|
+
}
|
|
1911
|
+
|
|
1912
|
+
function planningProjection(data,meta) {
|
|
1913
|
+
const tool=meta.tool;
|
|
1914
|
+
if(/^google_keyword_(?:ideas|historical_metrics)$/.test(tool)) {
|
|
1915
|
+
return {title:'Keyword research',columns:[
|
|
1916
|
+
{key:'keyword',label:'Keyword'},{key:'volume',label:'Average monthly searches'},{key:'competition',label:'Competition'},
|
|
1917
|
+
{key:'low',label:'Low top-of-page bid'},{key:'high',label:'High top-of-page bid'},{key:'history',label:'Monthly history'}
|
|
1918
|
+
],rows:workflowRows(data.results).map(row=>{
|
|
1919
|
+
const metrics=row.keywordIdeaMetrics??row.keywordMetrics??{};
|
|
1920
|
+
return {keyword:row.text,volume:nativeReportDecimal(metrics.avgMonthlySearches),competition:workflowLabel(metrics.competition),
|
|
1921
|
+
low:planningMicros(metrics.lowTopOfPageBidMicros),high:planningMicros(metrics.highTopOfPageBidMicros),
|
|
1922
|
+
history:monthlyHistory(metrics.monthlySearchVolumes)};
|
|
1923
|
+
}),notes:['Historical estimates. Google groups close variants in historical results.']};
|
|
1924
|
+
}
|
|
1925
|
+
if(/^microsoft_keyword_(?:ideas|historical_metrics)$/.test(tool)) {
|
|
1926
|
+
return {title:'Keyword research',columns:[
|
|
1927
|
+
{key:'keyword',label:'Keyword'},{key:'competition',label:'Competition'},{key:'bid',label:'Suggested bid'},
|
|
1928
|
+
{key:'history',label:'Monthly counts (newest first)'}
|
|
1929
|
+
],rows:workflowRows(data.rows).map(row=>({
|
|
1930
|
+
keyword:row.Keyword,competition:workflowLabel(row.Competition),
|
|
1931
|
+
bid:nativeReportDecimal(row.SuggestedBid)===null?null:nativeReportDecimal(row.SuggestedBid)+' '+(currencyOf(data)||'account units'),
|
|
1932
|
+
history:arr(row.MonthlySearchCounts).slice(0,24).map(item=>nativeReportDecimal(item)??'—').join(' · ')
|
|
1933
|
+
})),notes:data.notes};
|
|
1934
|
+
}
|
|
1935
|
+
if(/^apple_(?:search_)?suggestions$/.test(tool)) {
|
|
1936
|
+
const rows=workflowRows(data.result).map(row=>({
|
|
1937
|
+
term:row.phrase??row.keyword??row.category??row.name,
|
|
1938
|
+
popularity:row.searchPopularity??row.searchPopularity1to5??row.searchPopularity1to100,
|
|
1939
|
+
position:row.rank
|
|
1940
|
+
})).filter(row=>workflowText(row.term));
|
|
1941
|
+
if(!rows.length && arr(data.result).length)return null;
|
|
1942
|
+
return {title:'Keyword suggestions',columns:[{key:'term',label:'Term or category'},{key:'popularity',label:'Native popularity'},{key:'position',label:'Native rank'}],rows};
|
|
1943
|
+
}
|
|
1944
|
+
if(tool==='microsoft_keyword_traffic_estimates') {
|
|
1945
|
+
const rows=workflowRows(data.rows).flatMap(campaign=>workflowRows(campaign.AdGroupEstimates).flatMap(group=>workflowRows(group.KeywordEstimates))).flatMap(item=>{
|
|
1946
|
+
const term=object(item.Keyword)?item.Keyword.Text:item.Keyword;
|
|
1947
|
+
return Object.entries({Minimum:item.Minimum,Maximum:item.Maximum}).filter(([,value])=>object(value)).map(([bound,value])=>({
|
|
1948
|
+
row:[term,bound].filter(workflowText).join(' · '),clicks:value.Clicks,impressions:value.Impressions,
|
|
1949
|
+
cost:nativeReportDecimal(value.TotalCost)===null?null:nativeReportDecimal(value.TotalCost)+' '+(currencyOf(data)||'account units')
|
|
1950
|
+
}));
|
|
1951
|
+
});
|
|
1952
|
+
if(!rows.length&&arr(data.rows).length)return null;
|
|
1953
|
+
return {title:'Weekly traffic estimates',columns:[{key:'row',label:'Keyword and bound'},{key:'clicks',label:'Clicks'},
|
|
1954
|
+
{key:'impressions',label:'Impressions'},{key:'cost',label:'Total cost'}],rows,notes:data.notes};
|
|
1955
|
+
}
|
|
1956
|
+
if(forecastNames.has(tool)) {
|
|
1957
|
+
const values=tool==='meta_delivery_estimate'?workflowRows(data.estimates):[object(data.value)?data.value:data];
|
|
1958
|
+
const rows=values.flatMap((value,index)=>dataFields(value)
|
|
1959
|
+
.filter(field=>/audience|size|estimate|bound|minimum|maximum|lower|upper|reach|bid|impression|dau|mau|ready|status|currency/i.test(field.label)&&workflowText(field.after))
|
|
1960
|
+
.map(field=>({estimate:(values.length>1?'Estimate '+(index+1)+' · ':'')+field.label,value:/(^|\s)micros?$/i.test(field.label)?
|
|
1961
|
+
(nativeReportDecimal(field.after,6)??'—')+' '+(currencyOf(value)||'account units'):field.after}))
|
|
1962
|
+
);
|
|
1963
|
+
if(!rows.length && values.length)return null;
|
|
1964
|
+
return {title:tool==='spotify_bid_estimate'?'Bid estimate':tool==='meta_delivery_estimate'?'Delivery estimates':'Audience estimate',
|
|
1965
|
+
columns:[{key:'estimate',label:'Native measure'},{key:'value',label:'Estimate'}],rows,
|
|
1966
|
+
notes:['Estimates reflect the selected targeting and provider assumptions.']};
|
|
1967
|
+
}
|
|
1968
|
+
return null;
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1971
|
+
function renderPlanning(data,meta,projected) {
|
|
1972
|
+
const planning=projected||data.planning||{};
|
|
1973
|
+
const columns=arr(planning.columns).filter(value=>typeof value?.key==='string'&&typeof value?.label==='string').slice(0,12);
|
|
1974
|
+
const rows=arr(planning.rows),pageSize=100,pages=Math.max(1,Math.ceil(rows.length/pageSize));
|
|
1975
|
+
state.planningPage=Math.max(0,Math.min(state.planningPage,pages-1));
|
|
1976
|
+
const start=state.planningPage*pageSize,shown=rows.slice(start,start+pageSize);
|
|
1977
|
+
const notes=arr(planning.notes).filter(workflowText).map(note=>'<p class="notice">'+esc(note)+'</p>').join('');
|
|
1978
|
+
const detailHeader=projected?workflowHeader(columns.map(column=>column.label)):
|
|
1979
|
+
'<thead><tr>'+columns.map(column=>'<th scope="col">'+esc(column.label)+'</th>').join('')+'</tr></thead>';
|
|
1980
|
+
const detailRows=shown.map(row=>'<tr'+(projected?' role="row"':'')+'>'+columns.map((column,i)=>{
|
|
1981
|
+
const value=row&&Object.hasOwn(row,column.key)?row[column.key]:null;
|
|
1982
|
+
const html=column.key==='history'&&Array.isArray(value)&&projected?monthlySparkline(value):esc(value==null?'—':value);
|
|
1983
|
+
return projected?workflowCell(column.label,html,i===0):'<td>'+html+'</td>';
|
|
1984
|
+
}).join('')+'</tr>').join('');
|
|
1985
|
+
const table=columns.length&&shown.length?'<div class="planning-scroll" tabindex="0" role="region" aria-label="Planning estimate table">'+
|
|
1986
|
+
(projected?'<table class="planning-table workflow-stack" role="table">':'<table class="planning-table">')+detailHeader+
|
|
1987
|
+
(projected?'<tbody role="rowgroup">':'<tbody>')+detailRows+'</tbody></table></div>':workflowEmpty('No planning values were returned for this selection.');
|
|
1988
|
+
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>':'';
|
|
1989
|
+
const args=readPageArgs(meta,'data-planning-next');
|
|
1990
|
+
app.innerHTML=chrome(operationHeader(planning.title||'Planning estimates',meta.accountId,meta.provider)+notices({...data,notes:arr(data.notes).filter(note=>!arr(planning.notes).includes(note)),truncated:false})+
|
|
1991
|
+
'<div data-read-page-focus tabindex="-1">'+table+controls+(data.truncated?'<p class="notice">Partial native response. More estimates may exist.</p>':'')+notes+
|
|
1992
|
+
readPageMarkup(args,'data-planning-next','data-planning-status')+workflowDetails(data)+'</div>','Read-only estimates');
|
|
1993
|
+
app.querySelectorAll('[data-planning-page]').forEach(button=>button.addEventListener('click',()=>{
|
|
1994
|
+
if(button.disabled)return;
|
|
1995
|
+
state.planningPage+=button.dataset.planningPage==='next'?1:-1;
|
|
1996
|
+
renderPlanning(data,meta,projected);
|
|
1997
|
+
}));
|
|
1998
|
+
bindReadPage(meta,args,'data-planning-next','data-planning-status',value=>!!planningProjection(value,meta)||Array.isArray(value.planning?.rows));
|
|
1999
|
+
}
|
|
2000
|
+
`;
|
|
2001
|
+
|
|
2002
|
+
// src/read-page-ui.ts
|
|
2003
|
+
var READ_PAGE_UI = String.raw`
|
|
2004
|
+
let pendingReadPage=null;
|
|
2005
|
+
let readPageHistory=null;
|
|
2006
|
+
|
|
2007
|
+
function readPageArgs(meta,selector) {
|
|
2008
|
+
const args=galleryNext(meta);
|
|
2009
|
+
const scope=galleryScope(meta);
|
|
2010
|
+
if(readPageHistory?.scope!==scope || readPageHistory.selector!==selector) {
|
|
2011
|
+
readPageHistory={scope,selector,seen:new Set()};
|
|
2012
|
+
}
|
|
2013
|
+
readPageHistory.seen.add(galleryStable(meta.refresh?.arguments));
|
|
2014
|
+
return args&&!readPageHistory.seen.has(galleryStable(args))?args:null;
|
|
2015
|
+
}
|
|
2016
|
+
|
|
2017
|
+
function readPageMarkup(args,selector,statusSelector) {
|
|
2018
|
+
return args?'<div class="provider-pages"><button type="button" class="media-button" '+selector+'>Next page</button></div><p class="provider-message" '+statusSelector+' role="status"></p>':'';
|
|
2019
|
+
}
|
|
2020
|
+
|
|
2021
|
+
function readPageIgnoreEcho(data) {
|
|
2022
|
+
const pending=pendingReadPage,meta=data?._adport;
|
|
2023
|
+
return !!pending&&!!meta&&galleryMatches(meta,pending.meta)&&galleryStable(meta.refresh?.arguments)===pending.key;
|
|
2024
|
+
}
|
|
2025
|
+
|
|
2026
|
+
function bindReadPage(meta,args,selector,statusSelector,valid) {
|
|
2027
|
+
const button=app.querySelector('['+selector+']'),snapshot=state.result;
|
|
1354
2028
|
button?.addEventListener('click',async()=>{
|
|
1355
|
-
if(button.disabled
|
|
1356
|
-
|
|
2029
|
+
if(button.disabled||state.result!==snapshot)return;
|
|
2030
|
+
const pending={meta,key:galleryStable(args)};
|
|
2031
|
+
pendingReadPage=pending;
|
|
2032
|
+
button.disabled=true;
|
|
2033
|
+
button.textContent='Loading…';
|
|
1357
2034
|
try {
|
|
1358
|
-
const response=await callTool(meta.tool,
|
|
1359
|
-
if(state.result!==snapshot)return;
|
|
1360
|
-
if(response?.isError
|
|
2035
|
+
const response=await callTool(meta.tool,args,60000),value=resultData(response),next=value?._adport;
|
|
2036
|
+
if(state.result!==snapshot) {rememberHostResult(JSON.stringify(value));return;}
|
|
2037
|
+
if(response?.isError||value?.error||!next||next.view!==meta.view||!galleryMatches(next,meta)||
|
|
2038
|
+
galleryScope(next)!==galleryScope(meta)||galleryStable(next.refresh?.arguments)!==pending.key||!valid(value)) {
|
|
2039
|
+
throw new Error('The next page could not be confirmed.');
|
|
2040
|
+
}
|
|
2041
|
+
rememberHostResult(JSON.stringify(value));
|
|
1361
2042
|
acceptResult(response,true);
|
|
1362
|
-
|
|
2043
|
+
(app.querySelector('['+selector+']')||app.querySelector('[data-read-page-focus]'))?.focus({preventScroll:true});
|
|
2044
|
+
} catch(error) {
|
|
2045
|
+
if(state.result===snapshot) {
|
|
2046
|
+
app.querySelector('['+statusSelector+']').textContent=error?.message||'Could not load the next page.';
|
|
2047
|
+
button.disabled=false;
|
|
2048
|
+
button.textContent='Next page';
|
|
2049
|
+
}
|
|
2050
|
+
} finally {if(pendingReadPage===pending)pendingReadPage=null;}
|
|
1363
2051
|
});
|
|
1364
2052
|
}
|
|
1365
2053
|
`;
|
|
@@ -1434,7 +2122,7 @@ var REPORT_CHART_SCRIPT = String.raw`
|
|
|
1434
2122
|
const label=pretty(point.name)+(point.context?.length?' · '+point.context.join(' · '):'');
|
|
1435
2123
|
const range=point.range&&point.range.every(available)?point.range:null;
|
|
1436
2124
|
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>';
|
|
1437
|
-
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>';
|
|
2125
|
+
return '<li data-chart-value="'+(value===null?'':value)+'"><div class="report-bar-label"><span title="'+esc(label)+'">'+esc(label)+'</span><strong>'+esc(point.shortDisplay??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>';
|
|
1438
2126
|
}).join('')+'</ol>';
|
|
1439
2127
|
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>';
|
|
1440
2128
|
}).join('')+(groups.size>4?'<p class="report-chart-foot">Showing four units. All returned values are in Details.</p>':'');
|
|
@@ -1467,8 +2155,8 @@ var REPORT_CHART_SCRIPT = String.raw`
|
|
|
1467
2155
|
`;
|
|
1468
2156
|
|
|
1469
2157
|
// src/ui.ts
|
|
1470
|
-
var ADPORT_UI_URI = "ui://adport/insight-card-
|
|
1471
|
-
var ADPORT_SUMMARY_UI_URI = "ui://adport/summary-card-
|
|
2158
|
+
var ADPORT_UI_URI = "ui://adport/insight-card-v33.html";
|
|
2159
|
+
var ADPORT_SUMMARY_UI_URI = "ui://adport/summary-card-v33.html";
|
|
1472
2160
|
var ADPORT_UI_DOMAIN = "https://app.adport.dev";
|
|
1473
2161
|
var ADPORT_UI_RESOURCE_DOMAINS = [
|
|
1474
2162
|
ADPORT_UI_DOMAIN,
|
|
@@ -1700,6 +2388,7 @@ ${RECORD_UI_STYLES}
|
|
|
1700
2388
|
${APPLE_REPORT_UI_STYLES}
|
|
1701
2389
|
${NATIVE_REPORT_UI_STYLES}
|
|
1702
2390
|
${REPORT_CHART_STYLES}
|
|
2391
|
+
${WORKFLOW_UI_STYLES}
|
|
1703
2392
|
${RECEIPT_UI_STYLES}
|
|
1704
2393
|
${INSIGHT_UI_STYLES}
|
|
1705
2394
|
${TREND_UI_STYLES}
|
|
@@ -1778,8 +2467,17 @@ ${TREND_UI_STYLES}
|
|
|
1778
2467
|
const dated=rows.some(row=>typeof row.date==='string');
|
|
1779
2468
|
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>';
|
|
1780
2469
|
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>');
|
|
2470
|
+
const table=rows.length?'<details class="report-data"><summary>Returned rows · '+rows.length+'</summary>'+
|
|
2471
|
+
workflowTable(['Entity','Platform','Date','Spend','Clicks','Conversions','ROAS'],rows.map(row=>{
|
|
2472
|
+
const metrics=row.metrics||{},revenue=rowReturn(row);
|
|
2473
|
+
return [row.entity?.name||row.entity?.id,providerName(row.provider,meta.providerNames),row.date,
|
|
2474
|
+
available(metrics.spend)?money(metrics.spend,currency,6):null,metrics.clicks,metrics.conversions,
|
|
2475
|
+
available(revenue)&&metrics.spend>0?(revenue/metrics.spend).toFixed(2)+'×':available(metrics.roas)?metrics.roas+'×':null];
|
|
2476
|
+
}),'Returned performance rows')+'</details>':'';
|
|
2477
|
+
const incomplete=data.summary?.complete===false&&!data.truncated&&arr(data.errors).length===0?
|
|
2478
|
+
'<p class="notice">Totals cover only the returned rows.</p>':'';
|
|
1781
2479
|
trendResize?.disconnect();
|
|
1782
|
-
app.innerHTML=chrome(body,period+(currency?' · '+currency:''));
|
|
2480
|
+
app.innerHTML=chrome(incomplete+body+table,period+(currency?' · '+currency:''));
|
|
1783
2481
|
if(dated)mountReportTrend(rows,metric,currency,data);
|
|
1784
2482
|
app.querySelectorAll('[data-group]').forEach(button=>button.addEventListener('click',()=>{state.reportGroup=choices[Number(button.dataset.group)].key;renderReport(data,meta);}));
|
|
1785
2483
|
app.querySelectorAll('[data-metric]').forEach(button=>button.addEventListener('click',()=>{state.reportMetric=button.dataset.metric;renderReport(data,meta);}));
|
|
@@ -1787,6 +2485,7 @@ ${TREND_UI_STYLES}
|
|
|
1787
2485
|
${OPERATION_UI_SCRIPT}
|
|
1788
2486
|
${RECEIPT_UI_SCRIPT}
|
|
1789
2487
|
${RECORD_UI_SCRIPT}
|
|
2488
|
+
${READ_PAGE_UI}
|
|
1790
2489
|
${APPLE_REPORT_UI_SCRIPT}
|
|
1791
2490
|
${NATIVE_REPORT_UI_SCRIPT}
|
|
1792
2491
|
${REPORT_CHART_SCRIPT}
|
|
@@ -1808,16 +2507,8 @@ ${MEDIA_UPLOAD_UI}
|
|
|
1808
2507
|
${MEDIA_LIBRARY_UI}
|
|
1809
2508
|
${CREATIVE_UI_SCRIPT}
|
|
1810
2509
|
${PROVIDER_GALLERY_UI}
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
state.planningPage=Math.max(0,Math.min(state.planningPage,pages-1));
|
|
1814
|
-
const start=state.planningPage*pageSize, shown=rows.slice(start,start+pageSize);
|
|
1815
|
-
const notes=arr(planning.notes).filter(v=>typeof v==='string').map(v=>'<p class="notice">'+esc(v)+'</p>').join('');
|
|
1816
|
-
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>';
|
|
1817
|
-
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>':'';
|
|
1818
|
-
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');
|
|
1819
|
-
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);}));
|
|
1820
|
-
}
|
|
2510
|
+
${WORKFLOW_UI}
|
|
2511
|
+
${PLANNING_UI}
|
|
1821
2512
|
function render(result) {
|
|
1822
2513
|
cancelHold();clearTimeout(expiryTimer);trendResize?.disconnect();
|
|
1823
2514
|
let data=resultData(result);
|
|
@@ -1837,6 +2528,19 @@ ${PROVIDER_GALLERY_UI}
|
|
|
1837
2528
|
if (meta.view === 'accounts') return renderAccounts(data,meta);
|
|
1838
2529
|
if (meta.view === 'report') return renderReport(data,meta);
|
|
1839
2530
|
if (meta.view === 'operation') {renderOperation(data,meta);providerGalleryReviewControls(data,meta);return;}
|
|
2531
|
+
if (meta.tool === 'capabilities_list') return renderAvailability(data,meta);
|
|
2532
|
+
if (meta.tool === 'apple_change_history') return renderHistory(data,meta);
|
|
2533
|
+
if (meta.tool === 'apple_recommendations') return renderAppleRecommendations(data,meta);
|
|
2534
|
+
if (meta.tool === 'google_experiment_context') return renderExperiment(data,meta);
|
|
2535
|
+
if (['media_distribution_plan','media_distributions'].includes(meta.tool)) return renderDistribution(data,meta);
|
|
2536
|
+
if (['reddit_pixel_last_fired','pinterest_event_quality','meta_custom_conversion_stats','tiktok_pixel_event_stats',
|
|
2537
|
+
'spotify_dataset_diagnostics','openai_conversion_events'].includes(meta.tool)) return renderMeasurement(data,meta);
|
|
2538
|
+
if (['pinterest_feed_processing_results','pinterest_feed_item_issues','pinterest_catalog_item_batch_status',
|
|
2539
|
+
'pinterest_reconcile_catalog_item_batch','pinterest_local_inventory_batch_status','pinterest_reconcile_local_inventory_batch',
|
|
2540
|
+
'reddit_catalog_imports','reddit_catalog_import_issues','reddit_catalog_import_report','tiktok_catalog_feed_log',
|
|
2541
|
+
'tiktok_catalog_product_log','tiktok_catalog_video_log'].includes(meta.tool)) return renderCatalogProcessing(data,meta);
|
|
2542
|
+
const projected=planningProjection(data,meta);
|
|
2543
|
+
if (projected) return renderPlanning(data,meta,projected);
|
|
1840
2544
|
if (meta.view === 'records') return renderRecords(data,meta);
|
|
1841
2545
|
if (meta.view === 'receipt') return renderReceipt(data,meta);
|
|
1842
2546
|
if (meta.view === 'creatives') return renderCreatives(data,meta);
|
|
@@ -1851,13 +2555,13 @@ ${PROVIDER_GALLERY_UI}
|
|
|
1851
2555
|
function acceptResult(result,local=false) {
|
|
1852
2556
|
if (!result || typeof result !== 'object') return;
|
|
1853
2557
|
const incoming=resultData(result);
|
|
1854
|
-
if(!local && (providerGalleryIgnoreEcho(incoming) || mediaLibraryIgnoreEcho(incoming) || recordPagesIgnoreEcho(incoming))) return;
|
|
2558
|
+
if(!local && (providerGalleryIgnoreEcho(incoming) || mediaLibraryIgnoreEcho(incoming) || recordPagesIgnoreEcho(incoming) || readPageIgnoreEcho(incoming) || distributionIgnoreEcho(incoming))) return;
|
|
1855
2559
|
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;
|
|
1856
2560
|
const fingerprint=JSON.stringify(incoming);
|
|
1857
2561
|
// Host state updates can echo an old tool result after a local edit/apply.
|
|
1858
2562
|
if (!local && state.hasLocalResult && hostResults.has(fingerprint)) return;
|
|
1859
2563
|
if (local) state.hasLocalResult=true;
|
|
1860
|
-
else rememberHostResult(fingerprint);
|
|
2564
|
+
else {rememberHostResult(fingerprint);readPageHistory=null;}
|
|
1861
2565
|
clearTimeout(resultWait);
|
|
1862
2566
|
// ChatGPT can deliver the same result through both supported bridges.
|
|
1863
2567
|
// Do not reset an open disclosure when the second copy arrives.
|
|
@@ -1930,7 +2634,7 @@ ${PROVIDER_GALLERY_UI}
|
|
|
1930
2634
|
|
|
1931
2635
|
// src/index.ts
|
|
1932
2636
|
var PROVIDER_IDS = ["ga4", "gsc", "gtm", "google", "meta", "tiktok", "apple", "microsoft", "reddit", "snapchat", "spotify", "pinterest", "linkedin", "x", "openai"];
|
|
1933
|
-
var ADPORT_UI_RESOURCE_URIS = [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];
|
|
2637
|
+
var ADPORT_UI_RESOURCE_URIS = [ADPORT_UI_URI, "ui://adport/insight-card-v32.html", "ui://adport/insight-card-v31.html", "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, "ui://adport/summary-card-v32.html", "ui://adport/summary-card-v30.html"];
|
|
1934
2638
|
var DEFAULT_MCP_ICONS = [{
|
|
1935
2639
|
src: "https://app.adport.dev/icon.svg?brand=orange-dot-v2",
|
|
1936
2640
|
mimeType: "image/svg+xml",
|
|
@@ -1957,7 +2661,7 @@ function createMcpUiServer({ name = "adport", version = package_default.version,
|
|
|
1957
2661
|
function registerUiResources(server, uiDomain, uiResourceDomains, uiConnectDomains) {
|
|
1958
2662
|
const summaryDomains = uiResourceDomains.filter((domain) => domain === ADPORT_UI_DOMAIN || uiConnectDomains.includes(domain));
|
|
1959
2663
|
for (const uri of ADPORT_UI_RESOURCE_URIS) {
|
|
1960
|
-
const summary = uri
|
|
2664
|
+
const summary = uri.startsWith("ui://adport/summary-card-");
|
|
1961
2665
|
const resourceMeta = {
|
|
1962
2666
|
ui: {
|
|
1963
2667
|
...uiDomain ? { domain: uiDomain } : {},
|
|
@@ -2008,7 +2712,7 @@ function createMcpServer({ runtime, catalog = { profile: "full", providers: null
|
|
|
2008
2712
|
if (scopes && !scopes.includes(requiredScope) && !scopeDenial) continue;
|
|
2009
2713
|
const view = tool.presentation ?? viewForTool(tool.name, tool.annotations.readOnly ?? false);
|
|
2010
2714
|
const resourceUri = productionOnly && view !== "creatives" ? ADPORT_SUMMARY_UI_URI : ADPORT_UI_URI;
|
|
2011
|
-
const canRefresh = (view === "creatives" || view === "records"
|
|
2715
|
+
const canRefresh = tool.annotations.readOnly && (view === "creatives" || view === "records" || tool.pagination !== void 0);
|
|
2012
2716
|
const canPage = canRefresh && tool.pagination !== void 0;
|
|
2013
2717
|
const wrapOutput = !!tool.output && !(tool.output instanceof z.ZodObject);
|
|
2014
2718
|
const output = productionOnly && tool.output === writeOutput ? hostedWriteOutput : tool.output;
|
|
@@ -2149,4 +2853,4 @@ export {
|
|
|
2149
2853
|
createMcpServer,
|
|
2150
2854
|
runStdioServer
|
|
2151
2855
|
};
|
|
2152
|
-
//# sourceMappingURL=chunk-
|
|
2856
|
+
//# sourceMappingURL=chunk-RE4ZCAVJ.js.map
|