@reqvire-org/ads 0.4.4 → 0.4.5
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/README.md +11 -8
- package/dist/cli.mjs +1 -1
- package/dist/mcp/apps.mjs +7 -1
- package/dist/mcp/drafts.mjs +7 -0
- package/dist/mcp/preview-http.bundle.js +7 -0
- package/dist/mcp/preview-http.mjs +148 -0
- package/dist/mcp/preview-widget.bundle.js +20 -20
- package/dist/mcp/resource-loader.js +1 -1
- package/dist/mcp/sandbox-host.mjs +6 -1
- package/dist/mcp/server.mjs +25 -1
- package/dist/mcp/showcase-host.mjs +55 -5
- package/dist/mcp/showcase-http.mjs +66 -0
- package/dist/scenarios-compiler.mjs +19 -1
- package/dist/showcase/client.bundle.js +54 -54
- package/dist/showcase/comparison.js +15 -12
- package/dist/showcase/connection.js +10 -0
- package/dist/showcase/http-client.bundle.js +9 -0
- package/dist/showcase/http-connection.js +86 -0
- package/dist/showcase/http-preview.js +81 -0
- package/dist/showcase-http-routes.mjs +31 -0
- package/dist/skills/README.md +2 -2
- package/dist/skills/ads-designer/references/captures.md +1 -1
- package/dist/skills/ads-designer/references/runtimes.md +18 -2
- package/dist/skills/ads-designer/references/workflows.md +16 -0
- package/dist/skills/ads-import/references/captures.md +1 -1
- package/dist/skills/ads-import/references/runtimes.md +18 -2
- package/dist/skills/ads-import/references/workflows.md +16 -0
- package/dist/skills/ads-migrate/SKILL.md +1 -0
- package/dist/skills/ads-migrate/references/0.4.3-to-0.4.4.md +9 -0
- package/dist/skills/ads-migrate/references/0.4.4-to-0.4.5.md +72 -0
- package/dist/skills/ads-port/references/captures.md +1 -1
- package/dist/skills/ads-port/references/runtimes.md +18 -2
- package/dist/skills/ads-port/references/workflows.md +16 -0
- package/dist/verification/browser.mjs +2 -2
- package/docs/ADS.md +9 -7
- package/docs/ARCHITECTURE.md +48 -42
- package/docs/CHANGELOG.md +65 -0
- package/docs/GUIDE.md +15 -8
- package/docs/HTTP-SHOWCASE-POC.md +397 -0
- package/docs/MCP.md +63 -9
- package/docs/benchmarks/http-showcase-optimized.json +1879 -0
- package/docs/benchmarks/http-showcase-profile.json +308 -0
- package/docs/benchmarks/http-showcase.json +3069 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -234,14 +234,17 @@ Clients without Apps can inspect text/resources and use the regular showcase.
|
|
|
234
234
|
|
|
235
235
|
## Showcase
|
|
236
236
|
|
|
237
|
-
The showcase is
|
|
238
|
-
|
|
239
|
-
collapsible
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
237
|
+
The showcase is a neutral browser workspace delivered over HTTP. Brand, Icons,
|
|
238
|
+
Pictograms, Tokens, Components, Patterns and Composition share its header,
|
|
239
|
+
collapsible menu, theme/brand switches and preview area. The browser receives
|
|
240
|
+
catalogues and checked assets directly from the local ADS runtime, with live
|
|
241
|
+
build reports over server-sent events. It contains no MCP client.
|
|
242
|
+
|
|
243
|
+
Real scenarios run inside a persistent, isolated preview iframe. Compatible
|
|
244
|
+
edits update that frame while retaining state; project code and styles stay
|
|
245
|
+
inside its sandbox. Agents and external MCP Apps use the same compiler and
|
|
246
|
+
checks through the existing MCP interface. The project owns its implementations
|
|
247
|
+
and colocated scenarios/fixtures.
|
|
245
248
|
|
|
246
249
|
Starting `ads mcp` also starts the local showcase. Open the URL returned by
|
|
247
250
|
`ads_status`; use that existing runtime when an agent is already connected.
|
package/dist/cli.mjs
CHANGED
|
@@ -30,7 +30,7 @@ Usage: ads init [options] Run inside your project
|
|
|
30
30
|
assets [directory] Generate configured brand assets, glyphs, themes.generated.css and .ts,
|
|
31
31
|
the styles entry, and the public/review barrels from .ads.exports.ts files
|
|
32
32
|
mcp [directory] Serve stdio MCP tools/Apps and the local showcase website
|
|
33
|
-
showcase [directory] Serve the built-in
|
|
33
|
+
showcase [directory] Serve the built-in HTTP showcase (no stdio connection)
|
|
34
34
|
|
|
35
35
|
--help Show this help
|
|
36
36
|
--version Show the tool version
|
package/dist/mcp/apps.mjs
CHANGED
|
@@ -10,7 +10,13 @@ const safeJson = (value) => JSON.stringify(value).replaceAll("<", "\\u003c");
|
|
|
10
10
|
|
|
11
11
|
export function previewApp(selection) {
|
|
12
12
|
const script = readFileSync(new URL("./preview-widget.bundle.js", import.meta.url), "utf8").replaceAll("</script", "<\\/script");
|
|
13
|
-
return
|
|
13
|
+
return previewDocument(`<script type="module">${script}</script>`, selection);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The same frame document/framing for MCP Apps and local HTTP previews. */
|
|
17
|
+
export function previewDocument(scriptTag, selection) {
|
|
18
|
+
const seed = selection ? `<script type="application/json" id="ads-preview-selection">${safeJson(selection)}</script>` : "";
|
|
19
|
+
return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>ADS preview</title><style>html,body,#root{height:100%;margin:0}body{overflow:auto}#ads-preview-status{position:fixed;inset:12px 12px auto;z-index:2147483647;padding:12px;border:1px solid GrayText;background:Canvas;color:CanvasText;font:13px system-ui;white-space:pre-wrap}#ads-preview-status[hidden]{display:none}</style></head><body><aside id="ads-preview-status" role="status" hidden></aside><div id="root"></div>${seed}${scriptTag}</body></html>`;
|
|
14
20
|
}
|
|
15
21
|
|
|
16
22
|
export function tokenWidgetData(inventory) {
|
package/dist/mcp/drafts.mjs
CHANGED
|
@@ -1207,6 +1207,13 @@ export function createDraftController(directory, { edits, startPreview, prewarm
|
|
|
1207
1207
|
await session.starting;
|
|
1208
1208
|
return session.runtime.readResource(uri, signal);
|
|
1209
1209
|
},
|
|
1210
|
+
async capturePreview(id, uri, signal) {
|
|
1211
|
+
const session = previews.get(id);
|
|
1212
|
+
if (session?.error) throw new Error(`Draft preview is stale: ${session.error}`);
|
|
1213
|
+
if (!session?.starting) throw new Error("Draft preview is not active. Reopen ads_show_draft.");
|
|
1214
|
+
await session.starting;
|
|
1215
|
+
return session.runtime.capturePreview(uri, signal);
|
|
1216
|
+
},
|
|
1210
1217
|
fingerprint: () => `${draftStamp()}:${discoveryVersion}`,
|
|
1211
1218
|
async close() {
|
|
1212
1219
|
closed = true;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
function Pe(){let e=new Map,s=new Set,r=!1,t;function n(i){let u={data:e.get(i)?.data??{},callbacks:[],listeners:new Map};return e.set(i,u),{data:u.data,accept(d,m){if(!d||typeof d==="function")u.callbacks.push({deps:[i],callback:(a)=>d?.(a[0])});else u.callbacks.push({deps:typeof d==="string"?[d]:d,callback:(a)=>m?.(typeof d==="string"?a[0]:a)})},acceptExports(d,m){u.callbacks.push({deps:[i],callback:(a)=>m?.(a[0])})},dispose(d){u.dispose=d},prune(d){u.prune=d},invalidate(){r=!0},decline(){r=!0},on(d,m){let a=u.listeners.get(d)??new Set;a.add(m),u.listeners.set(d,a)},off(d,m){u.listeners.get(d)?.delete(m)},send(){throw Error("Preview hot-update custom messages are not a public transport.")}}}async function o(i){for(let c of e.values())for(let u of c.listeners.get(i)??[])await u()}return{context:n,observe(i,c,u){let d=e.get(i);if(!d)return;let m=import(c).then((a)=>{d.exports=a,d.isComponent=u});s.add(m),m.then(()=>s.delete(m),(a)=>{s.delete(m),t=a})},async update(i,c,u,d){if(await Promise.all(s),t)throw t;let m=new Map([...i].filter(([,l])=>l.hot).map(([l,f])=>[f.hot.id,{uri:l,record:f}])),a=new Map([...c].filter(([,l])=>l.hot).map(([l,f])=>[f.hot.id,{uri:l,record:f}])),w=new Map,h=new Map;for(let[l,{record:f}]of m)for(let v of[...f.imports,...f.dynamicImports]){let S=i.get(v)?.hot?.id;if(!S)continue;let E=w.get(S)??new Set;E.add(l),w.set(S,E)}function b(l,f=new Set){if(f.has(l))return!1;let v=e.get(l);if(v?.callbacks.some((R)=>R.deps.includes(l))&&a.has(l))return h.set(l,v),!0;let S=w.get(l);if(!S?.size)return!1;let E=new Set([...f,l]);for(let R of S)if(!b(R,E))return!1;return!0}for(let[l,{record:f}]of m){let v=a.get(l)?.record;if(!v||f.hot.source!==v.hot.source){if(!b(l))return!1}}if(!h.size)return!0;r=!1,await o("vite:beforeUpdate");let y=[];for(let[l,f]of h){if(!d())return!1;await f.dispose?.(f.data),y.push([l,f,await u(a.get(l).uri)])}if(!d())return!1;for(let[,l,f]of y)if(l.isComponent){let v=l.exports,S=Object.keys(f).filter((E)=>E!=="__esModule");if(!v||S.length!==Object.keys(v).filter((E)=>E!=="__esModule").length||S.some((E)=>!Object.hasOwn(v,E)||!l.isComponent(f[E])&&v[E]!==f[E]))return!1}for(let[l,f,v]of y)for(let S of f.callbacks)if(S.deps.includes(l))await S.callback(S.deps.map((E)=>E===l?v:void 0));return await o("vite:afterUpdate"),await new Promise((l)=>setTimeout(l,20)),d()&&!r},async dispose(){for(let i of e.values())await i.dispose?.(i.data),await i.prune?.(i.data);e.clear(),s.clear(),t=void 0}}}async function Se(e,s){let r=await crypto.subtle.digest("SHA-256",s),t="sha256:"+[...new Uint8Array(r)].map((n)=>n.toString(16).padStart(2,"0")).join("");if(s.length!==e.size||t!==e.digest)throw Object.assign(Error("Preview resource integrity check failed. Rebuild and reopen the preview."),{code:"ADS_RESOURCE_INTEGRITY",category:"build"});return s}function Re(e,s){let r=[],t=new Set;function n(o){if(t.has(o))return;t.add(o);let i=e.get(o);if(!i)throw Error(`Missing preview dependency metadata: ${o}`);for(let c of[...i.imports,...i.styles,...i.references])n(c);r.push(o)}return n(s),r}function Oe(e,s){if(!e||e.revision===s.revision)return[];let r=(t,n)=>{let o=new Map(Object.entries(t.assets));return JSON.stringify(Re(o,n.module).map((i)=>[i,o.get(i)]))};return s.scenarios.filter((t)=>{let n=e.scenarios.find((o)=>o.id===t.id);return!n||r(e,n)!==r(s,t)}).map((t)=>t.id)}class me{constructor(e){this.read=e,this.records=new Map,this.bytes=new Map,this.urls=new Map,this.styles=new Map,this.styleReady=new Map,this.revisions=new Set,this.loadedModules=new Set,this.executed=new Map,this.moduleHistory=new Set,this.importing=Promise.resolve(),this.mounting=Promise.resolve(),this.refreshDirty=!1,this.generation=0,this.prefetchGeneration=0,this.closed=!1,this.hot=Pe(),globalThis.__adsPreviewHot=this.hot,globalThis.__dsPreviewImport=(s)=>this.importModule(s)}register(e){if(e.schemaVersion!==1||!Array.isArray(e.scenarios)||!e.assets||typeof e.revision!=="string")throw Error("Unsupported preview manifest. Rebuild previews with the installed ADS version.");if(e.refresh&&(e.refresh.version!==1||typeof e.refresh.epoch!=="string"||!e.refresh.epoch||e.refresh.epoch.length>100))throw Error("Unsupported preview refresh protocol. Reopen with the current ADS version.");let s=new Set;for(let[r,t]of Object.entries(e.assets)){if(!/^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/.test(r)||!/^sha256:[a-f0-9]{64}$/.test(t.digest)||t.hot&&(!e.refresh||t.kind!=="module"||typeof t.hot.id!=="string"||!t.hot.id||t.hot.id.length>4096||s.has(t.hot.id)||!/^[a-f0-9]{64}$/.test(t.hot.source))||!["imports","dynamicImports","styles","references"].every((n)=>Array.isArray(t[n])&&t[n].every((o)=>Object.hasOwn(e.assets,o))))throw Error("Invalid preview dependency graph.");if(t.hot)s.add(t.hot.id);if(this.records.has(r)&&this.records.get(r).digest!==t.digest)throw Object.assign(Error("An immutable preview resource changed its content. Rebuild previews with the current ADS version."),{code:"ADS_RESOURCE_IDENTITY",category:"build",resourceUri:r})}for(let[r,t]of Object.entries(e.assets))this.records.set(r,t)}async resource(e){if(!this.bytes.has(e)){let s=(async()=>{let r=this.records.get(e);if(!r)throw Error(`Unknown preview dependency: ${e}`);let t;try{t=await this.read(e)}catch(i){throw Object.assign(Error(`Preview resource read failed for ${e}: ${i.message}`,{cause:i}),{code:"ADS_RESOURCE_READ",category:"transport",resourceUri:e})}if(this.closed)throw Error("The preview App was closed.");let n=t.contents.find((i)=>i.uri===e);if(!n)throw Object.assign(Error(`Missing preview dependency: ${e}`),{code:"ADS_RESOURCE_CONTENT",category:"build",resourceUri:e});let o=typeof n.text==="string"?new TextEncoder().encode(n.text):Uint8Array.from(atob(n.blob),(i)=>i.charCodeAt(0));try{return await Se(r,o)}catch(i){throw i.resourceUri=e,i}})();this.bytes.set(e,s),s.catch(()=>this.bytes.delete(e))}return this.bytes.get(e)}closure(e){return Re(this.records,e)}async prefetch(e,s){if(this.closed)return;this.register(e);let r=++this.prefetchGeneration,t=new Set,n=[],o=0;for(let d of s){let m=e.scenarios.find((h)=>h.id===d);if(!m)continue;let a=this.closure(m.module).filter((h)=>!this.bytes.has(h)&&!t.has(h)),w=a.reduce((h,b)=>h+this.records.get(b).size,0);if(o+w>16777216||t.size+a.length>256)continue;o+=w,n.push(d);for(let h of a)t.add(h)}let i=[...t],c=0,u=async()=>{while(!this.closed&&r===this.prefetchGeneration&&c<i.length)await this.resource(i[c++])};return await Promise.all(Array.from({length:Math.min(3,i.length)},u)),{scenarios:n,resources:i.length}}async materialize(e){let s=this.closure(e);await Promise.all(s.map((t)=>this.resource(t)));let r={};for(let t of s){if(this.closed)throw Error("The preview App was closed.");if(this.urls.has(t))continue;let n=this.records.get(t),o=await this.resource(t);if(n.kind==="module"||n.mimeType==="text/css"||n.mimeType==="text/javascript"){let c=new TextDecoder().decode(o);for(let u of n.references){let d=this.urls.get(u);if(!d)throw Error("Unsupported cyclic asset reference.");c=c.replaceAll(u,d)}o=c}let i=URL.createObjectURL(new Blob([o],{type:n.mimeType}));if(this.urls.set(t,i),n.kind==="module")r[t]=i}if(Object.keys(r).length){let t=document.createElement("script");t.type="importmap",t.textContent=JSON.stringify({imports:r}),document.head.append(t)}return s}async importModule(e){let s=this.importing.then(()=>this.materialize(e));this.importing=s.catch(()=>{});let r=await s;await this.attachStyles(r);try{let t=await import(e);this.loadedModules.add(e);for(let n of r){let o=this.records.get(n);if(o.hot)this.executed.set(o.hot.id,{uri:n,record:o}),this.moduleHistory.add(n)}return t}catch(t){throw Error(`Preview module import failed for ${e}: ${t.message}. Inspect the App resource bridge, browser network/CSP diagnostics and current build.`,{cause:t})}}async attachStyles(e){for(let s of e){if(this.records.get(s).mimeType!=="text/css")continue;if(this.styles.has(s)){await this.styleReady.get(s);continue}let t=document.createElement("link");t.rel="stylesheet",t.href=this.urls.get(s),this.styles.set(s,t);let n=new Promise((o,i)=>{t.onload=o,t.onerror=()=>i(Error("The host CSP blocked a preview stylesheet."))});this.styleReady.set(s,n),document.head.append(t);try{await n}catch(o){throw t.remove(),this.styles.delete(s),this.styleReady.delete(s),o}}}async refreshStyles(e,s){let r=[e],t=new Set,n=new Set;for(let o=0;o<r.length;o++){let i=r[o];if(t.has(i))continue;t.add(i);for(let c of await this.materialize(i)){n.add(c);for(let u of this.records.get(c).dynamicImports)if(this.loadedModules.has(u)||this.executed.has(this.records.get(u)?.hot?.id))r.push(u)}}if(await this.attachStyles([...n]),s!==this.generation||this.closed)return!1;for(let[o,i]of this.styles)if(!n.has(o))i.remove(),this.styles.delete(o),this.styleReady.delete(o);for(let o of n)if(this.styles.has(o))document.head.append(this.styles.get(o));return!0}async mount(e,s,r){let t=++this.generation,n=this.mounting.then(()=>t!==this.generation||this.closed?!1:this.mountRevision(e,s,r,t));return this.mounting=n.catch(()=>{}),n}async mountRevision(e,s,r,t){this.register(e);let n=e.scenarios.find((a)=>a.id===s);if(!n)throw Error("The selected scenario is no longer registered.");let o=JSON.stringify(this.closure(n.module).map((a)=>[a,this.records.get(a)])),i=new Map(this.closure(n.module).map((a)=>[a,this.records.get(a)])),c=(a)=>{throw Object.assign(Error(a),{code:"ADS_PREVIEW_REOPEN"})};if(this.refreshDirty)c("An interrupted module update requires a clean preview frame.");let u=[...this.urls.keys()].reduce((a,w)=>a+this.records.get(w).size,0);if(this.records.size>4096||u>67108864)c("Reopen the preview to release retained module revisions.");if(this.mounted&&this.mounted.refresh?.epoch!==e.refresh?.epoch)c("The preview compiler changed. Reopening an isolated frame for its new runtime.");if(e.refresh&&this.mounted){let a=new Map(Object.entries(e.assets)),w=new Map([...a].filter(([,y])=>y.hot).map(([y,l])=>[l.hot.id,{uri:y,record:l}]));for(let[y,{record:l}]of this.executed){let f=w.get(y);if(f&&f.record.hot.source!==l.hot.source&&this.moduleHistory.has(f.uri))c("Restoring a previous module revision requires a clean preview frame.")}let h=new Map([...this.executed.values()].map(({uri:y,record:l})=>[y,l]));this.refreshDirty=!0;let b=await this.hot.update(h,a,(y)=>this.importModule(y),()=>t===this.generation&&!this.closed);if(t!==this.generation||this.closed)return!1;if(!b)c("This edit changes a refresh boundary. Reopening the preview with fresh component state.");this.refreshDirty=!1;for(let y of this.executed.keys())if(w.has(y))this.executed.set(y,w.get(y));if(this.mounted.id===s){if(!await this.refreshStyles(n.module,t))return!1;return this.revisions.add(n.module),this.mounted={...this.mounted,signature:o,records:i,module:n.module},!0}}if(this.mounted?.id===s&&this.mounted.container===r&&this.mounted.signature===o)return this.refreshStyles(n.module,t);if(this.revisions.add(n.module),!e.refresh&&this.revisions.size>20)throw Object.assign(Error("Reopen the preview to release retained module revisions."),{code:"ADS_PREVIEW_REOPEN"});let d=await this.importModule(n.module);if(t!==this.generation)return!1;let m=this.unmount;if(this.unmount=void 0,this.mounted=void 0,await m?.(),t!==this.generation||this.closed)return!1;if(r.replaceChildren(),!await this.refreshStyles(n.module,t))return!1;if(typeof d.mount!=="function")throw Error("The compiled scenario has no mount adapter.");if(this.unmount=d.mount(r),typeof this.unmount!=="function")throw Error("The scenario mount adapter must return an unmount callback.");return this.mounted={id:s,container:r,signature:o,records:i,module:n.module,refresh:e.refresh},!0}async dispose(){if(this.closed)return;this.closed=!0,++this.generation,++this.prefetchGeneration,await this.mounting,await this.unmount?.(),await this.hot.dispose(),this.mounted=void 0;for(let e of this.styles.values())e.remove();for(let e of this.urls.values())URL.revokeObjectURL(e);if(this.styles.clear(),this.styleReady.clear(),this.urls.clear(),this.bytes.clear(),this.records.clear(),this.revisions.clear(),this.loadedModules.clear(),this.executed.clear(),this.moduleHistory.clear(),delete globalThis.__dsPreviewImport,globalThis.__adsPreviewHot===this.hot)delete globalThis.__adsPreviewHot}}var Ee="ads-preview-guide-options",Ce="ads-preview-guide-state",Ye=["off","hover","always"],Ke=["bounds","tracks","gaps","padding","margins","mini"],nt=Object.freeze({mode:"off",bounds:!0,tracks:!1,gaps:!1,padding:!0,margins:!0,mini:!1});function ge(e){return{mode:Ye.includes(e?.mode)?e.mode:e?.all===!0?"always":"off",...Object.fromEntries(Ke.map((r)=>[r,e?.[r]===!0]))}}function Me(e){let{mode:s,...r}=ge(e);return{all:s==="always",...r}}function Te(e){let{mode:s,...r}=ge(e);return s!=="off"&&Object.values(r).some(Boolean)}function $e(e,{onDetails:s=()=>{}}={}){let r=e.ownerDocument,t=r.defaultView,n=(P)=>parseFloat(P)||0,o,i,c="",u,d=!1,m=[],a="components",w,h={},b=new Set,y=new t.ResizeObserver(f),l=new t.MutationObserver(f);function f(){if(d&&!i)i=t.requestAnimationFrame(_)}function v(P){let B=P.target,H=B?.closest?.("[data-ads-source]"),N=B?.closest?.('button, summary, a[href], [role="button"]'),D=H&&e.contains(H)?N&&e.contains(N)?N:B:null;if(w!==D)w=D,f()}function S(){if(w)w=null,f()}function E(P){if(!e.contains(P.relatedTarget))S(P)}function R(P){let B=P.closest("[data-ads-source]")?.dataset.adsSource;return m.filter((H)=>H.schemaVersion===1&&H.source===B).flatMap((H)=>H.rules.filter((N)=>{try{return P.matches(N.selector)}catch{return!1}}).flatMap((N)=>N.declarations))}function U(){let P=[...e.querySelectorAll("[data-ads-source]")].filter((B)=>{let H=B.getBoundingClientRect();return H.width&&H.height});if(P.length)return P;return[...(e.querySelector(".ads-preview-root")??e).children].filter((B)=>!["STYLE","SCRIPT","LINK","H1"].includes(B.tagName))}let F=()=>({width:r.documentElement.clientWidth,height:r.documentElement.clientHeight});function T(P){let{width:B,height:H}=F(),N={left:0,top:0,right:B,bottom:H};for(let D=P.parentElement;D;D=D.parentElement){let de=t.getComputedStyle(D),ne=D.getBoundingClientRect(),ue=D.offsetWidth?ne.width/D.offsetWidth:1,A=D.offsetHeight?ne.height/D.offsetHeight:1;if(/(auto|scroll|hidden|clip)/.test(de.overflowX))N.left=Math.max(N.left,ne.left+D.clientLeft*ue),N.right=Math.min(N.right,ne.left+(D.clientLeft+D.clientWidth)*ue);if(/(auto|scroll|hidden|clip)/.test(de.overflowY))N.top=Math.max(N.top,ne.top+D.clientTop*A),N.bottom=Math.min(N.bottom,ne.top+(D.clientTop+D.clientHeight)*A)}return N}function _(){if(i=void 0,!d)return;let P=U();if(w&&!e.contains(w))w=null;let B=h.all===!0?[...P]:w?[w]:[];if(h.all===!0)for(let A of P)for(let I of A.querySelectorAll("*")){if(I.closest("svg")||["STYLE","SCRIPT","LINK"].includes(I.tagName)||B.includes(I))continue;let O=t.getComputedStyle(I);if(/grid|flex/.test(O.display)||["paddingTop","paddingRight","paddingBottom","paddingLeft","marginTop","marginRight","marginBottom","marginLeft"].some((te)=>n(O[te])!==0))B.push(I)}if(w&&!B.includes(w))B.push(w);let H=B.filter((A)=>h.mini===!0||/\/components\//.test(A.closest("[data-ads-source]")?.dataset.adsSource??"")||a==="components"||a==="tokens"),N=new Set(H.filter((A)=>!H.some((I)=>I!==A&&I.contains(A)))),D=[],de=new Set([e]),ne=[];for(let A of B){let Q=function(G,L,p,C,V,q,J=!1){let Y={bounds:"bounds",content:"bounds",column:"tracks",row:"tracks",gap:"gaps",gutter:"gaps",margin:"margins",padding:"padding","mini-unit":"mini"}[V];if(p<=0||C<=0||h[Y]===!1)return;let K=r.createElement("div");return K.dataset.adsGuide=V,Object.assign(K.style,{position:"absolute",left:`${G}px`,top:`${L}px`,width:`${p}px`,height:`${C}px`,boxSizing:"border-box",...J?{border:`1px solid ${q}`}:{background:q}}),fe.append(K),K},X=function(G,L,p,C){let[V,q,J,Y]=G.map((pe,Fe)=>Math.max(0,pe)*(Fe%2?g:x)),K=L?O.left-Y:O.left+k[3]*g,ie=L?O.top-V:O.top+k[0]*x,ae=L?O.width+Y+q:O.width-(k[1]+k[3])*g,ce=L?O.height+V+J:O.height-(k[0]+k[2])*x;Q(K,ie,ae,V,p,C),Q(K,ie+ce-J,ae,J,p,C),Q(K,ie+V,Y,ce-V-J,p,C),Q(K+ae-q,ie+V,q,ce-V-J,p,C)},I=t.getComputedStyle(A),O=A.getBoundingClientRect(),te=T(A);if(!O.width||!O.height||O.right<=te.left||O.left>=te.right||O.bottom<=te.top||O.top>=te.bottom)continue;de.add(A);let g=A.offsetWidth?O.width/A.offsetWidth:1,x=A.offsetHeight?O.height/A.offsetHeight:1,M=["Top","Right","Bottom","Left"],k=M.map((G)=>n(I[`border${G}Width`])),z=M.map((G)=>n(I[`padding${G}`])),le=M.map((G)=>n(I[`margin${G}`])),se=O.left+(k[3]+z[3])*g,oe=O.top+(k[0]+z[0])*x,W=O.width-(k[1]+k[3]+z[1]+z[3])*g,re=O.height-(k[0]+k[2]+z[0]+z[2])*x,fe=r.createElement("div");if(fe.dataset.adsSpatialSource=A.dataset.adsSource??"measured-box",Object.assign(fe.style,{position:"fixed",inset:"0",clipPath:`inset(${te.top}px ${Math.max(0,F().width-te.right)}px ${Math.max(0,F().height-te.bottom)}px ${te.left}px)`}),Q(O.left,O.top,O.width,O.height,"bounds","rgb(70 120 250 / .75)",!0),N.has(A)){let G=I.getPropertyValue("--grid-mini-unit").trim(),L=/^\d*\.?\d+px$/.test(G)?n(G):/^\d*\.?\d+rem$/.test(G)?n(G)*n(t.getComputedStyle(r.documentElement).fontSize):0;if(L>0){let p=t.devicePixelRatio||1,C=Math.floor(O.left*p),V=Math.floor(O.top*p),q=Math.ceil(O.right*p)-C,J=Math.ceil(O.bottom*p)-V,Y=Q(C/p,V/p,q/p,J/p,"mini-unit","transparent");if(Y&&q>0&&J>0){Y.dataset.adsUnit=`${L}`,Y.dataset.adsMajor=`${L*2}`;let K=r.createElement("canvas");K.width=q,K.height=J,Object.assign(K.style,{display:"block",width:`${q/p}px`,height:`${J/p}px`,imageRendering:"pixelated"});let ie=K.getContext("2d");if(ie){let ae=[L*g*p,L*x*p];for(let ce=0;;ce++){let pe=Math.round(O.left*p+ce*ae[0])-C;if(pe>=q)break;ie.fillStyle=ce%2?"#617dba14":"#617dba38",ie.fillRect(pe,0,1,J)}for(let ce=0;;ce++){let pe=Math.round(O.top*p+ce*ae[1])-V;if(pe>=J)break;ie.fillStyle=ce%2?"#617dba14":"#617dba38",ie.fillRect(0,pe,q,1)}}Y.append(K)}}}if(X(le,!0,"margin","rgb(234 149 43 / .2)"),a!=="composition"||w===A||h.padding===!0)X(z,!1,"padding","rgb(55 186 130 / .22)");let Z=R(A);if(I.display.includes("grid")){let G=function(L,p){let C=L.replace(/\[[^\]]*\]/g,"").trim().split(/\s+/);if(!C.length||!C.every((K)=>/^\d*\.?\d+px$/.test(K)))return;let V=C.map(n),q=n(p==="columns"?I.columnGap:I.rowGap)*(p==="columns"?g:x),J=p==="columns"&&I.direction==="rtl",Y=p==="columns"?J?se+W:se:oe;fe.dataset[p==="columns"?"adsGridColumns":"adsGridRows"]=String(V.length),V.forEach((K,ie)=>{let ae=K*(p==="columns"?g:x);if(J)Y-=ae;if(Q(p==="columns"?Y:se,p==="columns"?oe:Y,p==="columns"?ae:W,p==="columns"?re:ae,p==="columns"?"column":"row","rgb(200 66 135 / .35)",!0),Y+=J?0:ae,ie<V.length-1)Q(p==="columns"?J?Y-q:Y:se,p==="columns"?oe:Y,p==="columns"?q:W,p==="columns"?re:q,"gap","rgb(200 66 135 / .12)");Y+=J?-q:q})};if(G(I.gridTemplateColumns,"columns"),Z.some((L)=>L.property==="grid-template-rows"&&L.value!=="none"))G(I.gridTemplateRows,"rows");for(let L of A.children){let p=t.getComputedStyle(L),C=L.getBoundingClientRect();if(p.display==="none"||!C.width||!C.height)continue;let V=n(p.marginLeft)*g,q=n(p.marginRight)*g;Q(C.left-V,C.top,V,C.height,"gutter","rgb(200 66 135 / .16)"),Q(C.right,C.top,q,C.height,"gutter","rgb(200 66 135 / .16)")}}if(I.display.includes("flex")||a==="composition"){let G=[...A.children].filter((L)=>{let p=L.getBoundingClientRect();return p.width&&p.height});for(let L of G){de.add(L);let p=L.getBoundingClientRect();Q(p.left,p.top,p.width,p.height,"content","rgb(70 120 250 / .5)",!0)}for(let L=1;L<G.length;L++){let p=G[L-1].getBoundingClientRect(),C=G[L].getBoundingClientRect();if(C.top>=p.bottom)Q(Math.max(p.left,C.left),p.bottom,Math.min(p.right,C.right)-Math.max(p.left,C.left),C.top-p.bottom,"gap","rgb(200 66 135 / .16)");else if(C.left>=p.right)Q(p.right,Math.max(p.top,C.top),C.left-p.right,Math.min(p.bottom,C.bottom)-Math.max(p.top,C.top),"gap","rgb(200 66 135 / .16)");else if(p.left>=C.right)Q(C.right,Math.max(p.top,C.top),p.left-C.right,Math.min(p.bottom,C.bottom)-Math.max(p.top,C.top),"gap","rgb(200 66 135 / .16)")}}if(D.push(fe),w===A){let G=[...new Set(Z.flatMap((L)=>L.value.match(/--[\w-]+/g)??[]))];ne.push({label:A.getAttribute("aria-label")??A.getAttribute("role")??A.tagName.toLowerCase(),width:Math.round(O.width*10)/10,height:Math.round(O.height*10)/10,display:I.display,padding:z,margin:le,rowGap:I.rowGap,columnGap:I.columnGap,tokens:G})}}for(let A of b)if(!de.has(A))y.unobserve(A),b.delete(A);for(let A of de)if(!b.has(A))y.observe(A),b.add(A);let ue=ne[0];if(ue){u=w;let A=JSON.stringify(ue);if(A!==c)c=A,s(ue)}else if(u&&!e.contains(u))ee();o.replaceChildren(...D)}function ee(){u=void 0,c="",s(null)}function j(P){if(d===P){f();return}if(d=P,P)o=r.createElement("div"),o.id="ads-grid-overlay",o.setAttribute("aria-hidden","true"),o.style.cssText="position:fixed;inset:0;z-index:2147483646;pointer-events:none;overflow:hidden",r.body.append(o),l.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),l.observe(r.documentElement,{attributes:!0}),e.addEventListener("pointermove",v,{passive:!0}),e.addEventListener("pointerleave",S),e.addEventListener("focusin",v),e.addEventListener("focusout",E),t.addEventListener("resize",f),r.addEventListener("scroll",f,!0),f();else t.cancelAnimationFrame(i),i=void 0,y.disconnect(),b.clear(),l.disconnect(),e.removeEventListener("pointermove",v),e.removeEventListener("pointerleave",S),e.removeEventListener("focusin",v),e.removeEventListener("focusout",E),t.removeEventListener("resize",f),r.removeEventListener("scroll",f,!0),o?.remove(),o=void 0,w=null,ee()}return{setVisible:j,setGuides(P){h=P??{},f()},setMetadata(P,B){m=P,a=B,w=null,ee(),f()},dispose(){j(!1)}}}function Xe(e){let s=e.map((r)=>({...r}));for(let r=!0;r;){r=!1;e:for(let t=0;t<s.length;t++)for(let n=t+1;n<s.length;n++){let o=s[t],i=s[n];if(o.left<=i.right&&i.left<=o.right&&o.top<=i.bottom&&i.top<=o.bottom){s[t]={left:Math.min(o.left,i.left),top:Math.min(o.top,i.top),right:Math.max(o.right,i.right),bottom:Math.max(o.bottom,i.bottom)},s.splice(n,1),r=!0;break e}}}return s}function je(e,{decorate:s=!0}={}){let r=e.ownerDocument,t=r.defaultView,n=[],o=null,i=null,c=null,u=0,d=null,m=new t.ResizeObserver(()=>v()),a=new t.MutationObserver(()=>S()),w=()=>v();function h(E){let R=E.dataset.adsSource??"";return!R.includes(".ads.")&&n.some((U)=>R.startsWith(`${U}/`)||R.startsWith(`${U}.`))}function b(){if(d?.remove(),d=null,c)delete c.dataset.adsStaged,delete c.dataset.adsSubjectOnly}function y(E){if(E===c)return;if(c?.removeEventListener("scroll",w),m.disconnect(),b(),c=E,!c)return;c.addEventListener("scroll",w,{passive:!0}),m.observe(c)}function l(){y(e.querySelector(":scope > .ads-preview-root"));let E=!c?[]:o?[...c.querySelectorAll(o)]:n.length?[...c.querySelectorAll("[data-ads-source]")].filter(h):[],R=E.filter((T)=>!E.some((_)=>_!==T&&_.contains(T))),U=R.length===1?R[0].parentElement:null,F=U&&(U===c||U.parentElement===c&&U.children.length===1)&&[...c.children].every((T)=>T===d||T===U||T===R[0]);return c?.toggleAttribute("data-ads-subject-only",Boolean(F)),R}function f(){u=0;let E=l();if(!s||c?.hasAttribute("data-ads-subject-only")){if(d?.remove(),d=null,c)delete c.dataset.adsStaged;return}let R=(j)=>{let P=j.parentElement;if(!P||P===c||P.children.length!==1)return j;return[...P.childNodes].some((B)=>B.nodeType===3&&B.textContent.trim())?P:j},U=Xe(E.map(R).flatMap((j)=>{m.observe(j);let P=j.getBoundingClientRect(),B=i&&j.matches(i)?0:8;return P.width&&P.height?[{left:P.left-B,top:P.top-B,right:P.right+B,bottom:P.bottom+B}]:[]}));if(!U.length){b();return}let F=c.getBoundingClientRect(),T={left:F.left+c.clientLeft,top:F.top+c.clientTop};if(T.right=T.left+c.clientWidth,T.bottom=T.top+c.clientHeight,!d||d.parentElement!==c)d?.remove(),d=r.createElement("div"),d.dataset.adsSubjectStage="",d.setAttribute("aria-hidden","true"),Object.assign(d.style,{position:"fixed",inset:"0",pointerEvents:"none",background:"var(--bg-canvas, Canvas)",zIndex:"-1"}),c.prepend(d);c.dataset.adsStaged="";let _=U.map((j)=>({left:Math.max(j.left,T.left),top:Math.max(j.top,T.top),right:Math.min(j.right,T.right),bottom:Math.min(j.bottom,T.bottom)})).filter((j)=>j.right>j.left&&j.bottom>j.top),ee=(j)=>`M${j.left} ${j.top}H${j.right}V${j.bottom}H${j.left}Z`;d.style.clipPath=_.length?`path("${_.map(ee).join("")}")`:"inset(50%)",d.dataset.adsStages=String(U.length)}function v(){if(!u)u=t.requestAnimationFrame(f)}function S(){l(),v()}return a.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","hidden","open","data-ads-source"]}),t.addEventListener("resize",v),{setSubjects(E){n=[...E??[]],o=null,i=null,S()},setSubjectSelector(E,R=null){n=[],o=E||null,i=R,S()},refresh:S,dispose(){if(a.disconnect(),u)t.cancelAnimationFrame(u);t.removeEventListener("resize",v),y(null),b(),n=[],o=null,i=null}}}function Le(e){return Array.isArray(e)&&e.length>0&&e.every((s)=>s&&typeof s==="object"&&typeof s.token==="string"&&/^--[\w-]+$/.test(s.token)&&typeof s.property==="string"&&/^-?[a-z][a-z0-9-]*$/.test(s.property)&&typeof s.probe==="string"&&s.probe.trim().length>0)&&new Set(e.map((s)=>`${s.token}:${s.property}`)).size===e.length}function Ue(e,s){let r=s.getComputedStyle(e),t=e.getBoundingClientRect();if(r.display==="none"||r.visibility!=="visible"||!e.getClientRects().length||!(t.width||t.height))return!1;for(let n=e;n;n=n.parentElement)if(Number(s.getComputedStyle(n).opacity)===0)return!1;return!0}function Be(e,s){if(!Le(s))return{ok:!1,diagnostics:["Token preview needs explicit { token, property, probe } samples from the project fixture. Rebuild with the current compiler."]};let r=e.ownerDocument,{defaultView:t,documentElement:n}=r,o=[],i=[],c=[...e.querySelectorAll("[data-ads-token], [data-ads-property]")],u=new Set(s.map((d)=>`${d.token}:${d.property}`));for(let d of c)if(!u.has(`${d.dataset.adsToken}:${d.dataset.adsProperty}`))o.push(`Undeclared rendered token sample ${d.dataset.adsToken}:${d.dataset.adsProperty}.`);for(let d of s){if(!t.CSS.supports(d.property,d.probe)){o.push(`${d.token}: the fixture probe is invalid for ${d.property}.`);continue}let m=t.getComputedStyle(n).getPropertyValue(d.token).trim();if(!m||!t.CSS.supports(d.property,m)){o.push(`${d.token}: its current value is invalid for the fixture's ${d.property} binding.`);continue}let a=c.filter((h)=>h.dataset.adsToken===d.token&&h.dataset.adsProperty===d.property);if(!a.length){o.push(`${d.token} needs a rendered ${d.property} sample, not only a name/value label.`);continue}let w=!1;for(let h of a){let b=[];for(let f=h.parentElement;f&&f!==e;f=f.parentElement)if(f.tagName==="DETAILS"&&!f.open)f.open=!0,b.push(f);let y=n.getAttribute("style"),l=h.getAttribute("style");try{if(!/^(?:-[a-z]+-)?transition(?:-|$)/.test(d.property))h.style.setProperty("transition","none","important");let f=t.getComputedStyle(h).getPropertyValue(d.property),v=Ue(h,t);n.style.setProperty(d.token,d.probe,"important");let S=t.getComputedStyle(h).getPropertyValue(d.property);w=Boolean(S&&S!==f&&(v||Ue(h,t)))}finally{if(y===null)n.removeAttribute("style");else n.setAttribute("style",y);if(l===null)h.removeAttribute("style");else h.setAttribute("style",l);for(let f of b)f.open=!1}if(w)break}if(w)i.push(d);else o.push(`${d.token} has no visible ${d.property} sample that responds to its value. Hardcoded copies do not satisfy coverage.`)}return{ok:!o.length,verified:i,diagnostics:o}}function Ie({container:e=document.getElementById("root"),bindings:s=[],auditResources:r=!1}={}){let t=[],n=[],o=[];if(!e||!Array.isArray(s)||s.length>100)return{ok:!1,diagnostics:["Invalid bounded paint-audit descriptor."],verified:n};let i=e.ownerDocument,c=i.defaultView,u=["color","fill","stroke","stop-color","background-color","border-top-color","border-right-color","border-bottom-color","border-left-color"];function d(a,w,h,b=new Set){if(a=a.trim(),["none","currentColor"].includes(a))return!0;let y=/^var\(\s*(--[\w-]+)\s*\)$/.exec(a);if(y){let v=y[1];if(!h.tokens.includes(v)||b.has(v))return!1;let S=c.getComputedStyle(w).getPropertyValue(v).trim();return!!S&&c.CSS.supports("color",S)}let l=Array.isArray(h.themes)?h.themes:[];if(l.length&&a.startsWith("var(--ads-if-")){let v=/^var\(\s*--ads-if-([a-z][a-z0-9-]*)\s*,\s*(var\(\s*--[\w-]+\s*\)|currentColor|none)\s*\)/,S=a,E=[];while(S){let R=v.exec(S);if(!R)return!1;E.push(R),S=S.slice(R[0].length).trimStart()}return E.length===l.length&&E.every((R,U)=>R[1]===l[U]&&d(R[2],w,h,b))}let f=/^url\(\s*(["']?)#([^\s"'()#\\\p{Cc}]+)\1\s*\)$/u.exec(a);if(f&&c.CSS.supports("fill",a)){let v=[...i.querySelectorAll("[id]")].filter((S)=>S.id===f[2]);return v.length===1&&["linearGradient","radialGradient","pattern"].includes(v[0].localName)&&w.contains(v[0])}return!1}for(let a of s){if(!a||typeof a.scope!=="string"||!Array.isArray(a.tokens)||typeof a.prefix!=="string"||typeof a.suffix!=="string"){t.push("Invalid paint binding metadata; rebuild previews.");continue}let w;try{w=[...e.querySelectorAll(a.scope)]}catch{t.push(`${a.owner}: invalid binding scope.`);continue}if(w.length>20)o.push(`${a.owner}: only the first 20 instances were audited; use a focused scenario for complete evidence.`);for(let h of w.slice(0,20)){let b=[h,...h.querySelectorAll("*")];if(b.length>1000){o.push(`${a.owner}: instance exceeds 1000 elements; paint effects are not established.`);continue}let y=[...h.style].filter((l)=>l.startsWith(a.prefix)&&l.endsWith(a.suffix));if(y.length>100)o.push(`${a.owner}: only the first 100 binding keys were audited.`);for(let l of y.slice(0,100)){let f=h.style.getPropertyValue(l).trim(),v=l.slice(a.prefix.length,a.suffix?-a.suffix.length:void 0);if(!/^[A-Za-z0-9_-]+$/.test(v)||!d(f,h,a)){t.push(`${a.owner}: invalid or inaccessible paint ${l}: ${f}. Use an accessible token, instance-local SVG paint server, none or currentColor.`);continue}let S=h.getAttribute("style"),E=b.map((R)=>R.getAttribute("style"));try{for(let F of b)F.style.setProperty("transition","none","important");let R=b.map((F)=>u.map((T)=>c.getComputedStyle(F).getPropertyValue(T)));h.style.setProperty(l,"rgb(17, 103, 211)","important");let U=b.some((F,T)=>u.some((_,ee)=>c.getComputedStyle(F).getPropertyValue(_)!==R[T][ee]));if(!U)h.style.setProperty(l,"rgb(211, 67, 23)","important"),U=b.some((F,T)=>u.some((_,ee)=>c.getComputedStyle(F).getPropertyValue(_)!==R[T][ee]));if(!U)o.push(`${a.owner}: ${l} has no observed paint effect in its current instance. A written variable alone is not rendering evidence; check the relevant selected/visible consumer.`);else n.push({owner:a.owner,binding:a.name,variable:l})}finally{if(b.forEach((R,U)=>{if(E[U]===null)R.removeAttribute("style");else R.setAttribute("style",E[U])}),S===null)h.removeAttribute("style");else h.setAttribute("style",S)}}for(let l of b)for(let f of["fill","stroke","stop-color"]){let v=l.getAttribute(f);if(!v)continue;let S=/^var\(\s*(--[\w-]+)\s*\)$/.exec(v);if(S&&S[1].startsWith(a.prefix)&&S[1].endsWith(a.suffix)&&!y.includes(S[1]))t.push(`${a.owner}: ${S[1]} is consumed without a value in this instance.`);if(v.startsWith("url(")&&!d(v,h,a))t.push(`${a.owner}: missing, duplicated or out-of-instance local paint resource ${v}.`)}}}let m=r?[...e.querySelectorAll("[fill], [stroke], [style]")]:[];if(m.length>1000)o.push("Only the first 1000 potential SVG paint consumers were audited.");for(let a of m.slice(0,1000))for(let w of["fill","stroke"]){let h=a.getAttribute(w)??a.style.getPropertyValue(w);if(!h?.startsWith("url("))continue;let b=/^url\(\s*(["']?)#([^\s"'()#\\\p{Cc}]+)\1\s*\)$/u.exec(h)?.[2],y=b?[...i.querySelectorAll("[id]")].filter((f)=>f.id===b):[],l=a.ownerSVGElement??(a.localName==="svg"?a:null);if(y.length!==1||!l?.contains(y[0])||!["linearGradient","radialGradient","pattern"].includes(y[0]?.localName))t.push(`Invalid, missing, duplicated or nonlocal SVG paint resource ${h}. Keep IDs isolated per rendered instance.`)}return{ok:!t.length,complete:!o.length,verified:n,diagnostics:t.slice(0,40),limits:o.slice(0,20),scope:"observed App instances and current input; repeat after updates"}}var ze=/^[a-f0-9]{64}$/,Ze=/^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/;function xe(e){if(e?.schemaVersion!==1||!["react","preact"].includes(e.framework)||!ze.test(e.revision)||!e.assets||typeof e.assets!=="object"||Array.isArray(e.assets)||!Array.isArray(e.scenarios))throw Error("Invalid preview manifest update.");let s=new Set;for(let r of e.scenarios){if(!r||typeof r.id!=="string"||s.has(r.id)||e.assets[r.module]?.kind!=="module")throw Error("Invalid updated preview scenarios.");s.add(r.id)}for(let[r,t]of Object.entries(e.assets))if(!Ze.test(r)||!t||!["imports","dynamicImports","styles","references"].every((n)=>Array.isArray(t[n])&&t[n].every((o)=>Object.hasOwn(e.assets,o))))throw Error("Invalid updated preview dependencies.");return e}function ve(e,s){if(e?.version!==1)throw Error("Unsupported preview manifest update.");if(e.type==="full")return xe(e.manifest);if(!s||e.baseRevision!==s.revision)throw Error("Preview manifest update base does not match.");let r=e.header;if(!r||Object.hasOwn(r,"assets")||Object.hasOwn(r,"scenarios")||!ze.test(r.revision))throw Error("Invalid preview manifest update header.");if(e.type==="unchanged"){if(r.revision!==s.revision)throw Error("Unchanged preview revision does not match.");return xe({...r,assets:s.assets,scenarios:s.scenarios})}if(e.type!=="delta"||!e.assets?.upsert||!Array.isArray(e.assets.remove)||!Array.isArray(e.scenarios?.upsert)||!Array.isArray(e.scenarios.remove))throw Error("Invalid preview manifest delta.");let t=new Map(Object.entries(s.assets)),n=new Map(s.scenarios.map((c)=>[c.id,c]));for(let c of e.assets.remove)if(!t.delete(c))throw Error("Unknown removed preview asset.");for(let[c,u]of Object.entries(e.assets.upsert))t.set(c,u);for(let c of e.scenarios.remove)if(!n.delete(c))throw Error("Unknown removed preview scenario.");let o=new Set;for(let c of e.scenarios.upsert){if(!c||o.has(c.id))throw Error("Duplicate updated preview scenario.");o.add(c.id),n.set(c.id,c)}let i=e.scenarios.order??s.scenarios.map((c)=>c.id);if(!Array.isArray(i)||i.length!==n.size||new Set(i).size!==i.length||i.some((c)=>!n.has(c)))throw Error("Invalid updated preview scenario order.");return xe({...r,assets:Object.fromEntries(t),scenarios:i.map((c)=>n.get(c))})}function De(e){let s=new Map,r=new Map,t=0,n,o=0,i=0,c=!0;function u(m){s.delete(m.revision),s.set(m.revision,{graph:m,size:new TextEncoder().encode(JSON.stringify(m)).byteLength});let a=[...s.values()].reduce((w,h)=>w+h.size,0);while(s.size>6||a>8388608){let w=s.keys().next().value;a-=s.get(w).size,s.delete(w)}}let d=(m)=>JSON.parse(m.contents.find((a)=>typeof a.text==="string").text);return{clear(){t++,s.clear(),r.clear(),n=void 0,c=!0},async get(m,{revision:a,session:w}={}){let h=a&&s.get(a)?.graph;if(h&&(!w||h.session===w))return{...h,transportManifestUri:m};let b=n,y=t,l=JSON.stringify([m,a,w,b?.revision]);if(!r.has(l)){let f=++o,v=(async()=>{let S;if(b&&c)try{S=await e(m+"?from="+b.revision)}catch(U){if(U.code!==-32002&&!/unknown (?:ADS )?resource|resource not found/i.test(U.message))throw U;if(y===t)c=!1;S=await e(m)}else S=await e(m);let E=d(S),R=ve(E.type?E:{version:1,type:"full",manifest:E},b);if(y===t){if(u(R),f>=i)n=R,i=f}return R})();r.set(l,v),v.then(()=>{if(r.get(l)===v)r.delete(l)},()=>{if(r.get(l)===v)r.delete(l)})}return{...await r.get(l),transportManifestUri:m}}}}async function Ge(e,s=(r)=>new me(r)){let r=document.getElementById("root"),t=document.getElementById("ads-preview-status"),n,o=async(g)=>{if(!e.getHostCapabilities()?.serverResources)throw Error("This host does not forward MCP resource reads. Open the same preview in the ADS showcase.");try{return await e.readServerResource({uri:n?n+encodeURIComponent(g):g},{timeout:15000})}catch(x){if(x.code===-32601||x.message==="Method not found")throw Error("This host does not forward MCP resource reads. Open the same preview in the ADS showcase.");throw x}},i=s(o),c=De(o);document.documentElement.dataset.adsPreviewDelivery=e.delivery??"mcp-blob";let u,d,m,a,w,h=!1,b,y=0,l={},f=[],v="",S=!1,E,R,U=new Set;function F(g){if(e.getHostVersion()?.name!=="ADS showcase")return;let x=R;if(R=g,!x)return;let M=Oe(x,g).filter((k)=>k!==u&&U.has(k));if(!M.length)return;i.prefetch(g,M).then((k)=>_("prefetched",{revision:g.revision,...k})).catch((k)=>console.warn("ADS preview prefetch",k.message))}function T(g,x=!1){t.textContent=g,t.hidden=!g||e.getHostVersion()?.name==="ADS showcase",t.setAttribute("role",x?"alert":"status")}async function _(g,x={}){try{if(e.getHostCapabilities()?.logging)await e.sendLog({level:g==="error"?"error":"info",logger:"ads-preview",data:{state:g,id:u,...x}})}catch{}}let ee=!1,j=$e(r),P=je(r,{decorate:globalThis.__ADS_RENDER_AUDIT__!==!0}),B=".ads-token-sample:not(.ads-token-shadow):not(.ads-token-motion), .ads-token-stage-shadow, .ads-token-stage-motion, .ads-grid-example, .ads-foundation-ratios, .ads-brand-master, .ads-brand-art, .ads-brand-sizes img, .ads-pictogram-image";function H(g){l={...l,...g,styles:{...l.styles,...g.styles}};let x=l.adsTheme??(["light","dark"].includes(l.theme)?(f.find((M)=>M.scheme===l.theme)??{name:l.theme}).name:void 0);if(x)document.documentElement.dataset.theme=x;if(typeof l.adsBrand==="string"&&/^[a-z][a-z0-9-]*$/.test(l.adsBrand))document.documentElement.dataset.brand=l.adsBrand;j.setGuides(l.gridGuides),j.setVisible(ee&&l.gridOverlay===!0),N(),ue()}function N(){document.dispatchEvent(new CustomEvent(Ce,{detail:ge(l.gridGuideChoices??l.gridGuides)}))}function D(g){if(!g.detail){N();return}let x=ge(g.detail);H({gridGuideChoices:x,gridGuides:Me(x),gridOverlay:Te(x)}),_("guide-options",{options:x})}document.addEventListener(Ee,D);let de=(g)=>{if(typeof g.detail?.target==="string")_("navigate",{target:g.detail.target,token:g.detail.token})};document.addEventListener("ads-preview-navigate",de);let ne;function ue(){let g=l.adsFocus;if(!g||g.nonce===ne||g.target!==u||document.documentElement.dataset.adsPreviewState!=="ready")return;ne=g.nonce,document.dispatchEvent(new CustomEvent("ads-preview-focus",{detail:{token:g.token}}))}async function A(g="ads://preview/manifest",x,M){try{return await(i.manifest?i.manifest(g,{revision:x,session:M,scenario:u}):c.get(g,{revision:x,session:M}))}catch(k){throw Object.assign(Error(k.message,{cause:k}),{code:"ADS_MANIFEST_READ",category:"transport"})}}async function I(g,x,M=!1,k="",z=!1,le){let se=M||z;if(!k&&g===u&&x&&x===m&&(!le||le===a)&&se===S){T(v||(se?"Checking changes…":""),Boolean(v)),await _(v?"error":se?"checking":"ready",v?{message:v}:{revision:m});return}let oe=++y;++i.generation,u=g,ee=!1,j.setVisible(!1),U.add(g),document.documentElement.dataset.adsScenario=g,document.documentElement.dataset.adsPreviewState="loading";for(let W of["adsPreviewErrorCategory","adsPreviewErrorCode","adsPreviewResourceUri"])delete document.documentElement.dataset[W];v="",T(""),await _(k?"reverting":"loading");try{let W=performance.now(),re=await A(M?"ads://preview/live":"ads://preview/manifest",x,le);if(oe!==y)return;if(Array.isArray(re.themes))f=re.themes,H({});if(x&&re.revision!==x||le&&re.session!==le){if(oe===y)T("Updating preview…"),await _("loading",{code:"ADS_PREVIEW_CHANGED"});return}if(oe!==y)return;let fe=performance.now();performance.measure("ads-preview:manifest",{start:W,end:fe});let Q=await i.mount(re,g,r);if(performance.measure("ads-preview:load-mount",{start:fe,end:performance.now()}),!Q||oe!==y)return;let X=re.scenarios.find((Z)=>Z.id===g);if(r.dataset.adsScenarioKind=X?.kind??"",X?.foundation)P.setSubjectSelector(B,".ads-grid-example");else P.setSubjects(["components","patterns"].includes(X?.kind)?X.subjects:[]);if(m=re.revision,a=re.session,S=se,await new Promise((Z)=>requestAnimationFrame(()=>requestAnimationFrame(Z))),await document.fonts.ready,oe!==y)return;if(ee=["components","patterns","composition"].includes(X?.kind)||g==="tokens/Layout",j.setMetadata(Object.values(re.assets).flatMap((Z)=>Z.spatial?[Z.spatial]:[]),X?.kind),H({}),r.dataset.adsPaintBindings=JSON.stringify(X?.paintBindings??[]),r.dataset.adsPaintAudit=String(Boolean(X?.paintAudit)),r.dataset.adsPaintAuditComplete="not-requested",X?.paintBindings?.length||X?.paintAudit){let Z=Ie({container:r,bindings:X.paintBindings??[],auditResources:Boolean(X.paintAudit)});if(!Z.ok)throw Object.assign(Error(`Paint binding verification failed:
|
|
2
|
+
${Z.diagnostics.join(`
|
|
3
|
+
`)}`),{code:"ADS_PAINT_BINDING",category:"assertion"});if(r.dataset.adsPaintAuditComplete=String(Z.complete),!Z.complete)await _("audit-limited",{limits:Z.limits})}if(X?.kind==="tokens"&&!X.foundation){let Z=Be(r,X.samples);if(!Z.ok)throw v=`Token preview verification failed:
|
|
4
|
+
${Z.diagnostics.slice(0,20).join(`
|
|
5
|
+
`)}`,Object.assign(Error(v),{code:"ADS_TOKEN_SAMPLE",category:"assertion"})}if(oe===y){if(document.documentElement.dataset.adsPreviewRevision=m,document.documentElement.dataset.adsPreviewState=k?"error":se?"checking":"ready",T(k||(se?"Checking changes…":""),Boolean(k)),await _(k?"error":se?"checking":"ready",{revision:m,selectionRevision:d,...k?{message:k}:{}}),!se&&!k)F(re)}if(oe===y)ue()}catch(W){if(oe===y){if(document.documentElement.dataset.adsPreviewState="error",document.documentElement.dataset.adsPreviewErrorCategory=W.category??"runner",document.documentElement.dataset.adsPreviewErrorCode=W.code??"ADS_PREVIEW_STARTUP",W.resourceUri)document.documentElement.dataset.adsPreviewResourceUri=W.resourceUri;T(W.message,!0),await _("error",{message:W.message,...W.code?{code:W.code}:{},...W.category?{category:W.category}:{},...W.resourceUri?{resourceUri:W.resourceUri}:{}})}}}async function O(g){if(!u)return;if(document.visibilityState==="hidden"){if(g)b=g;return}if(h){if(g)b=g;return}h=!0;let x=y;try{let M=g??JSON.parse((await o("ads://project/build")).contents.find((z)=>typeof z.text==="string").text);if(x!==y)return;E=void 0;let k=M.previews.find((z)=>z.id===u);if(k?.live&&!k.current)if(k.live.revision!==m||M.session!==a||!S)await I(u,k.live.revision,!0,"",!1,M.session);else T(v||"Checking changes…",Boolean(v));else if(!k||!k.current){let z=k?.diagnostics?.[0]?.message;if(z&&S){let le=await A("ads://preview/manifest",M.manifestRevision,M.session);await I(u,le.revision,!1,`Build failed. Showing the previous preview.
|
|
6
|
+
${z}`,!1,M.session)}T(z?`Build failed. Showing the previous preview.
|
|
7
|
+
${z}`:"Rebuilding. This is the previous preview.",Boolean(z))}else{let z=await A("ads://preview/manifest",M.manifestRevision,M.session);if(x!==y)return;if(z.revision!==m||z.session!==a||S)await I(u,z.revision,!1,"",!1,M.session);else T(v,Boolean(v)),F(z)}}catch(M){if(x!==y)return;let k=`Preview freshness unavailable: ${M.message}`;if(T(k,!0),E!==k)E=k,await _("error",{message:k})}finally{h=!1;let M=b;if(b=void 0,M)O(M)}}e.onbuildreport=(g)=>{O(g)};let te=()=>{if(document.visibilityState!=="hidden")b=void 0,O()};document.addEventListener("visibilitychange",te),e.ontoolresult=(g)=>{let x=g.structuredContent?.draftScope;if(x!==n)++y,++i.generation,c.clear(),m=a=R=void 0,U.clear();n=x;let M=g.structuredContent?.previewResult?.structuredContent??g.structuredContent;if(M?.scenario?.id)d=M.manifestRevision,I(M.scenario.id,M.manifestRevision,M.manifestUri==="ads://preview/live","",M.build?.current===!1,M.build?.session).then(()=>{if(e.buildPollInterval===0)O()})},e.onhostcontextchanged=H,e.onteardown=async()=>(++y,u=b=void 0,e.onbuildreport=void 0,c.clear(),document.removeEventListener("visibilitychange",te),document.removeEventListener(Ee,D),document.removeEventListener("ads-preview-navigate",de),j.dispose(),P.dispose(),clearInterval(w),await i.dispose(),{});try{let g=performance.now();if(await e.connect(),performance.measure("ads-preview:connect",{start:g,end:performance.now()}),H(e.getHostContext()??{}),!e.getHostCapabilities()?.serverResources)throw Error("This host does not forward MCP resource reads. Open the same preview in the ADS showcase.");let x=e.buildPollInterval??150;if(x>0)w=setInterval(()=>{O()},x);let M=document.getElementById("ads-preview-selection");if(M)I(JSON.parse(M.textContent).id)}catch(g){T(g.message,!0)}window.addEventListener("pagehide",()=>{u=b=void 0,e.onbuildreport=void 0,clearInterval(w),c.clear(),i.dispose()},{once:!0})}class ke extends me{constructor(e,s){super(e);this.publish=s,this.visited=new Set,this.fetched=new Set,this.http=new AbortController,this.preparing=new Map,this.prepareSerial=0,this.preparedSerial=0}async manifest(e,{revision:s,session:r,scenario:t}){let n=this.prepared;if(n?.uri===e&&n.graph.revision===s&&(!r||n.graph.session===r)&&n.scenarios.includes(t))return{...n.graph,transportManifestUri:e,httpBase:n.base};let o=JSON.stringify([e,s,r,t]);if(!this.preparing.has(o)){let i=++this.prepareSerial,c=performance.now(),u=(async()=>{let d=await this.publish({uri:e,revision:s,scenario:t,retained:[...this.visited],from:n?.graph.revision});if(this.closed)throw Error("The HTTP preview was closed.");let m=ve(d.update,n?.graph);if(m.revision!==d.revision||!d.changed&&!d.scenarios.includes(t))throw Error("HTTP publication does not match its manifest.");if(d.changed)return{...m,transportManifestUri:e};if(i>=this.preparedSerial)this.preparedSerial=i,this.prepared={graph:m,uri:e,base:d.base,scenarios:d.scenarios};return performance.measure("ads-preview:http-prepare",{start:c,end:performance.now()}),{...m,transportManifestUri:e,httpBase:d.base}})();this.preparing.set(o,u),u.then(()=>this.preparing.delete(o),()=>this.preparing.delete(o))}return this.preparing.get(o)}async mountRevision(e,s,r,t){if(this.closed||t!==this.generation)return!1;if(!e.httpBase)throw Error("The preview graph has not been published for HTTP.");return this.base=e.httpBase,this.visited.add(s),super.mountRevision(e,s,r,t)}async materialize(e){let s=this.closure(e),r={};for(let t of s){if(this.closed)throw Error("The HTTP preview was closed.");if(this.urls.has(t))continue;let n=this.records.get(t),o=this.base+t.slice(13);if(n.kind==="asset"&&n.mimeType==="text/javascript"||n.references.some((i)=>this.urls.get(i)?.startsWith("blob:"))){let i=new TextDecoder().decode(await this.resource(t));for(let c of n.references){let u=this.urls.get(c);if(!u)throw Error("Unsupported cyclic asset reference.");i=i.replaceAll(c,u)}o=URL.createObjectURL(new Blob([i],{type:n.mimeType}))}if(this.urls.set(t,o),n.kind==="module")r[t]=o}if(Object.keys(r).length){let t=document.createElement("script");t.type="importmap",t.textContent=JSON.stringify({imports:r}),document.head.append(t)}return s}async resource(e){if(!this.bytes.has(e)){let s=(async()=>{let r=await fetch(this.base+e.slice(13)+"?raw=1",{signal:this.http.signal});if(!r.ok)throw Error(`HTTP preview asset unavailable: ${r.status}`);let t=new Uint8Array(await r.arrayBuffer());if(this.closed)throw Error("The HTTP preview was closed.");try{return await Se(this.records.get(e),t)}catch(n){throw n.resourceUri=e,n}})();this.bytes.set(e,s),s.catch(()=>this.bytes.delete(e))}return this.bytes.get(e)}async prefetch(e,s){if(this.closed)return;this.register(e);let r=++this.prefetchGeneration,t=new Set,n=[],o=0;for(let m of s){let a=e.scenarios.find((b)=>b.id===m);if(!a)continue;let w=this.closure(a.module).filter((b)=>!this.urls.has(b)&&!this.fetched.has(b)&&!t.has(b)),h=w.reduce((b,y)=>b+this.records.get(y).size,0);if(o+h>16777216||t.size+w.length>256||n.length>=128)continue;o+=h,n.push(m);for(let b of w)t.add(b)}if(!t.size)return{scenarios:n,resources:0};let i=await this.manifest(e.transportManifestUri,{revision:e.revision,session:e.session,scenario:n[0]});if(i.revision!==e.revision||this.closed||r!==this.prefetchGeneration)return{scenarios:[],resources:0};let c=[...t],u=0,d=async()=>{while(!this.closed&&r===this.prefetchGeneration&&u<c.length){let m=c[u++],a=await fetch(i.httpBase+m.slice(13),{signal:this.http.signal});if(!a.ok)throw Error(`HTTP preview prefetch failed: ${a.status}`);if(await a.arrayBuffer(),!this.closed)this.fetched.add(m)}};return await Promise.all(Array.from({length:Math.min(3,c.length)},d)),{scenarios:n,resources:c.length}}async dispose(){this.http.abort(),await super.dispose(),this.visited.clear(),this.fetched.clear(),this.prepared=void 0,this.preparing.clear()}}var{id:Ne,parentOrigin:He}=JSON.parse(document.getElementById("ads-http-instance").textContent),Qe=new EventSource(new URL("lifetime",location.href)),he=new Map,et=0,Ae=0,ye,Ve,_e=!1,be=(e)=>parent.postMessage({channel:"ads-preview-http",instance:Ne,epoch:Ae,...e},He);function qe(e,s){return new Promise((r,t)=>{let n=++et,o=setTimeout(()=>{he.delete(n),t(Error("HTTP preview control timed out."))},15000);he.set(n,{resolve:r,reject:t,timer:o}),be({method:e,params:s,request:n})})}var we={delivery:"http",buildPollInterval:0,getHostCapabilities:()=>({serverResources:{},logging:{}}),getHostVersion:()=>({name:"ADS showcase"}),getHostContext:()=>ye,connect:()=>new Promise((e)=>{Ve=e,be({method:"ready"})}),readServerResource:(e)=>qe("read",e),sendLog:(e)=>be({method:"log",params:e})};function We(){if(_e)return;_e=!0,window.removeEventListener("message",Je),Qe.close();for(let e of he.values())clearTimeout(e.timer),e.reject(Error("HTTP preview disposed."));he.clear()}async function Je(e){let s=e.data;if(e.source!==parent||e.origin!==He||s?.channel!=="ads-preview-http"||s.instance!==Ne)return;if(s.method==="init"){ye=s.params,Ve?.();return}if(s.method==="select"){for(let r of he.values())clearTimeout(r.timer),r.reject(Error("Preview selection superseded."));he.clear(),Ae=s.epoch,we.ontoolresult?.(s.params);return}if(s.epoch!==Ae)return;if(s.method==="context")ye=s.params,we.onhostcontextchanged?.(ye);else if(s.method==="build")we.onbuildreport?.(s.params);else if(s.method==="response"){let r=he.get(s.request);if(!r)return;if(clearTimeout(r.timer),he.delete(s.request),s.error)r.reject(Object.assign(Error(s.error),{code:s.code}));else r.resolve(s.result)}else if(s.method==="teardown")await we.onteardown?.(),be({method:"disposed"}),We()}window.addEventListener("message",Je);window.addEventListener("pagehide",We,{once:!0});await Ge(we,(e)=>new ke(e,(s)=>qe("prepare",s)));
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { gzipSync } from "node:zlib";
|
|
4
|
+
import { previewDocument } from "./apps.mjs";
|
|
5
|
+
import { previewManifestUpdate } from "../preview-manifest-update.mjs";
|
|
6
|
+
|
|
7
|
+
const assetPattern = /^ads:\/\/assets\/([a-f0-9]{64}\.[a-z0-9]+)$/;
|
|
8
|
+
const manifestUris = new Set(["ads://preview/manifest", "ads://preview/live"]);
|
|
9
|
+
const digest = bytes => `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
|
|
10
|
+
|
|
11
|
+
/** Bounded HTTP preview adapter. Capabilities own pinned, checked published bytes, never filesystem paths. */
|
|
12
|
+
export async function createHttpPreviewDelivery(parentOrigin) {
|
|
13
|
+
const script = await readFile(new URL("./preview-http.bundle.js", import.meta.url));
|
|
14
|
+
const frames = new Map();
|
|
15
|
+
let origin, closed = false;
|
|
16
|
+
const retire = id => { const frame = frames.get(id); frames.delete(id); if (frame) { frame.closed = true; frame.lease?.destroy(); } };
|
|
17
|
+
const expiry = setInterval(() => { for (const [id, frame] of frames) if (!frame.lease && Date.now() - frame.used > 60000) retire(id); }, 10000);
|
|
18
|
+
expiry.unref();
|
|
19
|
+
function frameFor(id, owner) {
|
|
20
|
+
const frame = frames.get(id);
|
|
21
|
+
if (closed || !frame || frame.closed || frame.owner !== owner) throw Object.assign(new Error("Unknown or retired HTTP preview instance."), { code: "ADS_PREVIEW_REOPEN" });
|
|
22
|
+
frame.used = Date.now();
|
|
23
|
+
return frame;
|
|
24
|
+
}
|
|
25
|
+
async function publish(frame, { uri, revision, scenario, retained = [], from }, signal) {
|
|
26
|
+
const profiling = process.env.ADS_PREVIEW_BENCH_PROFILE === "1", started = performance.now();
|
|
27
|
+
if (!manifestUris.has(uri) || (revision !== undefined && typeof revision !== "string") || (from !== undefined && !/^[a-f0-9]{64}$/.test(from)) || typeof scenario !== "string" || !Array.isArray(retained) || retained.length > 128 || retained.some(id => typeof id !== "string")) throw new Error("Invalid preview publication request.");
|
|
28
|
+
signal?.throwIfAborted();
|
|
29
|
+
const { graph, readAsset } = await frame.capture(uri, signal);
|
|
30
|
+
const graphReady = performance.now();
|
|
31
|
+
if (profiling) performance.measure("ads-http-profile:manifest-read", { start: started, end: graphReady });
|
|
32
|
+
const update = previewManifestUpdate(graph, frame.graph?.revision === from ? frame.graph : undefined);
|
|
33
|
+
// Tell the renderer which revision superseded its status read, without
|
|
34
|
+
// publishing assets for a selection it has not yet reconciled.
|
|
35
|
+
if (revision && graph.revision !== revision) return { revision: graph.revision, update, changed: true, scenarios: [] };
|
|
36
|
+
const entry = graph.scenarios.find(item => item.id === scenario);
|
|
37
|
+
if (!entry) throw new Error("The scenario is not in this published revision.");
|
|
38
|
+
const reachable = new Set();
|
|
39
|
+
function visit(id) {
|
|
40
|
+
if (reachable.has(id)) return;
|
|
41
|
+
const record = graph.assets[id];
|
|
42
|
+
if (!assetPattern.test(id) || !record) throw new Error("Invalid published preview graph.");
|
|
43
|
+
reachable.add(id);
|
|
44
|
+
for (const key of ["imports", "dynamicImports", "styles", "references"]) for (const dependency of record[key]) visit(dependency);
|
|
45
|
+
}
|
|
46
|
+
visit(entry.module);
|
|
47
|
+
for (const id of retained) {
|
|
48
|
+
const retainedEntry = graph.scenarios.find(item => item.id === id);
|
|
49
|
+
if (retainedEntry) visit(retainedEntry.module);
|
|
50
|
+
}
|
|
51
|
+
const missing = [...reachable].filter(id => !frame.assets.has(id));
|
|
52
|
+
const size = missing.reduce((sum, id) => sum + graph.assets[id].size, frame.size);
|
|
53
|
+
if (size > 64 * 1024 * 1024 || frame.assets.size + missing.length > 4096) throw Object.assign(new Error("Reopen the HTTP preview to release retained revisions."), { code: "ADS_PREVIEW_REOPEN" });
|
|
54
|
+
const added = new Map();
|
|
55
|
+
const pinStarted = performance.now();
|
|
56
|
+
// Pin the complete selected closure, including lazy branches, before acknowledging
|
|
57
|
+
// publication. Source history pruning cannot strand a still-mounted revision.
|
|
58
|
+
for (const id of missing) {
|
|
59
|
+
const record = graph.assets[id];
|
|
60
|
+
const content = readAsset(id);
|
|
61
|
+
if (!content) throw new Error("Missing published preview asset.");
|
|
62
|
+
const bytes = typeof content.text === "string" ? Buffer.from(content.text) : Buffer.from(content.blob, "base64");
|
|
63
|
+
if (bytes.length !== record.size || digest(bytes) !== record.digest) throw new Error("HTTP preview resource integrity check failed.");
|
|
64
|
+
added.set(id, { record, bytes });
|
|
65
|
+
}
|
|
66
|
+
signal?.throwIfAborted();
|
|
67
|
+
if (frame.closed || closed) throw new Error("HTTP preview closed during publication.");
|
|
68
|
+
for (const id of reachable) if (frame.assets.has(id) && frame.assets.get(id).record.digest !== graph.assets[id].digest) throw new Error("Immutable preview asset changed.");
|
|
69
|
+
for (const [id, asset] of added) frame.assets.set(id, asset);
|
|
70
|
+
frame.size = size;
|
|
71
|
+
frame.graph = graph;
|
|
72
|
+
if (profiling) {
|
|
73
|
+
performance.measure("ads-http-profile:pin-assets", { start: pinStarted, end: performance.now(), detail: { missing: missing.length, reachable: reachable.size } });
|
|
74
|
+
performance.measure("ads-http-profile:publish", { start: started, end: performance.now() });
|
|
75
|
+
}
|
|
76
|
+
return { base: `${origin}/preview/${frame.id}/assets/`, revision: graph.revision, resources: reachable.size, update,
|
|
77
|
+
scenarios: [scenario, ...retained.filter(id => graph.scenarios.some(entry => entry.id === id))] };
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
setOrigin(value) { origin = value; },
|
|
81
|
+
async control(owner, service, input, signal) {
|
|
82
|
+
if (closed) throw new Error("HTTP delivery is closed.");
|
|
83
|
+
if (input.op === "open") {
|
|
84
|
+
if (frames.size >= 16) throw new Error("HTTP preview instance limit reached.");
|
|
85
|
+
const scope = input.draftScope;
|
|
86
|
+
if (scope != null && !/^ads:\/\/drafts\/[a-z0-9][a-z0-9-]{0,79}\/resource\?uri=$/.test(scope)) throw new Error("Invalid draft resource scope.");
|
|
87
|
+
const id = randomBytes(24).toString("hex");
|
|
88
|
+
frames.set(id, { id, owner, capture: (uri, signal) => service.capturePreview(scope ? scope + encodeURIComponent(uri) : uri, signal), used: Date.now(), assets: new Map(), size: 0, pending: Promise.resolve() });
|
|
89
|
+
return { id, url: `${origin}/preview/${id}/frame.html`, parentOrigin };
|
|
90
|
+
}
|
|
91
|
+
const frame = frameFor(input.id, owner);
|
|
92
|
+
if (input.op === "close") { retire(input.id); return {}; }
|
|
93
|
+
if (input.op === "keepalive") return {};
|
|
94
|
+
if (input.op !== "prepare") throw new Error("Unknown HTTP preview operation.");
|
|
95
|
+
const task = frame.pending.then(() => publish(frame, input, signal));
|
|
96
|
+
frame.pending = task.catch(() => {});
|
|
97
|
+
return task;
|
|
98
|
+
},
|
|
99
|
+
serve(req, res) {
|
|
100
|
+
const url = new URL(req.url, origin);
|
|
101
|
+
const match = url.pathname.match(/^\/preview\/([a-f0-9]{48})\/(frame\.html|runtime\.js|lifetime|assets\/[a-f0-9]{64}\.[a-z0-9]+)$/);
|
|
102
|
+
if (!match) return false;
|
|
103
|
+
if (url.search && (match[2].startsWith("assets/") ? url.search !== "?raw=1" : true)) { res.writeHead(400); res.end(); return true; }
|
|
104
|
+
const frame = frames.get(match[1]);
|
|
105
|
+
if (!frame || frame.closed) { res.writeHead(404); res.end(); return true; }
|
|
106
|
+
frame.used = Date.now();
|
|
107
|
+
if (match[2] === "lifetime") {
|
|
108
|
+
if (frame.lease) { res.writeHead(409); res.end(); return true; }
|
|
109
|
+
frame.lease = res;
|
|
110
|
+
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-store", "Access-Control-Allow-Origin": "*" });
|
|
111
|
+
res.write(": active preview\n\n");
|
|
112
|
+
// A dropped network connection need not destroy interaction state.
|
|
113
|
+
// Explicit close still retires immediately; abandoned leases expire
|
|
114
|
+
// through the existing bounded 60-second idle cleanup.
|
|
115
|
+
res.once("close", () => { if (frame.lease === res) { frame.lease = undefined; frame.used = Date.now(); } });
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
118
|
+
const base = `${origin}/preview/${frame.id}/`;
|
|
119
|
+
let bytes, type, immutable = false;
|
|
120
|
+
if (match[2] === "frame.html") {
|
|
121
|
+
bytes = previewDocument(`<script id="ads-http-instance" type="application/json">${JSON.stringify({ id: frame.id, parentOrigin })}</script><script type="module" src="${base}runtime.js"></script>`);
|
|
122
|
+
type = "text/html";
|
|
123
|
+
} else if (match[2] === "runtime.js") { bytes = script; type = "text/javascript"; }
|
|
124
|
+
else {
|
|
125
|
+
const id = `ads://${match[2]}`, asset = frame.assets.get(id);
|
|
126
|
+
if (!asset) { res.writeHead(404); res.end(); return true; }
|
|
127
|
+
bytes = asset.bytes; type = asset.record.mimeType; immutable = true;
|
|
128
|
+
if (asset.record.references.length && !url.search) {
|
|
129
|
+
let text = bytes.toString();
|
|
130
|
+
for (const reference of asset.record.references) text = text.replaceAll(reference, base + "assets/" + reference.slice("ads://assets/".length));
|
|
131
|
+
bytes = Buffer.from(text);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
const compressed = bytes.length > 1024 && /^(?:text\/|application\/json|image\/svg)/.test(type) && /(?:^|,)\s*gzip\s*(?:,|$)/.test(req.headers["accept-encoding"] ?? "");
|
|
135
|
+
if (compressed) bytes = gzipSync(bytes);
|
|
136
|
+
res.writeHead(200, {
|
|
137
|
+
"Content-Type": type, "Content-Length": Buffer.byteLength(bytes), "X-Content-Type-Options": "nosniff",
|
|
138
|
+
"Vary": "Accept-Encoding", ...(compressed ? { "Content-Encoding": "gzip" } : {}),
|
|
139
|
+
"Cache-Control": immutable ? "private, max-age=31536000, immutable" : "no-store",
|
|
140
|
+
"Access-Control-Allow-Origin": "*", "Timing-Allow-Origin": "*", "Referrer-Policy": "no-referrer",
|
|
141
|
+
"Content-Security-Policy": `default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe-eval' blob: ${base}; style-src 'unsafe-inline' blob: ${base}; img-src data: blob: ${base}; font-src data: blob: ${base}; media-src data: blob: ${base}; connect-src blob: ${base}; worker-src blob: ${base}; frame-src data: blob:; frame-ancestors ${parentOrigin}; base-uri 'none'; object-src 'none'; form-action 'none'; sandbox allow-scripts allow-forms`,
|
|
142
|
+
});
|
|
143
|
+
res.end(bytes); return true;
|
|
144
|
+
},
|
|
145
|
+
retireOwner(owner) { for (const [id, frame] of frames) if (frame.owner === owner) retire(id); },
|
|
146
|
+
close() { closed = true; clearInterval(expiry); for (const id of frames.keys()) retire(id); },
|
|
147
|
+
};
|
|
148
|
+
}
|