@reqvire-org/ads 0.3.32 → 0.3.34

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.
Files changed (84) hide show
  1. package/README.md +9 -0
  2. package/dist/behavior-libraries.mjs +93 -0
  3. package/dist/behaviors.mjs +0 -6
  4. package/dist/bootstrap-ds/ds.config.json +1 -0
  5. package/dist/bootstrap-ds/vite.config.ts +2 -1
  6. package/dist/boundaries.mjs +2 -0
  7. package/dist/capture.mjs +8 -6
  8. package/dist/check.mjs +2 -0
  9. package/dist/config.mjs +9 -2
  10. package/dist/draft-boundary.mjs +27 -0
  11. package/dist/draft-workspace.mjs +10 -0
  12. package/dist/lint-config.mjs +8 -0
  13. package/dist/mcp/build-status.mjs +1 -1
  14. package/dist/mcp/catalog.mjs +4 -2
  15. package/dist/mcp/context.mjs +2 -2
  16. package/dist/mcp/draft-discovery.mjs +55 -0
  17. package/dist/mcp/draft-exports.mjs +40 -0
  18. package/dist/mcp/drafts.mjs +460 -0
  19. package/dist/mcp/edit-preparation.mjs +8 -7
  20. package/dist/mcp/execution-results.mjs +2 -0
  21. package/dist/mcp/mutations.mjs +6 -2
  22. package/dist/mcp/preview-watch.mjs +24 -5
  23. package/dist/mcp/preview-widget.bundle.js +14 -14
  24. package/dist/mcp/prompts.mjs +3 -2
  25. package/dist/mcp/server.mjs +178 -39
  26. package/dist/mcp/widget.bundle.js +1 -1
  27. package/dist/preview-files.mjs +2 -0
  28. package/dist/scenario-inspector.mjs +5 -5
  29. package/dist/scenario-program.mjs +36 -0
  30. package/dist/scenario-registry.mjs +90 -0
  31. package/dist/scenarios-compiler.mjs +68 -22
  32. package/dist/scenarios-vite.d.mts +1 -0
  33. package/dist/scenarios-vite.mjs +1 -0
  34. package/dist/scenarios.mjs +2 -1
  35. package/dist/showcase/client.bundle.js +28 -28
  36. package/dist/showcase/comparison.js +45 -0
  37. package/dist/showcase/draft-navigation.js +41 -0
  38. package/dist/showcase/preview-state.js +19 -0
  39. package/dist/showcase/style.css +5 -0
  40. package/dist/skills/README.md +5 -0
  41. package/dist/skills/ads-break-ui/SKILL.md +26 -0
  42. package/dist/skills/ads-break-ui/references/behaviors.md +10 -0
  43. package/dist/skills/ads-break-ui/references/captures.md +7 -0
  44. package/dist/skills/ads-break-ui/references/drafts.md +146 -0
  45. package/dist/skills/ads-break-ui/references/guarded-editing.md +6 -0
  46. package/dist/skills/ads-break-ui/references/validation.md +6 -0
  47. package/dist/skills/ads-designer/SKILL.md +33 -0
  48. package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +1 -0
  49. package/dist/skills/ads-designer/assets/bootstrap-ds/vite.config.ts +2 -1
  50. package/dist/skills/ads-designer/references/behaviors.md +10 -0
  51. package/dist/skills/ads-designer/references/captures.md +7 -0
  52. package/dist/skills/ads-designer/references/drafts.md +146 -0
  53. package/dist/skills/ads-designer/references/guarded-editing.md +6 -0
  54. package/dist/skills/ads-designer/references/validation.md +6 -0
  55. package/dist/skills/ads-import/SKILL.md +30 -0
  56. package/dist/skills/ads-import/references/behaviors.md +10 -0
  57. package/dist/skills/ads-import/references/captures.md +7 -0
  58. package/dist/skills/ads-import/references/drafts.md +146 -0
  59. package/dist/skills/ads-import/references/guarded-editing.md +6 -0
  60. package/dist/skills/ads-import/references/validation.md +6 -0
  61. package/dist/skills/ads-motion/SKILL.md +26 -0
  62. package/dist/skills/ads-motion/references/behaviors.md +10 -0
  63. package/dist/skills/ads-motion/references/captures.md +7 -0
  64. package/dist/skills/ads-motion/references/drafts.md +146 -0
  65. package/dist/skills/ads-motion/references/guarded-editing.md +6 -0
  66. package/dist/skills/ads-motion/references/validation.md +6 -0
  67. package/dist/skills/ads-port/SKILL.md +34 -1
  68. package/dist/skills/ads-port/references/behaviors.md +10 -0
  69. package/dist/skills/ads-port/references/captures.md +7 -0
  70. package/dist/skills/ads-port/references/drafts.md +146 -0
  71. package/dist/skills/ads-port/references/guarded-editing.md +6 -0
  72. package/dist/skills/ads-port/references/native-implementation.md +14 -1
  73. package/dist/skills/ads-port/references/validation.md +6 -0
  74. package/dist/unit-contracts.mjs +2 -2
  75. package/dist/units.mjs +6 -0
  76. package/dist/verification/browser.d.mts +27 -0
  77. package/dist/verification.mjs +3 -0
  78. package/docs/ADS.md +13 -0
  79. package/docs/ARCHITECTURE.md +94 -0
  80. package/docs/CHANGELOG.md +111 -0
  81. package/docs/CONTRACTS.md +8 -0
  82. package/docs/GUIDE.md +46 -9
  83. package/docs/MCP.md +90 -0
  84. package/package.json +6 -4
@@ -138,7 +138,7 @@ Boolean requesting whether a visible border and background is provided by the ho
138
138
  - omitted: host decides border`)}),q_=i.object({method:i.literal("ui/request-display-mode"),params:i.object({mode:Sa.describe("The display mode being requested.")})}),N_=i.object({mode:Sa.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),wR=i.union([i.literal("model"),i.literal("app")]).describe("Tool visibility scope - who can access the tool."),KT=i.object({resourceUri:i.string().optional(),visibility:i.array(wR).optional().describe(`Who can access this tool. Default: ["model", "app"]
139
139
  - "model": Tool visible to and callable by the agent
