@reqvire-org/ads 0.4.3 → 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 +12 -9
- package/dist/bun-compiler.mjs +6 -5
- package/dist/check.mjs +3 -43
- package/dist/cli.mjs +1 -1
- package/dist/contrast-composition.mjs +6 -60
- package/dist/contrast-styles.mjs +88 -0
- package/dist/mcp/apps.mjs +7 -1
- package/dist/mcp/build-status.mjs +8 -3
- package/dist/mcp/drafts.mjs +13 -1
- package/dist/mcp/preview-http.bundle.js +7 -0
- package/dist/mcp/preview-http.mjs +148 -0
- package/dist/mcp/preview-widget.bundle.js +47 -47
- package/dist/mcp/resource-loader.js +1 -201
- package/dist/mcp/sandbox-host.mjs +6 -1
- package/dist/mcp/server.mjs +35 -4
- package/dist/mcp/showcase-host.mjs +55 -5
- package/dist/mcp/showcase-http.mjs +66 -0
- package/dist/preview-bun.mjs +75 -60
- package/dist/preview-incremental.mjs +358 -0
- package/dist/preview-manifest-update.mjs +70 -0
- package/dist/preview-resources.mjs +33 -1
- package/dist/render-composition.mjs +27 -5
- 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 +3 -3
- package/dist/skills/ads-designer/SKILL.md +5 -1
- package/dist/skills/ads-designer/references/accessibility.md +6 -2
- package/dist/skills/ads-designer/references/captures.md +1 -1
- package/dist/skills/ads-designer/references/runtimes.md +31 -0
- 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 +31 -0
- package/dist/skills/ads-import/references/workflows.md +16 -0
- package/dist/skills/ads-migrate/SKILL.md +3 -1
- package/dist/skills/ads-migrate/references/0.4.1-to-0.4.2.md +2 -3
- package/dist/skills/ads-migrate/references/0.4.3-to-0.4.4.md +89 -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 +31 -0
- package/dist/skills/ads-port/references/workflows.md +16 -0
- package/dist/style-token-rules.mjs +51 -0
- package/dist/verification/browser.mjs +2 -2
- package/docs/ADS.md +9 -7
- package/docs/ARCHITECTURE.md +109 -48
- package/docs/CACHING.md +40 -1
- package/docs/CHANGELOG.md +100 -22
- package/docs/GUIDE.md +37 -10
- package/docs/HTTP-SHOWCASE-POC.md +397 -0
- package/docs/MCP.md +104 -25
- package/docs/benchmarks/README.md +1 -1
- 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 +6 -4
|
@@ -1,201 +1 @@
|
|
|
1
|
-
function closure(records, uri) {
|
|
2
|
-
const ordered = [], seen = new Set();
|
|
3
|
-
function visit(id) {
|
|
4
|
-
if (seen.has(id)) return;
|
|
5
|
-
seen.add(id);
|
|
6
|
-
const record=records.get(id);
|
|
7
|
-
if (!record) throw new Error(`Missing preview dependency metadata: ${id}`);
|
|
8
|
-
for (const dependency of [...record.imports,...record.styles,...record.references]) visit(dependency);
|
|
9
|
-
ordered.push(id);
|
|
10
|
-
}
|
|
11
|
-
visit(uri);return ordered;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export function changedPreviewScenarios(previous, next) {
|
|
15
|
-
if (!previous || previous.revision===next.revision) return [];
|
|
16
|
-
const signature=(graph,entry)=>{const records=new Map(Object.entries(graph.assets));return JSON.stringify(closure(records,entry.module).map(uri=>[uri,records.get(uri)]));};
|
|
17
|
-
return next.scenarios.filter(entry=>{const before=previous.scenarios.find(item=>item.id===entry.id);return !before || signature(previous,before)!==signature(next,entry);}).map(entry=>entry.id);
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
/** Native ES modules keep framework semantics, cycles, and live bindings intact. */
|
|
21
|
-
export class PreviewResourceLoader {
|
|
22
|
-
constructor(read) {
|
|
23
|
-
this.read = read;
|
|
24
|
-
this.records = new Map();
|
|
25
|
-
this.bytes = new Map();
|
|
26
|
-
this.urls = new Map();
|
|
27
|
-
this.styles = new Map();
|
|
28
|
-
this.styleReady = new Map();
|
|
29
|
-
this.revisions = new Set();
|
|
30
|
-
this.loadedModules = new Set();
|
|
31
|
-
this.importing = Promise.resolve();
|
|
32
|
-
this.generation = 0;
|
|
33
|
-
this.prefetchGeneration = 0;
|
|
34
|
-
this.closed = false;
|
|
35
|
-
globalThis.__dsPreviewImport = uri => this.importModule(uri);
|
|
36
|
-
}
|
|
37
|
-
register(manifest) {
|
|
38
|
-
if (manifest.schemaVersion !== 1 || !Array.isArray(manifest.scenarios) || !manifest.assets || typeof manifest.revision !== "string") throw new Error("Unsupported preview manifest. Rebuild previews with the installed ADS version.");
|
|
39
|
-
for (const [uri, record] of Object.entries(manifest.assets)) {
|
|
40
|
-
if (!/^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/.test(uri) || !/^sha256:[a-f0-9]{64}$/.test(record.digest)
|
|
41
|
-
|| !["imports", "dynamicImports", "styles", "references"].every(key => Array.isArray(record[key]) && record[key].every(ref => Object.hasOwn(manifest.assets, ref)))) throw new Error("Invalid preview dependency graph.");
|
|
42
|
-
if (this.records.has(uri) && this.records.get(uri).digest !== record.digest) throw Object.assign(new Error("An immutable preview resource changed its content. Rebuild previews with the current ADS version."), {code:"ADS_RESOURCE_IDENTITY", category:"build", resourceUri:uri});
|
|
43
|
-
}
|
|
44
|
-
// A rejected graph must not leave a partially registered revision behind.
|
|
45
|
-
for (const [uri, record] of Object.entries(manifest.assets)) this.records.set(uri, record);
|
|
46
|
-
}
|
|
47
|
-
async resource(uri) {
|
|
48
|
-
if (!this.bytes.has(uri)) {
|
|
49
|
-
const task = (async () => {
|
|
50
|
-
const record = this.records.get(uri);
|
|
51
|
-
if (!record) throw new Error(`Unknown preview dependency: ${uri}`);
|
|
52
|
-
let response;
|
|
53
|
-
try { response = await this.read(uri); }
|
|
54
|
-
catch (error) { throw Object.assign(new Error(`Preview resource read failed for ${uri}: ${error.message}`, { cause: error }), { code: "ADS_RESOURCE_READ", category: "transport", resourceUri: uri }); }
|
|
55
|
-
if (this.closed) throw new Error("The preview App was closed.");
|
|
56
|
-
const content = response.contents.find(item => item.uri === uri);
|
|
57
|
-
if (!content) throw Object.assign(new Error(`Missing preview dependency: ${uri}`), { code: "ADS_RESOURCE_CONTENT", category: "build", resourceUri: uri });
|
|
58
|
-
const bytes = typeof content.text === "string" ? new TextEncoder().encode(content.text) : Uint8Array.from(atob(content.blob), letter => letter.charCodeAt(0));
|
|
59
|
-
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
60
|
-
const actual = "sha256:" + [...new Uint8Array(digest)].map(byte => byte.toString(16).padStart(2, "0")).join("");
|
|
61
|
-
if (bytes.length !== record.size || actual !== record.digest) throw Object.assign(new Error("Preview resource integrity check failed. Rebuild and reopen the preview."), { code: "ADS_RESOURCE_INTEGRITY", category: "build", resourceUri: uri });
|
|
62
|
-
return bytes;
|
|
63
|
-
})();
|
|
64
|
-
this.bytes.set(uri, task);
|
|
65
|
-
task.catch(() => this.bytes.delete(uri));
|
|
66
|
-
}
|
|
67
|
-
return this.bytes.get(uri);
|
|
68
|
-
}
|
|
69
|
-
closure(uri) {
|
|
70
|
-
return closure(this.records,uri);
|
|
71
|
-
}
|
|
72
|
-
async prefetch(manifest, ids) {
|
|
73
|
-
if (this.closed) return;
|
|
74
|
-
this.register(manifest);
|
|
75
|
-
const generation=++this.prefetchGeneration, pending=new Set(), scenarios=[];
|
|
76
|
-
let bytes=0;
|
|
77
|
-
for (const id of ids) {
|
|
78
|
-
const entry=manifest.scenarios.find(entry=>entry.id===id);
|
|
79
|
-
if (!entry) continue;
|
|
80
|
-
const missing=this.closure(entry.module).filter(uri=>!this.bytes.has(uri)&&!pending.has(uri));
|
|
81
|
-
const size=missing.reduce((sum,uri)=>sum+this.records.get(uri).size,0);
|
|
82
|
-
if (bytes+size>16*1024*1024 || pending.size+missing.length>256) continue;
|
|
83
|
-
bytes+=size;scenarios.push(id);for(const uri of missing)pending.add(uri);
|
|
84
|
-
}
|
|
85
|
-
const queue=[...pending];let index=0;
|
|
86
|
-
const next=async()=>{while(!this.closed&&generation===this.prefetchGeneration&&index<queue.length)await this.resource(queue[index++]);};
|
|
87
|
-
await Promise.all(Array.from({length:Math.min(3,queue.length)},next));
|
|
88
|
-
return {scenarios,resources:queue.length};
|
|
89
|
-
}
|
|
90
|
-
async materialize(uri) {
|
|
91
|
-
const ordered = this.closure(uri);
|
|
92
|
-
await Promise.all(ordered.map(id => this.resource(id)));
|
|
93
|
-
const imports = {};
|
|
94
|
-
for (const id of ordered) {
|
|
95
|
-
if (this.closed) throw new Error("The preview App was closed.");
|
|
96
|
-
if (this.urls.has(id)) continue;
|
|
97
|
-
const record = this.records.get(id);
|
|
98
|
-
let bytes = await this.resource(id);
|
|
99
|
-
if (record.kind === "module" || record.mimeType === "text/css" || record.mimeType === "text/javascript") {
|
|
100
|
-
let text = new TextDecoder().decode(bytes);
|
|
101
|
-
for (const reference of record.references) {
|
|
102
|
-
const url = this.urls.get(reference);
|
|
103
|
-
if (!url) throw new Error("Unsupported cyclic asset reference.");
|
|
104
|
-
text = text.replaceAll(reference, url);
|
|
105
|
-
}
|
|
106
|
-
bytes = text;
|
|
107
|
-
}
|
|
108
|
-
const url = URL.createObjectURL(new Blob([bytes], { type: record.mimeType }));
|
|
109
|
-
this.urls.set(id, url);
|
|
110
|
-
if (record.kind === "module") imports[id] = url;
|
|
111
|
-
}
|
|
112
|
-
if (Object.keys(imports).length) {
|
|
113
|
-
const script = document.createElement("script");
|
|
114
|
-
script.type = "importmap";
|
|
115
|
-
script.textContent = JSON.stringify({ imports });
|
|
116
|
-
document.head.append(script);
|
|
117
|
-
}
|
|
118
|
-
return ordered;
|
|
119
|
-
}
|
|
120
|
-
async importModule(uri) {
|
|
121
|
-
const prepare = this.importing.then(() => this.materialize(uri));
|
|
122
|
-
this.importing = prepare.catch(() => {});
|
|
123
|
-
const dependencies = await prepare;
|
|
124
|
-
await this.attachStyles(dependencies);
|
|
125
|
-
try { const module = await import(/* @vite-ignore */ uri); this.loadedModules.add(uri); return module; }
|
|
126
|
-
catch (error) { throw new Error(`Preview module import failed for ${uri}: ${error.message}. Inspect the App resource bridge, browser network/CSP diagnostics and current build.`, { cause: error }); }
|
|
127
|
-
}
|
|
128
|
-
async attachStyles(dependencies) {
|
|
129
|
-
for (const id of dependencies) {
|
|
130
|
-
const record = this.records.get(id);
|
|
131
|
-
if (record.mimeType !== "text/css") continue;
|
|
132
|
-
if (this.styles.has(id)) { await this.styleReady.get(id); continue; }
|
|
133
|
-
const style = document.createElement("link");
|
|
134
|
-
style.rel = "stylesheet";
|
|
135
|
-
style.href = this.urls.get(id);
|
|
136
|
-
this.styles.set(id, style);
|
|
137
|
-
const ready = new Promise((resolve, reject) => { style.onload = resolve; style.onerror = () => reject(new Error("The host CSP blocked a preview stylesheet.")); });
|
|
138
|
-
this.styleReady.set(id, ready);
|
|
139
|
-
document.head.append(style);
|
|
140
|
-
try { await ready; } catch (error) { style.remove(); this.styles.delete(id); this.styleReady.delete(id); throw error; }
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
async refreshStyles(uri, generation) {
|
|
144
|
-
const roots = [uri], seen = new Set(), keep = new Set();
|
|
145
|
-
// A lazy module can keep identical JS bytes while its CSS metadata changes.
|
|
146
|
-
// Refresh only lazy branches already opened by this App, leaving unopened
|
|
147
|
-
// pages unfetched and retaining the currently mounted component state.
|
|
148
|
-
for (let index = 0; index < roots.length; index++) {
|
|
149
|
-
const root = roots[index]; if (seen.has(root)) continue; seen.add(root);
|
|
150
|
-
for (const id of await this.materialize(root)) {
|
|
151
|
-
keep.add(id);
|
|
152
|
-
for (const dynamic of this.records.get(id).dynamicImports) if (this.loadedModules.has(dynamic)) roots.push(dynamic);
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
await this.attachStyles([...keep]);
|
|
156
|
-
if (generation !== this.generation || this.closed) return false;
|
|
157
|
-
for (const [id, style] of this.styles) if (!keep.has(id)) { style.remove(); this.styles.delete(id); this.styleReady.delete(id); }
|
|
158
|
-
for (const id of keep) if (this.styles.has(id)) document.head.append(this.styles.get(id));
|
|
159
|
-
return true;
|
|
160
|
-
}
|
|
161
|
-
async mount(manifest, id, container) {
|
|
162
|
-
const generation = ++this.generation;
|
|
163
|
-
this.register(manifest);
|
|
164
|
-
const scenario = manifest.scenarios.find(entry => entry.id === id);
|
|
165
|
-
if (!scenario) throw new Error("The selected scenario is no longer registered.");
|
|
166
|
-
const signature = JSON.stringify(this.closure(scenario.module).map(uri => [uri, this.records.get(uri)]));
|
|
167
|
-
// A successful global graph revision may only affect another scenario.
|
|
168
|
-
// Retain this view's form/scroll state, then let the caller rerun its audits.
|
|
169
|
-
if (this.mounted?.id === id && this.mounted.container === container && this.mounted.signature === signature) return this.refreshStyles(scenario.module, generation);
|
|
170
|
-
// Background warming changes the global manifest without loading another
|
|
171
|
-
// module into this App. Only actual selected module revisions need a reset.
|
|
172
|
-
this.revisions.add(scenario.module);
|
|
173
|
-
if (this.revisions.size > 20) throw Object.assign(new Error("Reopen the preview to release modules retained across 20 build revisions."), { code: "ADS_PREVIEW_REOPEN" });
|
|
174
|
-
const module = await this.importModule(scenario.module);
|
|
175
|
-
if (generation !== this.generation) return false;
|
|
176
|
-
const unmount = this.unmount;
|
|
177
|
-
this.unmount = undefined;
|
|
178
|
-
this.mounted = undefined;
|
|
179
|
-
await unmount?.();
|
|
180
|
-
if (generation !== this.generation || this.closed) return false;
|
|
181
|
-
container.replaceChildren();
|
|
182
|
-
if (!await this.refreshStyles(scenario.module, generation)) return false;
|
|
183
|
-
if (typeof module.mount !== "function") throw new Error("The compiled scenario has no mount adapter.");
|
|
184
|
-
this.unmount = module.mount(container);
|
|
185
|
-
if (typeof this.unmount !== "function") throw new Error("The scenario mount adapter must return an unmount callback.");
|
|
186
|
-
this.mounted = { id, container, signature };
|
|
187
|
-
return true;
|
|
188
|
-
}
|
|
189
|
-
async dispose() {
|
|
190
|
-
if (this.closed) return;
|
|
191
|
-
this.closed = true;
|
|
192
|
-
++this.generation;
|
|
193
|
-
++this.prefetchGeneration;
|
|
194
|
-
await this.unmount?.();
|
|
195
|
-
this.mounted = undefined;
|
|
196
|
-
for (const style of this.styles.values()) style.remove();
|
|
197
|
-
for (const url of this.urls.values()) URL.revokeObjectURL(url);
|
|
198
|
-
this.styles.clear(); this.styleReady.clear(); this.urls.clear(); this.bytes.clear(); this.records.clear();this.revisions.clear();this.loadedModules.clear();
|
|
199
|
-
delete globalThis.__dsPreviewImport;
|
|
200
|
-
}
|
|
201
|
-
}
|
|
1
|
+
function S(){let t=new Map,o=new Set,n=!1,e;function s(r){let d={data:t.get(r)?.data??{},callbacks:[],listeners:new Map};return t.set(r,d),{data:d.data,accept(h,f){if(!h||typeof h==="function")d.callbacks.push({deps:[r],callback:(c)=>h?.(c[0])});else d.callbacks.push({deps:typeof h==="string"?[h]:h,callback:(c)=>f?.(typeof h==="string"?c[0]:c)})},acceptExports(h,f){d.callbacks.push({deps:[r],callback:(c)=>f?.(c[0])})},dispose(h){d.dispose=h},prune(h){d.prune=h},invalidate(){n=!0},decline(){n=!0},on(h,f){let c=d.listeners.get(h)??new Set;c.add(f),d.listeners.set(h,c)},off(h,f){d.listeners.get(h)?.delete(f)},send(){throw Error("Preview hot-update custom messages are not a public transport.")}}}async function i(r){for(let u of t.values())for(let d of u.listeners.get(r)??[])await d()}return{context:s,observe(r,u,d){let h=t.get(r);if(!h)return;let f=import(u).then((c)=>{h.exports=c,h.isComponent=d});o.add(f),f.then(()=>o.delete(f),(c)=>{o.delete(f),e=c})},async update(r,u,d,h){if(await Promise.all(o),e)throw e;let f=new Map([...r].filter(([,a])=>a.hot).map(([a,l])=>[l.hot.id,{uri:a,record:l}])),c=new Map([...u].filter(([,a])=>a.hot).map(([a,l])=>[l.hot.id,{uri:a,record:l}])),v=new Map,m=new Map;for(let[a,{record:l}]of f)for(let y of[...l.imports,...l.dynamicImports]){let g=r.get(y)?.hot?.id;if(!g)continue;let w=v.get(g)??new Set;w.add(a),v.set(g,w)}function b(a,l=new Set){if(l.has(a))return!1;let y=t.get(a);if(y?.callbacks.some((E)=>E.deps.includes(a))&&c.has(a))return m.set(a,y),!0;let g=v.get(a);if(!g?.size)return!1;let w=new Set([...l,a]);for(let E of g)if(!b(E,w))return!1;return!0}for(let[a,{record:l}]of f){let y=c.get(a)?.record;if(!y||l.hot.source!==y.hot.source){if(!b(a))return!1}}if(!m.size)return!0;n=!1,await i("vite:beforeUpdate");let p=[];for(let[a,l]of m){if(!h())return!1;await l.dispose?.(l.data),p.push([a,l,await d(c.get(a).uri)])}if(!h())return!1;for(let[,a,l]of p)if(a.isComponent){let y=a.exports,g=Object.keys(l).filter((w)=>w!=="__esModule");if(!y||g.length!==Object.keys(y).filter((w)=>w!=="__esModule").length||g.some((w)=>!Object.hasOwn(y,w)||!a.isComponent(l[w])&&y[w]!==l[w]))return!1}for(let[a,l,y]of p)for(let g of l.callbacks)if(g.deps.includes(a))await g.callback(g.deps.map((w)=>w===a?y:void 0));return await i("vite:afterUpdate"),await new Promise((a)=>setTimeout(a,20)),h()&&!n},async dispose(){for(let r of t.values())await r.dispose?.(r.data),await r.prune?.(r.data);t.clear(),o.clear(),e=void 0}}}async function x(t,o){let n=await crypto.subtle.digest("SHA-256",o),e="sha256:"+[...new Uint8Array(n)].map((s)=>s.toString(16).padStart(2,"0")).join("");if(o.length!==t.size||e!==t.digest)throw Object.assign(Error("Preview resource integrity check failed. Rebuild and reopen the preview."),{code:"ADS_RESOURCE_INTEGRITY",category:"build"});return o}function R(t,o){let n=[],e=new Set;function s(i){if(e.has(i))return;e.add(i);let r=t.get(i);if(!r)throw Error(`Missing preview dependency metadata: ${i}`);for(let u of[...r.imports,...r.styles,...r.references])s(u);n.push(i)}return s(o),n}function P(t,o){if(!t||t.revision===o.revision)return[];let n=(e,s)=>{let i=new Map(Object.entries(e.assets));return JSON.stringify(R(i,s.module).map((r)=>[r,i.get(r)]))};return o.scenarios.filter((e)=>{let s=t.scenarios.find((i)=>i.id===e.id);return!s||n(t,s)!==n(o,e)}).map((e)=>e.id)}class M{constructor(t){this.read=t,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=S(),globalThis.__adsPreviewHot=this.hot,globalThis.__dsPreviewImport=(o)=>this.importModule(o)}register(t){if(t.schemaVersion!==1||!Array.isArray(t.scenarios)||!t.assets||typeof t.revision!=="string")throw Error("Unsupported preview manifest. Rebuild previews with the installed ADS version.");if(t.refresh&&(t.refresh.version!==1||typeof t.refresh.epoch!=="string"||!t.refresh.epoch||t.refresh.epoch.length>100))throw Error("Unsupported preview refresh protocol. Reopen with the current ADS version.");let o=new Set;for(let[n,e]of Object.entries(t.assets)){if(!/^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/.test(n)||!/^sha256:[a-f0-9]{64}$/.test(e.digest)||e.hot&&(!t.refresh||e.kind!=="module"||typeof e.hot.id!=="string"||!e.hot.id||e.hot.id.length>4096||o.has(e.hot.id)||!/^[a-f0-9]{64}$/.test(e.hot.source))||!["imports","dynamicImports","styles","references"].every((s)=>Array.isArray(e[s])&&e[s].every((i)=>Object.hasOwn(t.assets,i))))throw Error("Invalid preview dependency graph.");if(e.hot)o.add(e.hot.id);if(this.records.has(n)&&this.records.get(n).digest!==e.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:n})}for(let[n,e]of Object.entries(t.assets))this.records.set(n,e)}async resource(t){if(!this.bytes.has(t)){let o=(async()=>{let n=this.records.get(t);if(!n)throw Error(`Unknown preview dependency: ${t}`);let e;try{e=await this.read(t)}catch(r){throw Object.assign(Error(`Preview resource read failed for ${t}: ${r.message}`,{cause:r}),{code:"ADS_RESOURCE_READ",category:"transport",resourceUri:t})}if(this.closed)throw Error("The preview App was closed.");let s=e.contents.find((r)=>r.uri===t);if(!s)throw Object.assign(Error(`Missing preview dependency: ${t}`),{code:"ADS_RESOURCE_CONTENT",category:"build",resourceUri:t});let i=typeof s.text==="string"?new TextEncoder().encode(s.text):Uint8Array.from(atob(s.blob),(r)=>r.charCodeAt(0));try{return await x(n,i)}catch(r){throw r.resourceUri=t,r}})();this.bytes.set(t,o),o.catch(()=>this.bytes.delete(t))}return this.bytes.get(t)}closure(t){return R(this.records,t)}async prefetch(t,o){if(this.closed)return;this.register(t);let n=++this.prefetchGeneration,e=new Set,s=[],i=0;for(let h of o){let f=t.scenarios.find((m)=>m.id===h);if(!f)continue;let c=this.closure(f.module).filter((m)=>!this.bytes.has(m)&&!e.has(m)),v=c.reduce((m,b)=>m+this.records.get(b).size,0);if(i+v>16777216||e.size+c.length>256)continue;i+=v,s.push(h);for(let m of c)e.add(m)}let r=[...e],u=0,d=async()=>{while(!this.closed&&n===this.prefetchGeneration&&u<r.length)await this.resource(r[u++])};return await Promise.all(Array.from({length:Math.min(3,r.length)},d)),{scenarios:s,resources:r.length}}async materialize(t){let o=this.closure(t);await Promise.all(o.map((e)=>this.resource(e)));let n={};for(let e of o){if(this.closed)throw Error("The preview App was closed.");if(this.urls.has(e))continue;let s=this.records.get(e),i=await this.resource(e);if(s.kind==="module"||s.mimeType==="text/css"||s.mimeType==="text/javascript"){let u=new TextDecoder().decode(i);for(let d of s.references){let h=this.urls.get(d);if(!h)throw Error("Unsupported cyclic asset reference.");u=u.replaceAll(d,h)}i=u}let r=URL.createObjectURL(new Blob([i],{type:s.mimeType}));if(this.urls.set(e,r),s.kind==="module")n[e]=r}if(Object.keys(n).length){let e=document.createElement("script");e.type="importmap",e.textContent=JSON.stringify({imports:n}),document.head.append(e)}return o}async importModule(t){let o=this.importing.then(()=>this.materialize(t));this.importing=o.catch(()=>{});let n=await o;await this.attachStyles(n);try{let e=await import(t);this.loadedModules.add(t);for(let s of n){let i=this.records.get(s);if(i.hot)this.executed.set(i.hot.id,{uri:s,record:i}),this.moduleHistory.add(s)}return e}catch(e){throw Error(`Preview module import failed for ${t}: ${e.message}. Inspect the App resource bridge, browser network/CSP diagnostics and current build.`,{cause:e})}}async attachStyles(t){for(let o of t){if(this.records.get(o).mimeType!=="text/css")continue;if(this.styles.has(o)){await this.styleReady.get(o);continue}let e=document.createElement("link");e.rel="stylesheet",e.href=this.urls.get(o),this.styles.set(o,e);let s=new Promise((i,r)=>{e.onload=i,e.onerror=()=>r(Error("The host CSP blocked a preview stylesheet."))});this.styleReady.set(o,s),document.head.append(e);try{await s}catch(i){throw e.remove(),this.styles.delete(o),this.styleReady.delete(o),i}}}async refreshStyles(t,o){let n=[t],e=new Set,s=new Set;for(let i=0;i<n.length;i++){let r=n[i];if(e.has(r))continue;e.add(r);for(let u of await this.materialize(r)){s.add(u);for(let d of this.records.get(u).dynamicImports)if(this.loadedModules.has(d)||this.executed.has(this.records.get(d)?.hot?.id))n.push(d)}}if(await this.attachStyles([...s]),o!==this.generation||this.closed)return!1;for(let[i,r]of this.styles)if(!s.has(i))r.remove(),this.styles.delete(i),this.styleReady.delete(i);for(let i of s)if(this.styles.has(i))document.head.append(this.styles.get(i));return!0}async mount(t,o,n){let e=++this.generation,s=this.mounting.then(()=>e!==this.generation||this.closed?!1:this.mountRevision(t,o,n,e));return this.mounting=s.catch(()=>{}),s}async mountRevision(t,o,n,e){this.register(t);let s=t.scenarios.find((c)=>c.id===o);if(!s)throw Error("The selected scenario is no longer registered.");let i=JSON.stringify(this.closure(s.module).map((c)=>[c,this.records.get(c)])),r=new Map(this.closure(s.module).map((c)=>[c,this.records.get(c)])),u=(c)=>{throw Object.assign(Error(c),{code:"ADS_PREVIEW_REOPEN"})};if(this.refreshDirty)u("An interrupted module update requires a clean preview frame.");let d=[...this.urls.keys()].reduce((c,v)=>c+this.records.get(v).size,0);if(this.records.size>4096||d>67108864)u("Reopen the preview to release retained module revisions.");if(this.mounted&&this.mounted.refresh?.epoch!==t.refresh?.epoch)u("The preview compiler changed. Reopening an isolated frame for its new runtime.");if(t.refresh&&this.mounted){let c=new Map(Object.entries(t.assets)),v=new Map([...c].filter(([,p])=>p.hot).map(([p,a])=>[a.hot.id,{uri:p,record:a}]));for(let[p,{record:a}]of this.executed){let l=v.get(p);if(l&&l.record.hot.source!==a.hot.source&&this.moduleHistory.has(l.uri))u("Restoring a previous module revision requires a clean preview frame.")}let m=new Map([...this.executed.values()].map(({uri:p,record:a})=>[p,a]));this.refreshDirty=!0;let b=await this.hot.update(m,c,(p)=>this.importModule(p),()=>e===this.generation&&!this.closed);if(e!==this.generation||this.closed)return!1;if(!b)u("This edit changes a refresh boundary. Reopening the preview with fresh component state.");this.refreshDirty=!1;for(let p of this.executed.keys())if(v.has(p))this.executed.set(p,v.get(p));if(this.mounted.id===o){if(!await this.refreshStyles(s.module,e))return!1;return this.revisions.add(s.module),this.mounted={...this.mounted,signature:i,records:r,module:s.module},!0}}if(this.mounted?.id===o&&this.mounted.container===n&&this.mounted.signature===i)return this.refreshStyles(s.module,e);if(this.revisions.add(s.module),!t.refresh&&this.revisions.size>20)throw Object.assign(Error("Reopen the preview to release retained module revisions."),{code:"ADS_PREVIEW_REOPEN"});let h=await this.importModule(s.module);if(e!==this.generation)return!1;let f=this.unmount;if(this.unmount=void 0,this.mounted=void 0,await f?.(),e!==this.generation||this.closed)return!1;if(n.replaceChildren(),!await this.refreshStyles(s.module,e))return!1;if(typeof h.mount!=="function")throw Error("The compiled scenario has no mount adapter.");if(this.unmount=h.mount(n),typeof this.unmount!=="function")throw Error("The scenario mount adapter must return an unmount callback.");return this.mounted={id:o,container:n,signature:i,records:r,module:s.module,refresh:t.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 t of this.styles.values())t.remove();for(let t of this.urls.values())URL.revokeObjectURL(t);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}}export{M as PreviewResourceLoader,P as changedPreviewScenarios,x as verifyPreviewAssetBytes};
|
|
@@ -1,20 +1,25 @@
|
|
|
1
1
|
import { createServer } from "node:http";
|
|
2
2
|
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { createHttpPreviewDelivery } from "./preview-http.mjs";
|
|
3
4
|
|
|
4
5
|
/** A different loopback port provides the browser host's separate sandbox origin. */
|
|
5
6
|
export async function startSandboxHost(parentOrigin) {
|
|
6
7
|
const script = await readFile(new URL("../showcase/sandbox.bundle.js", import.meta.url));
|
|
8
|
+
const delivery = await createHttpPreviewDelivery(parentOrigin);
|
|
7
9
|
const web = createServer((req, res) => {
|
|
8
10
|
const origin = `http://127.0.0.1:${web.address().port}`;
|
|
9
11
|
const url = new URL(req.url, origin);
|
|
10
12
|
if (req.headers.host !== new URL(origin).host || req.method !== "GET") { res.writeHead(403); res.end(); return; }
|
|
13
|
+
if (delivery?.serve(req, res)) return;
|
|
11
14
|
const javascript = url.pathname === "/sandbox.js";
|
|
12
15
|
if (!javascript &&( url.pathname !== "/sandbox.html" || url.searchParams.get("parent") !== parentOrigin)) { res.writeHead(404); res.end(); return; }
|
|
13
16
|
res.writeHead(200, { "Content-Type": javascript ? "text/javascript" : "text/html", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Content-Security-Policy": `frame-ancestors ${parentOrigin};object-src 'none'` });
|
|
14
17
|
res.end(javascript ? script : '<!doctype html><html><head><meta charset="utf-8"><style>html,body,iframe{height:100%;width:100%;margin:0;border:0;display:block;overflow:hidden}</style></head><body><script src="/sandbox.js"></script></body></html>');
|
|
15
18
|
});
|
|
16
19
|
await new Promise((resolve, reject) => { web.once("error", reject); web.listen(0, "127.0.0.1", resolve); });
|
|
17
|
-
|
|
20
|
+
delivery?.setOrigin(`http://127.0.0.1:${web.address().port}`);
|
|
21
|
+
return { delivery, url: `http://127.0.0.1:${web.address().port}/sandbox.html?parent=${encodeURIComponent(parentOrigin)}`, close() {
|
|
22
|
+
delivery?.close();
|
|
18
23
|
const stopped = new Promise(resolve => web.close(resolve));
|
|
19
24
|
web.closeAllConnections();
|
|
20
25
|
return stopped;
|
package/dist/mcp/server.mjs
CHANGED
|
@@ -24,7 +24,7 @@ import { startShowcaseHost } from "./showcase-host.mjs";
|
|
|
24
24
|
import { createSkillStore, page, SKILLS_EXTENSION } from "./skills.mjs";
|
|
25
25
|
import { projectDocuments, PROJECT_URI, readProjectDocument } from "./catalog.mjs";
|
|
26
26
|
import { APP_MIME, appMetadata, appUri, tokenWidgetData, previewApp, PREVIEW_APP_URI } from "./apps.mjs";
|
|
27
|
-
import { LIVE_PREVIEW_MANIFEST_URI, PREVIEW_MANIFEST_URI, readPreviewManifest, readPreviewAsset } from "../preview-resources.mjs";
|
|
27
|
+
import { LIVE_PREVIEW_MANIFEST_URI, PREVIEW_MANIFEST_URI, readPreviewManifest, readPreviewManifestUpdate, readPreviewAsset } from "../preview-resources.mjs";
|
|
28
28
|
import { livePreviewOptions, previewArtifactPath, withPreviewSession } from "../preview-scope.mjs";
|
|
29
29
|
import { getWorkflowPrompt, promptDefinitions } from "./prompts.mjs";
|
|
30
30
|
import { createReconfigurablePreviewWatch } from "./preview-watch.mjs";
|
|
@@ -813,6 +813,21 @@ export async function createAdsMcp(
|
|
|
813
813
|
}
|
|
814
814
|
const tokenInventory = () => analyze(root, "tokens");
|
|
815
815
|
const behaviorInventory = (args) => analyze(root, "behavior-page", [args]);
|
|
816
|
+
// Internal HTTP publication captures one authorized graph and keeps its asset
|
|
817
|
+
// lookup bound to that scope/revision. No client-supplied graph is trusted.
|
|
818
|
+
async function capturePreview(uri, signal) {
|
|
819
|
+
signal?.throwIfAborted();
|
|
820
|
+
if (uri.startsWith("ads://drafts/")) {
|
|
821
|
+
const url = new URL(uri), match = url.pathname.match(/^\/([a-z0-9][a-z0-9-]{0,79})\/resource$/);
|
|
822
|
+
if (!match || [...url.searchParams.keys()].some(key => key !== "uri") || !url.searchParams.get("uri")) throw new Error("Invalid draft resource address.");
|
|
823
|
+
return drafts.capturePreview(match[1], url.searchParams.get("uri"), signal);
|
|
824
|
+
}
|
|
825
|
+
if (![PREVIEW_MANIFEST_URI, LIVE_PREVIEW_MANIFEST_URI].includes(uri)) throw new Error("Invalid preview manifest resource.");
|
|
826
|
+
const options = uri === LIVE_PREVIEW_MANIFEST_URI ? livePreviewOptions(previewOptions()) : previewOptions();
|
|
827
|
+
const graph = JSON.parse((await read(uri, signal)).contents[0].text);
|
|
828
|
+
signal?.throwIfAborted();
|
|
829
|
+
return { graph, readAsset: id => { signal?.throwIfAborted(); return readPreviewAsset(options, id, graph); } };
|
|
830
|
+
}
|
|
816
831
|
async function read(uri, signal) {
|
|
817
832
|
if (uri === `${PROJECT_URI}/explorer`)
|
|
818
833
|
return {
|
|
@@ -1050,15 +1065,17 @@ export async function createAdsMcp(
|
|
|
1050
1065
|
contents: [executionResults.readResource(uri)],
|
|
1051
1066
|
};
|
|
1052
1067
|
else if (uri === CAPTURES_URI) value = await captureIndex();
|
|
1053
|
-
else if (uri === PREVIEW_MANIFEST_URI) {
|
|
1068
|
+
else if (uri === PREVIEW_MANIFEST_URI || uri.startsWith(PREVIEW_MANIFEST_URI + "?")) {
|
|
1054
1069
|
value = readPreviewManifest(previewOptions());
|
|
1055
1070
|
if (!value) throw new Error("Preview resources are not built yet. Invoke ads_show_scenario to start the managed compiler.");
|
|
1056
|
-
|
|
1071
|
+
if (uri !== PREVIEW_MANIFEST_URI) value = readPreviewManifestUpdate(previewOptions(), value, resourceQuery(uri, ["from"]).from);
|
|
1072
|
+
} else if (uri === LIVE_PREVIEW_MANIFEST_URI || uri.startsWith(LIVE_PREVIEW_MANIFEST_URI + "?")) {
|
|
1057
1073
|
const report = await builds(),
|
|
1058
1074
|
live = report.previews.find((entry) => entry.live)?.live;
|
|
1059
1075
|
value = readPreviewManifest(livePreviewOptions(previewOptions()));
|
|
1060
1076
|
if (!live || value?.revision !== live.revision || value.session !== report.session)
|
|
1061
1077
|
throw new Error("No live feedback for the current source. Use the verified preview after checks pass.");
|
|
1078
|
+
if (uri !== LIVE_PREVIEW_MANIFEST_URI) value = readPreviewManifestUpdate(livePreviewOptions(previewOptions()), value, resourceQuery(uri, ["from"]).from);
|
|
1062
1079
|
}
|
|
1063
1080
|
if (value !== undefined)
|
|
1064
1081
|
return {
|
|
@@ -1953,6 +1970,11 @@ export async function createAdsMcp(
|
|
|
1953
1970
|
});
|
|
1954
1971
|
server.setRequestHandler("resources/templates/list", () => ({
|
|
1955
1972
|
resourceTemplates: [
|
|
1973
|
+
...[PREVIEW_MANIFEST_URI, LIVE_PREVIEW_MANIFEST_URI].map(uri => ({
|
|
1974
|
+
uriTemplate: uri + "{?from}", name: "Internal preview manifest update",
|
|
1975
|
+
description: "Preview UI delta from a known SHA-256 revision; falls back to a full manifest when history expired. Live-source and draft-scope restrictions are unchanged.",
|
|
1976
|
+
mimeType: "application/json",
|
|
1977
|
+
})),
|
|
1956
1978
|
{
|
|
1957
1979
|
uriTemplate: "ads://drafts/{id}/resource?uri=ads%3A%2F%2Fproject%2Fscenarios",
|
|
1958
1980
|
name: "Draft scenario diagnostics",
|
|
@@ -2388,6 +2410,7 @@ export async function createAdsMcp(
|
|
|
2388
2410
|
return previewWatch.buildAll(signal, options);
|
|
2389
2411
|
},
|
|
2390
2412
|
readResource: read,
|
|
2413
|
+
capturePreview,
|
|
2391
2414
|
async callTool(name, args, signal) {
|
|
2392
2415
|
const tool = tools().find((tool) => tool.name === name);
|
|
2393
2416
|
if (!tool) throw new Error("Unknown preview tool.");
|
|
@@ -2480,6 +2503,12 @@ export function createDraftPreview(workspace, { id, host, showcaseUrl, mountPrev
|
|
|
2480
2503
|
}),
|
|
2481
2504
|
})
|
|
2482
2505
|
).server,
|
|
2506
|
+
{
|
|
2507
|
+
readResource: async (uri, signal) => (await preview()).readResource(uri, signal),
|
|
2508
|
+
capturePreview: async (uri, signal) => (await preview()).capturePreview(uri, signal),
|
|
2509
|
+
onBuildChange(listener) { listeners.add(listener); return () => listeners.delete(listener); },
|
|
2510
|
+
callTool: async (name, args, signal) => (await preview()).callTool(name, args, signal),
|
|
2511
|
+
},
|
|
2483
2512
|
);
|
|
2484
2513
|
return {
|
|
2485
2514
|
url,
|
|
@@ -2502,6 +2531,7 @@ export function createDraftPreview(workspace, { id, host, showcaseUrl, mountPrev
|
|
|
2502
2531
|
},
|
|
2503
2532
|
callTool: async (name, args, signal) => (await preview()).callTool(name, args, signal),
|
|
2504
2533
|
readResource: async (uri, signal) => (await preview()).readResource(uri, signal),
|
|
2534
|
+
capturePreview: async (uri, signal) => (await preview()).capturePreview(uri, signal),
|
|
2505
2535
|
// The draft's verified preview revision, as the project host reports its own: captures and
|
|
2506
2536
|
// behavior evidence record which build they observed.
|
|
2507
2537
|
previewRevision: () => readPreviewManifest(withPreviewSession(loadConfig(root), previewWatch.resourceSession()))?.revision ?? null,
|
|
@@ -2557,10 +2587,11 @@ export async function startAdsMcp(
|
|
|
2557
2587
|
let buildWatcher, buildChangeTimer;
|
|
2558
2588
|
const buildListeners = new Set();
|
|
2559
2589
|
const onBuildChange = (report) => {
|
|
2590
|
+
host?.buildChanged(report);
|
|
2560
2591
|
for (const listener of buildListeners) listener(report);
|
|
2561
2592
|
};
|
|
2562
2593
|
const showcaseUrl = () => host?.url;
|
|
2563
|
-
const mountPreview = (prefix, factory) => host?.mount(prefix, factory);
|
|
2594
|
+
const mountPreview = (prefix, factory, service) => host?.mount(prefix, factory, service);
|
|
2564
2595
|
if (showcase) {
|
|
2565
2596
|
// A 2025-era HTTP session observes the project like a stdio connection; per-request modern instances do not.
|
|
2566
2597
|
host = await startShowcaseHost(
|
|
@@ -4,6 +4,7 @@ import { createServer } from "node:http";
|
|
|
4
4
|
import { readFile } from "node:fs/promises";
|
|
5
5
|
import { Readable } from "node:stream";
|
|
6
6
|
import { createMcpHandler, isLegacyRequest, WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/server";
|
|
7
|
+
import { serveShowcaseHttp, showcaseHttpEvents } from "./showcase-http.mjs";
|
|
7
8
|
import { startSandboxHost } from "./sandbox-host.mjs";
|
|
8
9
|
|
|
9
10
|
const maxRequestBodySize = 2 * 1024 * 1024,
|
|
@@ -73,6 +74,7 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
73
74
|
[
|
|
74
75
|
["/", "index.html", "text/html"],
|
|
75
76
|
["/client.js", "client.bundle.js", "text/javascript"],
|
|
77
|
+
["/http-client.js", "http-client.bundle.js", "text/javascript"],
|
|
76
78
|
["/style.css", "style.css", "text/css"],
|
|
77
79
|
["/ui.css", "ui/ui.css", "text/css"],
|
|
78
80
|
["/favicon.svg", "favicon.svg", "image/svg+xml"],
|
|
@@ -86,7 +88,22 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
86
88
|
// Draft previews are served from this same host under /draft/<id>/: the same client, with that
|
|
87
89
|
// draft's own MCP endpoint. No other port or process.
|
|
88
90
|
const mounts = new Map();
|
|
89
|
-
const
|
|
91
|
+
const services = new Map();
|
|
92
|
+
const events = showcaseHttpEvents();
|
|
93
|
+
const buildReports = new Map();
|
|
94
|
+
const buildSubscriptions = new Map();
|
|
95
|
+
function publishBuild(uri, report) {
|
|
96
|
+
const signature = JSON.stringify(report);
|
|
97
|
+
if (buildReports.get(uri) === signature) return;
|
|
98
|
+
buildReports.set(uri, signature);
|
|
99
|
+
events.emit({ type: "build", uri, report });
|
|
100
|
+
}
|
|
101
|
+
const observer = await observe?.({
|
|
102
|
+
...handler.notify,
|
|
103
|
+
resourceUpdated(uri) { events.emit({ type: "resource", uri }); return handler.notify.resourceUpdated(uri); },
|
|
104
|
+
resourcesChanged() { events.emit({ type: "resources" }); return handler.notify.resourcesChanged(); },
|
|
105
|
+
toolsChanged() { events.emit({ type: "tools" }); return handler.notify.toolsChanged(); },
|
|
106
|
+
});
|
|
90
107
|
const requests = new Set();
|
|
91
108
|
let sandbox;
|
|
92
109
|
const web = createServer(async (req, res) => {
|
|
@@ -107,7 +124,30 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
107
124
|
}
|
|
108
125
|
if (route === "/host.json" && req.method === "GET") {
|
|
109
126
|
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
110
|
-
res.end(JSON.stringify({ sandboxUrl: sandbox?.url }));
|
|
127
|
+
res.end(JSON.stringify({ sandboxUrl: sandbox?.url, ...(sandbox?.delivery ? { httpPreview: true } : {}) }));
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (route === "/preview-http" && req.method === "POST" && sandbox?.delivery) {
|
|
131
|
+
const abort = new AbortController(); requests.add(abort);
|
|
132
|
+
res.once("close", () => { requests.delete(abort); abort.abort(); });
|
|
133
|
+
try {
|
|
134
|
+
let body = "";
|
|
135
|
+
for await (const chunk of req) { body += chunk; if (body.length > 4096) throw new Error("HTTP preview request too large."); }
|
|
136
|
+
const service = mount ? services.get(mount[0]) : observer;
|
|
137
|
+
if (!service?.capturePreview) throw new Error("The scoped preview reader is unavailable.");
|
|
138
|
+
const result = await sandbox.delivery.control(mount?.[0] ?? "/", service, JSON.parse(body), abort.signal);
|
|
139
|
+
abort.signal.throwIfAborted();
|
|
140
|
+
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" }); res.end(JSON.stringify(result));
|
|
141
|
+
} catch (error) { if (!abort.signal.aborted && !res.destroyed) { res.writeHead(400, { "Content-Type": "application/json", "Cache-Control": "no-store" }); res.end(JSON.stringify({ error: error.message, code: error.code })); } }
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (route.startsWith("/api/") && sandbox?.delivery) {
|
|
145
|
+
if (route === "/api/events" && req.method === "GET") { events.connect(res, mount?.[0] ?? "/"); return; }
|
|
146
|
+
const service = mount ? services.get(mount[0]) : observer;
|
|
147
|
+
if (!service) { res.writeHead(503); res.end("Showcase service unavailable."); return; }
|
|
148
|
+
const abort = new AbortController(); requests.add(abort);
|
|
149
|
+
res.once("close", () => { requests.delete(abort); abort.abort(); });
|
|
150
|
+
await serveShowcaseHttp(req, res, route.slice(5) + url.search, service, abort.signal);
|
|
111
151
|
return;
|
|
112
152
|
}
|
|
113
153
|
const asset = assets.get(route);
|
|
@@ -118,7 +158,7 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
118
158
|
"X-Content-Type-Options": "nosniff",
|
|
119
159
|
"Content-Security-Policy": `default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; frame-src ${sandbox ? new URL(sandbox.url).origin : "'none'"};connect-src 'self';object-src 'none'`,
|
|
120
160
|
});
|
|
121
|
-
res.end(asset
|
|
161
|
+
res.end(route === "/" && sandbox?.delivery && !["blob", "mcp"].includes(url.searchParams.get("delivery")) ? asset.bytes.toString().replace('src="client.js"', 'src="http-client.js"') : asset.bytes);
|
|
122
162
|
return;
|
|
123
163
|
}
|
|
124
164
|
if (route !== "/mcp") {
|
|
@@ -182,12 +222,19 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
182
222
|
let closing;
|
|
183
223
|
return {
|
|
184
224
|
url: `http://127.0.0.1:${web.address().port}/`,
|
|
225
|
+
buildChanged(report) { if (sandbox?.delivery) publishBuild("ads://project/build", report); },
|
|
185
226
|
/** Serve another MCP server's showcase under a path prefix such as /draft/<id>/. */
|
|
186
|
-
mount(prefix, mountFactory) {
|
|
227
|
+
mount(prefix, mountFactory, service) {
|
|
187
228
|
const mounted = createEndpoint(mountFactory);
|
|
188
229
|
mounts.set(prefix, mounted);
|
|
230
|
+
services.set(prefix, service);
|
|
231
|
+
const draft = /^\/draft\/([a-zA-Z0-9_-]+)\/$/.exec(prefix);
|
|
232
|
+
const buildUri = draft && `ads://drafts/${draft[1]}/resource?uri=${encodeURIComponent("ads://project/build")}`;
|
|
233
|
+
const unsubscribe = sandbox?.delivery && buildUri ? service?.onBuildChange?.(report => publishBuild(buildUri, report)) : undefined;
|
|
234
|
+
if (unsubscribe) buildSubscriptions.set(mounted, unsubscribe);
|
|
189
235
|
return async () => {
|
|
190
|
-
|
|
236
|
+
unsubscribe?.(); buildSubscriptions.delete(mounted); buildReports.delete(buildUri);
|
|
237
|
+
if (mounts.get(prefix) === mounted) { mounts.delete(prefix); services.delete(prefix); sandbox?.delivery?.retireOwner(prefix); }
|
|
191
238
|
await mounted.close();
|
|
192
239
|
};
|
|
193
240
|
},
|
|
@@ -196,6 +243,9 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
196
243
|
// Close sockets first: live subscriptions and preview requests must not
|
|
197
244
|
// hold shutdown open while protocol instances wait for cancellation.
|
|
198
245
|
const stopped = new Promise((resolve) => web.close(resolve));
|
|
246
|
+
events.close();
|
|
247
|
+
for (const unsubscribe of buildSubscriptions.values()) unsubscribe();
|
|
248
|
+
buildSubscriptions.clear(); buildReports.clear();
|
|
199
249
|
for (const request of requests) request.abort();
|
|
200
250
|
web.closeAllConnections();
|
|
201
251
|
const results = await Promise.allSettled([
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { httpPreviewAction, httpResourceUri } from "../showcase-http-routes.mjs";
|
|
2
|
+
|
|
3
|
+
/** HTTP presentation adapter over the same scoped services used by CLI/MCP. */
|
|
4
|
+
export async function serveShowcaseHttp(req, res, path, service, signal) {
|
|
5
|
+
try {
|
|
6
|
+
if (req.method === "GET") {
|
|
7
|
+
const uri = httpResourceUri(path);
|
|
8
|
+
const result = await service.readResource(uri, signal);
|
|
9
|
+
signal.throwIfAborted();
|
|
10
|
+
const content = result.contents?.find(item => typeof item.text === "string");
|
|
11
|
+
if (!content) throw new Error("The showcase resource contains no JSON data.");
|
|
12
|
+
JSON.parse(content.text);
|
|
13
|
+
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
14
|
+
res.end(content.text);
|
|
15
|
+
} else if (req.method === "POST") {
|
|
16
|
+
const chunks = []; let size = 0;
|
|
17
|
+
for await (const chunk of req) {
|
|
18
|
+
size += chunk.length;
|
|
19
|
+
if (size > 4096) throw new Error("Showcase action request too large.");
|
|
20
|
+
chunks.push(chunk);
|
|
21
|
+
}
|
|
22
|
+
const action = httpPreviewAction(path, JSON.parse(Buffer.concat(chunks).toString()));
|
|
23
|
+
// Tool schema parsing, read-only policy and exact revision gates stay in the service.
|
|
24
|
+
const result = await service.callTool(action.name, action.arguments, signal);
|
|
25
|
+
signal.throwIfAborted();
|
|
26
|
+
if (result.isError) throw Object.assign(new Error(result.content?.find(item => item.type === "text")?.text ?? "Preview failed."), result.structuredContent?.failure);
|
|
27
|
+
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
28
|
+
res.end(JSON.stringify(result.structuredContent));
|
|
29
|
+
} else {
|
|
30
|
+
res.writeHead(405, { Allow: "GET, POST" }); res.end();
|
|
31
|
+
}
|
|
32
|
+
} catch (error) {
|
|
33
|
+
if (signal.aborted || res.destroyed) return;
|
|
34
|
+
res.writeHead(400, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
35
|
+
res.end(JSON.stringify({ error: { message: error.message, code: error.code, category: error.category, resourceUri: error.resourceUri } }));
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function showcaseHttpEvents() {
|
|
40
|
+
const clients = new Set();
|
|
41
|
+
return {
|
|
42
|
+
emit(event) {
|
|
43
|
+
for (const client of clients) {
|
|
44
|
+
let value = event;
|
|
45
|
+
if (client.scope && ["resource", "build"].includes(event.type)) {
|
|
46
|
+
if (!event.uri.startsWith(client.scope)) continue;
|
|
47
|
+
value = { ...event, uri: decodeURIComponent(event.uri.slice(client.scope.length)) };
|
|
48
|
+
}
|
|
49
|
+
// Bound slow readers instead of accumulating event buffers indefinitely.
|
|
50
|
+
if (!client.res.write(`data: ${JSON.stringify(value)}\n\n`)) client.res.destroy();
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
connect(res, prefix) {
|
|
54
|
+
if (clients.size >= 64) { res.writeHead(503); res.end("Too many showcase event streams."); return; }
|
|
55
|
+
const draft = /^\/draft\/([a-zA-Z0-9_-]+)\/$/.exec(prefix);
|
|
56
|
+
const client = { res, scope: draft && `ads://drafts/${draft[1]}/resource?uri=` };
|
|
57
|
+
clients.add(client);
|
|
58
|
+
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" });
|
|
59
|
+
res.write('data: {"type":"ready"}\n\n');
|
|
60
|
+
const timer = setInterval(() => { if (!res.write(": heartbeat\n\n")) res.destroy(); }, 15000);
|
|
61
|
+
timer.unref();
|
|
62
|
+
res.once("close", () => { clearInterval(timer); clients.delete(client); });
|
|
63
|
+
},
|
|
64
|
+
close() { for (const client of clients) client.res.destroy(); clients.clear(); },
|
|
65
|
+
};
|
|
66
|
+
}
|