@three-blocks/devtools 1.0.1-alpha.229.gb2f4ea7d182c → 2.0.0-alpha.238.g8723f0a28ca3
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/CHANGELOG.md +30 -2
- package/README.md +27 -4
- package/dist/browser/shader-capture.d.ts +13 -1
- package/dist/browser/shader-capture.js +2 -2
- package/dist/{browser-smoke-X3NBYPHI.js → browser-smoke-EIKJ6OVK.js} +4 -4
- package/dist/chunk-4YRR36JN.js +97 -0
- package/dist/chunk-65VEJRRT.js +2 -0
- package/dist/chunk-GA7PGW2R.js +18 -0
- package/dist/{chunk-JMS5NTP7.js → chunk-JHBQB7WC.js} +1 -1
- package/dist/chunk-LUULHXFK.js +17 -0
- package/dist/chunk-NPLE7PPF.js +3 -0
- package/dist/{chunk-YLN3G2JS.js → chunk-OQLHTDDH.js} +1 -1
- package/dist/chunk-TRHSN2DJ.cjs +1 -0
- package/dist/{chunk-ILOEBEIQ.js → chunk-TUIINI6U.js} +1 -1
- package/dist/chunk-V34C7NIM.js +80 -0
- package/dist/chunk-W6UL2OW7.js +2 -0
- package/dist/cli.js +22 -22
- package/dist/environment-bake-XMRKQJXM.js +4 -0
- package/dist/index.d.ts +38 -8
- package/dist/index.js +24 -21
- package/dist/{shader-autowire-DCODBFMX.js → shader-autowire-SPE5DM2X.js} +1 -1
- package/dist/{shader-browser-ZGPGYM2U.js → shader-browser-EYE3UT2U.js} +1 -1
- package/dist/{shader-browser-FSCRBXJ7.js → shader-browser-WF4HNSAV.js} +1 -1
- package/dist/shader-capture-server.d.ts +22 -2
- package/dist/shader-capture-server.js +14 -14
- package/dist/shader-config-EOFU5D3Y.js +2 -0
- package/dist/{shader-project-runner-FJXPTLUO.js → shader-project-runner-S2AID2RJ.js} +1 -1
- package/dist/{shader-transform-DSFaVrux.d.ts → shader-transform-D160zMyt.d.ts} +3 -0
- package/dist/shader-watch-ISNWIAXN.js +2 -0
- package/dist/shader-workflow-T72N2CLS.js +2 -0
- package/dist/status-D2RF6QTL.js +2 -0
- package/dist/{text-atlas-BHPSDU7C.js → text-atlas-WRYJT3E7.js} +1 -1
- package/dist/transform.cjs +1 -1
- package/dist/transform.d.ts +1 -1
- package/dist/transform.js +1 -1
- package/dist/webpack-loader.cjs +1 -1
- package/dist/webpack-loader.d.ts +1 -1
- package/dist/webpack-loader.js +1 -1
- package/package.json +3 -3
- package/dist/chunk-4M7M55NS.js +0 -93
- package/dist/chunk-5X5NS5EW.js +0 -18
- package/dist/chunk-J6OESAZM.js +0 -76
- package/dist/chunk-NE7SC2BX.js +0 -2
- package/dist/chunk-NEWSG5RX.js +0 -3
- package/dist/chunk-PAH76FDD.js +0 -14
- package/dist/chunk-PY2ZLMZF.cjs +0 -1
- package/dist/chunk-ZDNZCQUQ.js +0 -2
- package/dist/environment-bake-5P4IAL4O.js +0 -4
- package/dist/shader-config-BYBJUL3C.js +0 -2
- package/dist/shader-watch-FVQNE263.js +0 -2
- package/dist/shader-workflow-HZWFWHTS.js +0 -2
- package/dist/status-TV3G3PG4.js +0 -2
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import {d,a as a$1,X,z,Y,B,U,m,l,h,g,S}from'./chunk-GA7PGW2R.js';import {a}from'./chunk-EI7MMDWY.js';import x from'process';import {createServer}from'http';import {createRequire}from'module';import {mkdtemp,rm,lstat,realpath}from'fs/promises';import A from'path';import {tmpdir}from'os';import {pathToFileURL}from'url';var Le=Object.freeze([{id:"three-inspector-invalid-json",pattern:/is not valid JSON/iu},{id:"chromium-webgpu-experimental",pattern:/WebGPU is experimental/iu}]);function it(n){return Le.some(e=>e.pattern.test(n))}a(it,"isDocumentedBrowserNoise");function me(n=x.env,e=x.platform){let t=n.THREE_BLOCKS_WEBGPU_BROWSER_ARGS?.split(/\s+/u).filter(Boolean);if(t&&t.length>0)return t;let r=["--enable-unsafe-webgpu"];return e==="darwin"&&r.push("--enable-gpu","--use-angle=metal"),e==="linux"&&r.push("--enable-features=Vulkan","--disable-vulkan-surface","--ignore-gpu-blocklist","--disable-gpu-driver-bug-workarounds","--disable-gpu-watchdog"),r}a(me,"webgpuBrowserArgs");function fe(n=x.env){let e=n.THREE_BLOCKS_WEBGL_BROWSER_ARGS?.split(/\s+/u).filter(Boolean);return e&&e.length>0?e:["--use-angle=swiftshader","--enable-unsafe-swiftshader","--ignore-gpu-blocklist"]}a(fe,"webglBrowserArgs");function pe(n=false,e=x.env){return n!==true&&e.THREE_BLOCKS_SOFTWARE_WEBGPU!=="1"}a(pe,"webgpuBrowserHeadless");var Z="three-blocks.shader-capture.runtime.v1";var Re="/__three-blocks/shaders/capture",K="/__three-blocks/shaders/telemetry",Te="/__three-blocks/shaders/runtime.js",ke="/__three-blocks/shaders/bootstrap.js",Ee="/__three-blocks/shaders/bridge.js",Pe=d.manifest*2,re=/^[a-z0-9][a-z0-9_-]{0,63}$/u,Ce=64,Be=2e3,We=[/is not valid JSON/iu,/WebGPU is experimental/iu];async function Ve(){try{return (await import('playwright')).chromium}catch(n){throw new Error('Shader browser work requires the optional "playwright" package. Install it in the project and run `npx playwright install chromium`.',{cause:n})}}a(Ve,"loadChromium");async function Je(n){let e;try{e=createRequire(A.join(n,"package.json")).resolve("vite");}catch(r){throw new Error("Shader capture requires Vite in the target project.",{cause:r})}let t=await import(pathToFileURL(e).href);if(typeof t.createServer!="function")throw new Error(`The target project's Vite entry does not export createServer(): ${e}`);return t.createServer}a(Je,"loadProjectCreateServer");var ne=class{static{a(this,"CaptureInbox");}#e=new Map;#t=new Map;wait(e,t){let r=this.#t.get(e);if(r!==void 0)return this.#t.delete(e),Promise.resolve(r);if(this.#e.has(e))throw new Error(`A shader capture is already waiting for scene "${e}".`);return new Promise((a,o)=>{let s=setTimeout(()=>{this.#e.delete(e),o(new Error(`Shader capture "${e}" timed out after ${t}ms.`));},t);this.#e.set(e,{resolve:a,reject:o,timer:s});})}receive(e){if(!a$1(e)||typeof e.scene!="string"||!re.test(e.scene))throw new Error("Capture POST has no safe scene key.");if(!this.#t.has(e.scene)&&!this.#e.has(e.scene)&&this.#t.size>=Ce)throw new Error("Capture POST exceeds the scene inbox limit.");let t=this.#e.get(e.scene);t?(clearTimeout(t.timer),this.#e.delete(e.scene),t.resolve(e)):this.#t.set(e.scene,e);}cancel(e,t){let r=this.#e.get(e);r&&(clearTimeout(r.timer),this.#e.delete(e),r.reject(t));}rejectAll(e){for(let t of this.#e.values())clearTimeout(t.timer),t.reject(e);this.#e.clear(),this.#t.clear();}};async function Ke(n,e){let t=await Promise.race([e.then(r=>({kind:"capture",value:r})),n.then(()=>({kind:"navigation"}))]);return t.kind==="capture"?t.value:e}a(Ke,"waitForShaderCaptureAcrossNavigation");var ae=class{static{a(this,"TelemetryHub");}#e=new Map;#t=new Map;markFirstRequest(e){re.test(e)&&!this.#t.has(e)&&this.#t.set(e,Date.now());}firstRequest(e){return this.#t.get(e)}receive(e){if(!a$1(e)||typeof e.scene!="string"||!re.test(e.scene))throw new Error("Shader telemetry has no bounded scene key.");if(!this.#e.has(e.scene)&&this.#e.size>=Ce)throw new Error("Shader telemetry exceeds the scene limit.");this.#e.set(e.scene,e);}read(e){return this.#e.get(e)}clear(e){this.#e.delete(e),this.#t.delete(e);}},qe=a(async(n,e,t,r,a)=>{let o=0;for(;n.__threeBlocksParityUsesAnimationLoop!==true&&o<e;)await r(),o+=1;if(n.__threeBlocksParityUsesAnimationLoop===true){let s=Number(n.__threeBlocksParityCompletedFrame||0),i=Number(t),d=Number.isSafeInteger(i)&&i>=s?i:s+e;for(n.__threeBlocksParityTargetFrame=d;Number(n.__threeBlocksParityCompletedFrame||0)<d;)await r();}return await a(),Number(n.__threeBlocksParityCompletedFrame||0)},"settleShaderParityFrames");function se(n,e){return `(() => {
|
|
2
|
+
const root = globalThis;
|
|
3
|
+
const scene = new URL(location.href).searchParams.get('captureId')
|
|
4
|
+
|| 'default';
|
|
5
|
+
const workerCapture = ${JSON.stringify(e??null).replaceAll("<","\\u003c")};
|
|
6
|
+
if (workerCapture) root[Symbol.for('three-blocks.shader-capture.worker-activation.v1')] = { ...workerCapture, scene };
|
|
7
|
+
const randomSeed = (value) => {
|
|
8
|
+
let state = 2166136261;
|
|
9
|
+
for (let index = 0; index < value.length; index++) state = Math.imul(state ^ value.charCodeAt(index), 16777619) >>> 0;
|
|
10
|
+
return state === 0 ? 0x9e3779b9 : state;
|
|
11
|
+
};
|
|
12
|
+
const advanceRandom = (state) => {
|
|
13
|
+
state ^= state << 13;
|
|
14
|
+
state ^= state >>> 17;
|
|
15
|
+
state ^= state << 5;
|
|
16
|
+
return state >>> 0;
|
|
17
|
+
};
|
|
18
|
+
const parityMode = new URL(location.href).searchParams.get('threeBlocksShaderMode');
|
|
19
|
+
if (parityMode === 'live' || parityMode === 'precompiled') {
|
|
20
|
+
root.__threeBlocksParityEpoch = 1700000000000;
|
|
21
|
+
root.__threeBlocksParityTime = 0;
|
|
22
|
+
Date.now = () => root.__threeBlocksParityEpoch + Number(root.__threeBlocksParityTime || 0);
|
|
23
|
+
}
|
|
24
|
+
const randomStreams = new Map();
|
|
25
|
+
Math.random = () => {
|
|
26
|
+
const stackLine = String(new Error().stack || '').split('\\n')[2] || 'unknown';
|
|
27
|
+
const originIndex = stackLine.indexOf(location.origin);
|
|
28
|
+
const callsite = (originIndex >= 0 ? stackLine.slice(0, originIndex) : stackLine).trim() || 'anonymous';
|
|
29
|
+
const next = advanceRandom(randomStreams.get(callsite) ?? randomSeed(scene + '|' + callsite));
|
|
30
|
+
randomStreams.set(callsite, next);
|
|
31
|
+
return next / 4294967296;
|
|
32
|
+
};
|
|
33
|
+
const readiness = { workerReady: false, assetsReady: false, textReady: false, compileEnd: false, firstFrame: false };
|
|
34
|
+
const stats = { buildCalls: 0, renderBuilds: 0, computeBuilds: 0, registeredBuilds: 0, registeredRenderBuilds: 0, registeredComputeBuilds: 0, buildMs: 0, syncBuildMs: 0, asyncBuildElapsedMs: 0, precompiledSetupMs: 0, maxSyncBuildMs: 0, maxPrecompiledSetupMs: 0, hydrationMs: 0, maxHydrationMs: 0, injected: 0, injectedRender: 0, injectedCompute: 0, missed: 0, missedRender: 0, missedCompute: 0, missedKeys: [] };
|
|
35
|
+
const settleParityFrames = ${qe.toString()};
|
|
36
|
+
const settle = (frames, requestedTarget) => settleParityFrames(
|
|
37
|
+
root,
|
|
38
|
+
frames,
|
|
39
|
+
requestedTarget,
|
|
40
|
+
() => new Promise((resolve) => requestAnimationFrame(resolve)),
|
|
41
|
+
() => new Promise((resolve) => setTimeout(resolve, 100)),
|
|
42
|
+
);
|
|
43
|
+
const bridge = { protocolVersion: 1, compatibility: ${JSON.stringify(n)}, transform: ${B}, readiness, stats, settle };
|
|
44
|
+
root.__threeBlocksShaderTools = bridge;
|
|
45
|
+
requestAnimationFrame(() => requestAnimationFrame(() => { readiness.firstFrame = true; }));
|
|
46
|
+
const poll = async () => {
|
|
47
|
+
try {
|
|
48
|
+
const response = await fetch('/__three-blocks/shaders/telemetry?scene=' + encodeURIComponent(scene), { cache: 'no-store' });
|
|
49
|
+
if (response.status !== 204 && response.ok) {
|
|
50
|
+
const payload = await response.json();
|
|
51
|
+
if (payload.protocolVersion !== 1 || payload.compatibility !== bridge.compatibility || payload.transform !== bridge.transform) throw new Error('incompatible shader telemetry');
|
|
52
|
+
Object.assign(stats, payload.stats);
|
|
53
|
+
if (Array.isArray(payload.demands)) bridge.demands = payload.demands;
|
|
54
|
+
if (typeof payload.demandTotal === 'number') bridge.demandTotal = payload.demandTotal;
|
|
55
|
+
readiness.workerReady = true;
|
|
56
|
+
if (payload.settled === true) {
|
|
57
|
+
readiness.assetsReady = true;
|
|
58
|
+
readiness.textReady = true;
|
|
59
|
+
readiness.compileEnd = true;
|
|
60
|
+
}
|
|
61
|
+
const smoke = root.__threeBlocksSmoke && typeof root.__threeBlocksSmoke === 'object' ? root.__threeBlocksSmoke : { protocolVersion: 1, worker: { offscreenCanvas: true, visible: true }, readiness: {} };
|
|
62
|
+
smoke.readiness = { ...(smoke.readiness || {}), ...readiness };
|
|
63
|
+
root.__threeBlocksSmoke = smoke;
|
|
64
|
+
}
|
|
65
|
+
} catch {}
|
|
66
|
+
setTimeout(poll, 40);
|
|
67
|
+
};
|
|
68
|
+
void poll();
|
|
69
|
+
})();`}a(se,"publicBridgeScript");function _e(n,e,t,r,a=false){let o=new URL(n.url??"/","http://three-blocks.invalid"),s=o.pathname;if(a&&n.method==="GET"&&/^\/three-blocks\/shaders\/[a-z0-9][a-z0-9_-]{0,63}\.(?:webgpu|webgl)\.json$/u.test(s))return e.statusCode=204,e.end(),true;if(s===K&&n.method==="GET"){let h=o.searchParams.get("scene")??"",S=r.read(h);return S===void 0?(e.statusCode=204,e.end()):(e.statusCode=200,e.setHeader("Content-Type","application/json"),e.end(JSON.stringify(S))),true}let i=s===Re,d=s===K;if(!i&&!d)return false;if(n.method!=="POST")return e.statusCode=405,e.end("POST required"),true;let c=[],w=0,f=false;return n.on("data",h=>{w+=h.byteLength,w>Pe?f=true:c.push(h);}),n.on("end",()=>{if(f){e.statusCode=413,e.end("capture payload too large");return}try{let h=JSON.parse(Buffer.concat(c).toString("utf8"));d?r.receive(h):t.receive(h),e.statusCode=204,e.end();}catch(h){e.statusCode=400,e.end(h instanceof Error?h.message:String(h));}}),true}a(_e,"handleCaptureEndpoint");function ze(n,e,t,r,a){return {name:"three-blocks:shader-capture-endpoint",transformIndexHtml(){return [{tag:"script",children:se(r,a),injectTo:"head-prepend"}]},configureServer(o){o.middlewares.use((s,i,d)=>{let w=new URL(s.url??"/","http://three-blocks.invalid").searchParams.get("captureId");w!==null&&e.markFirstRequest(w),!_e(s,i,n,e,t)&&d();});}}}a(ze,"captureEndpointPlugin");function ge(n,e,t){let r=new URL(e.url,n);for(let[a,o]of Object.entries(t))r.searchParams.set(a,o);return r.href}a(ge,"browserUrl");function Ye(n,e,t){let r=new URL(e.url,n);for(let a of ["capture","precompiled"])r.searchParams.delete(a);return r.searchParams.set("captureId",e.key),r.searchParams.set("threeBlocksShaderCapture","1"),r.searchParams.set("threeBlocksShaderMode","precompiled"),t==="webgl"&&r.searchParams.set("webgl","1"),r.searchParams.set("tbStats","1"),r.href}a(Ye,"publishedBrowserUrl");function ye(n){return We.some(e=>e.test(n))}a(ye,"knownNoise");async function M(n){let e;try{await Promise.race([n(),new Promise(t=>{e=setTimeout(t,Be);})]);}catch{}finally{e&&clearTimeout(e);}}a(M,"closeBrowserResource");async function J(n){let e;try{return await Promise.race([n().catch(()=>null),new Promise(t=>{e=setTimeout(()=>t(null),Be);})])}finally{e!==void 0&&clearTimeout(e);}}a(J,"readPageDiagnostic");function ee(n){let e=a(()=>{},"resolveFirst"),t=new Promise(s=>{e=s;}),r={console:[],page:[],first:t},a$1=false,o=a(s=>{a$1||(a$1=true,e(new Error(s)));},"report");return n.on("console",s=>{let i=s.type()==="warning"&&/\[three-blocks\/shaders\].*(?:has no entry|manifest miss|hydration)/iu.test(s.text());if(s.type()!=="error"&&!i||ye(s.text()))return;let d=s.location().url,c=d.length>0?`${s.text()} (${d})`:s.text();r.console.push(c),o(`Browser console ${i?"warning":"error"}: ${c}`);}),n.on("pageerror",s=>{if(ye(s.message))return;let i=s.stack||s.message;r.page.push(i),o(`Browser page error: ${i}`);}),n.on("crash",()=>o("Browser page crashed before shader capture completed.")),n.on("close",()=>o("Browser page closed before shader capture completed.")),r}a(ee,"collectErrors");function L(n,e,t=false){return typeof n[e]=="boolean"?n[e]:t}a(L,"booleanField");function Xe(n){if(!a$1(n))throw new Error("Browser shader stats are unavailable.");let e=a((t,r=true)=>{let a=n[t];if(typeof a!="number"||!Number.isFinite(a)||a<0||r&&!Number.isSafeInteger(a))throw new Error(`Browser shader stats.${t} is invalid.`);return a},"read");return {buildCalls:e("buildCalls"),renderBuilds:e("renderBuilds"),computeBuilds:e("computeBuilds"),registeredBuilds:e("registeredBuilds"),registeredRenderBuilds:e("registeredRenderBuilds"),registeredComputeBuilds:e("registeredComputeBuilds"),buildMs:e("buildMs",false),syncBuildMs:e("syncBuildMs",false),asyncBuildElapsedMs:e("asyncBuildElapsedMs",false),precompiledSetupMs:e("precompiledSetupMs",false),maxSyncBuildMs:e("maxSyncBuildMs",false),maxPrecompiledSetupMs:e("maxPrecompiledSetupMs",false),hydrationMs:e("hydrationMs",false),maxHydrationMs:e("maxHydrationMs",false),injected:e("injected"),injectedRender:e("injectedRender"),injectedCompute:e("injectedCompute"),missed:e("missed"),missedRender:e("missedRender"),missedCompute:e("missedCompute"),...Array.isArray(n.missedKeys)&&n.missedKeys.every(t=>typeof t=="string")?{missedKeys:n.missedKeys}:{}}}a(Xe,"parseStats");function W(n,e,t,r,a){if(!a$1(n))throw new Error("The page did not expose the public shader devtools bridge.");if(!t&&n.protocolVersion!==1)throw new Error(`Scene "${e.key}" exposed an unsupported shader bridge protocol.`);let o=n.readiness;if(!a$1(o))throw new Error("The shader bridge readiness snapshot is invalid.");let s={workerReady:L(o,"workerReady"),assetsReady:L(o,"assetsReady"),textReady:e.requiresText?L(o,"textReady"):true,compileEnd:L(o,"compileEnd"),firstFrame:L(o,"firstFrame",t)};if(!s.workerReady||!s.assetsReady||!s.textReady||!s.compileEnd)throw new Error(`Scene "${e.key}" did not reach worker/assets/text/compile readiness.`);let i=t?a:n.compatibility,d=t?B:n.transform;if(i!==a||d!==B)throw new Error(`Scene "${e.key}" exposed incompatible shader bridge metadata.`);Y(r);let c=Array.isArray(n.demands)?n.demands.filter(a$1).slice(0,64):void 0;return {compatibility:a,transform:d,readiness:s,stats:Xe(n.stats),...c===void 0?{}:{demands:c}}}a(W,"parseBridge");async function V(n,e){return n.evaluate(t=>{let r=globalThis;if(!t)return r.__threeBlocksShaderTools??null;let a=r.__threeBlocks,o=r.__threeBlocksTslStats;if(!a||typeof a!="object")return null;let s=a;return {readiness:{workerReady:s.workerReady===true,assetsReady:s.loadEnd===true||s.assetsReady===true,textReady:s.textReady===true,compileEnd:s.compileEnd===true,firstFrame:true},stats:o}},e)}a(V,"readBridge");async function xe(n,e){let t=await J(()=>n.evaluate(r=>{let a$1=globalThis,o=a(i=>{let d=a$1;for(let c of i.split(".")){if(d===null||typeof d!="object"&&typeof d!="function")return;d=Reflect.get(d,c);}return d},"resolveGlobal"),s=null;if(r!==null)try{s=JSON.stringify(o(`${r}Diagnostics`))??null;}catch{s=null;}return JSON.stringify({parityCompletedFrame:Number(a$1.__threeBlocksParityCompletedFrame??0),diagnostics:s})},e??null));return t===null?{alive:false,signature:""}:{alive:true,signature:t}}a(xe,"probePageProgress");async function F(n,e,t,r){let a$1=n.evaluate(async c=>{let f=globalThis.__threeBlocksShaderTools;if(f&&typeof f=="object"){let y=Reflect.get(f,"settle");if(typeof y=="function"){let u=await y(c.frames,c.targetFrame);return typeof u=="number"&&Number.isSafeInteger(u)?u:0}}if(!c.legacy||!c.modulePath)throw new Error("The public shader bridge does not provide deterministic settle().");let h=await import(c.modulePath);if(!h.store||typeof h.store!="object")throw new Error("Legacy deterministic store is unavailable.");let S=h.store;return S.recordFrameCount=0,S.recordFrameRate=60,S.recordTotalFrames=c.frames,S.recording=true,await new Promise((y,u)=>{let p=Date.now(),m=a(()=>{if(S.recording===false)return y();if(Date.now()-p>c.timeoutMs)return u(new Error("Legacy deterministic settle timed out."));setTimeout(m,25);},"poll");m();}),0},{frames:t,targetFrame:r,legacy:e.bridge.legacyLab,modulePath:e.bridge.deterministicModule??null,timeoutMs:e.timeoutMs}),o=j(e),s=false,i,d=(async()=>{let c=Date.now(),w=c,f="";for(;;){let h=o-(Date.now()-c);if(h<=0)throw new Error(`Shader parity settle timed out after ${o}ms.`);let S=e.timeoutMs-(Date.now()-w);if(S<=0){let y=await xe(n,e.readiness.global);if(s)throw new Error("Shader parity settle already resolved.");if(y.alive&&y.signature===f)throw new Error(`Shader parity settle timed out after ${e.timeoutMs}ms without progress (hard cap ${o}ms).`);f=y.signature,w=Date.now();continue}if(await new Promise(y=>{i=setTimeout(y,Math.min(S,h,2500));}),s)throw new Error("Shader parity settle already resolved.")}})();try{return await Promise.race([a$1,d])}finally{s=true,i!==void 0&&clearTimeout(i),d.catch(()=>{});}}a(F,"settlePage");async function Se(n,e,t){e.readiness.selector===void 0&&e.readiness.global===void 0||await Promise.race([n.waitForFunction(r=>{let a=globalThis;if(r.selector!==void 0&&a.document?.querySelector(r.selector)==null)return false;if(r.global===void 0)return true;let o=a;for(let d of r.global.split(".")){if((typeof o!="object"||o===null)&&typeof o!="function")return false;o=Reflect.get(o,d);}if(o===true)return true;if(typeof o!="object"||o===null||typeof Reflect.get(o,"then")!="function")return false;let s=a.__threeBlocksReadinessState,i=s instanceof Map?s:new Map;return s instanceof Map||(a.__threeBlocksReadinessState=i),i.has(o)||(i.set(o,false),Promise.resolve(o).then(()=>i.set(o,true),()=>i.set(o,false))),i.get(o)===true},e.readiness,{timeout:j(e)}),t.first.then(r=>Promise.reject(r))]);}a(Se,"waitForConfiguredReadiness");async function be(n){let e=n.locator("canvas"),r=(await e.evaluateAll(a=>a.map((o,s)=>{let i=o.getBoundingClientRect();return {index:s,area:Math.max(0,i.width)*Math.max(0,i.height)}}))).sort((a,o)=>o.area-a.area)[0];if(r===void 0||r.area<=0)throw new Error("Published page has no visible renderer canvas.");return Buffer.from(await e.nth(r.index).screenshot({type:"png"}))}a(be,"primaryCanvasScreenshot");async function te(n,e,t,r,a,o,s){let i=q(r,a,o),d=await U(),c=`(() => {
|
|
70
|
+
const runtime = globalThis[Symbol.for(${JSON.stringify(Z)})];
|
|
71
|
+
if (!runtime || typeof runtime.configureThreeBlocksShaderCapture !== 'function') {
|
|
72
|
+
throw new Error('@three-blocks/devtools attached shader capture runtime is incompatible.');
|
|
73
|
+
}
|
|
74
|
+
runtime.configureThreeBlocksShaderCapture(${JSON.stringify(i).replaceAll("<","\\u003c")});
|
|
75
|
+
})();`;await n.addInitScript({content:`${d}
|
|
76
|
+
${c}`}),await n.addInitScript({content:se(s,i)}),await n.route("**/*",async w=>{let f=w.request(),h=new URL(f.url()),S=h.pathname;if(f.method()==="GET"&&r!=="precompiled"&&/^\/three-blocks\/shaders\/[a-z0-9][a-z0-9_-]{0,63}\.(?:webgpu|webgl)\.json$/u.test(S)){await w.fulfill({status:204});return}if(S===K&&f.method()==="GET"){let p=t.read(h.searchParams.get("scene")??"");await w.fulfill(p===void 0?{status:204}:{status:200,contentType:"application/json",body:JSON.stringify(p)});return}let y=S===Re,u=S===K;if((y||u)&&f.method()==="POST"){let p=f.postDataBuffer()??Buffer.alloc(0);if(p.byteLength>Pe){await w.fulfill({status:413,body:"capture payload too large"});return}try{let m=JSON.parse(p.toString("utf8"));u?t.receive(m):e.receive(m),await w.fulfill({status:204});}catch(m){await w.fulfill({status:400,body:m instanceof Error?m.message:String(m)});}return}await w.continue();});}a(te,"configureAttachedContext");var Qe=Object.freeze({".avif":"image/avif",".css":"text/css; charset=utf-8",".gif":"image/gif",".html":"text/html; charset=utf-8",".ico":"image/x-icon",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".mp4":"video/mp4",".png":"image/png",".svg":"image/svg+xml",".wasm":"application/wasm",".webm":"video/webm",".webp":"image/webp",".woff":"font/woff",".woff2":"font/woff2"});function Ze(n){let e=[`<script src="${Ee}"></script>`,`<script type="module" src="${ke}"></script>`].join(""),t=/<head(?:\s[^>]*)?>/iu.exec(n);return t===null?`${e}${n}`:`${n.slice(0,t.index+t[0].length)}${e}${n.slice(t.index+t[0].length)}`}a(Ze,"injectStaticShaderCaptureHtml");function et(n,e,t){let r=q(n,e,t);return [`import { configureThreeBlocksShaderCapture } from ${JSON.stringify(Te)};`,`configureThreeBlocksShaderCapture( ${JSON.stringify(r).replaceAll("<","\\u003c")} );`].join(`
|
|
77
|
+
`)}a(et,"staticCaptureBootstrap");var tt=5e3;function j(n){return Math.max(n.maxTimeoutMs??n.timeoutMs,n.timeoutMs)}a(j,"configuredHardCapMs");function q(n,e,t){return {capture:n==="capture",backend:t,driven:true,forceLive:n!=="precompiled",settleFrames:e.settleFrames,settleTimeoutMs:e.settleTimeoutMs??3e4,...n==="capture"?{deadlineAt:Date.now()+Math.max(1e3,j(e)-tt)}:{},readiness:e.readiness,transform:B}}a(q,"shaderCaptureConfiguration");async function rt(n,e){let t=await m(n,e,s=>/\.(?:c|m)?js$/u.test(s),16384),r=false,a=false,o;for(let s of t){let i=(await l(n,s,d.texture,"Static application JavaScript")).data.toString("utf8");if(i.includes("nodeBuilderStateProvider")&&(r=true),i.includes("three-blocks.shader-capture.runtime.v1")&&(a=true,o??=s),r&&a)break}if(!r||!a)throw new Error("The static build does not contain the Three.js shader capture transform. Run `shaders capture` without an explicit driver or URL to preview adapter wiring and build automatically, or add the manual adapter from the package README and rebuild.");return {seen:true,applied:true,alreadyPresent:false,captureApplied:true,...o===void 0?{}:{id:o}}}a(rt,"inspectStaticCaptureTransform");async function nt(n,e){let t;try{t=decodeURIComponent(e);}catch{return}if(t.includes("\0"))return;let r=t.replace(/^\/+/u,""),a=A.resolve(n,r.length===0?"index.html":r);if(!h(n,a)||a===n||(await g(a)&&(await lstat(a)).isDirectory()&&(a=A.join(a,"index.html")),!await g(a)&&A.extname(a).length===0&&(a=A.join(n,"index.html")),!await g(a)))return;let o=await l(n,a,d.texture,"Static application asset");return {data:o.data,file:o.path}}a(nt,"staticRequestFile");async function at(n,e,t,r,a,o){let s=await realpath(n.root),i=await realpath(A.resolve(s,n.serve));if(!h(s,i)||i===s)throw new Error("--serve must name a built application directory inside the project root.");let d=await rt(s,i),c=await S(),w=et(e,r,t),f=se(z(n.runtime.three,t),q(e,r,t)),h$1=createServer((y,u)=>{(async()=>{if(_e(y,u,a,o,e!=="precompiled"))return;let p=new URL(y.url??"/","http://three-blocks.invalid");if(y.method!=="GET"&&y.method!=="HEAD"){u.statusCode=405,u.end("GET or HEAD required");return}let m=p.pathname===Te?c:p.pathname===ke?w:p.pathname===Ee?f:void 0;if(m!==void 0){u.statusCode=200,u.setHeader("Content-Type","text/javascript; charset=utf-8"),u.setHeader("Cache-Control","no-store"),u.end(y.method==="HEAD"?void 0:m);return}let g=await nt(i,p.pathname);if(g===void 0){u.statusCode=404,u.end("Not found");return}let v=A.extname(g.file).toLowerCase(),b=v===".html"?Buffer.from(Ze(g.data.toString("utf8"))):g.data;u.statusCode=200,u.setHeader("Content-Type",Qe[v]??"application/octet-stream"),u.setHeader("Content-Length",String(b.byteLength)),u.setHeader("Cache-Control","no-store"),u.end(y.method==="HEAD"?void 0:b);})().catch(p=>{if(u.headersSent)return u.destroy(p instanceof Error?p:void 0);u.statusCode=500,u.end(p instanceof Error?p.message:String(p));});});await new Promise((y,u)=>{h$1.once("error",u),h$1.listen(0,"127.0.0.1",()=>{h$1.off("error",u),y();});});let S$1=h$1.address();if(!S$1||typeof S$1=="string")throw new Error("Static capture server did not expose an ephemeral TCP address.");return {server:h$1,baseUrl:`http://127.0.0.1:${S$1.port}`,transform:d}}a(at,"startStaticShaderServer");function st(n,e,t){return n===e?true:t&&n!==void 0&&n!=="capture"&&e!=="capture"}a(st,"canReuseShaderBrowserSession");function ve(n){let e=n instanceof Error?n.message:String(n);return e.includes("Execution context was destroyed")&&e.includes("navigation")||/^launch: Timeout \d+ms exceeded\./u.test(e)}a(ve,"isRetryableShaderObservationNavigation");var N=class{static{a(this,"PlaywrightShaderDriver");}#e;#t=new ne;#n=new ae;#h;#m;#o;#i;#r;#a;#f;#l;#p;#w;#u=0;#c;constructor(e){this.#e=e;}#d(){return this.#h?.status??this.#m??{seen:false,applied:false,alreadyPresent:false}}async#g(e,t){if(this.#r?.isConnected()===true)return;this.#r=void 0;let r=await Ve();this.#c??=await mkdtemp(A.join(tmpdir(),"three-blocks-shader-cache-")),this.#r=await r.launch({headless:t==="webgl"?this.#e.headed!==true:pe(this.#e.headed===true),args:[...t==="webgl"?fe():me(),`--disk-cache-dir=${this.#c}`],timeout:e.timeoutMs}),this.#u=0;}async#s(e,t,r){let a;try{return await Promise.race([r(),new Promise((o,s)=>{a=setTimeout(()=>s(new Error(`launch: Timeout ${t.timeoutMs}ms exceeded.`)),t.timeoutMs);})])}catch(o){throw this.#r===e&&(this.#r=void 0),await M(()=>e.close()),o}finally{a!==void 0&&clearTimeout(a);}}async#y(e,t,r){let a=this.#o!==void 0||this.#i!==void 0||this.#e.url!==void 0&&this.#a!==void 0,o=this.#p===t&&(this.#i!==void 0?this.#l===e:st(this.#l,e,r.bridge.legacyLab));if(a&&o){this.#l=e,await this.#g(r,t);return}if(a&&await this.close(),this.#l=e,this.#p=t,this.#e.url!==void 0){let s=new URL(this.#e.url);if(!["http:","https:"].includes(s.protocol)||s.username||s.password||s.hash)throw new Error("Attached shader URL must be an HTTP(S) URL without credentials or a fragment.");this.#a=s.href,this.#m={seen:true,applied:true,alreadyPresent:false,captureApplied:true,id:"attached-application"},await this.#g(r,t);return}if(this.#e.serve!==void 0)try{let s=await at({root:this.#e.root,runtime:this.#e.runtime,serve:this.#e.serve,...this.#e.headed===void 0?{}:{headed:this.#e.headed}},e,t,r,this.#t,this.#n);this.#i=s.server,this.#m=s.transform,this.#a=s.baseUrl,await this.#g(r,t);return}catch(s){throw await this.close(),s}this.#h=X(this.#e.runtime.three,{disableTimestampQueries:x.env.THREE_BLOCKS_SOFTWARE_WEBGPU==="1",...r.bridge.legacyLab?{}:{capture:{capture:e==="capture",driven:true,forceLive:e!=="precompiled",forceWebGL:t==="webgl",settleFrames:r.settleFrames,settleTimeoutMs:r.settleTimeoutMs??3e4,readiness:r.readiness}}}),this.#f={THREE_BLOCKS_SHADER_TOOL:x.env.THREE_BLOCKS_SHADER_TOOL,THREE_BLOCKS_PRECOMPILE_CAPTURE_SERVER:x.env.THREE_BLOCKS_PRECOMPILE_CAPTURE_SERVER},x.env.THREE_BLOCKS_SHADER_TOOL="1",x.env.THREE_BLOCKS_PRECOMPILE_CAPTURE_SERVER="1";try{let s=await Je(this.#e.root);this.#o=await s({root:this.#e.root,logLevel:"error",plugins:[this.#h.plugin,ze(this.#t,this.#n,e!=="precompiled",z(this.#e.runtime.three,t),q(e,r,t))],server:{host:"127.0.0.1",port:0}}),await this.#o.listen();let i=this.#o.httpServer?.address();if(!i||typeof i=="string")throw new Error("Vite did not expose an ephemeral TCP address.");this.#a=`http://127.0.0.1:${i.port}`,await this.#g(r,t);}catch(s){throw await this.close(),s}}async capture(e,t,r="webgpu"){let a$2=Date.now();if(await this.#y("capture",r,t),!this.#r||!this.#a)throw new Error("Shader browser driver did not start.");let o=this.#r,s=await this.#s(o,t,()=>o.newContext({viewport:t.viewport}));this.#e.url!==void 0&&await this.#s(o,t,()=>te(s,this.#t,this.#n,"capture",t,r,z(this.#e.runtime.three,r)));let i=await this.#s(o,t,()=>s.newPage()),d=ee(i);this.#n.clear(e.key);let c=j(t),w=this.#t.wait(e.key,c),f=false;c>t.timeoutMs?(async()=>{let m=Math.min(5e3,Math.max(1e3,Math.round(t.timeoutMs/8))),g=Date.now(),v="",b="";for(;!f;){if(await new Promise(k=>setTimeout(k,m)),f)return;let T=this.#n.read(e.key),B=T===void 0?"":JSON.stringify(T);if(B!==v){v=B,g=Date.now();continue}if(Date.now()-g<t.timeoutMs)continue;let E=await xe(i,t.readiness.global);if(f)return;if(!E.alive||E.signature!==b){b=E.signature,g=Date.now();continue}this.#t.cancel(e.key,new Error(`Shader capture "${e.key}" timed out after ${t.timeoutMs}ms without progress (hard cap ${c}ms).`));return}})().catch(()=>{}):void 0;let S=Promise.race([w,d.first.then(m=>Promise.reject(m))]),y=a(()=>{},"resolveDisconnected"),u=new Promise(m=>{y=m;}),p=a(()=>y(new Error("Shader capture browser disconnected before posting a manifest.")),"onDisconnected");o.on("disconnected",p);try{let m=i.goto(ge(this.#a,e,{threeBlocksShaderCapture:"1",capture:"1",captureId:e.key,captureFrames:String(Math.max(4,t.settleFrames)),settleFrames:String(t.settleFrames),...r==="webgl"?{webgl:"1"}:{}}),{waitUntil:"domcontentloaded",timeout:t.timeoutMs}),g=await Ke(m,Promise.race([S,u.then(b=>Promise.reject(b))]));Y(this.#d());let v=[...d.page,...d.console];if(v.length>0)throw new Error(`Capture browser errors:
|
|
78
|
+
- ${v.join(`
|
|
79
|
+
- `)}`);return a$1(g)?{...g,timing:{...a$1(g.timing)?g.timing:{},launch:a$2,...this.#n.firstRequest(e.key)===void 0?{}:{firstRequest:this.#n.firstRequest(e.key)},posted:Date.now()}}:g}catch(m){let g=m instanceof Error?m:new Error(String(m));this.#t.cancel(e.key,g),await w.catch(()=>{});let v=this.#n.read(e.key);if(g.message.includes("timed out")){let b=await J(()=>i.evaluate(E=>{let k=globalThis,$=k.__threeBlocksShaderTools,Oe=$&&typeof $=="object"?$:void 0,Me=k.document,O=Reflect.get(k,Symbol.for("three-blocks.shader-capture.cache-value.v1")),I=k.location,Ae=I!==null&&typeof I=="object"&&typeof Reflect.get(I,"href")=="string"?String(Reflect.get(I,"href")):"http://three-blocks.invalid/",je=new URL(Ae).searchParams.get("captureId")??"default",oe=O!==null&&typeof O=="object"&&typeof Reflect.get(O,"registrations")=="function"?Reflect.apply(Reflect.get(O,"registrations"),O,[je]):void 0,ie=a(R=>{let _=k;for(let De of R.split(".")){if(_===null||typeof _!="object"&&typeof _!="function")return;_=Reflect.get(_,De);}return _},"resolveGlobal"),de=null,z=null;if(E!==null){let R=ie(E);de=R===true||R===false?R:R===void 0?"absent":R!==null&&typeof R.then=="function"?"promise":typeof R;try{let _=JSON.stringify(ie(`${E}Diagnostics`));z=typeof _=="string"?_.slice(0,2048):null;}catch{z=null;}}return {documentReadyState:Me?.readyState??null,parityTargetFrame:Number(k.__threeBlocksParityTargetFrame??0),parityCompletedFrame:Number(k.__threeBlocksParityCompletedFrame??0),readiness:Oe?.readiness??null,readinessGlobal:de,readinessDiagnostics:z,captureCache:O!==null&&typeof O=="object"?{activeScene:Reflect.get(O,"activeScene")??null,registrations:Array.isArray(oe)?oe.slice(0,16).map(R=>R!==null&&typeof R=="object"?{key:Reflect.get(R,"key")??null,kind:Reflect.get(R,"kind")??null}:null):null}:null,threeRuntimeResources:performance.getEntriesByType("resource").map(R=>R.name).filter(R=>R.includes("three.webgpu"))}},t.readiness.global??null)),T=t.readiness.global!==void 0&&b!==null&&b.readinessGlobal!==true,B=b===null?"Capture page did not answer diagnostics before the deadline; its main thread was blocked or gone. ":T?`Application readiness "${t.readiness.global}" never completed (state: ${JSON.stringify(b.readinessGlobal)}${b.readinessDiagnostics===null?"":`, diagnostics: ${b.readinessDiagnostics}`}). `:"";throw new Error(`${B}${g.message} Last capture state for "${e.key}": ${JSON.stringify({page:b,telemetry:v??null,transform:this.#d()})}`)}throw g}finally{f=true,o.off("disconnected",p),await M(()=>s.close()),this.#u++,(!o.isConnected()||this.#u>=(t.browserRelaunchScenes??8))&&(this.#r===o&&(this.#r=void 0),await M(()=>o.close()),this.#u=0);}}async observe(e,t,r,a,o="webgpu"){for(let s=0;s<2;s++)try{return await this.#S(e,o,t,r,a)}catch(i){if(s===0&&ve(i))continue;throw i}throw new Error(`Shader observation retry was exhausted for scene "${e.key}".`)}async#S(e,t,r,a,o){if(await this.#y(r,t,a),!this.#r||!this.#a)throw new Error("Shader browser driver did not start.");let s=this.#r,i=await this.#s(s,a,()=>s.newContext({viewport:a.viewport}));this.#e.url!==void 0&&await this.#s(s,a,()=>te(i,this.#t,this.#n,r,a,t,z(this.#e.runtime.three,t)));let d=await this.#s(s,a,()=>i.newPage()),c=ee(d);this.#n.clear(e.key);try{await d.goto(ge(this.#a,e,{threeBlocksShaderCapture:"1",threeBlocksShaderMode:r,captureId:e.key,...r==="live"?{precompiled:"0"}:{},...t==="webgl"?{webgl:"1"}:{}}),{waitUntil:"domcontentloaded",timeout:a.timeoutMs}),await Promise.race([d.waitForFunction(a.bridge.legacyLab?"globalThis.__threeBlocks?.compileEnd === true":"globalThis.__threeBlocksShaderTools?.readiness?.compileEnd === true",void 0,{timeout:j(a)}),c.first.then(u=>Promise.reject(u))]),W(await V(d,a.bridge.legacyLab),e,a.bridge.legacyLab,this.#d(),z(this.#e.runtime.three,t)),await Se(d,a,c),await Promise.race([d.waitForFunction(a.bridge.legacyLab?"true":"globalThis.__threeBlocksShaderTools?.readiness?.firstFrame === true",void 0,{timeout:j(a)}),c.first.then(u=>Promise.reject(u))]),await F(d,a,1);let w=Buffer.from(await d.screenshot({type:"png"})),f=e.parityFrames??a.parity.frames,h=await F(d,a,f,o),S=Buffer.from(await d.screenshot({type:"png"}));e.parityFrames!==void 0&&f<a.parity.frames&&await F(d,a,a.parity.frames-f);let y=W(await V(d,a.bridge.legacyLab),e,a.bridge.legacyLab,this.#d(),z(this.#e.runtime.three,t));return this.#w===void 0&&(this.#w=await d.evaluate(async u=>{if(u==="webgl"){let E=Reflect.get(globalThis,"document").querySelector("canvas")?.getContext("webgl2"),k=E?.getExtension("WEBGL_debug_renderer_info");return {adapter:E&&k?String(E.getParameter(k.UNMASKED_RENDERER_WEBGL)):"WebGL adapter",platform:navigator.platform||navigator.userAgent}}let p=Reflect.get(navigator,"gpu"),m=typeof p=="object"&&p!==null?Reflect.get(p,"requestAdapter"):void 0,g=typeof m=="function"?await Reflect.apply(m,p,[]):void 0,v=typeof g=="object"&&g!==null?Reflect.get(g,"info"):void 0,b=["description","device","architecture","vendor"].flatMap(T=>{let B=typeof v=="object"&&v!==null?Reflect.get(v,T):void 0;return typeof B=="string"&&B.length>0?[B]:[]});return {adapter:[...new Set(b)].join(" \xB7 ")||"WebGPU adapter",platform:navigator.platform||navigator.userAgent}},t)),{scene:e.key,mode:r,...y,frame:h,firstFrameScreenshot:w,screenshot:S,errors:[...c.page,...c.console]}}catch(w){let f=w instanceof Error?w:new Error(String(w));if(/(?:timed?\s*out|timeout)/iu.test(f.message)){let u=this.#n.read(e.key),p=await J(()=>d.evaluate(()=>{let m=globalThis,g=m.__threeBlocksShaderTools,v=g&&typeof g=="object"?g:void 0;return {documentReadyState:m.document?.readyState??null,parityTargetFrame:Number(m.__threeBlocksParityTargetFrame??0),parityCompletedFrame:Number(m.__threeBlocksParityCompletedFrame??0),readiness:v?.readiness??null,threeRuntimeResources:performance.getEntriesByType("resource").map(T=>T.name).filter(T=>T.includes("three.webgpu"))}}));throw new Error(`${f.message} Last ${r} state for "${e.key}": ${JSON.stringify({page:p,telemetry:u??null})}`)}let h=this.#n.read(e.key),y=(a$1(h)&&Array.isArray(h.demands)&&h.demands.length>0?JSON.stringify(h.demands).slice(0,6e3):void 0)??await J(()=>d.evaluate(u=>{let p=globalThis,m=Reflect.get(p,Symbol.for(u)),g=m!==null&&typeof m=="object"?Reflect.get(m,"readThreeBlocksShaderDemands"):void 0,v=typeof g=="function"?Reflect.apply(g,m,[]):void 0,b=p.__threeBlocksShaderTools,T=Array.isArray(v)&&v.length>0?v:b&&typeof b=="object"?Reflect.get(b,"demands"):void 0;return Array.isArray(T)&&T.length>0?JSON.stringify(T).slice(0,6e3):null},Z));throw typeof y=="string"?new Error(`${f.message}
|
|
80
|
+
${r} demands: ${y}`):f}finally{await M(()=>i.close());}}async observePublished(e,t,r="webgpu"){for(let a=0;a<2;a++)try{return await this.#b(e,r,t)}catch(o){if(a===0&&ve(o))continue;throw o}throw new Error(`Published shader observation retry was exhausted for scene "${e.key}".`)}async#b(e,t,r){if(await this.#y("precompiled",t,r),!this.#r||!this.#a)throw new Error("Shader browser driver did not start.");let a=this.#r,o=await this.#s(a,r,()=>a.newContext({viewport:r.viewport}));this.#e.url!==void 0&&await this.#s(a,r,()=>te(o,this.#t,this.#n,"precompiled",r,t,z(this.#e.runtime.three,t)));let s=await this.#s(a,r,()=>o.newPage()),i=ee(s);this.#n.clear(e.key);try{await s.goto(Ye(this.#a,e,t),{waitUntil:"domcontentloaded",timeout:r.timeoutMs}),await Promise.race([s.waitForFunction(r.bridge.legacyLab?"globalThis.__threeBlocks?.compileEnd === true":"globalThis.__threeBlocksShaderTools?.readiness?.compileEnd === true",void 0,{timeout:j(r)}),i.first.then(h=>Promise.reject(h))]),await Se(s,r,i),W(await V(s,r.bridge.legacyLab),e,r.bridge.legacyLab,this.#d(),z(this.#e.runtime.three,t)),await F(s,r,2);let d=await be(s),c=await F(s,r,120),w=await be(s),f=W(await V(s,r.bridge.legacyLab),e,r.bridge.legacyLab,this.#d(),z(this.#e.runtime.three,t));return {scene:e.key,mode:"precompiled",...f,frame:c,firstFrameScreenshot:d,beforeScreenshot:d,screenshot:w,errors:[...i.page,...i.console]}}finally{await M(()=>o.close());}}timingEnvironment(){return this.#w??{adapter:this.#p==="webgl"?"WebGL adapter":"WebGPU adapter",platform:`${x.platform}/${x.arch}`}}async close(){this.#t.rejectAll(new Error("Shader browser driver closed.")),this.#r&&await M(()=>this.#r?.close()??Promise.resolve());let e=this.#o?.httpServer,t=e?Reflect.get(e,"closeAllConnections"):void 0;if(e&&typeof t=="function"&&Reflect.apply(t,e,[]),this.#o&&await M(()=>this.#o?.close()??Promise.resolve()),this.#i){let r=this.#i;r.closeAllConnections(),await M(()=>new Promise(a=>{r.close(()=>a());}));}if(this.#r=void 0,this.#o=void 0,this.#i=void 0,this.#a=void 0,this.#h=void 0,this.#m=void 0,this.#l=void 0,this.#p=void 0,this.#w=void 0,this.#u=0,this.#c!==void 0&&(await rm(this.#c,{recursive:true,force:true}),this.#c=void 0),this.#f){for(let[r,a]of Object.entries(this.#f))a===void 0?delete x.env[r]:x.env[r]=a;this.#f=void 0;}}};function Et(n){return new N(n)}a(Et,"createPlaywrightShaderDriver");function Pt(n){return new N(n)}a(Pt,"createStaticPlaywrightShaderDriver");function Ct(n){return new N(n)}a(Ct,"createAttachedPlaywrightShaderDriver");export{Le as a,it as b,me as c,pe as d,Ke as e,qe as f,se as g,st as h,ve as i,Et as j,Pt as k,Ct as l};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {a as a$1}from'./chunk-HOZDD6PW.js';import t from'process';var i=Object.freeze([{id:"three-inspector-invalid-json",pattern:/is not valid JSON/iu},{id:"chromium-webgpu-experimental",pattern:/WebGPU is experimental/iu}]);function a(n){return i.some(e=>e.pattern.test(n))}a$1(a,"isDocumentedBrowserNoise");function l(n=t.env,e=t.platform){let s=n.THREE_BLOCKS_WEBGPU_BROWSER_ARGS?.split(/\s+/u).filter(Boolean);if(s&&s.length>0)return s;let o=["--enable-unsafe-webgpu"];return e==="darwin"&&o.push("--enable-gpu","--use-angle=metal"),e==="linux"&&o.push("--enable-features=Vulkan","--disable-vulkan-surface","--ignore-gpu-blocklist","--disable-gpu-driver-bug-workarounds","--disable-gpu-watchdog"),o}a$1(l,"webgpuBrowserArgs");function g(n=t.env){let e=n.THREE_BLOCKS_WEBGL_BROWSER_ARGS?.split(/\s+/u).filter(Boolean);return e&&e.length>0?e:["--use-angle=swiftshader","--enable-unsafe-swiftshader","--ignore-gpu-blocklist"]}a$1(g,"webglBrowserArgs");function p(n=false,e=t.env){return n!==true&&e.THREE_BLOCKS_SOFTWARE_WEBGPU!=="1"}a$1(p,"webgpuBrowserHeadless");export{a,l as b,g as c,p as d};
|
package/dist/cli.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {c,b as b$1,h,e,a as a$
|
|
2
|
+
import {c,b as b$1,h,e,a as a$2,f,d}from'./chunk-76WRV5MZ.js';import {a as a$1}from'./chunk-ZT6T2W4B.js';import {a}from'./chunk-HOZDD6PW.js';import o from'process';var r=o.argv.slice(2),ne=r.indexOf("--reporter"),G=r.find(e=>e.startsWith("--reporter="))?.slice(11)??(ne===-1?void 0:r[ne+1]),ae=ne!==-1&&(G===void 0||G.startsWith("--"))?'--reporter requires "plain" or "json".':G!==void 0&&G!=="json"&&G!=="plain"?'--reporter must be "plain" or "json".':void 0,g=r.includes("--json")||G==="json",ce=new Set(["--reporter","--root","--route","--build-mode","--expect-shaders","--width","--height","--timeout","--settle","--min-luminance","--hmr","--size","--output","--driver","--serve","--url","--runs","--debounce","--config","--mode"]),re=[];for(let e=0;e<r.length;e++){let t=r[e];if(t!==void 0){if(t.startsWith("--")){ce.has(t)&&e++;continue}re.push(t);}}var y=re[0]??"status",R=re[1];function $(e){let t=r.find(u=>u.startsWith(`${e}=`));if(t!==void 0){let u=t.slice(e.length+1);if(u.length===0)throw new Error(`${e} requires a value.`);return u}let i=r.indexOf(e);if(i===-1)return;let n=r[i+1];if(n===void 0||n.startsWith("--"))throw new Error(`${e} requires a value.`);return n}a($,"optionValue");function le(e){let t=[];for(let i=0;i<r.length;i++){let n=r[i];if(n!==void 0){if(n.startsWith(`${e}=`)){let u=n.slice(e.length+1);if(u.length===0)throw new Error(`${e} requires a value.`);t.push(u);}else if(n===e){let u=r[i+1];if(u===void 0||u.startsWith("--"))throw new Error(`${e} requires a value.`);t.push(u);}}}return t}a(le,"optionValues");function b(e){let t=$(e);if(t===void 0)return;let i=Number(t);if(!Number.isFinite(i))throw new Error(`${e} must be a finite number.`);return i}a(b,"numberOption");async function pe(e){let t=`Shader provider adapter patch:
|
|
3
3
|
${e}
|
|
4
|
-
`;if(
|
|
5
|
-
`:t),
|
|
6
|
-
`));}a
|
|
7
|
-
`)}a
|
|
8
|
-
`)}a
|
|
9
|
-
`),
|
|
10
|
-
`),
|
|
11
|
-
`);return}if(y==="shaders"){let{findShaderProjectRoot:
|
|
12
|
-
`),(
|
|
13
|
-
`:`${
|
|
14
|
-
`);},"onSceneRetry")});}finally{
|
|
15
|
-
`),!await
|
|
16
|
-
`:`${c.warn} ${
|
|
17
|
-
`);}return}if(m==="test"){let
|
|
18
|
-
`);return}let
|
|
19
|
-
`);},onError(
|
|
20
|
-
`);}});
|
|
21
|
-
`);else {f(
|
|
22
|
-
`),y==="status"&&
|
|
23
|
-
`):
|
|
24
|
-
`),
|
|
4
|
+
`;if(o.stderr.write(g?`${JSON.stringify({type:"shader-adapter-diff",diff:e})}
|
|
5
|
+
`:t),r.includes("--yes"))return true;if(!o.stdin.isTTY||!o.stderr.isTTY)throw new Error("Adapter wiring needs consent. Review the diff above, then rerun with --yes; no files were changed.");let{createInterface:i}=await import('readline/promises'),n=i({input:o.stdin,output:o.stderr});try{let u=await n.question("Apply this patch? (y/N) ");return /^y(?:es)?$/iu.test(u.trim())}finally{n.close();}}a(pe,"approveAdapterPatch");function W(e){return g?{update(){},stop(){}}:h(e)}a(W,"wait");function fe(){let e$1=a(f=>b$1.accent(f),"c"),t=a(f=>b$1.dim(f),"d"),i=c.mark?`${c.mark} `:"",n=[["Inspect",[[`${e$1("status")}`,`project report: shaders, text, browser evidence ${t("\u2014 no browser, no GPU")}`],[`${e$1("shaders")}`,"verify shader freshness and exit 1 with the exact recovery command"],[`${e$1("shaders status")} ${t("[--check]")}`,`per-scene shader freshness ${t("(--check exits 1 when not fresh)")}`],[`${e$1("text status")}`,"text atlas coverage"]]],["Produce",[[`${e$1("shaders capture")} ${t("[--if-stale] [--commit-timing] [--driver static --serve dist]")}`,"capture shaders plus a local timing estimate; during development use the overlay Capture button"],[`${e$1("shaders watch")} ${t("[--debounce <ms>]")}`,"recapture automatically while you work"],[`${e$1("text generate")} ${t("[--config <path>]")}`,"regenerate MSDF text atlases"],[`${e$1("environment bake")} ${t("[--size 256]")}`,"bake the PMREM room environment to KTX2"]]],["Verify",[[`${e$1("shaders test")}`,"median timing + zero-build + compute + pixel parity gate"],[`${e$1("shaders test --parity-only")}`,"one correctness pair per scene; no timing or published-page soak"],[`${e$1("browser smoke")} ${t("[--route /] [--hmr <module>]")}`,"boot the dev app, verify worker lifecycle + HMR"],[`${e$1("browser preview")} ${t("[--route /]...")}`,"build + serve production, verify precompiled hydration"]]]],u=["",`${i}${b$1.bold("three-blocks devtools")} ${b$1.dim(`v${a$1}`)}`,b$1.dim("WebGPU shader precompilation and verification for Three Blocks projects."),"",`${b$1.bold("Usage")}`,` ${e$1("three-blocks-devtools")} ${t("[command] [options] [--json]")}`];for(let[f,a]of n)u.push("",b$1.bold(f),...e(a,{indent:2,maxWidth:a$2.width-2}));u.push("",b$1.bold("Options"),...e([[t("--json"),"stable machine-readable report on stdout"],[t("--reporter <plain|json>"),"select the stable terminal or CI reporter"],[t("--root <path>"),"project root (defaults to the nearest three-blocks project)"],[t("--backend <webgpu|webgl|both>"),"select shader backend lanes (default: config, then both)"],[t("--headed"),"show the automation browser window"],[t("--runs <n>"),"shader timing captures after warmup (default 5)"],[t("--parity-only"),"skip timing warmup/repeats and the published-page soak"],[t("--commit-timing"),"also write shareable hardware-labelled build timing"],[t("--skip-browser"),"check shader schema and freshness without browser parity"],[t("--driver <vite|static>"),"capture through Vite or an already-built static app"],[t("--serve <path>"),"built application directory for --driver static"],[t("--url <url>"),"attach to an already-running transformed application"],[t("--yes"),"apply a previewed framework adapter patch non-interactively"]],{indent:2,maxWidth:a$2.width-2}),"",b$1.dim("During development, use the in-page overlay Capture button for one-click recapture."),b$1.dim("`shaders capture` remains the explicit isolated-browser fallback for batch and CI."),""),f(u.join(`
|
|
6
|
+
`));}a(fe,"help");function he(e){return e?`${e.render} render \xB7 ${e.compute} compute`:"no coverage"}a(he,"coverageText");function Z(e){return e<100?e.toFixed(1):Math.round(e).toString()}a(Z,"milliseconds");function q(e,t,i){return `${e} ${d(t,12)} ${i}`}a(q,"row");function de(e$1){if(e$1.skipped)return q(c.tick,"shaders",`fresh ${c.dot} capture skipped ${b$1.dim(`(--if-stale) \xB7 ${e$1.reason}`)}`);let t=Math.max(0,Math.round((e$1.durationMs??0)/1e3)),i=e$1.scenes.length,n=[q(c.tick,"shaders",`captured in ${t} s ${c.dot} wrote ${i} shader scene${i===1?"":"s"}`)];e$1.configuration?.created===true&&n.push(b$1.dim(` created ${e$1.configuration.file} with the default "/" capture route`));for(let f of e$1.scenes)n.push(q(c.tick,f.scene,`${he(f.coverage)} ${c.dot} ${b$1.dim(`${f.attempts} attempt${f.attempts===1?"":"s"}`)}`));let u=e$1.scenes.flatMap(f=>{let a$1=f.timing;if(a$1?.launch===void 0||a$1.firstRequest===void 0||a$1.readiness===void 0||a$1.lastBuild===void 0||a$1.settled===void 0||a$1.posted===void 0)return [];let m=a((O,l)=>`${Z(Math.max(0,l-O))} ms`,"elapsed");return [[f.scene,`launch\u2192request ${m(a$1.launch,a$1.firstRequest)} ${c.dot} ready ${m(a$1.firstRequest,a$1.readiness)} ${c.dot} last build ${m(a$1.readiness,a$1.lastBuild)} ${c.dot} settle ${m(a$1.lastBuild,a$1.settled)} ${c.dot} post ${m(a$1.settled,a$1.posted)}`]]});return u.length>0&&n.push("",b$1.bold("Capture stages"),...e(u,{indent:2,maxWidth:a$2.width-2})),e$1.measurement!==void 0&&n.push(` TSL builds at startup: ${e$1.measurement.beforeBuilds} \u2192 ${e$1.measurement.afterBuilds} ${c.dot} \u2248${Z(Math.abs(e$1.measurement.firstFrameDeltaMs))} ms TSL work avoided (single-capture estimate)`),n.push(b$1.dim(" a running dev server reloads on its own; otherwise refresh the page")),n.join(`
|
|
7
|
+
`)}a(de,"formatShaderCapture");function me(e){let t=[q(c.tick,"shaders",`no-GPU ${e.noGpu.state} ${c.dot} browser ${e.browser}`)];for(let i of e.scenes){let n=e.timing?.scenes[i.scene],u=n===void 0?`${i.coverage.render+i.coverage.compute} TSL build${i.coverage.render+i.coverage.compute===1?"":"s"} skipped`:`${n.builds} TSL build${n.builds===1?"":"s"} skipped ${c.dot} \u2248${Z(n.avoidedBuildMs)} ms \xB1 ${Z(n.spreadMs)} TSL work avoided ${c.dot} median of ${n.runs} ${c.dot} Latest local capture`,f=n!==void 0&&n.spreadMs>n.avoidedBuildMs*.4?` ${c.dot} ${b$1.warn("noisy measurement \u2014 close other GPU apps and re-run")}`:"";t.push(q(c.tick,i.scene,`${u} ${c.dot} ${i.coverage.compute} compute ${c.dot} ${(i.parity.diffRatio*100).toFixed(3)}% pixel diff${f}`));}return t.join(`
|
|
8
|
+
`)}a(me,"formatShaderTest");async function we(){if(ae!==void 0)throw new Error(ae);if(y==="help"||y==="--help"||r.includes("--help"))return fe();if(y==="version"||r.includes("--version")){f(g?JSON.stringify({version:a$1}):a$1);return}if(y==="browser"){let{formatBrowserPreviewReport:a,formatBrowserSmokeReport:m,runBrowserPreview:O,runBrowserSmoke:l}=await import('./browser-smoke-EIKJ6OVK.js'),{findProjectRoot:k}=await import('./status-D2RF6QTL.js');if(R==="preview"){let P=$("--root")??await k(),M=le("--route"),B=$("--build-mode"),T=$("--expect-shaders")??"precompiled";if(T!=="precompiled"&&T!=="live")throw new Error('--expect-shaders must be "precompiled" or "live".');let I=b("--width"),D=b("--height"),j=b("--timeout"),J=b("--settle"),A=b("--min-luminance"),V=W("building and verifying the production bundle"),E;try{E=await O({root:P,...M.length===0?{}:{routes:M},...B===void 0?{}:{buildMode:B},expectShaders:T,text:r.includes("--text"),...j===void 0?{}:{timeoutMs:j},...J===void 0?{}:{settleMs:J},...A===void 0?{}:{minimumLuminance:A},...I===void 0&&D===void 0?{}:{viewport:{width:I??1024,height:D??640}},headed:r.includes("--headed")});}finally{V.stop();}o.stdout.write(`${g?JSON.stringify(E,null,2):a(E)}
|
|
9
|
+
`),E.passed||(o.exitCode=1);return}if(R!=="smoke")throw new Error(`Unsupported browser command "${R??""}".`);let S=$("--root")??await k(),h=b("--width"),x=b("--height"),v=$("--route"),N=b("--timeout"),L=b("--settle"),_=b("--min-luminance"),U=$("--hmr");if(r.includes("--webgl")&&r.includes("--unsupported-worker"))throw new Error("--webgl and --unsupported-worker are mutually exclusive.");let K=W(`smoking ${v??"/"} in a real browser`),w;try{w=await l({root:S,...v===void 0?{}:{route:v},...N===void 0?{}:{timeoutMs:N},...L===void 0?{}:{settleMs:L},..._===void 0?{}:{minimumLuminance:_},...U===void 0?{}:{hmrModule:U},forceWebgl:r.includes("--webgl"),unsupportedWorker:r.includes("--unsupported-worker"),expectTextGenerationFailure:r.includes("--expect-text-generation-failure"),...h===void 0&&x===void 0?{}:{viewport:{width:h??1024,height:x??640}},headed:r.includes("--headed")});}finally{K.stop();}o.stdout.write(`${g?JSON.stringify(w,null,2):m(w)}
|
|
10
|
+
`),w.passed||(o.exitCode=1);return}if(y==="environment"){if(R!=="bake")throw new Error(`Unsupported environment command "${R??""}".`);let{bakeRoomEnvironment:a,formatEnvironmentBakeReport:m}=await import('./environment-bake-XMRKQJXM.js'),{findProjectRoot:O}=await import('./status-D2RF6QTL.js'),l=$("--root")??await O(),k=b("--size"),S=$("--output"),h=b("--timeout"),x=W("baking the room environment on the GPU"),v;try{v=await a({root:l,...k===void 0?{}:{size:k},...S===void 0?{}:{output:S},...h===void 0?{}:{timeoutMs:h},compression:r.includes("--no-zstd")?"none":"zstd",headed:r.includes("--headed")});}finally{x.stop();}o.stdout.write(`${g?JSON.stringify(v,null,2):m(v)}
|
|
11
|
+
`);return}if(y==="shaders"){let{findShaderProjectRoot:a$1}=await import('./shader-config-EOFU5D3Y.js'),m=R??"status";if(!["status","capture","test","watch"].includes(m))throw new Error(`Unsupported shader command "${m}".`);let O=$("--root"),l=await a$1(O),k=$("--driver");if(k!==void 0&&k!=="vite"&&k!=="static")throw new Error('--driver must be "vite" or "static".');let S=k,h=$("--serve"),x=$("--url"),v=$("--backend");if(v!==void 0&&v!=="webgpu"&&v!=="webgl"&&v!=="both")throw new Error('--backend must be "webgpu", "webgl", or "both".');let N=v;if(m==="status"){let{inspectShaderMatrix:w}=await import('./shader-workflow-T72N2CLS.js'),{formatShaderMatrixStatus:P}=await import('./status-D2RF6QTL.js'),M=await w(l,void 0,N);o.stdout.write(`${g?JSON.stringify(M,null,2):P(M)}
|
|
12
|
+
`),(r.includes("--check")||R===void 0)&&M.state!=="fresh"&&(o.exitCode=1);return}if(m==="capture"){let{captureShaders:w}=await import('./shader-workflow-T72N2CLS.js'),{applyShaderAutoWire:P,hasRegisterDevtoolsCall:M,inspectShaderAutoWire:B}=await import('./shader-autowire-SPE5DM2X.js'),{buildShaderCaptureProject:T,startNextShaderCaptureServer:I}=await import('./shader-project-runner-S2AID2RJ.js'),{inferShaderCaptureTarget:D}=await import('./shader-config-EOFU5D3Y.js'),j=S,J=h,A=x,V,E,ee;try{if(j===void 0&&J===void 0&&A===void 0){let c=await B(l);if(!c.configured&&c.plan!==void 0){if(!await pe(c.plan.diff))throw new Error("Adapter wiring was declined; no files were changed.");await P(c.plan);}else if(!c.configured&&c.bundler!=="vite"&&c.bundler!=="unknown")throw new Error(`${c.reason} No files were changed.`);if(c.bundler==="next")E=W("starting the project-local Next.js capture server"),V=await I(l),A=V.url,E.update("capturing shader scenes");else if(c.bundler==="webpack"||c.bundler==="esbuild"||c.bundler==="rollup"){E=W(`building the ${c.bundler} capture target`),await T(l);let C=await D(l);if(C.driverKind!=="static"||C.serve===void 0)throw new Error(`${c.bundler} build completed but no dist/, build/, or out/index.html was found; pass --driver static --serve <directory>.`);j="static",J=C.serve,E.update("capturing shader scenes");}}E??=W("capturing shader scenes"),ee=await w({root:l,headed:r.includes("--headed"),ifStale:r.includes("--if-stale"),commitTiming:r.includes("--commit-timing"),...N===void 0?{}:{backend:N},...j===void 0?{}:{driverKind:j},...J===void 0?{}:{serve:J},...A===void 0?{}:{url:A},onSceneStart:a((c,C,H)=>E?.update(`capturing ${b$1.accent(c)} ${b$1.dim(`(${C+1}/${H})`)}`),"onSceneStart"),onSceneRetry:a((c,C,H,ie,z)=>{let ue=z instanceof Error&&/timed out/iu.test(z.message),se=`capture attempt ${C}/${H} for "${c}" after ${ue?`timeout (${Math.round(ie/1e3)} s burned)`:`failure (${z instanceof Error?z.message:String(z)})`}`;o.stderr.write(g?`${JSON.stringify({type:"shader-capture-retry",scene:c,attempt:C,total:H,timeoutMs:ie,message:se})}
|
|
13
|
+
`:`${se}
|
|
14
|
+
`);},"onSceneRetry")});}finally{E?.stop(),await V?.close();}if(o.stdout.write(`${g?JSON.stringify(ee,null,2):de(ee)}
|
|
15
|
+
`),!await M(l)){let c$1="Add registerDevtools({ renderer }) from three-blocks/devtools so committed shader artifacts hydrate in development and production.";o.stderr.write(g?`${JSON.stringify({type:"shader-runtime-registration",state:"missing",message:c$1})}
|
|
16
|
+
`:`${c.warn} ${c$1}
|
|
17
|
+
`);}return}if(m==="test"){let w=$("--mode");if(w!==void 0&&w!=="strict")throw new Error('--mode currently supports only "strict".');let{testShaders:P}=await import('./shader-workflow-T72N2CLS.js'),M=W("verifying precompiled shaders against the live baseline"),B=b("--runs"),T;try{T=await P({root:l,headed:r.includes("--headed"),skipBrowser:r.includes("--skip-browser"),...S===void 0?{}:{driverKind:S},...h===void 0?{}:{serve:h},...x===void 0?{}:{url:x},...B===void 0?{}:{runs:B},parityOnly:r.includes("--parity-only"),commitTiming:r.includes("--commit-timing"),...N===void 0?{}:{backend:N},onSceneStart:a((I,D,j)=>M.update(`verifying ${b$1.accent(I)} ${b$1.dim(`(${D+1}/${j})`)}`),"onSceneStart")});}finally{M.stop();}o.stdout.write(`${g?JSON.stringify(T,null,2):me(T)}
|
|
18
|
+
`);return}let L=b("--debounce"),{watchShaders:_}=await import('./shader-watch-ISNWIAXN.js'),U=new AbortController;o.once("SIGINT",()=>U.abort()),o.once("SIGTERM",()=>U.abort());let K=await _({root:l,headed:r.includes("--headed"),...S===void 0?{}:{driverKind:S},...h===void 0?{}:{serve:h},...x===void 0?{}:{url:x},...L===void 0?{}:{debounceMs:L},signal:U.signal,onResult(w){o.stdout.write(`${g?JSON.stringify(w):de(w)}
|
|
19
|
+
`);},onError(w){o.stderr.write(`${g?JSON.stringify({error:w.message}):`${c.cross} ${b$1.danger(w.message)}`}
|
|
20
|
+
`);}});g||f(q(c.ring,"watching",b$1.dim(K.root))),await K.done;return}if(y==="text"&&R&&R!=="status"){if(R!=="generate")throw new Error(`Unsupported text command "${R}".`);let{generateTextAtlases:a}=await import('./text-atlas-WRYJT3E7.js'),{findProjectRoot:m}=await import('./status-D2RF6QTL.js'),O=r.indexOf("--config"),l=O===-1?"three-blocks.text.ts":r[O+1];if(l===void 0||l.startsWith("--"))throw new Error("--config requires a project-relative path.");let k=await m(),S=W("generating MSDF text atlases"),h;try{h=await a(k,l);}finally{S.stop();}if(g)o.stdout.write(`${JSON.stringify(h,null,2)}
|
|
21
|
+
`);else {f(q(c.tick,"text",`${h.glyphs} glyphs ${c.dot} ${h.atlases.length} atlas${h.atlases.length===1?"":"es"} regenerated`));for(let x of h.updatedFiles)f(` ${d(b$1.dim("updated"),12)} ${b$1.dim(x)}`);}return}if(!["status","text"].includes(y))throw new Error(`Unknown command "${y}".`);let{formatThreeBlocksStatus:e,inspectThreeBlocksStatus:t,threeBlocksStatusIsFresh:i}=await import('./status-D2RF6QTL.js'),n=await t(),u=(n.text);if(y==="text"&&!u)throw new Error("This project does not enable the text feature.");let f$1=y==="text"?u:n;o.stdout.write(`${g?JSON.stringify(f$1,null,2):y==="status"?e(n):JSON.stringify(f$1,null,2)}
|
|
22
|
+
`),y==="status"&&r.includes("--check")&&!i(n)&&(o.exitCode=1);}a(we,"main");we().catch(e=>{let t=e instanceof Error?e.message:String(e);g?o.stderr.write(`${JSON.stringify({error:t})}
|
|
23
|
+
`):o.stderr.write(`${c.cross} ${b$1.danger(t)}
|
|
24
|
+
`),o.exitCode=1;});
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {b,d,a as a$2}from'./chunk-W6UL2OW7.js';import {a as a$1,c,d as d$1,h,e}from'./chunk-5L2VS3BN.js';import {a}from'./chunk-HOZDD6PW.js';import {randomUUID}from'crypto';import {mkdir,lstat,realpath,writeFile,rename,rm,readFile}from'fs/promises';import p from'path';import {fileURLToPath}from'url';import F from'zlib';import {VK_FORMAT_R16G16B16A16_SFLOAT,KHR_SUPERCOMPRESSION_NONE,read,KHR_SUPERCOMPRESSION_ZSTD,write}from'ktx-parse';var N="/__three-blocks/devtools/environment-bake",Q="/__three-blocks/devtools/environment-bake/upload",T="virtual:three-blocks-devtools/environment-bake.ts",O=`\0${T}`,q=`/@id/__x00__${T}`,ee="src/assets/environment/room-environment.pmrem.ktx2",_=128*1024*1024,te=1;async function re(){try{let[e,r]=await Promise.all([import('playwright'),import('vite')]);return {chromium:e.chromium,createServer:r.createServer}}catch(e){throw new Error('Environment baking requires the optional "playwright" and "vite" packages. Install both in the project and run `npx playwright install chromium`.',{cause:e})}}a(re,"loadEnvironmentBakeBrowserTools");function j(e,r,t,n,o){let d=e??o;if(!Number.isSafeInteger(d)||d<t||d>n)throw new Error(`${r} must be an integer in ${t}...${n}.`);return d}a(j,"boundedInteger");function V(e){let r=j(e,"Environment cube size",16,1024,256);if((r&r-1)!==0)throw new Error("Environment cube size must be a power of two.");return r}a(V,"validateEnvironmentCubeSize");function ne(){return F}a(ne,"zstdFunctions");function oe(e){if(!/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,63}$/u.test(e))throw new Error("Browser reported an invalid Three.js revision.");return e}a(oe,"boundedThreeRevision");function ie(e){if(e.vkFormat!==VK_FORMAT_R16G16B16A16_SFLOAT)throw new Error("RoomEnvironment bake must be RGBA16F KTX2.");if(e.typeSize!==2)throw new Error("RoomEnvironment RGBA16F KTX2 must use a two-byte component type.");if(e.supercompressionScheme!==KHR_SUPERCOMPRESSION_NONE)throw new Error("Browser RoomEnvironment KTX2 must be uncompressed before deterministic encoding.");if(!Number.isSafeInteger(e.pixelWidth)||e.pixelWidth<=0||e.pixelWidth>8192||!Number.isSafeInteger(e.pixelHeight)||e.pixelHeight<=0||e.pixelHeight>8192||e.pixelDepth!==0||e.layerCount!==0||e.faceCount!==1||e.levels.length!==1||e.levels[0]===void 0)throw new Error("RoomEnvironment KTX2 has invalid CubeUV dimensions or topology.");let r=e.pixelWidth*e.pixelHeight*8;if(!Number.isSafeInteger(r)||r>_)throw new Error("RoomEnvironment KTX2 decoded payload exceeds the safety limit.");let t=e.levels[0],n=r+e.pixelHeight*256;if(t.levelData.byteLength<r||t.levelData.byteLength>n||t.levelData.byteLength%8!==0||t.uncompressedByteLength!==t.levelData.byteLength)throw new Error(`RoomEnvironment KTX2 level byte count ${t.levelData.byteLength} is outside the bounded RGBA16F CubeUV layout.`);return e.levels.map(o=>new Uint8Array(o.levelData))}a(ie,"validateRawContainer");function ae(e,r){return e.byteLength===r.byteLength&&Buffer.from(e).equals(Buffer.from(r))}a(ae,"sameBytes");function se(e,r){let t=V(r.cubeSize),n=oe(r.threeRevision);if(e.byteLength===0||e.byteLength>a$1.texture)throw new Error("RoomEnvironment KTX2 input exceeds the bounded texture size.");let o=read(e),d=ie(o),m=r.compression??"zstd",c$1=ne(),f=F.constants.ZSTD_c_compressionLevel;if(m==="zstd"&&(c$1.zstdCompressSync===void 0||c$1.zstdDecompressSync===void 0||f===void 0))throw new Error("This Node.js runtime does not provide deterministic Zstandard support; use --no-zstd explicitly to opt out.");if(o.supercompressionScheme=m==="zstd"?KHR_SUPERCOMPRESSION_ZSTD:KHR_SUPERCOMPRESSION_NONE,o.levelCount=d.length,o.levels=d.map(a=>{let l=m==="zstd"?c$1.zstdCompressSync?.(a,{params:{[f]:19}}):void 0;return {levelData:l===void 0?a:new Uint8Array(l.buffer,l.byteOffset,l.byteLength),uncompressedByteLength:a.byteLength}}),m==="zstd")for(let a of o.dataFormatDescriptor)a.bytesPlane=[0,0,0,0,0,0,0,0];o.keyValue={KTXorientation:"rd",KTXwriter:`three-blocks RoomEnvironment \xB7 three r${n}`};let u=write(o,{keepWriter:true});if(u.byteLength===0||u.byteLength>a$1.texture)throw new Error("Encoded RoomEnvironment KTX2 exceeds the bounded texture size.");let i=read(u);if(i.vkFormat!==VK_FORMAT_R16G16B16A16_SFLOAT||i.pixelWidth!==o.pixelWidth||i.pixelHeight!==o.pixelHeight||i.supercompressionScheme!==o.supercompressionScheme||i.keyValue.KTXorientation!=="rd"||i.levels.length!==d.length)throw new Error("RoomEnvironment KTX2 header failed round-trip validation.");for(let a=0;a<i.levels.length;a+=1){let l=i.levels[a],g=d[a];if(l===void 0||g===void 0)throw new Error(`RoomEnvironment KTX2 level ${a} is missing after round-trip.`);let R=m==="zstd"?c$1.zstdDecompressSync?.(l.levelData):l.levelData;if(R===void 0||l.uncompressedByteLength!==g.byteLength||!ae(R,g))throw new Error(`RoomEnvironment KTX2 level ${a} failed byte-for-byte round-trip validation.`)}let h=d.reduce((a,l)=>a+l.byteLength,0);return {bytes:u,metadata:{compression:m,cubeSize:t,format:"RGBA16F CubeUVReflectionMapping",height:i.pixelHeight,rawBytes:h,sha256:c(u),three:n,version:te,width:i.pixelWidth}}}a(se,"encodeRoomEnvironmentKtx2");var S=class{static{a(this,"BakeInbox");}promise;#t=a(()=>{},"#resolve");#r=a(()=>{},"#reject");#e=false;constructor(){this.promise=new Promise((r,t)=>{this.#t=r,this.#r=t;});}receive(r){return this.#e?false:(this.#e=true,this.#t(r),true)}reject(r){this.#e||(this.#e=true,this.#r(r));}};function ue(e){if(e.url!==void 0)try{return new URL(e.url,"http://three-blocks.invalid").pathname}catch{return}}a(ue,"requestPath");function y(e,r,t=""){e.statusCode=r,e.setHeader("Content-Type",t.startsWith("<!")?"text/html; charset=utf-8":"text/plain; charset=utf-8"),e.setHeader("Cache-Control","no-store"),e.end(t);}a(y,"respond");function de(e,r){return {name:"three-blocks:environment-bake",enforce:"post",resolveId(t){return t===T?O:void 0},load(t){return t===O?r:void 0},configureServer(t){t.middlewares.use((n,o,d)=>{let m=ue(n);if(m===N&&(n.method==="GET"||n.method==="HEAD")){let a=n.method==="HEAD"?"":`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Three Blocks environment bake</title></head><body><canvas id="three-blocks-environment-baker" width="1" height="1"></canvas><script type="module" src="${q}"></script></body></html>`;y(o,200,a);return}if(m!==Q)return d();if(n.method!=="POST"){y(o,405,"POST required");return}let c=n.headers["content-type"];if(typeof c!="string"||!c.toLowerCase().startsWith("image/ktx2")){y(o,415,"image/ktx2 required");return}let f=Number(n.headers["content-length"]??0);if(Number.isFinite(f)&&f>_){y(o,413,"Bake payload exceeds 128 MiB");return}let u=[],i=0,h=false;n.on("data",a=>{i+=a.byteLength,i>_?h=true:u.push(a);}),n.on("error",a=>e.reject(a)),n.on("end",()=>{if(h){y(o,413,"Bake payload exceeds 128 MiB"),e.reject(new Error("RoomEnvironment bake upload exceeded 128 MiB."));return}let a=n.headers["x-three-revision"];if(typeof a!="string"){y(o,400,"x-three-revision required"),e.reject(new Error("RoomEnvironment upload omitted the Three.js revision."));return}let l=e.receive({bytes:new Uint8Array(Buffer.concat(u)),threeRevision:a});y(o,l?204:409,l?"":"Bake upload already received");});});}}}a(de,"bakePlugin");async function me(){let e=p.dirname(fileURLToPath(import.meta.url)),r=[p.join(e,"browser","environment-bake.js"),p.join(e,"browser","environment-bake.ts")];for(let t of r)if(await d$1(t))return (await h(t,a$1.semanticInput,"Environment bake browser entry")).data.toString("utf8");throw new Error("The separately built environment bake browser entry is missing.")}a(me,"browserEntrySource");function ce(e){return new Promise((r,t)=>{e.on("pageerror",n=>{a$2(n.message)||t(n);}),e.on("console",n=>{n.type()==="error"&&!a$2(n.text())&&t(new Error(n.text()));});})}a(ce,"pageFailure");async function le(e,r){await e.waitForFunction(()=>globalThis.__THREE_BLOCKS_ROOM_ENVIRONMENT_BAKE__!==void 0,void 0,{timeout:Math.min(r,3e4)});let t=await e.evaluate(()=>globalThis.__THREE_BLOCKS_ROOM_ENVIRONMENT_BAKE__);if(!t||typeof t!="object"||Reflect.get(t,"ok")!==true){let n=t&&typeof t=="object"?Reflect.get(t,"error"):void 0;throw new Error(typeof n=="string"?n:"Browser RoomEnvironment bake did not report success.")}}a(le,"readBrowserBakeResult");var pe=a(async e=>{let{chromium:r,createServer:t}=await re(),n=new S,o,d$1,m,c,f=false;try{let u=await me();o=await t({root:e.root,configFile:!1,logLevel:"silent",optimizeDeps:{noDiscovery:!0},plugins:[de(n,u)],server:{host:"127.0.0.1",port:0,strictPort:!1}}),await o.listen();let i=o.httpServer?.address();if(!i||typeof i=="string")throw new Error("Environment bake Vite server has no ephemeral TCP address.");d$1=await r.launch({headless:d(e.headed),args:[...b()]}),m=await d$1.newContext({viewport:{width:320,height:240}});let h=await m.newPage(),a=ce(h),l=new Promise((R,H)=>{c=setTimeout(()=>H(new Error(`RoomEnvironment bake timed out after ${e.timeoutMs}ms.`)),e.timeoutMs),c.unref();});await h.goto(`http://127.0.0.1:${i.port}${N}?size=${e.size}`,{waitUntil:"domcontentloaded",timeout:Math.min(e.timeoutMs,3e4)});let g=await Promise.race([n.promise,a,l]);return await le(h,e.timeoutMs),g}catch(u){throw f=true,n.reject(u instanceof Error?u:new Error(String(u))),await n.promise.catch(()=>{}),u}finally{c&&clearTimeout(c);let u=[];if(await m?.close().catch(i=>u.push(`context: ${i instanceof Error?i.message:String(i)}`)),await d$1?.close().catch(i=>u.push(`browser: ${i instanceof Error?i.message:String(i)}`)),await o?.close().catch(i=>u.push(`Vite: ${i instanceof Error?i.message:String(i)}`)),!f&&u.length>0)throw new Error(`RoomEnvironment cleanup failed (${u.join("; ")}).`)}},"captureRoomEnvironment");function fe(e$1,r){let t=r??ee;if(p.isAbsolute(t)||t.length===0||t.length>2048||/[\u0000-\u001f\u007f]/u.test(t)||!t.endsWith(".ktx2"))throw new Error("Environment output must be a bounded project-relative .ktx2 path.");let n=p.resolve(e$1,t);if(!e(e$1,n)||n===e$1)throw new Error("Environment output escapes the project root.");return {asset:n,metadata:`${n.slice(0,-5)}.json`}}a(fe,"outputPaths");async function he(e$1,r){let t=p.relative(e$1,r);if(t==="")return;let n=e$1;for(let d of t.split(p.sep)){n=p.join(n,d),await d$1(n)||await mkdir(n);let m=await lstat(n);if(m.isSymbolicLink()||!m.isDirectory())throw new Error(`Environment output parent is not a real directory: ${n}.`)}let o=await realpath(r);if(!e(e$1,o))throw new Error("Environment output parent resolves outside the project root.")}a(he,"ensureSafeParent");async function M(e){if(!await d$1(e))return;let r=await lstat(e);if(r.isSymbolicLink()||!r.isFile())throw new Error(`Environment output target must be a regular file: ${e}.`)}a(M,"validateOutputTarget");async function ve(e,r,t,n){await Promise.all([M(e),M(t)]);let o=`${process.pid}-${randomUUID()}`,d=p.join(p.dirname(e),`.${p.basename(e)}.${o}.tmp`),m=p.join(p.dirname(t),`.${p.basename(t)}.${o}.tmp`),c=`${d}.backup`,f=`${m}.backup`,u=false,i=false,h=false,a=false;try{await Promise.all([writeFile(d,r,{flag:"wx"}),writeFile(m,n,{encoding:"utf8",flag:"wx"})]),await d$1(e)&&(await rename(e,c),u=!0),await d$1(t)&&(await rename(t,f),i=!0),await rename(d,e),h=!0,await rename(m,t),a=!0,await Promise.all([rm(c,{force:!0}),rm(f,{force:!0})]);}catch(l){throw a&&await rm(t,{force:true}),h&&await rm(e,{force:true}),i&&await rename(f,t),u&&await rename(c,e),l}finally{await Promise.all([rm(d,{force:true}),rm(m,{force:true}),rm(c,{force:true}),rm(f,{force:true})]);}}a(ve,"writeAtomicPair");function U(e,r){return p.relative(e,r).split(p.sep).join("/")}a(U,"portableRelative");async function _e(e){let r=await realpath(e.root),t=V(e.size??256),n=j(e.timeoutMs,"Environment bake timeoutMs",1e3,15*6e4,24e4),o=fe(r,e.output);await he(r,p.dirname(o.asset));let m=await(e.capture??pe)({root:r,size:t,timeoutMs:n,headed:e.headed===true}),c$1=se(m.bytes,{cubeSize:t,threeRevision:m.threeRevision,compression:e.compression??"zstd"}),f=`${JSON.stringify(c$1.metadata,null,2)}
|
|
3
|
+
`;await ve(o.asset,c$1.bytes,o.metadata,f);let u=await readFile(o.asset);if(c(u)!==c$1.metadata.sha256)throw new Error("Committed RoomEnvironment checksum does not match metadata.");return {schemaVersion:1,command:"environment bake",output:U(r,o.asset),metadataOutput:U(r,o.metadata),bytes:c$1.bytes.byteLength,metadata:c$1.metadata}}a(_e,"bakeRoomEnvironment");function ye(e){if(e<1e3)return `${e} B`;let r=e/1e3;return `${r>=100?Math.round(r):r.toFixed(1)} kB`}a(ye,"formatBytes");function Se(e){return [`\u2713 Environment ${e.metadata.width}\xD7${e.metadata.height} \xB7 CubeUV ${e.metadata.cubeSize}px \xB7 RGBA16F ${e.metadata.compression}`,` Output ${e.output} \xB7 ${ye(e.bytes)}`,` Checksum ${e.metadata.sha256}`].join(`
|
|
4
|
+
`)}a(Se,"formatEnvironmentBakeReport");export{_e as bakeRoomEnvironment,pe as captureRoomEnvironment,se as encodeRoomEnvironmentKtx2,Se as formatEnvironmentBakeReport,V as validateEnvironmentCubeSize};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { PrecompiledManifest } from 'three-blocks/shaders';
|
|
2
|
-
export { A as AppliedShaderProviderTransform, a as ApplyShaderProviderTransformOptions, S as SHADER_CAPTURE_CLIENT_ID, b as ShaderCaptureTransformOptions, c as ShaderProviderTransform, d as ShaderProviderTransformOptions, e as ShaderProviderTransformStatus, f as applyShaderProviderTransform, g as assertShaderProviderTransform, h as createShaderProviderTransform } from './shader-transform-
|
|
2
|
+
export { A as AppliedShaderProviderTransform, a as ApplyShaderProviderTransformOptions, S as SHADER_CAPTURE_CLIENT_ID, b as ShaderCaptureTransformOptions, c as ShaderProviderTransform, d as ShaderProviderTransformOptions, e as ShaderProviderTransformStatus, f as applyShaderProviderTransform, g as assertShaderProviderTransform, h as createShaderProviderTransform } from './shader-transform-D160zMyt.js';
|
|
3
3
|
import 'vite';
|
|
4
4
|
|
|
5
5
|
type ArtifactState = 'fresh' | 'pending';
|
|
@@ -37,6 +37,7 @@ interface ShaderCoverage {
|
|
|
37
37
|
readonly compute: number;
|
|
38
38
|
}
|
|
39
39
|
interface ShaderSceneReceipt {
|
|
40
|
+
readonly backend?: 'webgpu' | 'webgl';
|
|
40
41
|
readonly artifact: string;
|
|
41
42
|
readonly artifactHash: string;
|
|
42
43
|
/** Path relative to the configured public directory. */
|
|
@@ -64,6 +65,7 @@ interface ShaderReceiptV2 {
|
|
|
64
65
|
readonly name: '@three-blocks/devtools';
|
|
65
66
|
readonly version: string;
|
|
66
67
|
readonly compatibility: string;
|
|
68
|
+
readonly compatibilities?: Partial<Readonly<Record<'webgpu' | 'webgl', string>>>;
|
|
67
69
|
readonly transform: number;
|
|
68
70
|
readonly address: number;
|
|
69
71
|
readonly recipe: number;
|
|
@@ -171,10 +173,14 @@ declare function inspectTextAtlases(root: string, configurationPath?: string): P
|
|
|
171
173
|
declare const SHADER_TOOL_CONFIG_FILE = "three-blocks.shaders.json";
|
|
172
174
|
declare const SHADER_ARTIFACT_DIRECTORY = ".three-blocks/shaders";
|
|
173
175
|
declare const SHADER_PARITY_DIRECTORY = ".three-blocks/shaders/parity";
|
|
176
|
+
type ShaderBackend = 'webgpu' | 'webgl';
|
|
177
|
+
type ShaderBackendSelection = ShaderBackend | 'both';
|
|
174
178
|
interface ShaderSceneConfig {
|
|
175
179
|
readonly key: string;
|
|
176
180
|
/** Project-relative browser URL, including an optional query string. */
|
|
177
181
|
readonly url: string;
|
|
182
|
+
/** Restrict this scene to one renderer backend. Absent means every configured backend. */
|
|
183
|
+
readonly backend?: ShaderBackend;
|
|
178
184
|
readonly requiresText: boolean;
|
|
179
185
|
/** Optional authoritative project-relative semantic inputs for this scene. */
|
|
180
186
|
readonly inputs?: readonly string[];
|
|
@@ -204,6 +210,8 @@ interface ShaderReadinessConfig {
|
|
|
204
210
|
}
|
|
205
211
|
interface ShaderToolConfig {
|
|
206
212
|
readonly schemaVersion: 1;
|
|
213
|
+
/** Backends captured and release-gated by default. Absent means both. */
|
|
214
|
+
readonly backend?: ShaderBackendSelection;
|
|
207
215
|
readonly scenes: readonly ShaderSceneConfig[];
|
|
208
216
|
readonly settleFrames: number;
|
|
209
217
|
/** Total post-readiness settle ceiling. Defaults to 30 seconds. */
|
|
@@ -211,6 +219,14 @@ interface ShaderToolConfig {
|
|
|
211
219
|
/** Chromium is relaunched after this many isolated capture contexts. Defaults to 8. */
|
|
212
220
|
readonly browserRelaunchScenes?: number;
|
|
213
221
|
readonly timeoutMs: number;
|
|
222
|
+
/**
|
|
223
|
+
* Hard ceiling for one capture or parity observation when the page keeps
|
|
224
|
+
* showing progress (new registered builds, advancing parity frames, or a
|
|
225
|
+
* main thread busy compiling). `timeoutMs` remains the idle budget — a lane
|
|
226
|
+
* with no progress still fails after `timeoutMs`. Defaults to `timeoutMs`,
|
|
227
|
+
* which disables extension entirely.
|
|
228
|
+
*/
|
|
229
|
+
readonly maxTimeoutMs?: number;
|
|
214
230
|
readonly viewport: {
|
|
215
231
|
readonly width: number;
|
|
216
232
|
readonly height: number;
|
|
@@ -247,7 +263,7 @@ declare function ensureShaderToolConfig(root: string): Promise<EnsuredShaderTool
|
|
|
247
263
|
/** Published devtools protocol/package version. Kept dependency-free for instant CLI startup. */
|
|
248
264
|
declare const SHADER_DEVTOOLS_VERSION: "0.1.0";
|
|
249
265
|
|
|
250
|
-
declare const SHADER_PROVIDER_TRANSFORM_VERSION:
|
|
266
|
+
declare const SHADER_PROVIDER_TRANSFORM_VERSION: 60;
|
|
251
267
|
declare const SHADER_LOCAL_TIMING_FILE: "timing.local.json";
|
|
252
268
|
declare const SHADER_COMMITTED_TIMING_FILE: "timing.json";
|
|
253
269
|
declare const SHADER_PARITY_EVIDENCE_FILE: "parity.json";
|
|
@@ -347,7 +363,7 @@ interface ShaderCaptureProvenance {
|
|
|
347
363
|
readonly adapter: string;
|
|
348
364
|
readonly features: readonly string[];
|
|
349
365
|
}
|
|
350
|
-
interface ShaderCapturePayload extends Pick<PrecompiledManifest, 'modules' | 'nodes' | 'layouts' | 'attributePlans' | 'updatePlans' | 'requirementPlans' | 'states' | 'entries'> {
|
|
366
|
+
interface ShaderCapturePayload extends Pick<PrecompiledManifest, 'modules' | 'nodes' | 'layouts' | 'attributePlans' | 'updatePlans' | 'requirementPlans' | 'states' | 'entries' | 'fallbacks'> {
|
|
351
367
|
readonly protocolVersion: 2;
|
|
352
368
|
readonly compatibility: string;
|
|
353
369
|
readonly scene: string;
|
|
@@ -363,6 +379,7 @@ interface ShaderCapturePayload extends Pick<PrecompiledManifest, 'modules' | 'no
|
|
|
363
379
|
}
|
|
364
380
|
interface ValidatedShaderCapture {
|
|
365
381
|
readonly scene: string;
|
|
382
|
+
readonly backend: ShaderBackend;
|
|
366
383
|
readonly manifest: PrecompiledManifest;
|
|
367
384
|
readonly skipped: readonly ShaderSkippedBuild[];
|
|
368
385
|
readonly stats: ShaderCaptureStats;
|
|
@@ -372,6 +389,7 @@ interface ValidatedShaderCapture {
|
|
|
372
389
|
}
|
|
373
390
|
interface ValidateShaderCaptureOptions {
|
|
374
391
|
readonly scene: string;
|
|
392
|
+
readonly backend?: ShaderBackend;
|
|
375
393
|
readonly runtime: InstalledShaderRuntime;
|
|
376
394
|
}
|
|
377
395
|
declare function shaderCoverage(manifest: PrecompiledManifest): ShaderCoverage;
|
|
@@ -399,6 +417,7 @@ declare function writeShaderTimingTwins(root: string, scenes: Readonly<Record<st
|
|
|
399
417
|
interface WriteShaderArtifactsOptions {
|
|
400
418
|
readonly root: string;
|
|
401
419
|
readonly scenes: readonly ShaderSceneConfig[];
|
|
420
|
+
readonly backends?: readonly ShaderBackend[];
|
|
402
421
|
readonly captures: ReadonlyMap<string, ValidatedShaderCapture>;
|
|
403
422
|
readonly runtime: InstalledShaderRuntime;
|
|
404
423
|
readonly inputs: ReadonlyMap<string, Readonly<Record<string, string>>>;
|
|
@@ -427,6 +446,12 @@ interface ShaderBrowserObservation {
|
|
|
427
446
|
readonly transform: number;
|
|
428
447
|
readonly readiness: ShaderBrowserReadiness;
|
|
429
448
|
readonly stats: ShaderCaptureStats;
|
|
449
|
+
/**
|
|
450
|
+
* Tail of the lane's shader-demand journal (builds, skips, provider probes
|
|
451
|
+
* with lookup-time fingerprints). Diagnostic-only: consumed by identity-drift
|
|
452
|
+
* failure messages, never by gates.
|
|
453
|
+
*/
|
|
454
|
+
readonly demands?: readonly Record<string, unknown>[];
|
|
430
455
|
/** Application animation frame frozen for deterministic live/precompiled parity. */
|
|
431
456
|
readonly frame: number;
|
|
432
457
|
/** First observable rendered frame, before configured settling. */
|
|
@@ -439,10 +464,10 @@ interface ShaderPublishedObservation extends ShaderBrowserObservation {
|
|
|
439
464
|
readonly beforeScreenshot: Buffer;
|
|
440
465
|
}
|
|
441
466
|
interface ShaderBrowserDriver {
|
|
442
|
-
capture(scene: ShaderSceneConfig, config: ShaderToolConfig): Promise<unknown>;
|
|
443
|
-
observe(scene: ShaderSceneConfig, mode: 'live' | 'precompiled', config: ShaderToolConfig, targetFrame?: number): Promise<ShaderBrowserObservation>;
|
|
467
|
+
capture(scene: ShaderSceneConfig, config: ShaderToolConfig, backend?: ShaderBackend): Promise<unknown>;
|
|
468
|
+
observe(scene: ShaderSceneConfig, mode: 'live' | 'precompiled', config: ShaderToolConfig, targetFrame?: number, backend?: ShaderBackend): Promise<ShaderBrowserObservation>;
|
|
444
469
|
/** Observe the published route with strict precompiled telemetry enabled. */
|
|
445
|
-
observePublished(scene: ShaderSceneConfig, config: ShaderToolConfig): Promise<ShaderPublishedObservation>;
|
|
470
|
+
observePublished(scene: ShaderSceneConfig, config: ShaderToolConfig, backend?: ShaderBackend): Promise<ShaderPublishedObservation>;
|
|
446
471
|
timingEnvironment?(): PromiseLike<ShaderTimingEnvironment> | ShaderTimingEnvironment;
|
|
447
472
|
close(): Promise<void>;
|
|
448
473
|
}
|
|
@@ -499,6 +524,7 @@ declare function readInstalledShaderRuntime(root: string): Promise<InstalledShad
|
|
|
499
524
|
type ShaderMatrixState = 'fresh' | 'stale' | 'invalid' | 'missing';
|
|
500
525
|
interface ShaderSceneArtifactStatus {
|
|
501
526
|
readonly scene: string;
|
|
527
|
+
readonly backend: ShaderBackend;
|
|
502
528
|
readonly state: ShaderMatrixState;
|
|
503
529
|
readonly reason: string;
|
|
504
530
|
readonly coverage?: ShaderCoverage;
|
|
@@ -525,7 +551,7 @@ interface ShaderMatrixStatus {
|
|
|
525
551
|
readonly timing?: ShaderTiming;
|
|
526
552
|
}
|
|
527
553
|
/** Inspect all configured manifests without launching Vite, a browser, or a GPU. */
|
|
528
|
-
declare function inspectShaderMatrix(start?: string, runtimeOverride?: InstalledShaderRuntime): Promise<ShaderMatrixStatus>;
|
|
554
|
+
declare function inspectShaderMatrix(start?: string, runtimeOverride?: InstalledShaderRuntime, backendOverride?: ShaderBackendSelection): Promise<ShaderMatrixStatus>;
|
|
529
555
|
|
|
530
556
|
interface CaptureShadersOptions {
|
|
531
557
|
readonly start?: string;
|
|
@@ -541,6 +567,7 @@ interface CaptureShadersOptions {
|
|
|
541
567
|
/** Attach to an already-running transformed application. */
|
|
542
568
|
readonly url?: string;
|
|
543
569
|
readonly headed?: boolean;
|
|
570
|
+
readonly backend?: ShaderBackendSelection;
|
|
544
571
|
readonly ifStale?: boolean;
|
|
545
572
|
readonly attempts?: number;
|
|
546
573
|
/** Also write a shareable, hardware-labeled single-capture timing estimate. */
|
|
@@ -552,6 +579,7 @@ interface CaptureShadersOptions {
|
|
|
552
579
|
}
|
|
553
580
|
interface CaptureSceneResult {
|
|
554
581
|
readonly scene: string;
|
|
582
|
+
readonly backend: ShaderBackend;
|
|
555
583
|
readonly attempts: number;
|
|
556
584
|
readonly coverage: ShaderCoverage;
|
|
557
585
|
readonly skipped: number;
|
|
@@ -596,6 +624,7 @@ interface TestShadersOptions {
|
|
|
596
624
|
readonly serve?: string;
|
|
597
625
|
readonly url?: string;
|
|
598
626
|
readonly headed?: boolean;
|
|
627
|
+
readonly backend?: ShaderBackendSelection;
|
|
599
628
|
readonly skipBrowser?: boolean;
|
|
600
629
|
/** Measured live/precompiled pairs after one discarded warmup. Defaults to 5. */
|
|
601
630
|
readonly runs?: number;
|
|
@@ -610,6 +639,7 @@ interface TestShadersOptions {
|
|
|
610
639
|
}
|
|
611
640
|
interface ShaderSceneTestResult {
|
|
612
641
|
readonly scene: string;
|
|
642
|
+
readonly backend: ShaderBackend;
|
|
613
643
|
readonly coverage: ShaderCoverage;
|
|
614
644
|
readonly live: Omit<ShaderBrowserObservation, 'firstFrameScreenshot' | 'screenshot'>;
|
|
615
645
|
readonly precompiled: Omit<ShaderBrowserObservation, 'firstFrameScreenshot' | 'screenshot'>;
|
|
@@ -895,7 +925,7 @@ declare const DOCUMENTED_BROWSER_NOISE: readonly [{
|
|
|
895
925
|
readonly pattern: RegExp;
|
|
896
926
|
}];
|
|
897
927
|
declare function isDocumentedBrowserNoise(message: string): boolean;
|
|
898
|
-
/** Chromium launch flags used by public WebGPU
|
|
928
|
+
/** Chromium launch flags used by public WebGPU tools. */
|
|
899
929
|
declare function webgpuBrowserArgs(environment?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): readonly string[];
|
|
900
930
|
/** Lavapipe is most reliable in Chromium's headful mode under Xvfb. */
|
|
901
931
|
declare function webgpuBrowserHeadless(headed?: boolean, environment?: NodeJS.ProcessEnv): boolean;
|