diff --git a/.gitignore b/.gitignore index 650bc6d..6daa9b3 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,5 @@ node_modules/ /dist-gallery/ **/test-results/ **/playwright-report/ + +.private/ diff --git a/README-analytics.md b/README-analytics.md new file mode 100644 index 0000000..9cad49c --- /dev/null +++ b/README-analytics.md @@ -0,0 +1,19 @@ +# Optional 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. + +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. + +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. + +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. + +## 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. + +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). diff --git a/analytics/demo-analytics.js b/analytics/demo-analytics.js new file mode 100644 index 0000000..1acfe8e --- /dev/null +++ b/analytics/demo-analytics.js @@ -0,0 +1,76 @@ +/* Public, consented 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'}; + const path = w.location.pathname.replace(/\/*$/, '/'), example = routes[path]; + const actions = new Set(['exposed','option_exposed','selected','load_started','ready','load_failed','explored','edit_observed','review_action','field_edited','ai_started','ai_succeeded','ai_failed','export_requested','export_completed','export_failed','task_started','task_succeeded','task_failed','source_clicked','docs_clicked','build_opened','build_copied','citation_opened']); + const capabilities = new Set(['none','document','review','fields','ai','collaboration','version_history','answer']); + const FRAME_ORIGIN='https://www.superdoc.dev'; + const seen = new Set(); let loaded = false, granted = false, exposureTimer, frame=null, frameReady=false, initialized=false, blocked=false; const pending=[]; let origin='builtin_example'; let reobserve=()=>{}; + const privateSignal = () => w.navigator.globalPrivacyControl === true || w.superdocAnalyticsOptOut === true || [w.navigator.doNotTrack,w.doNotTrack].some(v=>['1','yes'].includes(String(v).toLowerCase())); + const cleanUrl=url=>!url.hash&&[...new URLSearchParams(url.search)].every(([k,v])=>k==='demo_entry'&&['homepage','gallery'].includes(v)); + const bootAllowed=w.location.hostname==='demos.superdoc.dev'&&!!example&&cleanUrl(w.location); + const initialEntry=new URLSearchParams(w.location.search).get('demo_entry'); + 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;}}; + 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; + const payload={page:example,example_id:target,document_origin:origin,entry:initialEntry==='homepage'?'homepage':initialEntry==='gallery'?'selection':'direct_link',action,capability}; + if(frameReady)post('event',payload);else if(pending.length<100)pending.push(payload);else return false; + seen.add(key);return true; + } + function apply(c) { + granted=!!c?.analytics&&!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); + 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); + 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{}} + const button=e.target.closest?.('button');if(button){if(button.hasAttribute('data-build-dialog')||button.textContent.trim()==='Build this')emit('build_opened','none',button.getAttribute('data-build-dialog')?.replace(/^build-/, '')||example);} + }); + d.addEventListener('visibilitychange',()=>{clearTimeout(exposureTimer);if(d.visibilityState==='visible')exposureTimer=setTimeout(()=>emit('exposed'),1000);}); + d.addEventListener('change',e=>{if(e.isTrusted&&e.target?.type==='file')origin='visitor_file';}); + d.addEventListener('input',e=>{if(e.isTrusted&&e.target.closest?.('[contenteditable="true"],[data-editor-host="v2"][role="textbox"]'))emit('edit_observed','document');}); + 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 + // 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; + w.history[method]=function(state,title,url){ + if(initialized&&url){const next=new URL(url,w.location.href);if(next.origin!==w.location.origin||next.pathname.replace(/\/*$/, '/')!==path||!cleanUrl(next)){blocked=true;stop();}} + return original(state,title,url); + }; + } + w.addEventListener('hashchange',()=>{if(w.location.hash){blocked=true;stop();}}); + w.addEventListener('message',event=>{ + if(event.origin!==FRAME_ORIGIN||event.source!==frame?.contentWindow||event.data?.channel!=='superdoc-demo-analytics-v1'||event.data.type!=='ready'||!granted)return; + frameReady=true;post('enable');for(const payload of pending.splice(0))post('event',payload); + }); + w.addEventListener('superdoc:demo',e=>{try{emit(e.detail?.action,e.detail?.capability,e.detail?.example||example);}catch{}}); + w.addEventListener('storage',e=>{if(e.key===KEY||e.key===null)apply(preference());}); + w.addEventListener('pageshow',e=>{if(e.persisted)apply(preference());}); + if(d.readyState==='loading')d.addEventListener('DOMContentLoaded',start,{once:true});else start(); +})(); diff --git a/canonical-collaboration-demo/client/src/components/ChatPanel.tsx b/canonical-collaboration-demo/client/src/components/ChatPanel.tsx index bdcf64b..cce4bc7 100644 --- a/canonical-collaboration-demo/client/src/components/ChatPanel.tsx +++ b/canonical-collaboration-demo/client/src/components/ChatPanel.tsx @@ -1,3 +1,4 @@ +const demoMetric = (action: string, capability = 'document') => { try { window.dispatchEvent(new CustomEvent('superdoc:demo', { detail: { action, capability } })); } catch { /* Analytics must not affect the demo. */ } }; import { FormEvent, KeyboardEvent, PointerEvent, useEffect, useLayoutEffect, useRef, useState } from 'react'; import Markdown from 'react-markdown'; import type { SuperDoc } from 'superdoc'; @@ -146,7 +147,9 @@ export function ChatPanel({ roomId, disabled, unavailableReason, width, onWidthC async function finishJob(job: Job) { onDocumentUpdated?.(); + if (job.status === 'failed') demoMetric('ai_failed', 'collaboration'); if (job.status === 'completed') { + demoMetric('ai_succeeded', 'collaboration'); const history = await api.getChatHistory(roomId); setMessages(history); setJobs((current) => current.filter((candidate) => candidate.id !== job.id)); @@ -208,10 +211,12 @@ export function ChatPanel({ roomId, disabled, unavailableReason, width, onWidthC promptNavigationRef.current = null; setPrompt(''); try { + demoMetric('ai_started', 'collaboration'); const job = await api.createJob(roomId, message, isSuggesting, selectedText || undefined); setJobs((current) => [...current, job]); await watchJob(job); } catch (caught) { + demoMetric('ai_failed', 'collaboration'); setError(caught instanceof Error ? caught.message : String(caught)); } } diff --git a/canonical-collaboration-demo/client/src/components/DocumentEditor.tsx b/canonical-collaboration-demo/client/src/components/DocumentEditor.tsx index 31c3788..1d3e3df 100644 --- a/canonical-collaboration-demo/client/src/components/DocumentEditor.tsx +++ b/canonical-collaboration-demo/client/src/components/DocumentEditor.tsx @@ -1,3 +1,4 @@ +const demoMetric = (action: string, capability = 'document') => { try { window.dispatchEvent(new CustomEvent('superdoc:demo', { detail: { action, capability } })); } catch { /* Analytics must not affect the demo. */ } }; import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { SuperDocEditor, type SuperDocEditorProps } from '@superdoc/react'; import type { SuperDoc } from 'superdoc'; @@ -56,6 +57,7 @@ export const DocumentEditor = memo(function DocumentEditor({ room, mode, onActiv }, [onConnectedUsersChange]); const handleConnectionChange = useCallback>(({ state }) => { synced.current = state === 'synced'; + if (synced.current) demoMetric('task_succeeded', 'collaboration'); onConnectedUsersChange(synced.current ? presenceCount.current : null); }, [onConnectedUsersChange]); @@ -123,7 +125,7 @@ export const DocumentEditor = memo(function DocumentEditor({ room, mode, onActiv instance.current = superdoc; mountedEditor.current = true; setEditorReady(true); - onReady(superdoc); + onReady(superdoc); demoMetric('ready', 'collaboration'); }} onException={(event) => { console.error('SuperDoc error', event); diff --git a/custom-word-editor/src/components/DocumentToolbar/TrackedChangesControls.tsx b/custom-word-editor/src/components/DocumentToolbar/TrackedChangesControls.tsx index d56e9f3..0926eb2 100644 --- a/custom-word-editor/src/components/DocumentToolbar/TrackedChangesControls.tsx +++ b/custom-word-editor/src/components/DocumentToolbar/TrackedChangesControls.tsx @@ -1,3 +1,4 @@ +const demoMetric = (action: string, capability = 'document') => { try { window.dispatchEvent(new CustomEvent('superdoc:demo', { detail: { action, capability } })); } catch { /* Optional analytics. */ } }; import { useState } from 'react'; import { useSuperDocCommand } from 'superdoc/ui/react'; import './TrackedChangesControls.css'; @@ -16,11 +17,14 @@ export function TrackedChangesControls() { setPending(action); setError(''); try { + demoMetric('task_started', 'review'); const result = await command.executeAsync(); if (result === false || (typeof result === 'object' && result !== null && 'success' in result && !result.success)) { + demoMetric('task_failed', 'review'); setError(`Could not ${action} all tracked changes.`); - } + } else { demoMetric('task_succeeded', 'review'); } } catch { + demoMetric('task_failed', 'review'); setError(`Could not ${action} all tracked changes.`); } finally { setPending(null); diff --git a/custom-word-editor/src/demo/components/topbar/Topbar.tsx b/custom-word-editor/src/demo/components/topbar/Topbar.tsx index d58a3a1..ec04262 100644 --- a/custom-word-editor/src/demo/components/topbar/Topbar.tsx +++ b/custom-word-editor/src/demo/components/topbar/Topbar.tsx @@ -1,3 +1,4 @@ +const demoMetric = (action: string, capability = 'document') => { try { window.dispatchEvent(new CustomEvent('superdoc:demo', { detail: { action, capability } })); } catch { /* Analytics must not affect the demo. */ } }; import { useRef, useState, type ReactNode } from 'react'; import { BlankDOCX } from 'superdoc'; import { useSuperDocDocument, useSuperDocHost, useSuperDocUI } from 'superdoc/ui/react'; @@ -20,8 +21,11 @@ export function Topbar({ viewControls, onDocumentReplaced }: { viewControls?: Re const exportDocument = async (exportedName = 'reviewed-contract') => { if (!host || !('export' in host) || typeof host.export !== 'function') return; setSaving(true); + demoMetric('export_requested'); try { await host.export({ exportType: ['docx'], exportedName }); + demoMetric('export_completed'); + } catch (error) { demoMetric('export_failed'); throw error; } finally { setSaving(false); } @@ -83,13 +87,15 @@ export function Topbar({ viewControls, onDocumentReplaced }: { viewControls?: Re }], }); setSaving(true); + demoMetric('export_requested'); const result = await ui.document.export({ exportType: ['docx'], triggerDownload: false }); if (!(result instanceof Blob)) throw new Error('SuperDoc did not return a DOCX file.'); const writable = await handle.createWritable(); await writable.write(result); - await writable.close(); + await writable.close(); demoMetric('export_completed'); } catch (error) { if (error instanceof DOMException && error.name === 'AbortError') return; + demoMetric('export_failed'); console.error(error); setImportError('The document could not be saved.'); } finally { diff --git a/custom-word-editor/src/superdoc/SuperDocEditor.tsx b/custom-word-editor/src/superdoc/SuperDocEditor.tsx index 0e591aa..b352756 100644 --- a/custom-word-editor/src/superdoc/SuperDocEditor.tsx +++ b/custom-word-editor/src/superdoc/SuperDocEditor.tsx @@ -1,3 +1,4 @@ +const demoMetric = (action: string, capability = 'document') => { try { window.dispatchEvent(new CustomEvent('superdoc:demo', { detail: { action, capability } })); } catch { /* Optional analytics. */ } }; import { useCallback, useEffect, useRef, useState } from 'react'; import type { RefObject } from 'react'; import { SuperDoc } from 'superdoc'; @@ -63,7 +64,7 @@ export function SuperDocEditor({ contentControls: true, }, onReady: ({ superdoc: readySuperDoc }) => { - ready = true; + ready = true; demoMetric('ready'); setError(''); setSuperDoc(readySuperDoc); }, @@ -71,7 +72,7 @@ export function SuperDocEditor({ // Protected edits are expected rejections, not document-open failures. if ('code' in exception && exception.code === 'edit-rejected') return; console.error(exception.error); - if (!ready) setError('The review document could not be opened.'); + if (!ready) { demoMetric('load_failed'); setError('The review document could not be opened.'); } }, }); diff --git a/dist-landing/index.html b/dist-landing/index.html index d2a6132..e59e95c 100644 --- a/dist-landing/index.html +++ b/dist-landing/index.html @@ -123,6 +123,7 @@ try { await navigator.clipboard.writeText(dialog.querySelector('code').textContent); copy.textContent = 'Copied'; + window.dispatchEvent(new CustomEvent('superdoc:demo', {detail:{action:'build_copied',capability:'none',example:dialog.id.replace(/^build-/, '')}})); status.textContent = 'Commands copied to clipboard.'; } catch { status.textContent = 'Could not access the clipboard. Select the commands above and copy them.'; diff --git a/rag/apps/web/App.tsx b/rag/apps/web/App.tsx index 3a2202a..01a66d7 100644 --- a/rag/apps/web/App.tsx +++ b/rag/apps/web/App.tsx @@ -1,3 +1,13 @@ +const demoMetric = (action: string, capability = "document") => { + try { + window.dispatchEvent( + new CustomEvent("superdoc:demo", { detail: { action, capability } }), + ); + } catch { + /* Analytics must not affect the demo. */ + } +}; + import { useCallback, useState } from "react"; import { createRoot } from "react-dom/client"; import { ChatPanel } from "./components/ChatPanel"; @@ -24,6 +34,7 @@ function App() { const doc = resp.documents.find((d) => d.id === citation.documentId); if (doc) setActiveFilename(doc.filename); } + demoMetric("citation_opened", "answer"); setActiveCitation(null); requestAnimationFrame(() => setActiveCitation(citation)); }, diff --git a/rag/apps/web/components/ChatPanel.tsx b/rag/apps/web/components/ChatPanel.tsx index 33a8531..2922903 100644 --- a/rag/apps/web/components/ChatPanel.tsx +++ b/rag/apps/web/components/ChatPanel.tsx @@ -1,3 +1,13 @@ +const demoMetric = (action: string, capability = "document") => { + try { + window.dispatchEvent( + new CustomEvent("superdoc:demo", { detail: { action, capability } }), + ); + } catch { + /* Analytics must not affect the demo. */ + } +}; + import { useEffect, useRef, useState } from "react"; import { type Citation, queryDocuments } from "../lib/api"; import { ChatMessage } from "./ChatMessage"; @@ -56,7 +66,9 @@ export function ChatPanel({ onCitationClick, disabled }: Props) { setLoading(true); try { + demoMetric("ai_started", "answer"); const result = await queryDocuments(q); + demoMetric("ai_succeeded", "answer"); setMessages((m) => m.map((msg) => msg.id === loadingMsg.id @@ -70,6 +82,7 @@ export function ChatPanel({ onCitationClick, disabled }: Props) { ), ); } catch (err) { + demoMetric("ai_failed", "answer"); setMessages((m) => m.map((msg) => msg.id === loadingMsg.id diff --git a/scripts/assemble-release.mjs b/scripts/assemble-release.mjs index 2dd1058..661ebd4 100644 --- a/scripts/assemble-release.mjs +++ b/scripts/assemble-release.mjs @@ -1,3 +1,4 @@ +import { installDemoAnalytics } from './install-demo-analytics.mjs'; import { cp, mkdir, readFile, rm } from "node:fs/promises"; import path from "node:path"; import { renderGallery } from "./render-gallery.mjs"; @@ -36,3 +37,5 @@ await collabAssets(output); // Attach the version-history API and WebSocket proxy to the static release. await assembleVersionHistory({ output, backendUrl: process.env.VERSION_HISTORY_BACKEND_URL }); console.log(`Assembled ${manifest.length} demos from demos.json`); + +await installDemoAnalytics(output, manifest.map(d=>d.liveDemoUri.replace(/^\/+|\/+$/g,''))); diff --git a/scripts/build-gallery.mjs b/scripts/build-gallery.mjs index c90d18e..952af0b 100644 --- a/scripts/build-gallery.mjs +++ b/scripts/build-gallery.mjs @@ -1,3 +1,4 @@ +import { installDemoAnalytics } from './install-demo-analytics.mjs'; import { cp, mkdir, readFile, rm } from "node:fs/promises"; import { spawnSync } from "node:child_process"; import path from "node:path"; @@ -62,3 +63,5 @@ await cp( await renderGallery({ mode: "local", output: path.join(output, "index.html") }); console.log(`Built local gallery in ${path.relative(root, output)}/`); + +await installDemoAnalytics(output, [...demos.map(d=>d.route),'collab']); diff --git a/scripts/demo-analytics.test.mjs b/scripts/demo-analytics.test.mjs new file mode 100644 index 0000000..d195d87 --- /dev/null +++ b/scripts/demo-analytics.test.mjs @@ -0,0 +1,34 @@ +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; + 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 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;}}; +} +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);}); +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`,()=>{ + 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 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); + }); +} +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); +}); diff --git a/scripts/install-demo-analytics.mjs b/scripts/install-demo-analytics.mjs new file mode 100644 index 0000000..1e518c1 --- /dev/null +++ b/scripts/install-demo-analytics.mjs @@ -0,0 +1,6 @@ +import {copyFile,readFile,writeFile} from 'node:fs/promises'; +import path from 'node:path'; +export async function installDemoAnalytics(output,routes){ + await copyFile(new URL('../analytics/demo-analytics.js',import.meta.url),path.join(output,'demo-analytics.js')); + for(const route of ['',...routes]){const file=path.join(output,route,'index.html'),html=await readFile(file,'utf8');if(!html.includes('src="/demo-analytics.js"'))await writeFile(file,html.replace('','\n'));} +} diff --git a/template-builder-document-api-v2-demo/src/App.vue b/template-builder-document-api-v2-demo/src/App.vue index 262deb9..9abfa4d 100644 --- a/template-builder-document-api-v2-demo/src/App.vue +++ b/template-builder-document-api-v2-demo/src/App.vue @@ -1,4 +1,6 @@