From 8732c36c23adb961ce6348718b17dc9d35ed937c Mon Sep 17 00:00:00 2001 From: jelkes1 Date: Mon, 16 Nov 2026 16:58:15 -0800 Subject: [PATCH 1/3] Remove the injected demo analytics prompt and settings button --- README-analytics.md | 6 +++++- analytics/demo-analytics.js | 14 +------------- scripts/demo-analytics.test.mjs | 16 ++++++++++++---- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/README-analytics.md b/README-analytics.md index c890e4d..070f668 100644 --- a/README-analytics.md +++ b/README-analytics.md @@ -2,7 +2,7 @@ Production release assembly installs one shared, consented GA4 adapter for the gallery and all five demo apps. Local quickstarts and preview hosts do not transmit measurements. A cross-origin frame on www.superdoc.dev runs the Google tag, so the vendor cannot read the demo document, its title or room URL. Only bounded event categories cross the frame boundary. The adapter reuses SuperDoc's existing `G-E4T80WRJGS` property and preference format. It never loads identified CRM tracking. -Public events use fixed demo/action/capability values only. Query values, rooms, filenames, documents, prompts, error text and citation text are excluded. Refusal, withdrawal, DNT, GPC, opt-out and incoming private URLs suppress transport. Later private navigation removes the measurement frame without changing application navigation. Auto-created demo rooms remain measurable only from a clean public entry. Change or withdraw the choice through Privacy settings. Events deduplicate per page and action category, rather than counting keystrokes or polling. +Public events use fixed demo/action/capability values only. Query values, rooms, filenames, documents, prompts, error text and citation text are excluded. Refusal, withdrawal, DNT, GPC, opt-out and incoming private URLs suppress transport. Later private navigation removes the measurement frame without changing application navigation. Auto-created demo rooms remain measurable only from a clean public entry. The adapter does not inject a consent prompt, floating settings button or other visible controls. Existing saved analytics choices and browser privacy signals still govern measurement. Events deduplicate per page and action category, rather than counting keystrokes or polling. Readiness comes from the editor callback. Review, fields, agent jobs, Q&A and saved versions use actual completion/failure callbacks. Browser export completion does not establish successful Word rendering or a completed developer evaluation. Gallery cards and source/Build this use measure discovery and implementation interest separately. Do not sum per-demo users or compare new collection with an untracked baseline. @@ -78,3 +78,7 @@ Josh's November 15 direction applies to every future demo and example, including For a gallery addition, CI executes the real adapter against every `demos.json` route and requires its stable ID plus consent/refusal behavior. A new manifest entry with no registered tracking fails the existing release tests. Update the adapter, isolated homepage frame allowlist and Growth labels/queries together, add actual readiness/success/failure callbacks and verify production ingestion after the normal reviewed releases. Never add a generic arbitrary-event or arbitrary-URL escape hatch to make coverage pass. For a new public host or standalone example, prepare the same coverage through its owning repository and normal review before posting. A local quickstart or downloaded source example must remain free of analytics by default. Native video views, link clicks, example downloads and successful interactive actions are different measures. Unsupported platform metrics remain explicitly unavailable, never zero or invented. Do not alter old posts, customer links or private rooms to manufacture attribution. Follow the existing content worker's [future demo measurement standard](https://github.com/superdoc/sales-engine/blob/main/docs/demo-analytics.md#future-demos-and-examples). + +## Visible demo UI + +The shared measurement adapter must not add a modal, banner, floating privacy control or other unsolicited demo UI. Keep developer-facing UI changes separate and visible in normal review; adding measurement is not authority to introduce a new visitor interaction. The existing adapter regression executes fresh, declined and granted preferences on the gallery and every published demo route and rejects injected visible controls. Preserve prior choices, private-room guards and the bounded payload contract when changing measurement behavior. diff --git a/analytics/demo-analytics.js b/analytics/demo-analytics.js index 1acfe8e..23e6cee 100644 --- a/analytics/demo-analytics.js +++ b/analytics/demo-analytics.js @@ -29,21 +29,9 @@ frame=d.createElement('iframe');frame.hidden=true;frame.title='Optional demo analytics';frame.referrerPolicy='no-referrer';frame.setAttribute('sandbox','allow-scripts allow-same-origin');frame.src=FRAME_ORIGIN+'/demo-analytics-frame.html';d.body.append(frame); emit('load_started'); reobserve(); if(d.visibilityState==='visible')exposureTimer=setTimeout(()=>{if(d.visibilityState==='visible')emit('exposed');},1000); } - // A single per-origin settings surface; never inherit another person's consent. - function settings(force=false){ - if(!publicSurface())return; - if(!force&&preference())return; - if(d.getElementById('superdoc-demo-consent'))return; - const panel=d.createElement('section');panel.id='superdoc-demo-consent';panel.setAttribute('aria-label','Optional demo analytics'); - panel.style.cssText='position:fixed;bottom:12px;right:12px;max-width:min(360px,calc(100vw - 24px));padding:16px;background:white;color:#242424;border:1px solid #ccc;border-radius:12px;z-index:99999;font:14px/1.5 system-ui;box-shadow:0 4px 24px #0002'; - const text=d.createElement('p');text.textContent='Help us improve these demos with optional usage analytics. Document contents, prompts and filenames are excluded.';panel.append(text); - for(const [label,value] of [['Allow analytics',true],['Decline',false]]){const b=d.createElement('button');b.textContent=label;b.style.cssText='padding:8px;margin:4px';b.onclick=()=>{const choice={version:1,savedAt:Date.now(),analytics:value&&!privateSignal(),identification:false};try{w.localStorage.setItem(KEY,JSON.stringify(choice));}catch{}panel.remove();apply(choice);};panel.append(b);} - const privacy=d.createElement('a');privacy.href='https://superdocportal.dev/privacy';privacy.textContent='Privacy policy';panel.append(privacy);d.body.append(panel); - } function start(){ if(!publicSurface())return; - initialized=true;apply(preference());settings(); - const b=d.createElement('button');b.textContent='Privacy settings';b.style.cssText='position:fixed;left:8px;bottom:8px;z-index:9998;font:12px system-ui;padding:5px';b.onclick=()=>settings(true);d.body.append(b); + initialized=true;apply(preference()); d.addEventListener('click',e=>{ if(!e.isTrusted)return;const a=e.target.closest?.('a'); if(a){try{const url=new URL(a.href,w.location.href),target=routes[url.pathname.replace(/\/*$/, '/')];if(url.origin===w.location.origin&&target&&target!=='gallery'){emit('selected','none',target);if(!url.search&&!url.hash){url.searchParams.set('demo_entry','gallery');a.href=url.href;}}else if(url.hostname==='github.com'||url.hostname==='docs.superdoc.dev'){const card=a.closest('.demo-card'),live=card?.querySelector('.card-main-link');let id=example;try{if(live)id=routes[new URL(live.href).pathname.replace(/\/*$/, '/')];}catch{}emit(url.hostname==='github.com'?'source_clicked':'docs_clicked','none',id);}}catch{}} diff --git a/scripts/demo-analytics.test.mjs b/scripts/demo-analytics.test.mjs index d195d87..2beb580 100644 --- a/scripts/demo-analytics.test.mjs +++ b/scripts/demo-analytics.test.mjs @@ -1,14 +1,14 @@ import {test} from 'node:test';import assert from 'node:assert/strict';import vm from 'node:vm';import {readFile} from 'node:fs/promises'; const code=await readFile(new URL('../analytics/demo-analytics.js',import.meta.url),'utf8'); function fixture({pathname='/custom-word-editor/',consent=true,host='demos.superdoc.dev',search='',hash='',dnt='0',gpc=false}={}){ - const listeners={},events=[],scripts=[],nodes=[],storage=new Map();let reloads=0; + const listeners={},events=[],scripts=[],nodes=[],created=[],storage=new Map();let reloads=0; if(consent!==null)storage.set('superdoc_cookie_preferences',JSON.stringify({version:1,savedAt:Date.now(),analytics:consent,identification:false})); - const el=(tag)=>({style:{},contentWindow:{postMessage(message){if(message.type==='event')events.push(['event','superdoc_demo_event',message.payload]);}},setAttribute(){},append(...v){nodes.push(...v);for(const n of v)if(n.src?.endsWith('/demo-analytics-frame.html')){scripts.push(n);queueMicrotask(()=>listeners.message?.({origin:'https://www.superdoc.dev',source:n.contentWindow,data:{channel:'superdoc-demo-analytics-v1',type:'ready'}}));}},remove(){}}); - const document={readyState:'complete',visibilityState:'visible',head:{append:s=>scripts.push(s)},body:el(),createElement:el,getElementById:()=>null,addEventListener:(k,f)=>{listeners['d:'+k]=f;},querySelectorAll:()=>[]}; + const el=(tag)=>({tag,style:{},contentWindow:{postMessage(message){if(message.type==='event')events.push(['event','superdoc_demo_event',message.payload]);}},setAttribute(){},append(...v){nodes.push(...v);for(const n of v)if(n.src?.endsWith('/demo-analytics-frame.html')){scripts.push(n);queueMicrotask(()=>listeners.message?.({origin:'https://www.superdoc.dev',source:n.contentWindow,data:{channel:'superdoc-demo-analytics-v1',type:'ready'}}));}},remove(){}}); + const document={readyState:'complete',visibilityState:'visible',head:{append:s=>scripts.push(s)},body:el(),createElement:tag=>{const n=el(tag);created.push(n);return n;},getElementById:()=>null,addEventListener:(k,f)=>{listeners['d:'+k]=f;},querySelectorAll:()=>[]}; const window={document,location:{hostname:host,pathname,search,hash,origin:'https://'+host,href:'https://'+host+pathname+search+hash,reload:()=>reloads++},navigator:{doNotTrack:dnt,globalPrivacyControl:gpc},localStorage:{getItem:k=>storage.get(k),setItem:(k,v)=>storage.set(k,v)},addEventListener:(k,f)=>{listeners[k]=f;}}; vm.runInNewContext(code,{window,document,URL,URLSearchParams,Date,Set,Map,setTimeout,clearTimeout}); if(scripts[0])listeners.message?.({origin:'https://www.superdoc.dev',source:scripts[0].contentWindow,data:{channel:'superdoc-demo-analytics-v1',type:'ready'}}); - return {window,scripts,nodes,events:()=>events,emit:(detail)=>listeners['superdoc:demo']?.({detail}),withdraw:()=>{storage.set('superdoc_cookie_preferences',JSON.stringify({version:1,savedAt:Date.now(),analytics:false}));listeners.storage({key:'superdoc_cookie_preferences'});return reloads;}}; + return {window,scripts,nodes,created,events:()=>events,emit:(detail)=>listeners['superdoc:demo']?.({detail}),withdraw:()=>{storage.set('superdoc_cookie_preferences',JSON.stringify({version:1,savedAt:Date.now(),analytics:false}));listeners.storage({key:'superdoc_cookie_preferences'});return reloads;}}; } test('production events are bounded and deduplicated, without private caller properties',()=>{const f=fixture();f.emit({action:'task_succeeded',capability:'review',prompt:'secret',room:'secret'});f.emit({action:'task_succeeded',capability:'review'});f.emit({action:'arbitrary',capability:'review'});assert.equal(f.scripts.length,1);assert.equal(f.events().filter(x=>x[2].action==='task_succeeded').length,1);assert.ok(!JSON.stringify(f.events()).includes('secret'));assert.equal(f.events()[0][2].page,'custom-word-editor');assert.equal(f.window.gtag,undefined);}); for(const opts of [{consent:false},{consent:null},{dnt:'1'},{gpc:true},{host:'preview.pages.dev'},{search:'?room=private'},{hash:'#token'},{search:'?demo_entry=private'}])test('no provider or events for '+JSON.stringify(opts),()=>{const f=fixture(opts);f.emit({action:'task_succeeded',capability:'document'});assert.equal(f.scripts.length,0);assert.equal(f.events().length,0);}); @@ -32,3 +32,11 @@ for(const demo of manifest){ test('unregistered future routes cannot silently acquire a vendor transport',()=>{ const f=fixture({pathname:'/future-unregistered-example/'});assert.equal(f.scripts.length,0);assert.equal(f.events().length,0); }); + +for(const pathname of ['/',...manifest.map(d=>d.liveDemoUri)])for(const consent of [null,false,true]){ + test(`analytics adds no visible prompt or floating controls on ${pathname} with preference ${consent}`,()=>{ + const f=fixture({pathname,consent}); + assert.deepEqual(f.created.filter(n=>n.tag!=='iframe').map(n=>n.tag),[]); + assert.equal(f.nodes.some(n=>/Allow analytics|Decline|Privacy settings|Help us improve/.test(n.textContent??'')),false); + }); +} From edb18aea2f068a578f47094cfc8211cca0ffa2d2 Mon Sep 17 00:00:00 2001 From: jelkes1 Date: Mon, 16 Nov 2026 17:04:13 -0800 Subject: [PATCH 2/3] Run bounded public demo analytics without a prompt --- README-analytics.md | 8 ++++---- analytics/demo-analytics.js | 8 ++++---- scripts/demo-analytics.test.mjs | 17 ++++++++++++----- 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/README-analytics.md b/README-analytics.md index 070f668..f5d8b60 100644 --- a/README-analytics.md +++ b/README-analytics.md @@ -1,8 +1,8 @@ -# Optional demo analytics +# Demo analytics -Production release assembly installs one shared, consented GA4 adapter for the gallery and all five demo apps. Local quickstarts and preview hosts do not transmit measurements. A cross-origin frame on www.superdoc.dev runs the Google tag, so the vendor cannot read the demo document, its title or room URL. Only bounded event categories cross the frame boundary. The adapter reuses SuperDoc's existing `G-E4T80WRJGS` property and preference format. It never loads identified CRM tracking. +Production release assembly installs one shared, bounded GA4 adapter for the gallery and all five demo apps. Local quickstarts and preview hosts do not transmit measurements. A cross-origin frame on www.superdoc.dev runs the Google tag, so the vendor cannot read the demo document, its title or room URL. Only bounded event categories cross the frame boundary. The adapter reuses SuperDoc's existing `G-E4T80WRJGS` property and preference format. It never loads identified CRM tracking. -Public events use fixed demo/action/capability values only. Query values, rooms, filenames, documents, prompts, error text and citation text are excluded. Refusal, withdrawal, DNT, GPC, opt-out and incoming private URLs suppress transport. Later private navigation removes the measurement frame without changing application navigation. Auto-created demo rooms remain measurable only from a clean public entry. The adapter does not inject a consent prompt, floating settings button or other visible controls. Existing saved analytics choices and browser privacy signals still govern measurement. Events deduplicate per page and action category, rather than counting keystrokes or polling. +Public events use fixed demo/action/capability values only. Query values, rooms, filenames, documents, prompts, error text and citation text are excluded. Refusal, withdrawal, DNT, GPC, opt-out and incoming private URLs suppress transport. Later private navigation removes the measurement frame without changing application navigation. Auto-created demo rooms remain measurable only from a clean public entry. The adapter does not inject a consent prompt, floating settings button or other visible controls. On supported public routes, bounded analytics runs without a prompt unless a saved decline or browser opt-out blocks it. Saved declines remain effective even after the normal preference age window; this adapter does not enable visitor identification. Events deduplicate per page and action category, rather than counting keystrokes or polling. Readiness comes from the editor callback. Review, fields, agent jobs, Q&A and saved versions use actual completion/failure callbacks. Browser export completion does not establish successful Word rendering or a completed developer evaluation. Gallery cards and source/Build this use measure discovery and implementation interest separately. Do not sum per-demo users or compare new collection with an untracked baseline. @@ -81,4 +81,4 @@ For a new public host or standalone example, prepare the same coverage through i ## Visible demo UI -The shared measurement adapter must not add a modal, banner, floating privacy control or other unsolicited demo UI. Keep developer-facing UI changes separate and visible in normal review; adding measurement is not authority to introduce a new visitor interaction. The existing adapter regression executes fresh, declined and granted preferences on the gallery and every published demo route and rejects injected visible controls. Preserve prior choices, private-room guards and the bounded payload contract when changing measurement behavior. +The shared measurement adapter must not add a modal, banner, floating privacy control or other unsolicited demo UI. Keep developer-facing UI changes separate and visible in normal review; adding measurement is not authority to introduce a new visitor interaction. The existing adapter regression executes fresh, declined and granted preferences on the gallery and every published demo route and rejects injected visible controls. Preserve saved declines, DNT/GPC/explicit opt-out, withdrawal, private-room guards and the bounded payload contract. The gallery default is measurement without a prompt; do not infer permission to change tracking on another host or in local/downloaded examples. diff --git a/analytics/demo-analytics.js b/analytics/demo-analytics.js index 23e6cee..0576844 100644 --- a/analytics/demo-analytics.js +++ b/analytics/demo-analytics.js @@ -1,4 +1,4 @@ -/* Public, consented demo measurements. No document or session data is read. */ +/* Bounded public demo measurements. No document or session data is read. */ (() => { const w = window, d = document, KEY = 'superdoc_cookie_preferences'; const routes = {'/':'gallery','/custom-word-editor/':'custom-word-editor','/collab/':'agentic-collaboration','/builder/':'template-builder-api-v2','/docrag/':'docrag','/version-history/':'version-history'}; @@ -14,7 +14,7 @@ const publicSurface=()=>bootAllowed&&!blocked&&w.location.pathname.replace(/\/*$/, '/')===path&&!w.location.hash; function post(type,payload){frame?.contentWindow?.postMessage({channel:'superdoc-demo-analytics-v1',type,...(payload?{payload}:{})},FRAME_ORIGIN);} function stop(){granted=false;clearTimeout(exposureTimer);pending.length=0;post('disable');frame?.remove();frame=null;frameReady=false;loaded=false;} - const preference = () => {try{const c=JSON.parse(w.localStorage.getItem(KEY)),age=Date.now()-c.savedAt;return c.version===1&&age>=0&&age<180*86400000&&typeof c.analytics==='boolean'?c:null;}catch{return null;}}; + const preference = () => {try{const c=JSON.parse(w.localStorage.getItem(KEY)),age=Date.now()-c.savedAt;return c?.version===1&&typeof c.analytics==='boolean'&&(c.analytics===false||(age>=0&&age<180*86400000))?c:null;}catch{return null;}}; function emit(action, capability='none', target=example) { if (!granted || privateSignal() || !publicSurface() || !actions.has(action) || !capabilities.has(capability) || !Object.values(routes).includes(target)) return false; const key=[target,action,capability].join(':'); if(seen.has(key))return false; @@ -23,7 +23,7 @@ seen.add(key);return true; } function apply(c) { - granted=!!c?.analytics&&!privateSignal()&&!!publicSurface(); + granted=c?.analytics!==false&&!privateSignal()&&!!publicSurface(); if(!granted){stop();return;} if(loaded)return;loaded=true; frame=d.createElement('iframe');frame.hidden=true;frame.title='Optional demo analytics';frame.referrerPolicy='no-referrer';frame.setAttribute('sandbox','allow-scripts allow-same-origin');frame.src=FRAME_ORIGIN+'/demo-analytics-frame.html';d.body.append(frame); @@ -43,7 +43,7 @@ if(example==='gallery'&&w.IntersectionObserver){const timers=new Map();const observer=new IntersectionObserver(entries=>{for(const item of entries){clearTimeout(timers.get(item.target));if(item.isIntersecting&&item.intersectionRatio>=.5)timers.set(item.target,setTimeout(()=>{if(d.visibilityState==='visible'){const a=item.target.querySelector('a[href]');try{emit('option_exposed','none',routes[new URL(a.href).pathname.replace(/\/*$/, '/')]);}catch{}}},1000));}},{threshold:[0,.5]});reobserve=()=>{observer.disconnect();d.querySelectorAll('.demo-card').forEach(el=>observer.observe(el));};reobserve();d.addEventListener('visibilitychange',()=>{if(d.visibilityState!=='visible'){for(const t of timers.values())clearTimeout(t);}else reobserve();});} } // Generated demo-room setup happens before start. Incoming private links - // never opt in. Later private navigation stops measurements without changing + // never enable measurement. Later private navigation stops measurements without changing // application navigation or sending the new URL to the vendor frame. for(const method of ['pushState','replaceState']){ const original=w.history?.[method]?.bind(w.history);if(!original)continue; diff --git a/scripts/demo-analytics.test.mjs b/scripts/demo-analytics.test.mjs index 2beb580..968c426 100644 --- a/scripts/demo-analytics.test.mjs +++ b/scripts/demo-analytics.test.mjs @@ -1,30 +1,31 @@ import {test} from 'node:test';import assert from 'node:assert/strict';import vm from 'node:vm';import {readFile} from 'node:fs/promises'; const code=await readFile(new URL('../analytics/demo-analytics.js',import.meta.url),'utf8'); -function fixture({pathname='/custom-word-editor/',consent=true,host='demos.superdoc.dev',search='',hash='',dnt='0',gpc=false}={}){ +function fixture({pathname='/custom-word-editor/',consent=true,host='demos.superdoc.dev',search='',hash='',dnt='0',gpc=false,optOut=false,consentAgeDays=0}={}){ const listeners={},events=[],scripts=[],nodes=[],created=[],storage=new Map();let reloads=0; - if(consent!==null)storage.set('superdoc_cookie_preferences',JSON.stringify({version:1,savedAt:Date.now(),analytics:consent,identification:false})); + if(consent!==null)storage.set('superdoc_cookie_preferences',JSON.stringify({version:1,savedAt:Date.now()-consentAgeDays*86400000,analytics:consent,identification:false})); const el=(tag)=>({tag,style:{},contentWindow:{postMessage(message){if(message.type==='event')events.push(['event','superdoc_demo_event',message.payload]);}},setAttribute(){},append(...v){nodes.push(...v);for(const n of v)if(n.src?.endsWith('/demo-analytics-frame.html')){scripts.push(n);queueMicrotask(()=>listeners.message?.({origin:'https://www.superdoc.dev',source:n.contentWindow,data:{channel:'superdoc-demo-analytics-v1',type:'ready'}}));}},remove(){}}); const document={readyState:'complete',visibilityState:'visible',head:{append:s=>scripts.push(s)},body:el(),createElement:tag=>{const n=el(tag);created.push(n);return n;},getElementById:()=>null,addEventListener:(k,f)=>{listeners['d:'+k]=f;},querySelectorAll:()=>[]}; - const window={document,location:{hostname:host,pathname,search,hash,origin:'https://'+host,href:'https://'+host+pathname+search+hash,reload:()=>reloads++},navigator:{doNotTrack:dnt,globalPrivacyControl:gpc},localStorage:{getItem:k=>storage.get(k),setItem:(k,v)=>storage.set(k,v)},addEventListener:(k,f)=>{listeners[k]=f;}}; + const window={document,superdocAnalyticsOptOut:optOut,location:{hostname:host,pathname,search,hash,origin:'https://'+host,href:'https://'+host+pathname+search+hash,reload:()=>reloads++},navigator:{doNotTrack:dnt,globalPrivacyControl:gpc},localStorage:{getItem:k=>storage.get(k),setItem:(k,v)=>storage.set(k,v)},addEventListener:(k,f)=>{listeners[k]=f;}}; vm.runInNewContext(code,{window,document,URL,URLSearchParams,Date,Set,Map,setTimeout,clearTimeout}); if(scripts[0])listeners.message?.({origin:'https://www.superdoc.dev',source:scripts[0].contentWindow,data:{channel:'superdoc-demo-analytics-v1',type:'ready'}}); return {window,scripts,nodes,created,events:()=>events,emit:(detail)=>listeners['superdoc:demo']?.({detail}),withdraw:()=>{storage.set('superdoc_cookie_preferences',JSON.stringify({version:1,savedAt:Date.now(),analytics:false}));listeners.storage({key:'superdoc_cookie_preferences'});return reloads;}}; } test('production events are bounded and deduplicated, without private caller properties',()=>{const f=fixture();f.emit({action:'task_succeeded',capability:'review',prompt:'secret',room:'secret'});f.emit({action:'task_succeeded',capability:'review'});f.emit({action:'arbitrary',capability:'review'});assert.equal(f.scripts.length,1);assert.equal(f.events().filter(x=>x[2].action==='task_succeeded').length,1);assert.ok(!JSON.stringify(f.events()).includes('secret'));assert.equal(f.events()[0][2].page,'custom-word-editor');assert.equal(f.window.gtag,undefined);}); -for(const opts of [{consent:false},{consent:null},{dnt:'1'},{gpc:true},{host:'preview.pages.dev'},{search:'?room=private'},{hash:'#token'},{search:'?demo_entry=private'}])test('no provider or events for '+JSON.stringify(opts),()=>{const f=fixture(opts);f.emit({action:'task_succeeded',capability:'document'});assert.equal(f.scripts.length,0);assert.equal(f.events().length,0);}); +for(const opts of [{consent:false},{consent:false,consentAgeDays:200},{optOut:true},{dnt:'1'},{gpc:true},{host:'preview.pages.dev'},{search:'?room=private'},{hash:'#token'},{search:'?demo_entry=private'}])test('no provider or events for '+JSON.stringify(opts),()=>{const f=fixture(opts);f.emit({action:'task_succeeded',capability:'document'});assert.equal(f.scripts.length,0);assert.equal(f.events().length,0);}); test('consent withdrawal stops custom events and removes the isolated transport',()=>{const f=fixture();assert.equal(f.withdraw(),0);const n=f.events().length;f.emit({action:'task_succeeded',capability:'document'});assert.equal(f.events().length,n);}); test('task failures and successful operations remain distinct',()=>{const f=fixture();f.emit({action:'task_failed',capability:'review'});f.emit({action:'task_succeeded',capability:'review'});assert.equal(f.events().filter(x=>x[2].action.startsWith('task_')).length,2);}); // A manifest addition must exercise the real adapter, not silently install an inert script. const manifest=JSON.parse(await readFile(new URL('../demos.json',import.meta.url),'utf8')); for(const demo of manifest){ - test(`published manifest demo ${demo.id} has consented measurement coverage`,()=>{ + test(`published manifest demo ${demo.id} has bounded measurement coverage`,()=>{ const f=fixture({pathname:demo.liveDemoUri}); assert.equal(f.scripts.length,1,`${demo.id}: register its public route before release`); const start=f.events().find(e=>e[2].action==='load_started'); assert.equal(start?.[2].example_id,demo.id,`${demo.id}: stable identity must match the published manifest`); f.emit({action:'ready',capability:'document'}); assert.ok(f.events().some(e=>e[2].action==='ready'&&e[2].example_id===demo.id)); + const fresh=fixture({pathname:demo.liveDemoUri,consent:null});assert.equal(fresh.scripts.length,1,`${demo.id}: fresh public visitors use bounded measurement without a prompt`); const declined=fixture({pathname:demo.liveDemoUri,consent:false});declined.emit({action:'ready',capability:'document'}); assert.equal(declined.scripts.length,0);assert.equal(declined.events().length,0); }); @@ -40,3 +41,9 @@ for(const pathname of ['/',...manifest.map(d=>d.liveDemoUri)])for(const consent assert.equal(f.nodes.some(n=>/Allow analytics|Decline|Privacy settings|Help us improve/.test(n.textContent??'')),false); }); } + +test('fresh public visitors emit bounded usage without any consent prompt or visible control',()=>{ + const f=fixture({consent:null});f.emit({action:'task_succeeded',capability:'document',prompt:'PRIVATE',filename:'PRIVATE'}); + assert.equal(f.scripts.length,1);assert.ok(f.events().some(x=>x[2].action==='task_succeeded')); + assert.equal(f.created.filter(n=>n.tag!=='iframe').length,0);assert.doesNotMatch(JSON.stringify(f.events()),/PRIVATE/); +}); From de891c1fdb928c0de58b4461638ba714d14d642f Mon Sep 17 00:00:00 2001 From: Matthew Connelly Date: Mon, 16 Nov 2026 20:38:03 -0500 Subject: [PATCH 3/3] docs: align analytics verification with default collection --- README-analytics.md | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/README-analytics.md b/README-analytics.md index f5d8b60..0b2d383 100644 --- a/README-analytics.md +++ b/README-analytics.md @@ -6,7 +6,7 @@ Public events use fixed demo/action/capability values only. Query values, rooms, Readiness comes from the editor callback. Review, fields, agent jobs, Q&A and saved versions use actual completion/failure callbacks. Browser export completion does not establish successful Word rendering or a completed developer evaluation. Gallery cards and source/Build this use measure discovery and implementation interest separately. Do not sum per-demo users or compare new collection with an untracked baseline. -`node --test scripts/*.test.mjs` checks the release scripts and bounded consent contract. Build all affected apps and verify actual deployed ingestion before calling tracking live. Growth's existing Analytics and weekly metrics report own reporting; this adds no schedule or provider. Public content and private room semantics are unchanged. +`node --test scripts/*.test.mjs` checks the release scripts and bounded preference and opt-out contract. Build all affected apps and verify actual deployed ingestion before calling tracking live. Growth's existing Analytics and weekly metrics report own reporting; this adds no schedule or provider. Public content and private room semantics are unchanged. Release order: deploy homepage PR235 and verify its inert frame route first, then merge this gallery PR through the trusted maintainer workflow. The new transport has no historical baseline. @@ -18,10 +18,13 @@ custom event, an outgoing Google request, then a received event in GA4. 1. Open `https://demos.superdoc.dev/` without a query or fragment. Open DevTools, select **Network**, enable **Preserve log**, and reload. Confirm `/demo-analytics.js` returns JavaScript rather than the gallery HTML fallback. -2. Allow optional analytics through the gallery consent control. Wait for the +2. Analytics starts automatically on eligible public routes; there is no consent + prompt or floating settings button. Wait for the `www.superdoc.dev/demo-analytics-frame.html` frame and Google tag to load. - Declined consent, DNT/GPC, opt-out, private links and blocked Google requests - prevent collection; do not bypass those controls to make a check pass. + Saved declines (including older declines), DNT/GPC, explicit opt-out, private + links and blocked Google requests prevent collection. Query strings other than + `demo_entry=homepage|gallery`, including UTM parameters, also block collection; + use the clean public URL when verifying and preserve opt-out controls. 3. Filter Network by `collect` (all request types). Page activation should produce `superdoc_demo_event` with `load_started` and, after about one visible second, `exposed`. Click a demo card or source/docs link to check an actual user action. @@ -35,7 +38,7 @@ custom event, an outgoing Google request, then a received event in GA4. source observation, so it is not the immediate smoke-test surface. For an optional synthetic smoke test, run this once in the gallery page's console -after consent and frame initialization: +after the analytics frame and Google tag have initialized: ```js window.dispatchEvent(new CustomEvent('superdoc:demo', { @@ -73,9 +76,9 @@ is mocked and does not send synthetic activity to production. ## Every future published demo and example -Josh's November 15 direction applies to every future demo and example, including public customer follow-ups and launches outside this gallery. Before readiness, record the stable resource ID, canonical public destination, developer task, meaningful action and expected result, native social/video metrics where relevant, reporting coverage and collection start date. Reuse the existing consented GA4 transport, Growth Analytics and weekly metrics publisher. +Josh's November 15 direction applies to every future demo and example, including public customer follow-ups and launches outside this gallery. Before readiness, record the stable resource ID, canonical public destination, developer task, meaningful action and expected result, native social/video metrics where relevant, reporting coverage and collection start date. Reuse the existing bounded GA4 transport, Growth Analytics and weekly metrics publisher. -For a gallery addition, CI executes the real adapter against every `demos.json` route and requires its stable ID plus consent/refusal behavior. A new manifest entry with no registered tracking fails the existing release tests. Update the adapter, isolated homepage frame allowlist and Growth labels/queries together, add actual readiness/success/failure callbacks and verify production ingestion after the normal reviewed releases. Never add a generic arbitrary-event or arbitrary-URL escape hatch to make coverage pass. +For a gallery addition, CI executes the real adapter against every `demos.json` route and requires its stable ID plus default collection and saved-refusal behavior. A new manifest entry with no registered tracking fails the existing release tests. Update the adapter, isolated homepage frame allowlist and Growth labels/queries together, add actual readiness/success/failure callbacks and verify production ingestion after the normal reviewed releases. Never add a generic arbitrary-event or arbitrary-URL escape hatch to make coverage pass. For a new public host or standalone example, prepare the same coverage through its owning repository and normal review before posting. A local quickstart or downloaded source example must remain free of analytics by default. Native video views, link clicks, example downloads and successful interactive actions are different measures. Unsupported platform metrics remain explicitly unavailable, never zero or invented. Do not alter old posts, customer links or private rooms to manufacture attribution. Follow the existing content worker's [future demo measurement standard](https://github.com/superdoc/sales-engine/blob/main/docs/demo-analytics.md#future-demos-and-examples).