140
140
  - "app": Tool callable by the app from this server only`),csp:i.never().optional(),permissions:i.never().optional()}),GT=i.object({mimeTypes:i.array(i.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),xR=i.object({method:i.literal("ui/download-file"),params:i.object({contents:i.array(i.union([ht,mt])).describe("Resource contents to download \u2014 embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),TR=i.object({method:i.literal("ui/message"),params:i.object({role:i.literal("user").describe('Message role, currently only "user" is supported.'),content:i.array(Ee).describe("Message content blocks (text, image, etc.).")})}),YT=i.object({method:i.literal("ui/notifications/sandbox-resource-ready"),params:i.object({html:i.string().describe("HTML content to load into the inner iframe."),sandbox:i.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Ef.optional().describe("CSP configuration from resource metadata."),permissions:kf.optional().describe("Sandbox permissions from resource metadata.")})}),QT=i.object({method:i.literal("ui/notifications/tool-result"),params:Ye.describe("Standard MCP tool execution result.")}),j_=i.object({toolInfo:i.object({id:Te.optional().describe("JSON-RPC id of the tools/call request."),tool:Ge.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:cR.optional().describe("Current color theme preference."),styles:_R.optional().describe("Style configuration for theming the app."),displayMode:Sa.optional().describe("How the UI is currently displayed."),availableDisplayModes:i.array(Sa).optional().describe("Display modes the host supports."),containerDimensions:i.union([i.object({height:i.number().describe("Fixed container height in pixels.")}),i.object({maxHeight:i.union([i.number(),i.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(i.union([i.object({width:i.number().describe("Fixed container width in pixels.")}),i.object({maxWidth:i.union([i.number(),i.undefined()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
141
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:i.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:i.string().optional().describe("User's timezone in IANA format."),userAgent:i.string().optional().describe("Host application identifier."),platform:i.union([i.literal("web"),i.literal("desktop"),i.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:i.object({touch:i.boolean().optional().describe("Whether the device supports touch input."),hover:i.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:i.object({top:i.number().describe("Top safe area inset in pixels."),right:i.number().describe("Right safe area inset in pixels."),bottom:i.number().describe("Bottom safe area inset in pixels."),left:i.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),XT=i.object({method:i.literal("ui/notifications/host-context-changed"),params:j_.describe("Partial context update containing only changed fields.")}),PR=i.object({method:i.literal("ui/update-model-context"),params:i.object({content:i.array(Ee).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:i.record(i.string(),i.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),ER=i.object({method:i.literal("ui/initialize"),params:i.object({appInfo:Pe.describe("App identification (name and version)."),appCapabilities:zR.describe("Features and capabilities this app provides."),protocolVersion:i.string().describe("Protocol version this app supports.")})}),kR=i.object({protocolVersion:i.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Pe.describe("Host application identification and version."),hostCapabilities:vR.describe("Features and capabilities provided by the host."),hostContext:j_.describe("Rich context about the host environment.")}).passthrough();var Ql=class{eventTarget;eventSource;messageListener;constructor(t=window.parent,o){this.eventTarget=t,this.eventSource=o,this.messageListener=r=>{if(o&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let n=ct.safeParse(r.data);n.success?(console.debug("Parsed message",n.data),this.onmessage?.(n.data)):r.data?.jsonrpc!=="2.0"?console.debug("Ignoring non-JSON-RPC message",n.error.message,r):(console.error("Failed to parse message",n.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+n.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(t,o){t.method!==aR&&console.debug("Sending message",t),this.eventTarget.postMessage(t,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion};var $R=[A_],Xl=class extends ma{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new Tf;_methods=new Pf;setRequestHandler=(...t)=>{let[o,...r]=O_("request",t)??t;this._methods.claim(o,"setRequestHandler"),super.setRequestHandler.call(this,o,...r)};setNotificationHandler=(...t)=>{let[o,...r]=O_("notification",t)??t;this._methods.claim(o,"setNotificationHandler"),super.setNotificationHandler.call(this,o,...r)};removeRequestHandler=t=>{this._methods.release(t),super.removeRequestHandler(t)};removeNotificationHandler=t=>{this._methods.release(t),super.removeNotificationHandler(t)};replaceRequestHandler=(t,...o)=>{this._methods.replace(t),super.setRequestHandler.call(this,t,...o)};_wrapHandler(t,o){let r=super._wrapHandler(t,o);return t==="ui/initialize"||t==="ping"?r:async(n,s)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${t}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),r(n,s))}eventSchemas={sizechange:gR,sandboxready:fR,initialized:RR,requestteardown:yR,loggingmessage:bo};setEventHandler(t,o){this._ensureEventSlot(t),this._events.setHandler(t,o)}getEventHandler(t){return this._events.getHandler(t)}addEventListener(t,o){this._ensureEventSlot(t),this._events.addEventListener(t,o)}removeEventListener(t,o){this._events.removeEventListener(t,o)}_ensureEventSlot(t){if(this._registeredEvents.has(t))return;let o=this.eventSchemas[t];if(!o)throw Error(`Unknown event: ${String(t)}`);let r=n=>{t==="initialized"&&(this._initializedReceived=!0),this._events.dispatch(t,n)};t==="loggingmessage"?this.setNotificationHandler("notifications/message",n=>{r(n.params)}):this.setNotificationHandler(o.shape.method.value,{params:o.shape.params},n=>r(n)),this._registeredEvents.add(t)}warnIfRequestHandlerReplaced(t,o,r){o&&r&&console.warn(`[MCP Apps] ${t} handler replaced. Previous handler will no longer be called.`)}constructor(t,o,r,n){super(n),this._client=t,this._hostInfo=o,this._hostCapabilities=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=n?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:ER.shape.params,result:kR},s=>this._onAppsInitialize(s)),this.replaceRequestHandler("ping",(s,a)=>(this.onping?.(s.params,a),{})),this.replaceRequestHandler("ui/request-display-mode",{params:q_.shape.params,result:N_},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(t){return t}assertCapabilityForMethod(t){}assertRequestHandlerCapability(t){}assertNotificationCapability(t){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(t){this.setEventHandler("sizechange",t)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(t){this.setEventHandler("sandboxready",t)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(t){this.setEventHandler("initialized",t)}_onmessage;get onmessage(){return this._onmessage}set onmessage(t){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,t),this._onmessage=t,this.replaceRequestHandler("ui/message",{params:TR.shape.params,result:mR},async(o,r)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(o,r)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(t){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,t),this._onopenlink=t,this.replaceRequestHandler("ui/open-link",{params:dR.shape.params,result:pR},async(o,r)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(o,r)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(t){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,t),this._ondownloadfile=t,this.replaceRequestHandler("ui/download-file",{params:xR.shape.params,result:hR},async(o,r)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(o,r)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(t){this.setEventHandler("requestteardown",t)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(t){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,t),this._onrequestdisplaymode=t,this.replaceRequestHandler("ui/request-display-mode",{params:q_.shape.params,result:N_},async(o,r)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(o,r)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(t){this.setEventHandler("loggingmessage",t)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(t){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,t),this._onupdatemodelcontext=t,this.replaceRequestHandler("ui/update-model-context",{params:PR.shape.params,result:We},async(o,r)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(o,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(t){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,t),this._oncalltool=t,this.replaceRequestHandler("tools/call",async(o,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(o.params,r)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(t){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,t),this._oncreatesamplingmessage=t,this.replaceRequestHandler("sampling/createMessage",async(o,r)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(o.params,r)})}sendToolListChanged(t={}){return this.notification({method:"notifications/tools/list_changed",params:t})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(t){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,t),this._onlistresources=t,this.replaceRequestHandler("resources/list",async(o,r)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(o.params,r)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(t){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,t),this._onlistresourcetemplates=t,this.replaceRequestHandler("resources/templates/list",async(o,r)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(o.params,r)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(t){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,t),this._onreadresource=t,this.replaceRequestHandler("resources/read",async(o,r)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(o.params,r)})}sendResourceListChanged(t={}){return this.notification({method:"notifications/resources/list_changed",params:t})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(t){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,t),this._onlistprompts=t,this.replaceRequestHandler("prompts/list",async(o,r)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(o.params,r)})}sendPromptListChanged(t={}){return this.notification({method:"notifications/prompts/list_changed",params:t})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(t){let o=t.protocolVersion;return this._appInfo!==void 0&&console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values."),this._appCapabilities=t.appCapabilities,this._appInfo=t.appInfo,{protocolVersion:$R.includes(o)?o:A_,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(t){let o={},r=!1;for(let n of Object.keys(t)){let s=this._hostContext[n],a=t[n];CR(s,a)||(o[n]=a,r=!0)}r&&(this._hostContext=t,this.sendHostContextChange(o))}sendHostContextChange(t){return this.notification({method:"ui/notifications/host-context-changed",params:t})}sendToolInput(t){return this.notification({method:"ui/notifications/tool-input",params:t})}sendToolInputPartial(t){return this.notification({method:"ui/notifications/tool-input-partial",params:t})}sendToolResult(t){return this.notification({method:"ui/notifications/tool-result",params:t})}sendToolCancelled(t){return this.notification({method:"ui/notifications/tool-cancelled",params:t})}sendSandboxResourceReady(t){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:t})}teardownResource(t,o){return this.request({method:"ui/resource-teardown",params:t},bR,o)}sendResourceTeardown=this.teardownResource;callTool(t,o){return this.request({method:"tools/call",params:t},o)}listTools(t,o){return this.request({method:"tools/list",params:t},o)}async connect(t){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let o=this._client.getServerCapabilities();if(!o)throw Error("Client server capabilities not available");o.tools&&(this.oncalltool=async(r,n)=>this._client.request({method:"tools/call",params:r},{signal:n.mcpReq.signal}),o.tools.listChanged&&this._client.setNotificationHandler("notifications/tools/list_changed",r=>this.sendToolListChanged(r.params))),o.resources&&(this.onlistresources=async(r,n)=>this._client.request({method:"resources/list",params:r},{signal:n.mcpReq.signal}),this.onlistresourcetemplates=async(r,n)=>this._client.request({method:"resources/templates/list",params:r},{signal:n.mcpReq.signal}),this.onreadresource=async(r,n)=>this._client.request({method:"resources/read",params:r},{signal:n.mcpReq.signal}),o.resources.listChanged&&this._client.setNotificationHandler("notifications/resources/list_changed",r=>this.sendResourceListChanged(r.params))),o.prompts&&(this.onlistprompts=async(r,n)=>this._client.request({method:"prompts/list",params:r},{signal:n.mcpReq.signal}),o.prompts.listChanged&&this._client.setNotificationHandler("notifications/prompts/list_changed",r=>this.sendPromptListChanged(r.params)))}return super.connect(t)}};function CR(e,t){return JSON.stringify(e)===JSON.stringify(t)}function L_(e,t){let o=new DOMParser().parseFromString(e,"text/html"),r=o.createElement("meta");if(r.httpEquiv="Content-Security-Policy",r.content=t,o.head.prepend(r),!o.querySelector("base[href]")){let n=o.querySelector("base")??o.createElement("base");n.setAttribute("href","about:srcdoc"),r.after(n)}return"<!doctype html>"+o.documentElement.outerHTML}var $e=new Yl({name:"ADS preview",version:"1.0.0"},{},{autoResize:!0}),Wr=document.getElementById("ads-token-root"),Lt=document.getElementById("ads-widget-status"),tu=document.getElementById("ads-token-theme"),eu=document.getElementById("ads-scenario-root"),To,Me=0,U_="",Br=30,Z_=document.createElement("style");Wr&&document.head.append(Z_);function ou(e){e!=="light"&&e!=="dark"||(document.documentElement.dataset.theme=e,tu&&(tu.value=e),Wr&&To&&wo())}function Oe(e,t){let o=document.createElement(e);return o.textContent=t,o}function IR(e){let t=Oe("li","");t.dataset.token=e.name;let o=getComputedStyle(document.documentElement).getPropertyValue(e.name).trim(),r=Oe("details","");r.className="token-source";let n=Oe("summary","");n.title=`${e.name}: ${o||"Conditional or unset"}. Click to inspect source definitions.`;let s=Oe("code",e.name);s.className="token-name";let a=Oe("span",o||"Conditional or unset");n.append(s,a);let l=Oe("dl","");l.append(Oe("dt","Computed in preview"),Oe("dd",o||"Conditional or unset")),e.meaning&&l.append(Oe("dt","Meaning"),Oe("dd",e.meaning));for(let u of e.definitions)l.append(Oe("dt",u.scope),Oe("dd",`${u.value} \xB7 ${u.file}:${u.line}`));return r.append(n,l),t.append(r),t}function wo(){Z_.textContent=To.css;let e=To.tokens.filter(t=>`${t.name} ${t.type??""}`.toLowerCase().includes(U_.toLowerCase()));document.getElementById("ads-token-list").replaceChildren(...e.slice(Me,Me+Br).map(IR)),document.querySelector("footer").hidden=e.length<=Br,document.getElementById("ads-token-count").textContent=e.length?`${Me+1}\u2013${Math.min(Me+Br,e.length)} of ${e.length}`:"No matching tokens",document.getElementById("ads-token-prev").disabled=Me===0,document.getElementById("ads-token-next").disabled=Me+Br>=e.length,Lt.textContent=`${e.length} matching definitions \xB7 ${To.diagnostics.length} diagnostics`}Wr&&($e.ontoolinput=()=>{Me=0,To&&wo()},To=JSON.parse(document.getElementById("ads-token-seed").textContent),ou("light"),document.getElementById("ads-token-search").addEventListener("input",e=>{U_=e.target.value,Me=0,wo()}),tu.addEventListener("change",()=>ou(tu.value)),document.getElementById("ads-token-prev").addEventListener("click",()=>{Me=Math.max(0,Me-Br),wo()}),document.getElementById("ads-token-next").addEventListener("click",()=>{Me+=Br,wo()}),document.getElementById("ads-token-refresh").addEventListener("click",async()=>{try{let e=await $e.readServerResource({uri:"ads://project/tokens"});To=JSON.parse(e.contents.find(t=>"text"in t).text),Me=0,wo()}catch(e){Lt.textContent=`Refresh failed: ${e.message}`}}));var xo,$f,D_=!1,_a=0;async function H_(e){if($f=e,!D_||!eu)return;let t=e?.structuredContent?.scenario?.resourceUri;if(!t||!t.startsWith("ui://ads/previews/"))return;let o=++_a;Wr&&(Wr.hidden=!0,Lt=document.getElementById("ads-scenario-status")),eu.hidden=!1;try{if(!$e.getHostCapabilities()?.serverResources)throw new Error("This Apps host does not forward server resources. Use the project showcase URL from the tool result.");let n=(await $e.readServerResource({uri:t})).contents.find(u=>u.mimeType==="text/html;profile=mcp-app"&&typeof u.text=="string");if(!n)throw new Error("Scenario HTML is unavailable.");if(o!==_a)return;xo&&(await xo.close(),xo=void 0);let s=document.createElement("iframe");s.title=e.structuredContent.scenario.title,s.setAttribute("sandbox","allow-scripts allow-forms"),eu.replaceChildren(s);let a=new Xl(null,{name:"ADS scenario host",version:"1.0.0"},{serverResources:{},serverTools:{}},{hostContext:$e.getHostContext()});xo=a,a.onreadresource=u=>$e.readServerResource(u),a.oncalltool=u=>$e.callServerTool(u),a.onsizechange=({height:u})=>{u&&(s.height=String(Math.min(1e4,Math.max(120,u))))},a.oninitialized=async()=>{await a.sendToolInput({arguments:{}}),await a.sendToolResult(e),o===_a&&window.parent.postMessage({type:"ads-preview-ready"},"*")},await a.connect(new Ql(s.contentWindow,s.contentWindow));let l="default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe-eval' blob:; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; worker-src blob: data:; connect-src blob:; base-uri about:; object-src 'none'; form-action 'none'";s.srcdoc=L_(n.text,l),Lt.hidden=!0}catch(r){o===_a&&(Lt.hidden=!1,Lt.textContent=r.message,window.parent.postMessage({type:"ads-preview-ready"},"*"))}}eu&&($e.ontoolresult=e=>{H_(e)},$e.onteardown=async()=>{++_a;let e=xo;xo=void 0;try{await e?.teardownResource({},{timeout:500})}catch{}return await e?.close(),{}});$e.onhostcontextchanged=e=>{ou(e.theme),xo?.setHostContext(e)};try{await $e.connect(),D_=!0,$f&&H_($f),ou($e.getHostContext()?.theme),Wr&&(document.getElementById("ads-token-refresh").disabled=!$e.getHostCapabilities()?.serverResources,wo())}catch{Lt&&(Lt.textContent="Apps bridge unavailable. Samples remain usable; inspect project data through ADS tools/resources.")}
141
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:i.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:i.string().optional().describe("User's timezone in IANA format."),userAgent:i.string().optional().describe("Host application identifier."),platform:i.union([i.literal("web"),i.literal("desktop"),i.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:i.object({touch:i.boolean().optional().describe("Whether the device supports touch input."),hover:i.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:i.object({top:i.number().describe("Top safe area inset in pixels."),right:i.number().describe("Right safe area inset in pixels."),bottom:i.number().describe("Bottom safe area inset in pixels."),left:i.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),XT=i.object({method:i.literal("ui/notifications/host-context-changed"),params:j_.describe("Partial context update containing only changed fields.")}),PR=i.object({method:i.literal("ui/update-model-context"),params:i.object({content:i.array(Ee).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:i.record(i.string(),i.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),ER=i.object({method:i.literal("ui/initialize"),params:i.object({appInfo:Pe.describe("App identification (name and version)."),appCapabilities:zR.describe("Features and capabilities this app provides."),protocolVersion:i.string().describe("Protocol version this app supports.")})}),kR=i.object({protocolVersion:i.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Pe.describe("Host application identification and version."),hostCapabilities:vR.describe("Features and capabilities provided by the host."),hostContext:j_.describe("Rich context about the host environment.")}).passthrough();var Ql=class{eventTarget;eventSource;messageListener;constructor(t=window.parent,o){this.eventTarget=t,this.eventSource=o,this.messageListener=r=>{if(o&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let n=ct.safeParse(r.data);n.success?(console.debug("Parsed message",n.data),this.onmessage?.(n.data)):r.data?.jsonrpc!=="2.0"?console.debug("Ignoring non-JSON-RPC message",n.error.message,r):(console.error("Failed to parse message",n.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+n.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(t,o){t.method!==aR&&console.debug("Sending message",t),this.eventTarget.postMessage(t,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion};var $R=[A_],Xl=class extends ma{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new Tf;_methods=new Pf;setRequestHandler=(...t)=>{let[o,...r]=O_("request",t)??t;this._methods.claim(o,"setRequestHandler"),super.setRequestHandler.call(this,o,...r)};setNotificationHandler=(...t)=>{let[o,...r]=O_("notification",t)??t;this._methods.claim(o,"setNotificationHandler"),super.setNotificationHandler.call(this,o,...r)};removeRequestHandler=t=>{this._methods.release(t),super.removeRequestHandler(t)};removeNotificationHandler=t=>{this._methods.release(t),super.removeNotificationHandler(t)};replaceRequestHandler=(t,...o)=>{this._methods.replace(t),super.setRequestHandler.call(this,t,...o)};_wrapHandler(t,o){let r=super._wrapHandler(t,o);return t==="ui/initialize"||t==="ping"?r:async(n,s)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${t}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),r(n,s))}eventSchemas={sizechange:gR,sandboxready:fR,initialized:RR,requestteardown:yR,loggingmessage:bo};setEventHandler(t,o){this._ensureEventSlot(t),this._events.setHandler(t,o)}getEventHandler(t){return this._events.getHandler(t)}addEventListener(t,o){this._ensureEventSlot(t),this._events.addEventListener(t,o)}removeEventListener(t,o){this._events.removeEventListener(t,o)}_ensureEventSlot(t){if(this._registeredEvents.has(t))return;let o=this.eventSchemas[t];if(!o)throw Error(`Unknown event: ${String(t)}`);let r=n=>{t==="initialized"&&(this._initializedReceived=!0),this._events.dispatch(t,n)};t==="loggingmessage"?this.setNotificationHandler("notifications/message",n=>{r(n.params)}):this.setNotificationHandler(o.shape.method.value,{params:o.shape.params},n=>r(n)),this._registeredEvents.add(t)}warnIfRequestHandlerReplaced(t,o,r){o&&r&&console.warn(`[MCP Apps] ${t} handler replaced. Previous handler will no longer be called.`)}constructor(t,o,r,n){super(n),this._client=t,this._hostInfo=o,this._hostCapabilities=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=n?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:ER.shape.params,result:kR},s=>this._onAppsInitialize(s)),this.replaceRequestHandler("ping",(s,a)=>(this.onping?.(s.params,a),{})),this.replaceRequestHandler("ui/request-display-mode",{params:q_.shape.params,result:N_},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(t){return t}assertCapabilityForMethod(t){}assertRequestHandlerCapability(t){}assertNotificationCapability(t){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(t){this.setEventHandler("sizechange",t)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(t){this.setEventHandler("sandboxready",t)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(t){this.setEventHandler("initialized",t)}_onmessage;get onmessage(){return this._onmessage}set onmessage(t){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,t),this._onmessage=t,this.replaceRequestHandler("ui/message",{params:TR.shape.params,result:mR},async(o,r)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(o,r)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(t){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,t),this._onopenlink=t,this.replaceRequestHandler("ui/open-link",{params:dR.shape.params,result:pR},async(o,r)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(o,r)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(t){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,t),this._ondownloadfile=t,this.replaceRequestHandler("ui/download-file",{params:xR.shape.params,result:hR},async(o,r)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(o,r)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(t){this.setEventHandler("requestteardown",t)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(t){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,t),this._onrequestdisplaymode=t,this.replaceRequestHandler("ui/request-display-mode",{params:q_.shape.params,result:N_},async(o,r)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(o,r)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(t){this.setEventHandler("loggingmessage",t)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(t){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,t),this._onupdatemodelcontext=t,this.replaceRequestHandler("ui/update-model-context",{params:PR.shape.params,result:We},async(o,r)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(o,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(t){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,t),this._oncalltool=t,this.replaceRequestHandler("tools/call",async(o,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(o.params,r)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(t){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,t),this._oncreatesamplingmessage=t,this.replaceRequestHandler("sampling/createMessage",async(o,r)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(o.params,r)})}sendToolListChanged(t={}){return this.notification({method:"notifications/tools/list_changed",params:t})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(t){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,t),this._onlistresources=t,this.replaceRequestHandler("resources/list",async(o,r)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(o.params,r)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(t){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,t),this._onlistresourcetemplates=t,this.replaceRequestHandler("resources/templates/list",async(o,r)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(o.params,r)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(t){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,t),this._onreadresource=t,this.replaceRequestHandler("resources/read",async(o,r)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(o.params,r)})}sendResourceListChanged(t={}){return this.notification({method:"notifications/resources/list_changed",params:t})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(t){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,t),this._onlistprompts=t,this.replaceRequestHandler("prompts/list",async(o,r)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(o.params,r)})}sendPromptListChanged(t={}){return this.notification({method:"notifications/prompts/list_changed",params:t})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(t){let o=t.protocolVersion;return this._appInfo!==void 0&&console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values."),this._appCapabilities=t.appCapabilities,this._appInfo=t.appInfo,{protocolVersion:$R.includes(o)?o:A_,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(t){let o={},r=!1;for(let n of Object.keys(t)){let s=this._hostContext[n],a=t[n];CR(s,a)||(o[n]=a,r=!0)}r&&(this._hostContext=t,this.sendHostContextChange(o))}sendHostContextChange(t){return this.notification({method:"ui/notifications/host-context-changed",params:t})}sendToolInput(t){return this.notification({method:"ui/notifications/tool-input",params:t})}sendToolInputPartial(t){return this.notification({method:"ui/notifications/tool-input-partial",params:t})}sendToolResult(t){return this.notification({method:"ui/notifications/tool-result",params:t})}sendToolCancelled(t){return this.notification({method:"ui/notifications/tool-cancelled",params:t})}sendSandboxResourceReady(t){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:t})}teardownResource(t,o){return this.request({method:"ui/resource-teardown",params:t},bR,o)}sendResourceTeardown=this.teardownResource;callTool(t,o){return this.request({method:"tools/call",params:t},o)}listTools(t,o){return this.request({method:"tools/list",params:t},o)}async connect(t){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let o=this._client.getServerCapabilities();if(!o)throw Error("Client server capabilities not available");o.tools&&(this.oncalltool=async(r,n)=>this._client.request({method:"tools/call",params:r},{signal:n.mcpReq.signal}),o.tools.listChanged&&this._client.setNotificationHandler("notifications/tools/list_changed",r=>this.sendToolListChanged(r.params))),o.resources&&(this.onlistresources=async(r,n)=>this._client.request({method:"resources/list",params:r},{signal:n.mcpReq.signal}),this.onlistresourcetemplates=async(r,n)=>this._client.request({method:"resources/templates/list",params:r},{signal:n.mcpReq.signal}),this.onreadresource=async(r,n)=>this._client.request({method:"resources/read",params:r},{signal:n.mcpReq.signal}),o.resources.listChanged&&this._client.setNotificationHandler("notifications/resources/list_changed",r=>this.sendResourceListChanged(r.params))),o.prompts&&(this.onlistprompts=async(r,n)=>this._client.request({method:"prompts/list",params:r},{signal:n.mcpReq.signal}),o.prompts.listChanged&&this._client.setNotificationHandler("notifications/prompts/list_changed",r=>this.sendPromptListChanged(r.params)))}return super.connect(t)}};function CR(e,t){return JSON.stringify(e)===JSON.stringify(t)}function L_(e,t){let o=new DOMParser().parseFromString(e,"text/html"),r=o.createElement("meta");if(r.httpEquiv="Content-Security-Policy",r.content=t,o.head.prepend(r),!o.querySelector("base[href]")){let n=o.querySelector("base")??o.createElement("base");n.setAttribute("href","about:srcdoc"),r.after(n)}return"<!doctype html>"+o.documentElement.outerHTML}var $e=new Yl({name:"ADS preview",version:"1.0.0"},{},{autoResize:!0}),Wr=document.getElementById("ads-token-root"),Lt=document.getElementById("ads-widget-status"),tu=document.getElementById("ads-token-theme"),eu=document.getElementById("ads-scenario-root"),To,Me=0,U_="",Br=30,Z_=document.createElement("style");Wr&&document.head.append(Z_);function ou(e){e!=="light"&&e!=="dark"||(document.documentElement.dataset.theme=e,tu&&(tu.value=e),Wr&&To&&wo())}function Oe(e,t){let o=document.createElement(e);return o.textContent=t,o}function IR(e){let t=Oe("li","");t.dataset.token=e.name;let o=getComputedStyle(document.documentElement).getPropertyValue(e.name).trim(),r=Oe("details","");r.className="token-source";let n=Oe("summary","");n.title=`${e.name}: ${o||"Conditional or unset"}. Click to inspect source definitions.`;let s=Oe("code",e.name);s.className="token-name";let a=Oe("span",o||"Conditional or unset");n.append(s,a);let l=Oe("dl","");l.append(Oe("dt","Computed in preview"),Oe("dd",o||"Conditional or unset")),e.meaning&&l.append(Oe("dt","Meaning"),Oe("dd",e.meaning));for(let u of e.definitions)l.append(Oe("dt",u.scope),Oe("dd",`${u.value} \xB7 ${u.file}:${u.line}`));return r.append(n,l),t.append(r),t}function wo(){Z_.textContent=To.css;let e=To.tokens.filter(t=>`${t.name} ${t.type??""}`.toLowerCase().includes(U_.toLowerCase()));document.getElementById("ads-token-list").replaceChildren(...e.slice(Me,Me+Br).map(IR)),document.querySelector("footer").hidden=e.length<=Br,document.getElementById("ads-token-count").textContent=e.length?`${Me+1}\u2013${Math.min(Me+Br,e.length)} of ${e.length}`:"No matching tokens",document.getElementById("ads-token-prev").disabled=Me===0,document.getElementById("ads-token-next").disabled=Me+Br>=e.length,Lt.textContent=`${e.length} matching definitions \xB7 ${To.diagnostics.length} diagnostics`}Wr&&($e.ontoolinput=()=>{Me=0,To&&wo()},To=JSON.parse(document.getElementById("ads-token-seed").textContent),ou("light"),document.getElementById("ads-token-search").addEventListener("input",e=>{U_=e.target.value,Me=0,wo()}),tu.addEventListener("change",()=>ou(tu.value)),document.getElementById("ads-token-prev").addEventListener("click",()=>{Me=Math.max(0,Me-Br),wo()}),document.getElementById("ads-token-next").addEventListener("click",()=>{Me+=Br,wo()}),document.getElementById("ads-token-refresh").addEventListener("click",async()=>{try{let e=await $e.readServerResource({uri:"ads://project/tokens"});To=JSON.parse(e.contents.find(t=>"text"in t).text),Me=0,wo()}catch(e){Lt.textContent=`Refresh failed: ${e.message}`}}));var xo,$f,D_=!1,_a=0;async function H_(e){if($f=e,!D_||!eu)return;let t=e?.structuredContent?.draftScope;e=e?.structuredContent?.previewResult??e;let o=e?.structuredContent?.scenario?.resourceUri;if(!o||!o.startsWith("ui://ads/previews/"))return;let r=++_a;Wr&&(Wr.hidden=!0,Lt=document.getElementById("ads-scenario-status")),eu.hidden=!1;try{if(!$e.getHostCapabilities()?.serverResources)throw new Error("This Apps host does not forward server resources. Use the project showcase URL from the tool result.");let s=(await $e.readServerResource({uri:t?t+encodeURIComponent(o):o})).contents.find(d=>d.mimeType==="text/html;profile=mcp-app"&&typeof d.text=="string");if(!s)throw new Error("Scenario HTML is unavailable.");if(r!==_a)return;xo&&(await xo.close(),xo=void 0);let a=document.createElement("iframe");a.title=e.structuredContent.scenario.title,a.setAttribute("sandbox","allow-scripts allow-forms"),eu.replaceChildren(a);let l=new Xl(null,{name:"ADS scenario host",version:"1.0.0"},{serverResources:{},serverTools:{}},{hostContext:$e.getHostContext()});xo=l,l.onreadresource=d=>$e.readServerResource({...d,uri:t?t+encodeURIComponent(d.uri):d.uri}),l.oncalltool=d=>$e.callServerTool(d),l.onsizechange=({height:d})=>{d&&(a.height=String(Math.min(1e4,Math.max(120,d))))},l.oninitialized=async()=>{await l.sendToolInput({arguments:{}}),await l.sendToolResult(e),r===_a&&window.parent.postMessage({type:"ads-preview-ready"},"*")},await l.connect(new Ql(a.contentWindow,a.contentWindow));let u="default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe-eval' blob:; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; worker-src blob: data:; connect-src blob:; base-uri about:; object-src 'none'; form-action 'none'";a.srcdoc=L_(s.text,u),Lt.hidden=!0}catch(n){r===_a&&(Lt.hidden=!1,Lt.textContent=n.message,window.parent.postMessage({type:"ads-preview-ready"},"*"))}}eu&&($e.ontoolresult=e=>{H_(e)},$e.onteardown=async()=>{++_a;let e=xo;xo=void 0;try{await e?.teardownResource({},{timeout:500})}catch{}return await e?.close(),{}});$e.onhostcontextchanged=e=>{ou(e.theme),xo?.setHostContext(e)};try{await $e.connect(),D_=!0,$f&&H_($f),ou($e.getHostContext()?.theme),Wr&&(document.getElementById("ads-token-refresh").disabled=!$e.getHostCapabilities()?.serverResources,wo())}catch{Lt&&(Lt.textContent="Apps bridge unavailable. Samples remain usable; inspect project data through ADS tools/resources.")}
142
142
  /*! Bundled license information:
143
143
 
144
144
  @modelcontextprotocol/client/dist/src-WCy6ifGf.mjs:
@@ -1,5 +1,6 @@
1
1
  import { readdirSync } from "node:fs";
2
2
  import path from "node:path";
3
+ import { isDraftFile } from "./draft-boundary.mjs";
3
4
 
4
5
  const metadata = new Set(["node_modules", ".git", ".ds", ".vite", "coverage"]);
5
6
  const generated = new Set(["dist", "build", "target", "out", ".next", ".nuxt", ".svelte-kit", ".turbo"]);
@@ -14,6 +15,7 @@ export function createPreviewFileFilter({root, config}) {
14
15
  ? file !== ".." && !file.startsWith(`..${path.sep}`) && !path.isAbsolute(file)
15
16
  : file === parent || file.startsWith(parent + path.sep);
16
17
  return file => {
18
+ if (isDraftFile(file)) return true;
17
19
  const relative = path.relative(root, path.resolve(file)), parts = relative.split(path.sep);
18
20
  if (parts.some(name => metadata.has(name))) return true;
19
21
  const key = canonical(relative);
@@ -1,12 +1,12 @@
1
1
  import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
2
2
  import { loadConfig } from "./config.mjs";
3
- import { inspectScenarios } from "./scenarios.mjs";
3
+ import { discoverScenarioRegistry } from "./scenario-registry.mjs";
4
4
 
5
5
  // Discovery is semantic source analysis. Keep it off the live compiler's event
6
6
  // loop; the caller fences each result against the exact project input digest.
7
7
  if (!isMainThread && workerData?.adsScenarioInspector) {
8
- parentPort.on("message", ({ id }) => {
9
- try { parentPort.postMessage({ id, result: inspectScenarios(loadConfig(workerData.root)) }); }
8
+ parentPort.on("message", ({ id, root = workerData.root }) => {
9
+ try { parentPort.postMessage({ id, result: discoverScenarioRegistry(loadConfig(root)) }); }
10
10
  catch (error) { parentPort.postMessage({ id, error: error.message }); }
11
11
  });
12
12
  }
@@ -16,7 +16,7 @@ export function createScenarioInspector(root) {
16
16
  const pending = new Map();
17
17
  function fail(error) { for (const task of pending.values()) task.reject(error); pending.clear(); }
18
18
  return {
19
- inspect() {
19
+ inspect(directory = root) {
20
20
  if (!worker) {
21
21
  worker = new Worker(new URL(import.meta.url), { workerData: { adsScenarioInspector: true, root } });
22
22
  worker.on("message", ({ id, result, error }) => {
@@ -27,7 +27,7 @@ export function createScenarioInspector(root) {
27
27
  worker.on("exit", () => { fail(new Error("Scenario inspector closed.")); worker = undefined; });
28
28
  }
29
29
  const id = ++sequence;
30
- return new Promise((resolve, reject) => { pending.set(id, { resolve, reject }); worker.postMessage({ id }); });
30
+ return new Promise((resolve, reject) => { pending.set(id, { resolve, reject }); worker.postMessage({ id, root: directory }); });
31
31
  },
32
32
  async close() { const previous = worker; worker = undefined; fail(new Error("Scenario inspector closed.")); await previous?.terminate(); },
33
33
  };
@@ -0,0 +1,36 @@
1
+ import ts from "typescript";
2
+ import path from "node:path";
3
+ import { isContractFile, isScenarioFile, sourceFiles } from "./config.mjs";
4
+ import { projectCompilerOptions } from "./boundaries.mjs";
5
+
6
+ /** Preview-only checker reuse. Validation keeps its independent fresh program. */
7
+ export function createScenarioProgram() {
8
+ let previous, signature;
9
+ const sources = new Map();
10
+ return {
11
+ build(options) {
12
+ const compilerOptions = { ...projectCompilerOptions(options), allowJs: true };
13
+ const next = JSON.stringify([options.root, compilerOptions]);
14
+ if (signature !== next) { previous = undefined; sources.clear(); signature = next; }
15
+ const files = sourceFiles(options.dsRoot);
16
+ const roots = files.some(isContractFile) ? files.filter(file => /\.[cm]?[jt]sx?$/.test(file))
17
+ : [path.join(options.dsRoot, options.config.publicEntry), path.join(options.dsRoot, options.config.reviewEntry), ...files.filter(isScenarioFile)];
18
+ const host = ts.createCompilerHost(compilerOptions, true), load = host.getSourceFile.bind(host);
19
+ // New/deleted modules and changed dependency exports must resolve again;
20
+ // source-tree reuse does not grant reuse of old failed module lookups.
21
+ host.hasInvalidatedResolutions = () => true;
22
+ host.getSourceFile = (file, languageVersion, onError, force) => {
23
+ const text = host.readFile(file), cached = sources.get(file), mode = JSON.stringify(languageVersion);
24
+ if (!force && cached && cached.text === text && cached.mode === mode) return cached.source;
25
+ const source = load(file, languageVersion, onError, force);
26
+ if (source) sources.set(file, { text, mode, source }); else sources.delete(file);
27
+ return source;
28
+ };
29
+ previous = ts.createProgram({ rootNames: roots, options: compilerOptions, host, oldProgram: previous });
30
+ const retained = new Set(previous.getSourceFiles().map(file => file.fileName));
31
+ for (const file of sources.keys()) if (!retained.has(file)) sources.delete(file);
32
+ return previous;
33
+ },
34
+ clear() { previous = undefined; signature = undefined; sources.clear(); },
35
+ };
36
+ }
@@ -0,0 +1,90 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { loadConfig, isInside } from "./config.mjs";
5
+ import { inspectScenarios } from "./scenarios.mjs";
6
+ import { previewSourceRevision } from "./preview-inputs.mjs";
7
+ import { createScenarioProgram } from "./scenario-program.mjs";
8
+
9
+ const hash = value => createHash("sha256").update(value).digest("hex");
10
+ const filename = "scenario-registry.json";
11
+ const maxBytes = 8 * 1024 * 1024;
12
+ const programs = new Map();
13
+ function programFor(root) {
14
+ const program = programs.get(root) ?? createScenarioProgram();
15
+ programs.delete(root); programs.set(root, program);
16
+ while (programs.size > 2) { const oldest = programs.keys().next().value; programs.get(oldest).clear(); programs.delete(oldest); }
17
+ return program;
18
+ }
19
+ // A source checkout and a published build have different code even when their
20
+ // package versions match. Cache identities follow the actual discovery code.
21
+ const toolRevision = (() => {
22
+ const root = import.meta.dirname, rows = [];
23
+ function visit(directory) {
24
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
25
+ const file = path.join(directory, entry.name);
26
+ if (entry.isDirectory() && !["skills", "bootstrap-ds", "showcase"].includes(entry.name)) visit(file);
27
+ else if (entry.isFile() && /\.(?:mjs|js|cjs|json)$/.test(entry.name)) rows.push([path.relative(root, file), hash(readFileSync(file))]);
28
+ }
29
+ }
30
+ visit(root);
31
+ return hash(JSON.stringify([rows, process.versions.bun ?? process.version, process.platform, process.arch]));
32
+ })();
33
+
34
+ function validRegistry(value, options) {
35
+ return value && Array.isArray(value.scenarios) && value.scenarios.length <= 10000
36
+ && value.scenarios.every(item => typeof item?.id === "string" && /^(?:tokens|components|patterns|composition)\/[\w./-]+$/.test(item.id)
37
+ && path.posix.normalize(item.id) === item.id && typeof item.title === "string"
38
+ && ["tokens", "components", "patterns", "composition"].includes(item.kind)
39
+ && typeof item.file === "string" && isInside(options.dsRoot, path.resolve(options.root, item.file))
40
+ && item.artifact === `.ds/scenarios/${item.id}/index.html` && Array.isArray(item.covers) && Array.isArray(item.tokens))
41
+ && Array.isArray(value.diagnostics) && value.diagnostics.every(item => typeof item?.message === "string" && typeof item.rule === "string");
42
+ }
43
+
44
+ function read(options, revision) {
45
+ const file = path.join(options.root, ".ds", filename);
46
+ try {
47
+ const stat = lstatSync(file);
48
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size > maxBytes || realpathSync(file) !== file) return;
49
+ const snapshot = JSON.parse(readFileSync(file, "utf8"));
50
+ if (snapshot.schemaVersion === 1 && snapshot.root === options.root && snapshot.toolRevision === toolRevision
51
+ && snapshot.revision === revision && snapshot.digest === hash(JSON.stringify(snapshot.registry)) && validRegistry(snapshot.registry, options)) return snapshot.registry;
52
+ } catch { /* Missing/corrupt/generated data is a cache miss, never evidence. */ }
53
+ }
54
+
55
+ /** Read a current discovery snapshot without starting semantic analysis. */
56
+ export function readScenarioRegistry(options) {
57
+ return read(options, previewSourceRevision(options));
58
+ }
59
+
60
+ function write(options, revision, registry) {
61
+ const directory = path.join(options.root, ".ds"), file = path.join(directory, filename), temporary = `${file}.${randomUUID()}.tmp`;
62
+ try {
63
+ if (existsSync(directory) && realpathSync(directory) !== directory) return;
64
+ mkdirSync(directory, { recursive: true });
65
+ if (realpathSync(directory) !== directory) return;
66
+ const content = JSON.stringify({ schemaVersion: 1, root: options.root, toolRevision, revision, digest: hash(JSON.stringify(registry)), registry });
67
+ if (Buffer.byteLength(content) > maxBytes) return;
68
+ writeFileSync(temporary, content);
69
+ renameSync(temporary, file);
70
+ } catch { /* Read-only projects can still discover scenarios without caching. */ }
71
+ finally { try { rmSync(temporary, { force: true }); } catch { /* Optional cache cleanup must not prevent discovery. */ } }
72
+ }
73
+
74
+ /** Share semantic discovery between preview hosts and compiler processes.
75
+ * This snapshot contains metadata/diagnostics only, never validated outputs or
76
+ * passing check results. Validation continues to inspect source independently. */
77
+ export function discoverScenarioRegistry(options) {
78
+ for (let attempt = 0; attempt < 2; ++attempt) {
79
+ // Contract inspectors memoize TypeScript programs on options. A new source
80
+ // revision needs fresh options as well as a fresh registry.
81
+ const current = loadConfig(options.root), revision = previewSourceRevision(current);
82
+ const cached = read(current, revision);
83
+ if (cached) return cached;
84
+ const registry = inspectScenarios(current, programFor(current.root).build(current));
85
+ if (revision !== previewSourceRevision(loadConfig(current.root))) continue;
86
+ write(current, revision, registry);
87
+ return registry;
88
+ }
89
+ throw Object.assign(new Error("Sources changed during scenario discovery. Retry against the current source."), { code: "ADS_SCENARIO_SOURCE_CHANGED" });
90
+ }
@@ -1,8 +1,9 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
3
3
  import path from "node:path";
4
+ import { isDraftPreviewWorkspace } from "./draft-workspace.mjs";
4
5
  import { loadConfig, isInside } from "./config.mjs";
5
- import { inspectScenarios } from "./scenarios.mjs";
6
+ import { discoverScenarioRegistry } from "./scenario-registry.mjs";
6
7
  import { artifactDigest, createBuildReporter } from "./mcp/build-status.mjs";
7
8
  import { cachedPreviewPublication, previewArtifactHtml, readPreviewManifest } from "./preview-resources.mjs";
8
9
  import { previewArtifactPath, withPreviewSession } from "./preview-scope.mjs";
@@ -18,7 +19,7 @@ const fileDigest = file => { try { return digest(readFileSync(file)); } catch {
18
19
  export function createPreviewCache(options, compilerFiles = []) {
19
20
  const { root } = options;
20
21
  const key = file => isInside(import.meta.dirname,file) ? `ads-tool/${path.relative(import.meta.dirname,file)}` : isInside(root,file) ? `project/${path.relative(root,file)}` : file;
21
- const adapterFiles = [import.meta.filename, ...["preview-builder.mjs", "preview-workers.mjs", "preview-files.mjs", "preview-inputs.mjs", "preview-resources.mjs", "preview-scope.mjs", "scenario-groups.mjs", "scenario-inspector.mjs", "scenarios-vite.mjs", "linaria.mjs", "linaria/atomic-css.cjs", "linaria/atomic-styled.cjs", "linaria/preserve-values.cjs"].map(file => path.join(import.meta.dirname, file)), ...compilerFiles,
22
+ const adapterFiles = [import.meta.filename, ...["preview-builder.mjs", "preview-workers.mjs", "preview-files.mjs", "preview-inputs.mjs", "preview-resources.mjs", "preview-scope.mjs", "scenario-groups.mjs", "scenario-inspector.mjs", "scenario-registry.mjs", "scenarios-vite.mjs", "linaria.mjs", "linaria/atomic-css.cjs", "linaria/atomic-styled.cjs", "linaria/preserve-values.cjs"].map(file => path.join(import.meta.dirname, file)), ...compilerFiles,
22
23
  ...["package.json", "package-lock.json", "bun.lock", "bun.lockb", "node_modules/.package-lock.json"].map(file => path.join(root, file))];
23
24
  const adapterDigest = () => digest(JSON.stringify(adapterFiles.map(file => [key(file), fileDigest(file)])));
24
25
  const loadedAdapter = adapterDigest();
@@ -79,7 +80,21 @@ export function createPreviewCache(options, compilerFiles = []) {
79
80
  artifact: artifactDigest(path.join(root, previewArtifactPath(options, entry.artifact))) };
80
81
  }
81
82
  }
82
- function recordGraph(revision, entries) { value.graphRevision=revision;value.graphInputs=inputs();value.registry=entries;save(); }
83
+ function recordCurrent(stamp, update) {
84
+ // Publication and dependency hashing can overlap the next external edit.
85
+ // Never attach the previous output to bytes newer than its compiled stamp.
86
+ if (inputs() !== stamp) return false;
87
+ const previous = value;
88
+ value = { ...value, entries: { ...value.entries } };
89
+ try {
90
+ update();
91
+ if (inputs() !== stamp) { value = previous; return false; }
92
+ save();
93
+ return true;
94
+ } catch (error) { value = previous; throw error; }
95
+ }
96
+ function graph(revision, entries, stamp) { value.graphRevision=revision;value.graphInputs=stamp;value.registry=entries; }
97
+ function recordGraph(revision, entries, stamp = inputs()) { return recordCurrent(stamp, () => graph(revision, entries, stamp)); }
83
98
  return { inputs, reusable, reload, snapshot: () => structuredClone(value), seed(state) { value=structuredClone(state);save(); }, graphRevision: () => value.graphRevision, recordGraph, validated: stamp => value.validation === stamp,
84
99
  registry(stamp) {
85
100
  if(value.validation!==stamp || value.graphInputs!==stamp || !Array.isArray(value.registry) || !value.registry.length || value.registry.length>1000)return null;
@@ -92,11 +107,10 @@ export function createPreviewCache(options, compilerFiles = []) {
92
107
  if (adapterDigest() !== loadedAdapter) throw Object.assign(new Error("Preview compiler code or dependencies changed. Invoke the preview again to restart the builder and load current code."), { code: "ADS_PREVIEW_RESTART" });
93
108
  },
94
109
  validate(stamp) { value.validation = stamp; save(); },
95
- recordAll(entries, dependencies, revision) { recordEntries(entries, dependencies); recordGraph(revision,entries); },
96
- record(entry, dependencies) {
97
- recordEntries([entry], dependencies);
98
- save();
110
+ recordAll(entries, dependencies, revision, stamp = inputs()) {
111
+ return recordCurrent(stamp, () => { recordEntries(entries, dependencies); graph(revision, entries, stamp); });
99
112
  },
113
+ record(entry, dependencies, stamp = inputs()) { return recordCurrent(stamp, () => recordEntries([entry], dependencies)); },
100
114
  };
101
115
  }
102
116
 
@@ -134,7 +148,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
134
148
  const cache = createPreviewCache(options, compilerFiles);
135
149
  function registry() {
136
150
  options = withPreviewSession(loadConfig(root), process.env.ADS_MCP_BUILD_SESSION);
137
- const result = inspectScenarios(options);
151
+ const result = discoverScenarioRegistry(options);
138
152
  if (result.diagnostics.length) throw Object.assign(new Error(result.diagnostics.map(item => `${item.file}: ${item.message}`).join("\n")), { scenarios: result.scenarios });
139
153
  mkdirSync(path.join(root, ".ds/scenarios"), { recursive: true });
140
154
  writeFileSync(path.join(root, ".ds/scenarios/manifest.json"), JSON.stringify({ schemaVersion: 1, scenarios: result.scenarios }, null, 2));
@@ -155,10 +169,12 @@ export async function runScenarioCompiler(directory, { watched = false, validate
155
169
  let stopped = false;
156
170
  let generation = 0;
157
171
  let publishedStamp;
172
+ let publishedEntries = new Set();
158
173
  let validation;
159
174
  let observedSourceRevision = previewSourceRevision(options);
160
175
  let invalidation;
161
176
  const inspector = watched && buildGraph ? createScenarioInspector(root) : null;
177
+ let discovering, unknownRevision;
162
178
  let liveCandidate, verifying = false;
163
179
  function failure(error) {
164
180
  try { reporter.failure(error); } catch (reportError) { console.error(reportError); }
@@ -167,6 +183,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
167
183
  }
168
184
  if (registryFailure) failure(registryFailure);
169
185
  function gate(stamp) {
186
+ if (isDraftPreviewWorkspace(root)) return Promise.resolve();
170
187
  if (cache.validated(stamp)) return Promise.resolve();
171
188
  return validation ??= Promise.resolve().then(validate).then(() => {
172
189
  if (stamp !== cache.inputs()) throw new Error("Sources changed during preview validation. Waiting for the current build.");
@@ -216,7 +233,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
216
233
  if (failure) throw failure.reason;
217
234
  cache.assertCompiler();
218
235
  if (stopped || started !== generation || stamp !== cache.inputs()) return; // Watch queued a newer revision.
219
- if (!reuse) cache.record(entry, dependencies);
236
+ if (!reuse && !cache.record(entry, dependencies, stamp)) return;
220
237
  reporter.ready(entry.id, revision);
221
238
  reporter.progress("idle");
222
239
  } catch (error) {
@@ -265,10 +282,10 @@ export async function runScenarioCompiler(directory, { watched = false, validate
265
282
  const publication = outcomes[1].value;
266
283
  if (publication) {
267
284
  publication.publish(reporter.session);
268
- cache.recordAll(entries, dependencies, publication.revision);
285
+ if (!cache.recordAll(entries, dependencies, publication.revision, stamp)) return;
269
286
  } else {
270
287
  cached.publish(reporter.session);
271
- cache.recordGraph(cached.revision,entries);
288
+ if (!cache.recordGraph(cached.revision,entries,stamp)) return;
272
289
  }
273
290
  for (const entry of entries) { pending.delete(entry.id); reporter.ready(entry.id, revisions.get(entry.id)); }
274
291
  publishedStamp = stamp;
@@ -288,12 +305,20 @@ export async function runScenarioCompiler(directory, { watched = false, validate
288
305
  cache.reload();
289
306
  const sourceRevision = previewSourceRevision(options), stamp = cache.inputs();
290
307
  const prepared=cache.registry(stamp);
291
- if(prepared){entries=prepared;reporter.setApps(buildApps());}
292
- const candidate = { generation, stamp, sourceRevision, entries: [...entries], dependencies: new Set(), registryReused:!!prepared };
293
- // One multi-entry build covers every requested scenario in this revision.
294
- // Navigation must not enqueue the same shared graph once per visited entry.
308
+ // A guarded edit can publish a checked graph while this watcher's discovery
309
+ // still describes the previous revision. Adopt its current metadata before
310
+ // comparing registries. A partial watched graph cannot replace the catalogue.
311
+ if (prepared?.length === entries.length && prepared.every((entry, index) => entry.id === entries[index].id)) {
312
+ entries = prepared;
313
+ reporter.setApps(buildApps());
314
+ }
315
+ const registryReused = !!prepared && JSON.stringify(prepared) === JSON.stringify(entries);
316
+ const selected = registryReused ? prepared : entries.filter(entry => requested.has(entry.id));
317
+ const candidate = { generation, stamp, sourceRevision, registry: [...entries], entries: selected, dependencies: new Set(), registryReused };
318
+ // Retain roots requested by other mounted Apps, without compiling untouched
319
+ // catalogue entries. Production/unwatched builds still cover all entries.
295
320
  for (const entry of candidate.entries) pending.delete(entry.id);
296
- candidate.revisions = reporter.batch(() => new Map(entries.map(entry => [entry.id, reporter.begin(entry.id, { sourceRevision })])));
321
+ candidate.revisions = reporter.batch(() => new Map(candidate.entries.map(entry => [entry.id, reporter.begin(entry.id, { sourceRevision })])));
297
322
  reporter.progress("validation-and-compilation");
298
323
  const track = { name: "ads-live-preview-dependencies", generateBundle() {
299
324
  for (const id of this.getModuleIds()) {
@@ -355,7 +380,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
355
380
  }
356
381
  // Give compiled feedback priority before starting CPU-heavy validation.
357
382
  // An already running check continues; later edits replace its candidate.
358
- const inspection=candidate.reused&&candidate.registryReused?Promise.resolve({scenarios:candidate.entries,diagnostics:[]}):inspector.inspect();
383
+ const inspection=candidate.reused&&candidate.registryReused?Promise.resolve({scenarios:candidate.registry,diagnostics:[]}):inspector.inspect();
359
384
  const outcomes = [compiled, ...await Promise.allSettled([gate(candidate.stamp), inspection])];
360
385
  if (stopped) return;
361
386
  if (candidate !== liveCandidate || candidate.generation !== generation || candidate.stamp !== cache.inputs()) {
@@ -366,7 +391,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
366
391
  if (outcomes[2].status === "rejected") throw outcomes[2].reason;
367
392
  const registry = outcomes[2].value;
368
393
  if (registry.diagnostics.length) throw new Error(registry.diagnostics.map(item => `${item.file}: ${item.message}`).join("\n"));
369
- if (JSON.stringify(registry.scenarios) !== JSON.stringify(candidate.entries)) {
394
+ if (JSON.stringify(registry.scenarios) !== JSON.stringify(candidate.registry)) {
370
395
  entries = registry.scenarios;
371
396
  writeFileSync(path.join(root, ".ds/scenarios/manifest.json"), JSON.stringify({ schemaVersion: 1, scenarios: entries }, null, 2));
372
397
  reporter.batch(() => { reporter.setApps(buildApps()); reporter.live(undefined); reporter.progress("idle"); });
@@ -384,14 +409,17 @@ export async function runScenarioCompiler(directory, { watched = false, validate
384
409
  const publication = outcomes[0].value;
385
410
  if (stopped || candidate !== liveCandidate || candidate.generation !== generation || candidate.stamp !== cache.inputs()) continue;
386
411
  publication.publish(reporter.session);
387
- if (!candidate.reused) cache.recordAll(candidate.entries, candidate.dependencies, publication.revision);
388
- else cache.recordGraph(publication.revision,candidate.entries);
412
+ const recorded = !candidate.reused
413
+ ? cache.recordAll(candidate.entries, candidate.dependencies, publication.revision, candidate.stamp)
414
+ : cache.recordGraph(publication.revision,candidate.entries,candidate.stamp);
415
+ if (!recorded) { if (candidate === liveCandidate) liveCandidate = undefined; continue; }
389
416
  reporter.batch(() => {
390
417
  for (const entry of candidate.entries) reporter.ready(entry.id, candidate.revisions.get(entry.id));
391
418
  reporter.live(undefined);
392
419
  reporter.progress("idle");
393
420
  });
394
421
  publishedStamp = candidate.stamp;
422
+ publishedEntries = new Set(candidate.entries.map(entry => entry.id));
395
423
  } catch (error) {
396
424
  if (!candidate.failed) rejectLive(candidate, error);
397
425
  }
@@ -412,6 +440,23 @@ export async function runScenarioCompiler(directory, { watched = false, validate
412
440
  } catch (error) { failure(error); }
413
441
  finally { compiling = false; }
414
442
  }
443
+ function discoverUnknownEntries() {
444
+ if (!inspector || discovering) return;
445
+ const revision = previewSourceRevision(options);
446
+ if (unknownRevision === revision) return;
447
+ unknownRevision = revision;
448
+ discovering = inspector.inspect().then(result => {
449
+ if (stopped) return;
450
+ if (previewSourceRevision(options) !== revision) { unknownRevision = undefined; return; }
451
+ if (result.diagnostics.length) throw new Error(result.diagnostics.map(item => `${item.file}: ${item.message}`).join("\n"));
452
+ if (JSON.stringify(result.scenarios) === JSON.stringify(entries)) return;
453
+ ++generation; entries = result.scenarios; registryFailure = undefined; liveCandidate = undefined;
454
+ reporter.setApps(buildApps());
455
+ writeFileSync(path.join(root, ".ds/scenarios/manifest.json"), JSON.stringify({ schemaVersion: 1, scenarios: entries }));
456
+ for (const id of requested) if (!entries.some(entry => entry.id === id)) requested.delete(id);
457
+ request();
458
+ }).catch(error => { if (!stopped) failure(error); }).finally(() => { discovering = undefined; });
459
+ }
415
460
  function request(startBuild = true) {
416
461
  const file = process.env.ADS_MCP_REQUEST_FILE;
417
462
  if (!file || !existsSync(file)) return;
@@ -423,13 +468,14 @@ export async function runScenarioCompiler(directory, { watched = false, validate
423
468
  if (requested.size) sourceChanged("invalidate",options.config.dsDir,true);
424
469
  }
425
470
  active = entries.find(entry => entry.artifact === value.active)?.id;
471
+ if (value.files.some(file => !entries.some(entry => entry.artifact === file))) discoverUnknownEntries();
426
472
  for (const file of value.files) {
427
473
  const entry = entries.find(entry => entry.artifact === file);
428
474
  if (entry && !requested.has(entry.id)) {
429
475
  requested.add(entry.id);
430
476
  const covered = liveCandidate && !liveCandidate.failed && liveCandidate.generation === generation
431
477
  && liveCandidate.stamp === cache.inputs() && liveCandidate.entries.some(item => item.id === entry.id);
432
- if (!buildGraph || publishedStamp !== cache.inputs() && !covered) pending.add(entry.id);
478
+ if (!buildGraph || (!publishedEntries.has(entry.id) || publishedStamp !== cache.inputs()) && !covered) pending.add(entry.id);
433
479
  }
434
480
  }
435
481
  if (startBuild) void drain();
@@ -474,7 +520,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
474
520
  } catch (error) {
475
521
  registryFailure = error; failure(error);
476
522
  }
477
- }, 100);
523
+ }, 16);
478
524
  }
479
525
  // Do not allocate recursive OS watches for node_modules or generated trees.
480
526
  const watchers = new Map();
@@ -1,3 +1,4 @@
1
1
  import type { Plugin } from "vite";
2
2
  export function scenarioRegistryPlugin(directory?: string): Plugin;
3
3
  export function inlineScenarioHtml(): Plugin;
4
+ export function draftImportGuard(): Plugin;
@@ -5,6 +5,7 @@ import { inspectScenarios } from "./scenarios.mjs";
5
5
  import { configureReviewAlias } from "./preview-resources.mjs";
6
6
  export { createPreviewResources, previewEntriesPlugin } from "./preview-resources.mjs";
7
7
  export { createVitePreviewBuilder } from "./preview-builder.mjs";
8
+ export { draftImportGuard } from "./draft-boundary.mjs";
8
9
 
9
10
  /** Project-owned rendering; this plugin supplies only discoverable module entries. */
10
11
  export function scenarioRegistryPlugin(directory = process.cwd()) {
@@ -41,7 +41,8 @@ export function publicUi(program, options) {
41
41
  export function inspectScenarios(options, suppliedProgram) {
42
42
  const { root, dsRoot } = options;
43
43
  const files = sourceFiles(dsRoot).filter(isScenarioFile);
44
- const program = suppliedProgram ?? inspectUnitContracts(options).program ?? ts.createProgram([path.join(dsRoot, options.config.publicEntry), path.join(dsRoot, options.config.reviewEntry), ...files], { ...projectCompilerOptions(options), allowJs: true });
44
+ const contracts = inspectUnitContracts(options, suppliedProgram);
45
+ const program = suppliedProgram ?? contracts.program ?? ts.createProgram([path.join(dsRoot, options.config.publicEntry), path.join(dsRoot, options.config.reviewEntry), ...files], { ...projectCompilerOptions(options), allowJs: true });
45
46
  const apis = scenarioApi(program, options);
46
47
  const duplicate = apis.find((item, index) => apis.some((other, otherIndex) => index !== otherIndex && item.name === other.name));
47
48
  const known = new Map(apis.filter(item => item.kind !== "controllers").map((item) => [item.name, item]));