@three-blocks/devtools 1.0.0-alpha.194.g5e3cc4492aa3 → 1.0.0-alpha.208.g664cb7c258f9
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 +22 -4
- package/dist/{browser-smoke-MKYIJVVA.js → browser-smoke-FPR2OZ37.js} +1 -1
- package/dist/{chunk-G65XQ3DF.js → chunk-5RSAQ74G.js} +3 -3
- package/dist/chunk-E6JYGHBW.js +76 -0
- package/dist/chunk-HLYATKSG.js +93 -0
- package/dist/{chunk-FP3ZS4BD.js → chunk-KLGY4Q2M.js} +1 -1
- package/dist/cli.js +8 -8
- package/dist/index.js +3 -3
- package/dist/{shader-browser-IUZ6CO3W.js → shader-browser-SZJLKYYT.js} +1 -1
- package/dist/{shader-browser-C2YETRGE.js → shader-browser-ZCKOOMQ3.js} +1 -1
- package/dist/{shader-watch-EI5D7GCN.js → shader-watch-VWJGRJ23.js} +1 -1
- package/dist/{shader-workflow-AAH3FM4U.js → shader-workflow-I2RA75GO.js} +1 -1
- package/dist/{status-76TXXSRT.js → status-GATTL2MS.js} +1 -1
- package/package.json +3 -3
- package/dist/chunk-LZX5NCGL.js +0 -76
- package/dist/chunk-QMP2MC4S.js +0 -93
package/CHANGELOG.md
CHANGED
|
@@ -1,12 +1,28 @@
|
|
|
1
1
|
# @three-blocks/devtools
|
|
2
2
|
|
|
3
|
-
## 1.0.0-alpha.
|
|
3
|
+
## 1.0.0-alpha.208.g664cb7c258f9
|
|
4
|
+
|
|
5
|
+
- Tools: Baked Motion depth encoding no longer treats an unset quality value as lossless.
|
|
4
6
|
|
|
5
7
|
- Tools: Mesh to Splat now installs beside administrator-owned engine caches on Windows.
|
|
6
8
|
|
|
7
9
|
- Tools: Mesh to Splat, OAV, and VAV are now installable from the Blender hub.
|
|
8
10
|
|
|
9
|
-
-
|
|
11
|
+
- Website: The examples gallery now shows 22 scenes while four examples are being remade.
|
|
12
|
+
|
|
13
|
+
- Website: Gaussian Splat Morph now fits comfortably on mobile screens.
|
|
14
|
+
|
|
15
|
+
- Website: 3D smoke now responds to touch and starts inside live documentation previews.
|
|
16
|
+
|
|
17
|
+
- Website: Examples stay interactive with arrow navigation and source-only controls.
|
|
18
|
+
|
|
19
|
+
- Tools: The presentation now plays real examples and leads with free access and lifetime licensing.
|
|
20
|
+
|
|
21
|
+
- Tools: The presentation Studio now starts on port 3001.
|
|
22
|
+
|
|
23
|
+
- Devtools: Fresh scene receipts now precompile automatically while edited scenes stay live.
|
|
24
|
+
|
|
25
|
+
- Website: Baked Motion controls now stay compact on narrow and short screens.
|
|
10
26
|
|
|
11
27
|
- Website: Spotlight Type no longer flashes blank while its canvas text initializes.
|
|
12
28
|
|
|
@@ -20,11 +36,13 @@
|
|
|
20
36
|
|
|
21
37
|
- Devtools: Compute shaders now warm asynchronously and ocean shaders hydrate without setup.
|
|
22
38
|
|
|
39
|
+
- Starter: The starter now offers only Minimal and the MSDF-powered Website.
|
|
40
|
+
|
|
23
41
|
- Starter: Website demos now rebuild with the current Devtools during local development.
|
|
24
42
|
|
|
25
43
|
- Tools: Example parity now reuses evidence when captures and execution contracts are unchanged.
|
|
26
44
|
|
|
27
|
-
- Tools: Example optimization now
|
|
45
|
+
- Tools: Example optimization now retries browser startup and times out stalled parity checks.
|
|
28
46
|
|
|
29
47
|
- Website: Mobile navigation now opens from a responsive menu on every page.
|
|
30
48
|
|
|
@@ -46,7 +64,7 @@
|
|
|
46
64
|
|
|
47
65
|
- Website: Release pages show the exact version with a short changelog.
|
|
48
66
|
|
|
49
|
-
- Packages: Built from `
|
|
67
|
+
- Packages: Built from `664cb7c258f9`.
|
|
50
68
|
|
|
51
69
|
|
|
52
70
|
This changelog is generated from Changesets.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {b,a as a$3}from'./chunk-
|
|
2
|
+
import {b,a as a$3}from'./chunk-KLGY4Q2M.js';import'./chunk-76WRV5MZ.js';import'./chunk-JMS5NTP7.js';import'./chunk-5RSAQ74G.js';import'./chunk-HLYATKSG.js';import {a as a$2,b as b$1,c as c$1}from'./chunk-NE7SC2BX.js';import'./chunk-ZT6T2W4B.js';import'./chunk-NEWSG5RX.js';import {a as a$1}from'./chunk-ZDNZCQUQ.js';import {j,a as a$4,c}from'./chunk-5L2VS3BN.js';import {a}from'./chunk-HOZDD6PW.js';import {randomUUID}from'crypto';import {mkdir,realpath,writeFile,rename,rm}from'fs/promises';import F from'path';import {PNG}from'pngjs';var ye="virtual:three-blocks-devtools/browser-smoke",ve=`\0${ye}`,Ke=`/@id/__x00__${ye}`,Be=9e4;async function Ee(){try{let[e,r]=await Promise.all([import('playwright'),import('vite')]);return {chromium:e.chromium,vite:r}}catch(e){throw new Error('Browser smoke and preview require the optional "playwright" and "vite" packages. Install both in the project and run `npx playwright install chromium`.',{cause:e})}}a(Ee,"loadBrowserSmokeTools");function V(e,r,o,t,n){let a=e??n;if(!Number.isSafeInteger(a)||a<o||a>t)throw new Error(`${r} must be an integer in ${o}...${t}.`);return a}a(V,"boundedInteger");function _e(e,r,o,t,n){let a=e??n;if(!Number.isFinite(a)||a<o||a>t)throw new Error(`${r} must be a finite number in ${o}...${t}.`);return a}a(_e,"boundedRatio");function Pe(e){let r=e??"/";if(r.length===0||r.length>2048||/[\u0000-\u001f\u007f]/u.test(r))throw new Error("Browser smoke route must be a bounded project URL.");let o=new URL(r,"http://three-blocks.invalid/");if(o.origin!=="http://three-blocks.invalid"||o.hash.length>0)throw new Error("Browser smoke route must stay within the project and have no fragment.");return `${o.pathname}${o.search}`}a(Pe,"safeRoute");function N(e,r){return e[r]===true}a(N,"booleanField");function $(e,r){if(!a$1(e)||!a$1(e.value))return {source:"missing",backend:"unknown",worker:false,workerReady:false,assetsReady:false,compileEnd:false,textEnabled:r,textReady:!r,firstFrame:false};let o=e.value,t=e.source==="public";if(t&&o.protocolVersion!==1)return {source:"public",backend:"unknown",worker:false,workerReady:false,assetsReady:false,compileEnd:false,textEnabled:r,textReady:!r,firstFrame:false};let n=a$1(o.readiness)?o.readiness:o,a=o.worker,d=t&&a$1(a)?a.offscreenCanvas===true&&a.visible===true:a===true;return {source:t?"public":"legacy",backend:t&&a$1(a)?a.offscreenCanvas===true?"OffscreenCanvas":"MainThread":a===true?"OffscreenCanvas":"unknown",worker:d,workerReady:N(n,"workerReady"),assetsReady:N(n,"assetsReady")||N(n,"loadEnd"),compileEnd:N(n,"compileEnd"),textEnabled:r,textReady:!r||N(n,"textReady"),firstFrame:N(n,"firstFrame")}}a($,"parseBrowserSmokeLifecycle");function ie(e){let r=PNG.sync.read(e),o=Math.floor(r.width*.25),t=Math.floor(r.width*.75),n=Math.floor(r.height*.25),a=Math.floor(r.height*.75),d=0,c=0;for(let f=n;f<a;f+=2)for(let p=o;p<t;p+=2){let h=(f*r.width+p)*4,l=r.data[h],i=r.data[h+1],s=r.data[h+2];l===void 0||i===void 0||s===void 0||(d+=Math.max(l,i,s),c+=1);}return c===0?0:d/c}a(ie,"screenshotLuminance");function Je(){return `
|
|
3
3
|
import * as THREE from 'three/webgpu';
|
|
4
4
|
import { createAssetLoaderRegistry, createAssetManager, createThreeAssetAdapters, defineAssets } from 'three-blocks/assets';
|
|
5
5
|
import { SceneHotReloader } from 'three-blocks/hmr';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {b,e as e$2,a as a$3,d as d$1,c as c$2,j as j$1,i as i$1,f as f$2,h as h$2,g as g$1}from'./chunk-
|
|
2
|
+
import {b,e as e$2,a as a$3,d as d$1,c as c$2,j as j$1,i as i$1,f as f$2,h as h$2,g as g$1}from'./chunk-HLYATKSG.js';import {a as a$4}from'./chunk-ZT6T2W4B.js';import {e as e$1,f,b as b$1,h as h$1,g,c as c$3}from'./chunk-NEWSG5RX.js';import {a as a$2,c as c$1}from'./chunk-ZDNZCQUQ.js';import {j,a as a$1,c,d,k,h,e,i,f as f$1}from'./chunk-5L2VS3BN.js';import {a}from'./chunk-HOZDD6PW.js';import {realpath,readdir,readFile,lstat,mkdir,writeFile}from'fs/promises';import ve from'os';import P from'path';import {SHADER_ADDRESS_SCHEMA_VERSION,SHADER_RECIPE_SCHEMA_VERSION,SHADER_HYDRATION_SCHEMA_VERSION}from'three-blocks/shaders';import {createRequire}from'module';var Pe=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".wgsl",".glsl",".vert",".frag",".json",".css"],Ie=new Set(Pe),Be=/^(?:three-blocks\.shaders\.json|(?:precompile|three-blocks\.shaders)\.config\.(?:cjs|cts|js|mjs|mts|ts))$/u,gr=/(?:^|\/)scene\.(?:cjs|cts|js|jsx|mjs|mts|ts|tsx)$/u,Sr=/\b(?:export\s+)?(?:async\s+)?function\s+createScene\b|\bcreateScene\s*=\s*(?:async\s*)?\(/u,yr=/\b(?:[A-Za-z_$][\w$]*\.)*(?:shaders|shaderCache|sceneShaders)\s*\.\s*(?:material|pipeline|compute|container)\s*\(/u,wr=/\b(import|export)(?!\s*\()\s*(type\b\s*)?(?:[^"'();]*?\bfrom\s*)?["']([^"']+)["']/gu,vr=/\bimport\s*\(\s*["']([^"']+)["']\s*\)/gu,br=/\b(?:import|export)(?!\s*\()\s*(?:[^"'();]*?\bfrom\s*)?["']([^"']+)["']|\bimport\s*\(\s*["']([^"']+)["']\s*\)/gu,Er=/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u,Oe=4096,kr="./shaders";function Ye(e,r){let t=P.relative(e,r).split(P.sep).join("/");if(t.length===0||/[\u0000-\u001f\u007f]/u.test(t))throw new Error("Semantic input has an unsafe relative path.");return t}a(Ye,"portableRelativePath");function Ce(e,r){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{throw new Error(`Shader-relevant source ${JSON.stringify(r)} is not valid UTF-8.`)}}a(Ce,"sourceText");function Ae(e,r){let t="",n="code";for(let i=0;i<e.length;i++){let s=e[i]??"",a=e[i+1]??"";if(n==="code"){if(s==="/"&&a==="/"){t+=" ",n="line-comment",i++;continue}if(s==="/"&&a==="*"){t+=" ",n="block-comment",i++;continue}if(s==="'"||s==='"'||s==="`"){n=s==="'"?"single":s==='"'?"double":"template",t+=r?s:" ";continue}t+=s;continue}if(n==="line-comment"){s===`
|
|
3
3
|
`?(t+=`
|
|
4
4
|
`,n="code"):t+=" ";continue}if(n==="block-comment"){s==="*"&&a==="/"?(t+=" ",n="code",i++):t+=s===`
|
|
5
5
|
`?`
|
|
@@ -7,8 +7,8 @@ import {b,e as e$2,a as a$3,d as d$1,c as c$2,j as j$1,i as i$1,f as f$2,h as h$
|
|
|
7
7
|
`?`
|
|
8
8
|
`:" ",s===l&&(n="code");}return t}a(Ae,"lexicalSource");function Rr(e){let r=new Set,t=Ae(e,true);for(let n of t.matchAll(wr))n[2]===void 0&&n[3]!==void 0&&r.add(n[3]);for(let n of t.matchAll(vr))n[1]!==void 0&&r.add(n[1]);return [...r].sort()}a(Rr,"importSpecifiers");function xr(e){let r=new Set;for(let t of Ae(e,true).matchAll(br)){let n=t[1]??t[2];n!==void 0&&r.add(n);}return [...r].sort()}a(xr,"runtimeSpecifiers");function Xe(e){return (e.split(/[?#]/u,1)[0]??e).replaceAll("\\","/")}a(Xe,"cleanSpecifier");function Tr(e,r,t){let n=Xe(r),i;if(n.startsWith("./")||n.startsWith("../"))i=P.posix.normalize(P.posix.join(P.posix.dirname(e),n));else if(n.startsWith("@/"))i=`src/${n.slice(2)}`;else if(n.startsWith("/src/"))i=n.slice(1);else return;if(i===".three-blocks"||i.startsWith(".three-blocks/"))return;let s=P.posix.extname(i).toLowerCase(),a=new Set([i]);if(s.length===0||!Ie.has(s)){for(let l of Pe)a.add(`${i}${l}`);for(let l of Pe)a.add(`${i}/index${l}`);}else if([".js",".mjs",".cjs",".jsx"].includes(s)){let l=i.slice(0,-s.length);for(let u of [".ts",".tsx",".mts",".cts"])a.add(`${l}${u}`);}return [...a].find(l=>t.has(l))}a(Tr,"resolveProjectImport");function $r(e,r){let t=Ae(r,false);return gr.test(e)||Sr.test(t)||yr.test(t)}a($r,"isShaderRoot");async function me(e,r){let t=await realpath(e);if(r!==void 0){let o={},h=0;for(let m of r){let b=await j(t,P.join(t,m),a$1.semanticInput,"Declared shader semantic input");if(h+=b.data.byteLength,h>a$1.semanticTotal)throw new Error("Declared shader semantic inputs exceed the total inspection size limit.");o[m]=c(b.data);}return o}let n=new Map,i=P.join(t,"src");if(await d(i))for(let o of await k(t,i,h=>Ie.has(P.extname(h).toLowerCase()))){let h=await j(t,o,a$1.semanticInput,"Shader semantic input");n.set(Ye(t,o),h.data);}for(let o of await readdir(t,{withFileTypes:true})){if(!o.isFile()||!Be.test(o.name)&&!Ie.has(P.extname(o.name).toLowerCase()))continue;let h=await j(t,P.join(t,o.name),a$1.semanticInput,Be.test(o.name)?"Shader configuration input":"Shader semantic input");n.set(o.name,h.data);}if(n.size>Oe)throw new Error(`Shader input discovery exceeds the ${Oe}-file limit.`);let s=new Set,a=new Map;for(let[o,h]of n){if(!o.includes("/")&&Be.test(o)&&s.add(o),!o.startsWith("src/"))continue;let m=Ce(h,o);a.set(o,m),$r(o,m)&&s.add(o);}if(s.size===0)throw new Error("No shader registration or scene source root was found.");let l=new Set,u=[...s].sort();for(;u.length>0;){let o=u.shift();if(o===void 0||l.has(o))continue;let h=n.get(o);if(h===void 0)continue;l.add(o);let m=a.get(o)??Ce(h,o);for(let b of Rr(m)){let x=Tr(o,b,n);x!==void 0&&!l.has(x)&&u.push(x);}u.sort();}let f=0,w={};for(let o of [...l].sort()){let h=n.get(o);if(h===void 0)throw new Error(`Shader input ${JSON.stringify(o)} disappeared during inspection.`);if(f+=h.byteLength,f>a$1.semanticTotal)throw new Error("Semantic shader inputs exceed the total inspection size limit.");w[o]=c(h);}return w}a(me,"snapshotShaderInputs");function je(e){if(typeof e=="string")return e;if(a$2(e))return je(e.import)??je(e.default)}a(je,"conditionalImportTarget");async function Ge(e,r){let t=e;for(;;){let n=P.join(t,"node_modules",...r.split("/"),"package.json");if(await d(n)){let s=await h(n,a$1.packageJson,`${r} package.json`),a=JSON.parse(s.data.toString("utf8"));if(!a$2(a)||a.name!==r||typeof a.version!="string"||!Er.test(a.version))throw new Error(`Installed ${r} package metadata is invalid.`);return {root:P.dirname(s.path),manifest:a}}let i=P.dirname(t);if(i===t)break;t=i;}throw new Error(`Cannot verify the installed ${r} package.`)}a(Ge,"findInstalledPackage");async function Mr(e$1,r){if(!a$2(r.exports))throw new Error("Installed three-blocks package has no public exports map.");let t=je(r.exports[kr]);if(t===void 0||!t.startsWith("./"))throw new Error("Installed three-blocks shader export has no import target.");let n=await realpath(e$1),i=[P.resolve(n,t)],s=new Map,a=0;for(;i.length>0;){let u=i.shift();if(u===void 0)break;let f=await h(u,a$1.semanticInput,"Three Blocks shader runtime module");if(!e(n,f.path)||f.path===n)throw new Error("Three Blocks shader runtime closure escapes its package.");let w=Ye(n,f.path);if(s.has(w))continue;if(a+=f.data.byteLength,a>a$1.semanticTotal)throw new Error("Three Blocks shader runtime closure exceeds the inspection limit.");s.set(w,c(f.data));let o=Ce(f.data,w);for(let h of xr(o)){let m=Xe(h);if(!m.startsWith("./")&&!m.startsWith("../"))continue;let b=P.resolve(P.dirname(f.path),m);if(!e(n,b))throw new Error("Three Blocks shader runtime import escapes its package.");i.push(b);}if(i.sort(),s.size+i.length>Oe)throw new Error("Three Blocks shader runtime closure exceeds the file limit.")}let l=[...s].sort((u,f)=>u[0].localeCompare(f[0])).map(([u,f])=>`${u}\0${f}`).join(`
|
|
9
9
|
`);return c(l)}a(Mr,"shaderRuntimeClosure");async function se(e){let[r,t]=await Promise.all([Ge(e,"three"),Ge(e,"three-blocks")]);return {three:String(r.manifest.version),threeBlocks:String(t.manifest.version),threeBlocksShaderClosure:await Mr(t.root,t.manifest)}}a(se,"readInstalledShaderRuntime");var Ze=4096,Pr=createRequire(import.meta.url),Qe,R=new Proxy({},{get(e,r){return Qe??=Pr("typescript"),Reflect.get(Qe,r)}});function U(e){let r=e;for(;R.isParenthesizedExpression(r)||R.isAsExpression(r)||R.isSatisfiesExpression(r)||R.isNonNullExpression(r);)r=r.expression;return r}a(U,"unwrap");function Ir(e){if(R.isIdentifier(e)||R.isStringLiteral(e)||R.isNumericLiteral(e))return e.text}a(Ir,"propertyName");function pe(e,r){let t=new Map;for(let n of e.properties){if(!R.isPropertyAssignment(n))throw new Error(`${r} may contain only static property assignments.`);let i=Ir(n.name);if(i===void 0||t.has(i))throw new Error(`${r} contains a computed or duplicate property.`);t.set(i,n.initializer);}return t}a(pe,"properties");function ge(e,r){if(e===void 0)throw new Error(`${r} is missing.`);let t=U(e);if(!R.isObjectLiteralExpression(t))throw new Error(`${r} must be a static object literal.`);return t}a(ge,"objectLiteral");function Se(e,r){if(e===void 0)throw new Error(`${r} is missing.`);let t=U(e);if(!R.isStringLiteral(t)&&!R.isNoSubstitutionTemplateLiteral(t))throw new Error(`${r} must be a string literal.`);return t.text}a(Se,"stringLiteral");function ye(e,r){if(e===void 0)throw new Error(`${r} is missing.`);let t=U(e);if(!R.isNumericLiteral(t))throw new Error(`${r} must be a numeric literal.`);return Number(t.text)}a(ye,"numericLiteral");function er(e,r){if(e===void 0)throw new Error(`${r} is missing.`);let t=U(e);if(!R.isArrayLiteralExpression(t))throw new Error(`${r} must be a static array literal.`);return t.elements}a(er,"arrayLiteral");function Or(e,r){if(e===void 0)throw new Error(`${r} is missing.`);let t=U(e);if(t.kind===R.SyntaxKind.NullKeyword)return null;if(!R.isNumericLiteral(t))throw new Error(`${r} must be null or a numeric literal.`);return Number(t.text)}a(Or,"numericOrNullLiteral");function Cr(e){return e.parseDiagnostics??[]}a(Cr,"parseDiagnostics");function rr(e,r,t,n){let i=R.createSourceFile(r,e,R.ScriptTarget.Latest,true,R.ScriptKind.TS),s=Cr(i);if(s.length>0)throw new Error(`Shader manifest is not valid TypeScript: ${R.flattenDiagnosticMessageText(s[0]?.messageText??"parse error"," ")}`);let a$1=i.statements.filter(R.isExportAssignment).filter(m=>!m.isExportEquals);if(a$1.length!==1)throw new Error("Shader manifest must contain exactly one default export.");let l=pe(ge(a$1[0]?.expression,"Shader manifest default export"),"Shader manifest"),u=l.get("version");if(u===void 0||!R.isNumericLiteral(U(u))||Number(U(u).getText(i))!==3)throw new Error("Shader manifest version must be the numeric literal 3.");if(Se(l.get("scene"),"Shader manifest scene")!==t)throw new Error(`Shader manifest scene does not match "${t}".`);if(n){if(Se(l.get("three"),"Shader manifest Three.js version")!==n.three||Se(l.get("threeBlocks"),"Shader manifest Three Blocks version")!==n.threeBlocks)throw new Error("Shader manifest runtime versions do not match its receipt.");let m=pe(ge(l.get("runtime"),"Shader manifest runtime"),"Shader manifest runtime");if(Se(m.get("id"),"Shader manifest runtime id")!==n.compatibility||ye(m.get("address"),"Shader manifest address schema")!==n.address||ye(m.get("recipe"),"Shader manifest recipe schema")!==n.recipe||ye(m.get("hydration"),"Shader manifest hydration schema")!==n.hydration)throw new Error("Shader manifest runtime compatibility schemas do not match its receipt.")}let f=pe(ge(l.get("entries"),"Shader manifest entries"),"Shader manifest entries");if(f.size===0||f.size>Ze)throw new Error(`Shader manifest must contain between 1 and ${Ze} entries.`);let w=er(l.get("modules"),"Shader manifest modules").map((m,b)=>{let x=U(m);if(!R.isStringLiteral(x)&&!R.isNoSubstitutionTemplateLiteral(x))throw new Error(`Shader manifest module ${b} must be a WGSL string literal.`);if(x.text.length===0)throw new Error(`Shader manifest module ${b} is empty.`);return x.text}),o=er(l.get("states"),"Shader manifest states").map((m,b)=>{let x=pe(ge(m,`Shader manifest state ${b}`),`Shader manifest state ${b}`),E=a(($,I)=>{let L=Or(x.get($),`Shader manifest state ${b} ${$}`);if(L===null)return false;let p=w[L];if(p===void 0||!p.includes(I))throw new Error(`Shader manifest state ${b} ${$} does not reference a ${I} module.`);return true},"moduleAt"),O=E("vertex","@vertex"),C=E("fragment","@fragment"),A=E("compute","@compute");if(A&&(O||C))throw new Error(`Shader manifest state ${b} mixes render and compute stages.`);if(!A&&!O&&!C)throw new Error(`Shader manifest state ${b} contains no shader stage.`);return {vertex:O,fragment:C,compute:A}}),h={render:0,vertex:0,fragment:0,compute:0};for(let[m,b]of f){if(m.length===0||/[\u0000-\u001f\u007f]/.test(m))throw new Error("Shader manifest contains an invalid entry key.");let x=ye(b,`Shader manifest entry "${m}"`),E=o[x];if(E===void 0)throw new Error(`Shader manifest entry "${m}" references an absent state.`);(E.vertex||E.fragment)&&(h.render+=1),E.vertex&&(h.vertex+=1),E.fragment&&(h.fragment+=1),E.compute&&(h.compute+=1);}return h}a(rr,"inspectPrecompiledManifest");function jr(e,r){return e.render===r.render&&e.vertex===r.vertex&&e.fragment===r.fragment&&e.compute===r.compute}a(jr,"sameCoverage");function Ar(e){let r=e.some(n=>n.state==="invalid")?"invalid":e.some(n=>n.state==="missing")?"missing":e.some(n=>n.state==="stale")?"stale":"fresh",t=e.filter(n=>n.state===r);return {state:r,reason:r==="fresh"?`${e.length} configured shader scene${e.length===1?" is":"s are"} fresh.`:t.map(n=>`${n.scene}: ${n.reason}`).join("; ")}}a(Ar,"classifyMatrix");function Dr(e,r){let t=e.tool;if(!t)return "Shader receipt has no public tool compatibility metadata.";if(t.compatibility!==r)return "Shader receipt targets a different runtime compatibility contract.";if(t.transform!==b)return "Shader receipt uses a different provider transform version.";if(t.address!==SHADER_ADDRESS_SCHEMA_VERSION||t.recipe!==SHADER_RECIPE_SCHEMA_VERSION||t.hydration!==SHADER_HYDRATION_SCHEMA_VERSION)return "Shader receipt uses incompatible address, recipe, or hydration schemas."}a(Dr,"exactToolCompatibility");function _r(e,r){let t=Object.keys(r).filter(s=>Object.hasOwn(e,s)&&e[s]!==r[s]),n=Object.keys(r).filter(s=>!Object.hasOwn(e,s)),i=Object.keys(e).filter(s=>!Object.hasOwn(r,s));return {...t.length>0?{changedInputs:t}:{},...n.length>0?{addedInputs:n}:{},...i.length>0?{removedInputs:i}:{}}}a(_r,"inputChanges");async function we(e=process.cwd(),r){let t=await e$1(e),n=await f(t),i$1=P.join(t,b$1),s=a(()=>({schemaVersion:1,root:t,state:"missing",reason:`${b$1}/meta.json is absent.`,scenes:n.scenes.map(a=>({scene:a.key,state:"missing",reason:"No committed shader receipt."}))}),"missing");if(!await d(i$1)||!await d(P.join(i$1,"meta.json")))return s();try{let a=await i(t,i$1,"Shader artifact directory"),l=await j(a,P.join(a,"meta.json"),a$1.receipt,"Shader receipt"),u=c$1(JSON.parse(l.data.toString("utf8"))),f=await e$2(a,l.data),w=r??await se(t),o=a$3(w.three),h=new Set(n.scenes.map(p=>p.key)),b=Object.keys(u.scenes).filter(p=>!h.has(p));if(b.length>0)throw new Error(`Shader receipt contains unconfigured scenes: ${b.join(", ")}.`);let x=Dr(u,o);if(x)throw new Error(x);let E=u.runtime.three!==w.three||u.runtime.threeBlocks!==w.threeBlocks,O=u.runtime.threeBlocksShaderClosure!==w.threeBlocksShaderClosure,C=u.tool?.version!==a$4,A=P.join(t,n.publicDir??"public"),$=[];for(let p of n.scenes){let c$1=u.scenes[p.key];if(!c$1){$.push({scene:p.key,state:"missing",reason:"Scene is absent from the complete receipt matrix."});continue}let M=await j(a,P.join(a,c$1.artifact),a$1.manifest,"Shader manifest");if(c(M.data)!==c$1.artifactHash)throw new Error(`Shader artifact checksum differs for scene "${p.key}".`);if(c$1.asset!==void 0&&c$1.assetHash!==void 0){let N=await j(A,P.join(A,c$1.asset),a$1.manifest,"Static shader manifest");if(c(N.data)!==c$1.assetHash)throw new Error(`Static shader manifest checksum differs for scene "${p.key}".`)}if(c$1.bytes!==void 0&&c$1.bytes!==M.data.byteLength)throw new Error(`Shader artifact byte count differs for scene "${p.key}".`);let S=rr(M.data.toString("utf8"),M.path,p.key,{three:u.runtime.three,threeBlocks:u.runtime.threeBlocks,compatibility:o,address:SHADER_ADDRESS_SCHEMA_VERSION,recipe:SHADER_RECIPE_SCHEMA_VERSION,hydration:SHADER_HYDRATION_SCHEMA_VERSION});if(!jr(S,c$1.coverage))throw new Error(`Shader coverage differs for scene "${p.key}".`);if(!n.allowLiveBuilds&&c$1.skipped&&c$1.skipped.render+c$1.skipped.compute>0)throw new Error(`Scene "${p.key}" contains skipped live builds but allowLiveBuilds is false.`);let j$1=await me(t,p.inputs),v=_r(c$1.inputs,j$1),g=(v.changedInputs?.length??0)+(v.addedInputs?.length??0)+(v.removedInputs?.length??0),y=E||O||C||g>0,T=f?.scenes[p.key],F=T===void 0||f===void 0?void 0:{...T,schemaVersion:f.schemaVersion,measuredAt:f.measuredAt,source:f.source,...f.source==="committed-capture"?{adapter:f.adapter,platform:f.platform}:{}};$.push({scene:p.key,state:y?"stale":"fresh",reason:E?"Installed runtime versions differ from the receipt.":O?"Installed three-blocks/shaders runtime closure differs from the receipt.":C?`Receipt was generated by @three-blocks/devtools ${u.tool?.version??"unknown"}.`:g>0?`${g} semantic shader input${g===1?"":"s"} changed.`:"Manifest, runtime, schemas, transform, and semantic inputs match.",coverage:S,...!y&&F!==void 0&&F.builds===S.render+S.compute?{timing:F}:{},...v});}let I=Ar($),L=I.state==="fresh"&&f!==void 0&&$.every(p=>p.timing!==void 0)?f:void 0;return {schemaVersion:1,root:t,...I,scenes:$,runtime:w,receipt:u,...L===void 0?{}:{timing:L}}}catch(a){let l=a instanceof Error?a.message:String(a);return {schemaVersion:1,root:t,state:"invalid",reason:l,scenes:n.scenes.map(u=>({scene:u.key,state:"invalid",reason:l}))}}}a(we,"inspectShaderMatrix");var dr=".three-blocks/shaders/pending-capture";function Nr(e){return (e instanceof Error?`${e.name}: ${e.message}`:String(e)).includes("ShaderHydrationError:")}a(Nr,"isShaderHydrationFailure");async function Vr(e,r,t){if(r.length===0)return;let n=P.join(e,b$1,"meta.json"),i=await readFile(n);if(c(i)!==c(t))throw new Error("Shader receipt changed before failed scenes could be marked for recapture.");let s=c$1(JSON.parse(i.toString("utf8"))),a=c(t),l=new Set(r),u=c$1({...s,scenes:Object.fromEntries(Object.entries(s.scenes).map(([f,w])=>[f,l.has(f)?{...w,inputs:{...w.inputs,[dr]:a}}:w]))});await f$1(n,`${d$1(u)}
|
|
10
|
-
`);}a(Vr,"markShaderScenesForRecapture");function Hr(e,r){return d$1(e)===d$1(r)}a(Hr,"equalSnapshot");async function Rt(e={}){let r=e.root?await realpath(e.root):await e$1(e.start),t=e.config===void 0?await h$1(r):void 0,n=e.config??t?.config??await f(r),i=e.runtime??await se(r),s=n.scenes,a$1,l={},u;if(e.ifStale){let S=await we(r,i);if(S.state==="fresh"&&S.scenes.every(j=>j.timing!==void 0))return {schemaVersion:1,root:r,skipped:true,reason:S.reason,scenes:[]};if(S.state!=="invalid"&&S.receipt!==void 0){let j=S.state==="fresh";s=n.scenes.filter(v=>{let g=S.scenes.find(y=>y.scene===v.key);return g?.state!=="fresh"||j&&g.timing===void 0}),a$1=S.receipt;for(let v of S.scenes){if(v.state!=="fresh"||v.timing===void 0)continue;let{builds:g,liveBuildMs:y,precompiledBuildMs:T,avoidedBuildMs:F,runs:N,spreadMs:q}=v.timing;l[v.scene]={builds:g,liveBuildMs:y,precompiledBuildMs:T,avoidedBuildMs:F,runs:N,spreadMs:q},v.timing.source==="committed-capture"&&v.timing.adapter!==void 0&&v.timing.platform!==void 0&&(u={adapter:v.timing.adapter,platform:v.timing.platform});}}}let f$1=performance.now(),w=a$1!==void 0&&(a$1.runtime.three!==i.three||a$1.runtime.threeBlocks!==i.threeBlocks||a$1.runtime.threeBlocksShaderClosure!==i.threeBlocksShaderClosure||a$1.tool?.version!==a$4)?c(d$1({runtime:a$1.runtime,tool:a$1.tool})):void 0,o=a(async()=>new Map(await Promise.all(n.scenes.map(async S=>[S.key,await me(r,S.inputs)]))),"snapshotInputs"),h=await o(),m=a(async()=>{let S=await o();for(let j of n.scenes){let v=h.get(j.key),g=S.get(j.key);if(v===void 0||g===void 0||!Hr(v,g))throw new Error(`Semantic shader inputs changed during capture for scene "${j.key}"; the current scene was not committed.`)}},"assertInputsUnchanged"),b=e.driver===void 0,x=e.driver===void 0&&e.driverKind===void 0&&e.serve===void 0&&e.url===void 0?await g(r):void 0,E=e.serve??x?.serve,O=e.driverKind??x?.driverKind??(E===void 0?"vite":"static");if(e.url!==void 0&&(e.serve!==void 0||e.driverKind!==void 0))throw new Error("--url cannot be combined with --driver or --serve.");if(O==="vite"&&E!==void 0)throw new Error("--serve requires the static shader driver.");if(O==="static"&&E===void 0&&e.driver===void 0)throw new Error("The static shader driver requires --serve <built-directory>.");let C=e.driver===void 0?await import('./shader-browser-
|
|
10
|
+
`);}a(Vr,"markShaderScenesForRecapture");function Hr(e,r){return d$1(e)===d$1(r)}a(Hr,"equalSnapshot");async function Rt(e={}){let r=e.root?await realpath(e.root):await e$1(e.start),t=e.config===void 0?await h$1(r):void 0,n=e.config??t?.config??await f(r),i=e.runtime??await se(r),s=n.scenes,a$1,l={},u;if(e.ifStale){let S=await we(r,i);if(S.state==="fresh"&&S.scenes.every(j=>j.timing!==void 0))return {schemaVersion:1,root:r,skipped:true,reason:S.reason,scenes:[]};if(S.state!=="invalid"&&S.receipt!==void 0){let j=S.state==="fresh";s=n.scenes.filter(v=>{let g=S.scenes.find(y=>y.scene===v.key);return g?.state!=="fresh"||j&&g.timing===void 0}),a$1=S.receipt;for(let v of S.scenes){if(v.state!=="fresh"||v.timing===void 0)continue;let{builds:g,liveBuildMs:y,precompiledBuildMs:T,avoidedBuildMs:F,runs:N,spreadMs:q}=v.timing;l[v.scene]={builds:g,liveBuildMs:y,precompiledBuildMs:T,avoidedBuildMs:F,runs:N,spreadMs:q},v.timing.source==="committed-capture"&&v.timing.adapter!==void 0&&v.timing.platform!==void 0&&(u={adapter:v.timing.adapter,platform:v.timing.platform});}}}let f$1=performance.now(),w=a$1!==void 0&&(a$1.runtime.three!==i.three||a$1.runtime.threeBlocks!==i.threeBlocks||a$1.runtime.threeBlocksShaderClosure!==i.threeBlocksShaderClosure||a$1.tool?.version!==a$4)?c(d$1({runtime:a$1.runtime,tool:a$1.tool})):void 0,o=a(async()=>new Map(await Promise.all(n.scenes.map(async S=>[S.key,await me(r,S.inputs)]))),"snapshotInputs"),h=await o(),m=a(async()=>{let S=await o();for(let j of n.scenes){let v=h.get(j.key),g=S.get(j.key);if(v===void 0||g===void 0||!Hr(v,g))throw new Error(`Semantic shader inputs changed during capture for scene "${j.key}"; the current scene was not committed.`)}},"assertInputsUnchanged"),b=e.driver===void 0,x=e.driver===void 0&&e.driverKind===void 0&&e.serve===void 0&&e.url===void 0?await g(r):void 0,E=e.serve??x?.serve,O=e.driverKind??x?.driverKind??(E===void 0?"vite":"static");if(e.url!==void 0&&(e.serve!==void 0||e.driverKind!==void 0))throw new Error("--url cannot be combined with --driver or --serve.");if(O==="vite"&&E!==void 0)throw new Error("--serve requires the static shader driver.");if(O==="static"&&E===void 0&&e.driver===void 0)throw new Error("The static shader driver requires --serve <built-directory>.");let C=e.driver===void 0?await import('./shader-browser-SZJLKYYT.js'):void 0,A=e.driver??(e.url!==void 0?C.createAttachedPlaywrightShaderDriver({root:r,runtime:i,url:e.url,...e.headed!==void 0?{headed:e.headed}:{}}):O==="static"?C.createStaticPlaywrightShaderDriver({root:r,runtime:i,serve:E,...e.headed!==void 0?{headed:e.headed}:{}}):C.createPlaywrightShaderDriver({root:r,runtime:i,...e.headed!==void 0?{headed:e.headed}:{}})),$=new Map,I=[],L=a$1!==void 0&&n.scenes.every(S=>a$1?.scenes[S.key]!==void 0),p=a$1,c$1,M=e.attempts??2;if(!Number.isSafeInteger(M)||M<1||M>5)throw new Error("Shader capture attempts must be an integer in 1...5.");try{for(let[g,y]of s.entries()){e.onSceneStart?.(y.key,g,s.length);let T,F,N=0;for(;N<M;N++)try{if(T=c$2(await A.capture(y,n),{scene:y.key,runtime:i}),T.skipped.length>0&&!n.allowLiveBuilds)throw new Error(`Scene "${y.key}" contains ${T.skipped.length} unregistered live shader build${T.skipped.length===1?"":"s"} while allowLiveBuilds is false.`);break}catch(q){F=q,T=void 0,N+1<M&&e.onSceneRetry?.(y.key,N+2,M,n.timeoutMs,q);}if(!T)throw new Error(`Shader capture "${y.key}" failed after ${M} attempts: ${F instanceof Error?F.message:String(F)}`);if($.set(y.key,T),I.push({scene:y.key,attempts:N+1,coverage:T.coverage,skipped:T.skipped.length,startupBuilds:T.stats.registeredBuilds,startupBuildMs:T.stats.buildMs,...T.timing===void 0?{}:{timing:T.timing}}),L&&p!==void 0){await m();let q=new Map(n.scenes.map(W=>{let re=W.key===y.key?h.get(W.key):p?.scenes[W.key]?.inputs;if(re===void 0)throw new Error(`Shader checkpoint is missing scene "${W.key}".`);return w!==void 0&&!$.has(W.key)&&(re={...re,[dr]:w}),[W.key,re]}));c$1=await j$1({root:r,scenes:n.scenes,captures:new Map([[y.key,T]]),runtime:i,inputs:q,previousReceipt:p,publicDirectory:n.publicDir??"public"}),p=c$1.receipt;}}await m(),c$1??=await j$1({root:r,scenes:n.scenes,captures:$,runtime:i,inputs:h,...a$1===void 0?{}:{previousReceipt:a$1},publicDirectory:n.publicDir??"public"});let S={...l};for(let g of I)S[g.scene]={builds:g.coverage.render+g.coverage.compute,setupMeasured:!1,liveBuildMs:g.startupBuildMs,precompiledBuildMs:0,avoidedBuildMs:g.startupBuildMs,runs:1,spreadMs:0};if(e.commitTiming===!0){let g=u??{adapter:$.values().next().value?.provenance?.adapter??"WebGPU adapter",platform:`${ve.platform()}/${ve.arch()}`};await i$1(r,S,await(A.timingEnvironment?.()??g));}else await f$2(r,S);let j=await readFile(P.join(c$1.directory,"meta.json")),v=await e$2(c$1.directory,j);return {schemaVersion:1,root:r,skipped:!1,reason:`Wrote ${I.length} shader scene${I.length===1?"":"s"}.`,durationMs:performance.now()-f$1,scenes:I,measurement:{beforeBuilds:I.reduce((g,y)=>g+y.startupBuilds,0),afterBuilds:0,firstFrameDeltaMs:-I.reduce((g,y)=>g+y.startupBuildMs,0),source:"capture-build-phase"},...t===void 0?{}:{configuration:{created:t.created,file:t.file}},written:c$1,...v===void 0?{}:{timing:v}}}finally{b&&await A.close();}}a(Rt,"captureShaders");function Wr(e){return ["workerReady","assetsReady",...e.requiresText?["textReady"]:[],"compileEnd","firstFrame"]}a(Wr,"requiredReadiness");function ar(e){if(e.length===0)throw new Error("Cannot take the median of an empty shader timing capture.");let r=[...e].sort((s,a)=>s-a),t=Math.floor(r.length/2),n=r[t];if(n===void 0)throw new Error("Shader timing median is unavailable.");if(r.length%2===1)return n;let i=r[t-1];if(i===void 0)throw new Error("Shader timing median pair is unavailable.");return (i+n)/2}a(ar,"median");function De(e,r,t,n){if(e.scene!==r.key||e.mode!==t)throw new Error(`Browser observation identity differs for scene "${r.key}".`);if(e.compatibility!==n||e.transform!==b)throw new Error(`Browser observation compatibility differs for scene "${r.key}".`);let i=Wr(r).filter(s=>e.readiness[s]!==true);if(i.length>0)throw new Error(`Scene "${r.key}" ${t} observation is missing readiness bits: ${i.join(", ")}.`);if(e.errors.length>0)throw new Error(`Scene "${r.key}" ${t} browser errors:
|
|
11
11
|
- ${e.errors.join(`
|
|
12
|
-
- `)}`)}a(De,"assertObservation");function Kr(e,r,t,n){if(r.render>0&&t.stats.registeredRenderBuilds===0)throw new Error(`Scene "${e.key}" live baseline exercised no registered render pipeline.`);if(r.compute>0&&t.stats.registeredComputeBuilds===0)throw new Error(`Scene "${e.key}" live baseline exercised no registered compute kernel.`);cr(e,r,n);}a(Kr,"assertZeroBuild");function cr(e,r,t){if(t.stats.registeredRenderBuilds!==0||t.stats.registeredComputeBuilds!==0){let n=t.stats.missedKeys??[];throw new Error(`Scene "${e.key}" injected path performed ${t.stats.registeredRenderBuilds} render and ${t.stats.registeredComputeBuilds} compute registered live builds.`+(n.length>0?` Missed keys: ${n.join(", ")}.`:""))}if(r.render>0&&t.stats.injectedRender===0)throw new Error(`Scene "${e.key}" injected no render entries.`);if(r.compute>0&&t.stats.injectedCompute===0)throw new Error(`Scene "${e.key}" injected no compute entries.`);if(t.stats.missed!==0||t.stats.missedRender!==0||t.stats.missedCompute!==0)throw new Error(`Scene "${e.key}" injected path reported shader manifest misses.`)}a(cr,"assertPrecompiledZeroBuild");async function zr(e,r,t,n,i){let s=P.join(e,c$3);if(await d(s)){let l=await lstat(s);if(l.isSymbolicLink()||!l.isDirectory())throw new Error("Shader parity artifact directory is not a real directory.")}else await mkdir(s,{recursive:true});let a=[`${r}.live.png`,`${r}.precompiled.png`,`${r}.diff.png`];return await Promise.all([t,n,i].map(async(l,u)=>{let f=a[u];if(f===void 0)throw new Error("Parity artifact mapping failed.");let w=P.join(s,f);if(await d(w)){let o=await lstat(w);if(o.isSymbolicLink()||!o.isFile())throw new Error(`Shader parity target is not a regular file: ${f}.`)}await writeFile(w,l,{mode:384});})),a.map(l=>`${c$3}/${l}`)}a(zr,"writeParityFailure");async function xt(e={}){let r=e.root?await realpath(e.root):await e$1(e.start),t=e.runtime??await se(r),n=a$3(t.three),i=await we(r,t);if(i.state!=="fresh")throw new Error(`Shader no-GPU validation is ${i.state}: ${i.reason}`);if(e.skipBrowser)return {schemaVersion:1,root:r,noGpu:i,browser:"skipped",scenes:[]};if(e.parityOnly===true&&e.commitTiming===true)throw new Error("Parity-only shader verification cannot commit timing.");let s=e.runs??5;if(!Number.isSafeInteger(s)||s<1||s>100)throw new Error("Shader timing runs must be an integer in 1...100.");let a$1=e.config??await f(r),l=await readFile(P.join(r,b$1,"meta.json")),u=c$1(JSON.parse(l.toString("utf8")));if(i.receipt===void 0||d$1(u)!==d$1(i.receipt))throw new Error("Shader receipt changed after no-GPU validation; restart browser parity verification.");let f$1=e.driver===void 0,w=e.driver===void 0&&e.driverKind===void 0&&e.serve===void 0&&e.url===void 0?await g(r):void 0,o=e.serve??w?.serve,h=e.driverKind??w?.driverKind??(o===void 0?"vite":"static");if(e.url!==void 0&&(e.serve!==void 0||e.driverKind!==void 0))throw new Error("--url cannot be combined with --driver or --serve.");if(h==="vite"&&o!==void 0)throw new Error("--serve requires the static shader driver.");if(h==="static"&&o===void 0&&e.driver===void 0)throw new Error("The static shader driver requires --serve <built-directory>.");let m=e.driver===void 0?await import('./shader-browser-
|
|
12
|
+
- `)}`)}a(De,"assertObservation");function Kr(e,r,t,n){if(r.render>0&&t.stats.registeredRenderBuilds===0)throw new Error(`Scene "${e.key}" live baseline exercised no registered render pipeline.`);if(r.compute>0&&t.stats.registeredComputeBuilds===0)throw new Error(`Scene "${e.key}" live baseline exercised no registered compute kernel.`);cr(e,r,n);}a(Kr,"assertZeroBuild");function cr(e,r,t){if(t.stats.registeredRenderBuilds!==0||t.stats.registeredComputeBuilds!==0){let n=t.stats.missedKeys??[];throw new Error(`Scene "${e.key}" injected path performed ${t.stats.registeredRenderBuilds} render and ${t.stats.registeredComputeBuilds} compute registered live builds.`+(n.length>0?` Missed keys: ${n.join(", ")}.`:""))}if(r.render>0&&t.stats.injectedRender===0)throw new Error(`Scene "${e.key}" injected no render entries.`);if(r.compute>0&&t.stats.injectedCompute===0)throw new Error(`Scene "${e.key}" injected no compute entries.`);if(t.stats.missed!==0||t.stats.missedRender!==0||t.stats.missedCompute!==0)throw new Error(`Scene "${e.key}" injected path reported shader manifest misses.`)}a(cr,"assertPrecompiledZeroBuild");async function zr(e,r,t,n,i){let s=P.join(e,c$3);if(await d(s)){let l=await lstat(s);if(l.isSymbolicLink()||!l.isDirectory())throw new Error("Shader parity artifact directory is not a real directory.")}else await mkdir(s,{recursive:true});let a=[`${r}.live.png`,`${r}.precompiled.png`,`${r}.diff.png`];return await Promise.all([t,n,i].map(async(l,u)=>{let f=a[u];if(f===void 0)throw new Error("Parity artifact mapping failed.");let w=P.join(s,f);if(await d(w)){let o=await lstat(w);if(o.isSymbolicLink()||!o.isFile())throw new Error(`Shader parity target is not a regular file: ${f}.`)}await writeFile(w,l,{mode:384});})),a.map(l=>`${c$3}/${l}`)}a(zr,"writeParityFailure");async function xt(e={}){let r=e.root?await realpath(e.root):await e$1(e.start),t=e.runtime??await se(r),n=a$3(t.three),i=await we(r,t);if(i.state!=="fresh")throw new Error(`Shader no-GPU validation is ${i.state}: ${i.reason}`);if(e.skipBrowser)return {schemaVersion:1,root:r,noGpu:i,browser:"skipped",scenes:[]};if(e.parityOnly===true&&e.commitTiming===true)throw new Error("Parity-only shader verification cannot commit timing.");let s=e.runs??5;if(!Number.isSafeInteger(s)||s<1||s>100)throw new Error("Shader timing runs must be an integer in 1...100.");let a$1=e.config??await f(r),l=await readFile(P.join(r,b$1,"meta.json")),u=c$1(JSON.parse(l.toString("utf8")));if(i.receipt===void 0||d$1(u)!==d$1(i.receipt))throw new Error("Shader receipt changed after no-GPU validation; restart browser parity verification.");let f$1=e.driver===void 0,w=e.driver===void 0&&e.driverKind===void 0&&e.serve===void 0&&e.url===void 0?await g(r):void 0,o=e.serve??w?.serve,h=e.driverKind??w?.driverKind??(o===void 0?"vite":"static");if(e.url!==void 0&&(e.serve!==void 0||e.driverKind!==void 0))throw new Error("--url cannot be combined with --driver or --serve.");if(h==="vite"&&o!==void 0)throw new Error("--serve requires the static shader driver.");if(h==="static"&&o===void 0&&e.driver===void 0)throw new Error("The static shader driver requires --serve <built-directory>.");let m=e.driver===void 0?await import('./shader-browser-SZJLKYYT.js'):void 0,{compareShaderScreenshots:b}=await import('./shader-parity-XPKQQK26.js'),x=a(()=>e.url!==void 0?m.createAttachedPlaywrightShaderDriver({root:r,runtime:t,url:e.url,...e.headed!==void 0?{headed:e.headed}:{}}):h==="static"?m.createStaticPlaywrightShaderDriver({root:r,runtime:t,serve:o,...e.headed!==void 0?{headed:e.headed}:{}}):m.createPlaywrightShaderDriver({root:r,runtime:t,...e.headed!==void 0?{headed:e.headed}:{}}),"createDriver"),E=e.driver??x(),O=e.driver??x();await h$2(r,a$1.scenes.map(L=>L.key),l);let C=[],A={},$=[],I=new Set;try{for(let[p,c]of a$1.scenes.entries()){e.onSceneStart?.(c.key,p,a$1.scenes.length);let M=i.scenes.find(B=>B.scene===c.key);if(!M?.coverage)throw new Error(`Fresh receipt has no coverage for scene "${c.key}".`);let S=M.coverage,j=a(async B=>{let te=B?"live":"precompiled",G=B?"precompiled":"live",Y=B?E:O,oe=B?O:E,K=await Y.observe(c,te,a$1),de=await oe.observe(c,G,a$1,K.frame),k=K.mode==="live"?K:de,X=K.mode==="precompiled"?K:de;De(k,c,"live",n),De(X,c,"precompiled",n),Kr(c,S,k,X);let Fe=a(async(fr,Le,Ne)=>{let V=b(Le,Ne,a$1.parity.channelTolerance,c.maxDiffRatio??a$1.parity.maxDiffRatio);if(V.matches)return V;let hr=await zr(r,c.key,Le,Ne,V.diff),mr=V.nonBlack?`${V.differentPixels}/${V.totalPixels} pixels differ (${(V.diffRatio*100).toFixed(3)}%).`:`rendered output is black (live=${V.baselineLuminance.toFixed(4)}, precompiled=${V.precompiledLuminance.toFixed(4)}).`;throw new Error(`Shader ${fr} parity failed for scene "${c.key}" at completed frames live=${k.frame}, precompiled=${X.frame}: ${mr} Artifacts: ${hr.join(", ")}`)},"compare");await Fe("first frame",k.firstFrameScreenshot,X.firstFrameScreenshot);let ur=await Fe("settled",k.screenshot,X.screenshot);return {live:k,precompiled:X,parity:ur}},"observePair"),v,g,y;if(e.parityOnly===!0)try{v=await j(!0);}catch(B){Nr(B)&&I.add(c.key),$.push({scene:c.key,error:B}),e.onSceneError?.(c.key,B);continue}else {await j(!0);let B=[];for(let k=0;k<s;k++)B.push(await j(k%2===0));let te=B[B.length-1];if(te===void 0)throw new Error(`Shader timing produced no runs for scene "${c.key}".`);if(v=te,g=await O.observePublished(c,a$1),De(g,c,"precompiled",n),cr(c,S,g),y=c.runtimeMotion?b(g.beforeScreenshot,g.screenshot,a$1.parity.channelTolerance,1):void 0,y&&y.diffRatio<1e-4)throw new Error(`Published scene "${c.key}" stopped animating during its normal 120-frame soak (changed ${y.differentPixels}/${y.totalPixels} canvas pixels).`);let G=a(k=>k.stats.buildMs+(k.stats.precompiledSetupMs??0)+(k.stats.hydrationMs??0),"observedNodeBuilderMs"),Y=ar(B.map(k=>G(k.live))),oe=ar(B.map(k=>G(k.precompiled))),K=Math.max(0,Y-oe),de=B.map(k=>Math.max(0,G(k.live)-G(k.precompiled)));A[c.key]={builds:S.render+S.compute,setupMeasured:!0,liveBuildMs:Y,precompiledBuildMs:oe,avoidedBuildMs:K,runs:s,spreadMs:Math.max(...de.map(k=>Math.abs(k-K)))};}let{diff:T,...F}=v.parity,{firstFrameScreenshot:N,screenshot:q,...W}=v.live,{firstFrameScreenshot:re,screenshot:Ur,...lr}=v.precompiled,be;if(g!==void 0){let{beforeScreenshot:B,firstFrameScreenshot:te,screenshot:G,...Y}=g;be=Y;}C.push({scene:c.key,coverage:S,live:W,precompiled:lr,...be===void 0?{}:{published:be},parity:F,...y===void 0?{}:{runtimeMotion:{differentPixels:y.differentPixels,totalPixels:y.totalPixels,diffRatio:y.diffRatio}}}),await g$1(r,[c.key],l);}if(e.parityOnly===!0){if(await Vr(r,[...I],l),$.length>0)throw new Error(`Shader parity failed for ${$.length}/${a$1.scenes.length} scene(s):
|
|
13
13
|
`+$.map(p=>{let c=p.error instanceof Error?p.error.message:String(p.error);return ` - ${p.scene}: ${c}`}).join(`
|
|
14
14
|
`));return {schemaVersion:1,root:r,noGpu:i,browser:"passed",scenes:C}}if(e.commitTiming===!0){let p={adapter:"WebGPU adapter",platform:`${ve.platform()}/${ve.arch()}`},c=await(E.timingEnvironment?.()??p),M=await i$1(r,A,c);return {schemaVersion:1,root:r,noGpu:i,browser:"passed",scenes:C,timing:M.local,committedTiming:M.committed}}let L=await f$2(r,A);return {schemaVersion:1,root:r,noGpu:i,browser:"passed",scenes:C,timing:L}}finally{f$1&&(await O.close(),await E.close());}}a(xt,"testShaders");export{rr as a,me as b,se as c,we as d,Rt as e,xt as f};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import {d,a as a$1,T,v,U,x as x$1,Q,m,l,h,g,O as O$1}from'./chunk-RQEPJ6GC.js';import {a}from'./chunk-EI7MMDWY.js';import b from'process';import {createServer}from'http';import {createRequire}from'module';import {mkdtemp,rm,lstat,realpath}from'fs/promises';import k from'path';import {tmpdir}from'os';import {pathToFileURL}from'url';var ve=Object.freeze([{id:"three-inspector-invalid-json",pattern:/is not valid JSON/iu},{id:"chromium-webgpu-experimental",pattern:/WebGPU is experimental/iu}]);function We(r){return ve.some(e=>e.pattern.test(r))}a(We,"isDocumentedBrowserNoise");function ee(r=b.env,e=b.platform){let t=r.THREE_BLOCKS_WEBGPU_BROWSER_ARGS?.split(/\s+/u).filter(Boolean);if(t&&t.length>0)return t;let n=["--enable-unsafe-webgpu"];return e==="darwin"&&n.push("--enable-gpu","--use-angle=metal"),e==="linux"&&n.push("--enable-features=Vulkan","--disable-vulkan-surface","--ignore-gpu-blocklist","--disable-gpu-driver-bug-workarounds","--disable-gpu-watchdog"),n}a(ee,"webgpuBrowserArgs");function te(r=false,e=b.env){return r!==true&&e.THREE_BLOCKS_SOFTWARE_WEBGPU!=="1"}a(te,"webgpuBrowserHeadless");var re="three-blocks.shader-capture.runtime.v1";var ce="/__three-blocks/shaders/capture",N="/__three-blocks/shaders/telemetry",ue="/__three-blocks/shaders/runtime.js",he="/__three-blocks/shaders/bootstrap.js",me="/__three-blocks/shaders/bridge.js",fe=d.manifest*2,W=/^[a-z0-9][a-z0-9_-]{0,63}$/u,pe=64,we=2e3,Be=[/is not valid JSON/iu,/WebGPU is experimental/iu];async function xe(){try{return (await import('playwright')).chromium}catch(r){throw new Error('Shader browser work requires the optional "playwright" package. Install it in the project and run `npx playwright install chromium`.',{cause:r})}}a(xe,"loadChromium");async function Oe(r){let e;try{e=createRequire(k.join(r,"package.json")).resolve("vite");}catch(n){throw new Error("Shader capture requires Vite in the target project.",{cause:n})}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(Oe,"loadProjectCreateServer");var q=class{static{a(this,"CaptureInbox");}#e=new Map;#t=new Map;wait(e,t){let n=this.#t.get(e);if(n!==void 0)return this.#t.delete(e),Promise.resolve(n);if(this.#e.has(e))throw new Error(`A shader capture is already waiting for scene "${e}".`);return new Promise((o,s)=>{let i=setTimeout(()=>{this.#e.delete(e),s(new Error(`Shader capture "${e}" timed out after ${t}ms.`));},t);this.#e.set(e,{resolve:o,reject:s,timer:i});})}receive(e){if(!a$1(e)||typeof e.scene!="string"||!W.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>=pe)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 n=this.#e.get(e);n&&(clearTimeout(n.timer),this.#e.delete(e),n.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 Me(r,e){let t=await Promise.race([e.then(n=>({kind:"capture",value:n})),r.then(()=>({kind:"navigation"}))]);return t.kind==="capture"?t.value:e}a(Me,"waitForShaderCaptureAcrossNavigation");var G=class{static{a(this,"TelemetryHub");}#e=new Map;#t=new Map;markFirstRequest(e){W.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"||!W.test(e.scene))throw new Error("Shader telemetry has no bounded scene key.");if(!this.#e.has(e.scene)&&this.#e.size>=pe)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);}},je=a(async(r,e,t,n,o)=>{let s=0;for(;r.__threeBlocksParityUsesAnimationLoop!==true&&s<e;)await n(),s+=1;if(r.__threeBlocksParityUsesAnimationLoop===true){let i=Number(r.__threeBlocksParityCompletedFrame||0),a=Number(t),c=Number.isSafeInteger(a)&&a>=i?a:i+e;for(r.__threeBlocksParityTargetFrame=c;Number(r.__threeBlocksParityCompletedFrame||0)<c;)await n();}return await o(),Number(r.__threeBlocksParityCompletedFrame||0)},"settleShaderParityFrames");function J(r){return `(() => {
|
|
2
|
+
const root = globalThis;
|
|
3
|
+
const scene = new URL(location.href).searchParams.get('captureId')
|
|
4
|
+
|| 'default';
|
|
5
|
+
const randomSeed = (value) => {
|
|
6
|
+
let state = 2166136261;
|
|
7
|
+
for (let index = 0; index < value.length; index++) state = Math.imul(state ^ value.charCodeAt(index), 16777619) >>> 0;
|
|
8
|
+
return state === 0 ? 0x9e3779b9 : state;
|
|
9
|
+
};
|
|
10
|
+
const advanceRandom = (state) => {
|
|
11
|
+
state ^= state << 13;
|
|
12
|
+
state ^= state >>> 17;
|
|
13
|
+
state ^= state << 5;
|
|
14
|
+
return state >>> 0;
|
|
15
|
+
};
|
|
16
|
+
const parityMode = new URL(location.href).searchParams.get('threeBlocksShaderMode');
|
|
17
|
+
if (parityMode === 'live' || parityMode === 'precompiled') {
|
|
18
|
+
root.__threeBlocksParityEpoch = 1700000000000;
|
|
19
|
+
root.__threeBlocksParityTime = 0;
|
|
20
|
+
Date.now = () => root.__threeBlocksParityEpoch + Number(root.__threeBlocksParityTime || 0);
|
|
21
|
+
}
|
|
22
|
+
const randomStreams = new Map();
|
|
23
|
+
Math.random = () => {
|
|
24
|
+
const stackLine = String(new Error().stack || '').split('\\n')[2] || 'unknown';
|
|
25
|
+
const originIndex = stackLine.indexOf(location.origin);
|
|
26
|
+
const callsite = (originIndex >= 0 ? stackLine.slice(0, originIndex) : stackLine).trim() || 'anonymous';
|
|
27
|
+
const next = advanceRandom(randomStreams.get(callsite) ?? randomSeed(scene + '|' + callsite));
|
|
28
|
+
randomStreams.set(callsite, next);
|
|
29
|
+
return next / 4294967296;
|
|
30
|
+
};
|
|
31
|
+
const readiness = { workerReady: false, assetsReady: false, textReady: false, compileEnd: false, firstFrame: false };
|
|
32
|
+
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: [] };
|
|
33
|
+
const settleParityFrames = ${je.toString()};
|
|
34
|
+
const settle = (frames, requestedTarget) => settleParityFrames(
|
|
35
|
+
root,
|
|
36
|
+
frames,
|
|
37
|
+
requestedTarget,
|
|
38
|
+
() => new Promise((resolve) => requestAnimationFrame(resolve)),
|
|
39
|
+
() => new Promise((resolve) => setTimeout(resolve, 100)),
|
|
40
|
+
);
|
|
41
|
+
const bridge = { protocolVersion: 1, compatibility: ${JSON.stringify(r)}, transform: ${x$1}, readiness, stats, settle };
|
|
42
|
+
root.__threeBlocksShaderTools = bridge;
|
|
43
|
+
requestAnimationFrame(() => requestAnimationFrame(() => { readiness.firstFrame = true; }));
|
|
44
|
+
const poll = async () => {
|
|
45
|
+
try {
|
|
46
|
+
const response = await fetch('/__three-blocks/shaders/telemetry?scene=' + encodeURIComponent(scene), { cache: 'no-store' });
|
|
47
|
+
if (response.status !== 204 && response.ok) {
|
|
48
|
+
const payload = await response.json();
|
|
49
|
+
if (payload.protocolVersion !== 1 || payload.compatibility !== bridge.compatibility || payload.transform !== bridge.transform) throw new Error('incompatible shader telemetry');
|
|
50
|
+
Object.assign(stats, payload.stats);
|
|
51
|
+
readiness.workerReady = true;
|
|
52
|
+
if (payload.settled === true) {
|
|
53
|
+
readiness.assetsReady = true;
|
|
54
|
+
readiness.textReady = true;
|
|
55
|
+
readiness.compileEnd = true;
|
|
56
|
+
}
|
|
57
|
+
const smoke = root.__threeBlocksSmoke && typeof root.__threeBlocksSmoke === 'object' ? root.__threeBlocksSmoke : { protocolVersion: 1, worker: { offscreenCanvas: true, visible: true }, readiness: {} };
|
|
58
|
+
smoke.readiness = { ...(smoke.readiness || {}), ...readiness };
|
|
59
|
+
root.__threeBlocksSmoke = smoke;
|
|
60
|
+
}
|
|
61
|
+
} catch {}
|
|
62
|
+
setTimeout(poll, 40);
|
|
63
|
+
};
|
|
64
|
+
void poll();
|
|
65
|
+
})();`}a(J,"publicBridgeScript");function ye(r,e,t,n,o=false){let s=new URL(r.url??"/","http://three-blocks.invalid"),i=s.pathname;if(o&&r.method==="GET"&&/^\/three-blocks\/shaders\/[a-z0-9][a-z0-9_-]{0,63}\.json$/u.test(i))return e.statusCode=204,e.end(),true;if(i===N&&r.method==="GET"){let u=s.searchParams.get("scene")??"",m=n.read(u);return m===void 0?(e.statusCode=204,e.end()):(e.statusCode=200,e.setHeader("Content-Type","application/json"),e.end(JSON.stringify(m))),true}let a=i===ce,c=i===N;if(!a&&!c)return false;if(r.method!=="POST")return e.statusCode=405,e.end("POST required"),true;let h=[],f=0,w=false;return r.on("data",u=>{f+=u.byteLength,f>fe?w=true:h.push(u);}),r.on("end",()=>{if(w){e.statusCode=413,e.end("capture payload too large");return}try{let u=JSON.parse(Buffer.concat(h).toString("utf8"));c?n.receive(u):t.receive(u),e.statusCode=204,e.end();}catch(u){e.statusCode=400,e.end(u instanceof Error?u.message:String(u));}}),true}a(ye,"handleCaptureEndpoint");function Fe(r,e,t,n){return {name:"three-blocks:shader-capture-endpoint",transformIndexHtml(){return [{tag:"script",children:J(n),injectTo:"head-prepend"}]},configureServer(o){o.middlewares.use((s,i,a)=>{let h=new URL(s.url??"/","http://three-blocks.invalid").searchParams.get("captureId");h!==null&&e.markFirstRequest(h),!ye(s,i,r,e,t)&&a();});}}}a(Fe,"captureEndpointPlugin");function se(r,e,t){let n=new URL(e.url,r);for(let[o,s]of Object.entries(t))n.searchParams.set(o,s);return n.href}a(se,"browserUrl");function Le(r,e){let t=new URL(e.url,r);for(let n of ["capture","precompiled"])t.searchParams.delete(n);return t.searchParams.set("captureId",e.key),t.searchParams.set("threeBlocksShaderMode","precompiled"),t.searchParams.set("tbStats","1"),t.href}a(Le,"publishedBrowserUrl");function oe(r){return Be.some(e=>e.test(r))}a(oe,"knownNoise");async function E(r){let e;try{await Promise.race([r(),new Promise(t=>{e=setTimeout(t,we);})]);}catch{}finally{e&&clearTimeout(e);}}a(E,"closeBrowserResource");async function ie(r){let e;try{return await Promise.race([r().catch(()=>null),new Promise(t=>{e=setTimeout(()=>t(null),we);})])}finally{e!==void 0&&clearTimeout(e);}}a(ie,"readPageDiagnostic");function V(r){let e=a(()=>{},"resolveFirst"),t=new Promise(i=>{e=i;}),n={console:[],page:[],first:t},o=false,s=a(i=>{o||(o=true,e(new Error(i)));},"report");return r.on("console",i=>{let a=i.type()==="warning"&&/\[three-blocks\/shaders\].*(?:has no entry|manifest miss|hydration)/iu.test(i.text());if(i.type()!=="error"&&!a||oe(i.text()))return;let c=i.location().url,h=c.length>0?`${i.text()} (${c})`:i.text();n.console.push(h),s(`Browser console ${a?"warning":"error"}: ${h}`);}),r.on("pageerror",i=>{if(oe(i.message))return;let a=i.stack||i.message;n.page.push(a),s(`Browser page error: ${a}`);}),r.on("crash",()=>s("Browser page crashed before shader capture completed.")),r.on("close",()=>s("Browser page closed before shader capture completed.")),n}a(V,"collectErrors");function x(r,e,t=false){return typeof r[e]=="boolean"?r[e]:t}a(x,"booleanField");function Ae(r){if(!a$1(r))throw new Error("Browser shader stats are unavailable.");let e=a((t,n=true)=>{let o=r[t];if(typeof o!="number"||!Number.isFinite(o)||o<0||n&&!Number.isSafeInteger(o))throw new Error(`Browser shader stats.${t} is invalid.`);return o},"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(r.missedKeys)&&r.missedKeys.every(t=>typeof t=="string")?{missedKeys:r.missedKeys}:{}}}a(Ae,"parseStats");function A(r,e,t,n,o){if(!a$1(r))throw new Error("The page did not expose the public shader devtools bridge.");if(!t&&r.protocolVersion!==1)throw new Error(`Scene "${e.key}" exposed an unsupported shader bridge protocol.`);let s=r.readiness;if(!a$1(s))throw new Error("The shader bridge readiness snapshot is invalid.");let i={workerReady:x(s,"workerReady"),assetsReady:x(s,"assetsReady"),textReady:e.requiresText?x(s,"textReady"):true,compileEnd:x(s,"compileEnd"),firstFrame:x(s,"firstFrame",t)};if(!i.workerReady||!i.assetsReady||!i.textReady||!i.compileEnd)throw new Error(`Scene "${e.key}" did not reach worker/assets/text/compile readiness.`);let a=t?o:r.compatibility,c=t?x$1:r.transform;if(a!==o||c!==x$1)throw new Error(`Scene "${e.key}" exposed incompatible shader bridge metadata.`);return U(n),{compatibility:o,transform:c,readiness:i,stats:Ae(r.stats)}}a(A,"parseBridge");async function D(r,e){return r.evaluate(t=>{let n=globalThis;if(!t)return n.__threeBlocksShaderTools??null;let o=n.__threeBlocks,s=n.__threeBlocksTslStats;if(!o||typeof o!="object")return null;let i=o;return {readiness:{workerReady:i.workerReady===true,assetsReady:i.loadEnd===true||i.assetsReady===true,textReady:i.textReady===true,compileEnd:i.compileEnd===true,firstFrame:true},stats:s}},e)}a(D,"readBridge");async function O(r,e,t,n){let o=r.evaluate(async i=>{let c=globalThis.__threeBlocksShaderTools;if(c&&typeof c=="object"){let w=Reflect.get(c,"settle");if(typeof w=="function"){let u=await w(i.frames,i.targetFrame);return typeof u=="number"&&Number.isSafeInteger(u)?u:0}}if(!i.legacy||!i.modulePath)throw new Error("The public shader bridge does not provide deterministic settle().");let h=await import(i.modulePath);if(!h.store||typeof h.store!="object")throw new Error("Legacy deterministic store is unavailable.");let f=h.store;return f.recordFrameCount=0,f.recordFrameRate=60,f.recordTotalFrames=i.frames,f.recording=true,await new Promise((w,u)=>{let m=Date.now(),d=a(()=>{if(f.recording===false)return w();if(Date.now()-m>i.timeoutMs)return u(new Error("Legacy deterministic settle timed out."));setTimeout(d,25);},"poll");d();}),0},{frames:t,targetFrame:n,legacy:e.bridge.legacyLab,modulePath:e.bridge.deterministicModule??null,timeoutMs:e.timeoutMs}),s;try{return await Promise.race([o,new Promise((i,a)=>{s=setTimeout(()=>a(new Error(`Shader parity settle timed out after ${e.timeoutMs}ms.`)),e.timeoutMs);})])}finally{s!==void 0&&clearTimeout(s);}}a(O,"settlePage");async function ae(r,e,t){e.readiness.selector===void 0&&e.readiness.global===void 0||await Promise.race([r.waitForFunction(n=>{let o=globalThis;if(n.selector!==void 0&&o.document?.querySelector(n.selector)==null)return false;if(n.global===void 0)return true;let s=o;for(let c of n.global.split(".")){if((typeof s!="object"||s===null)&&typeof s!="function")return false;s=Reflect.get(s,c);}if(s===true)return true;if(typeof s!="object"||s===null||typeof Reflect.get(s,"then")!="function")return false;let i=o.__threeBlocksReadinessState,a=i instanceof Map?i:new Map;return i instanceof Map||(o.__threeBlocksReadinessState=a),a.has(s)||(a.set(s,false),Promise.resolve(s).then(()=>a.set(s,true),()=>a.set(s,false))),a.get(s)===true},e.readiness,{timeout:e.timeoutMs}),t.first.then(n=>Promise.reject(n))]);}a(ae,"waitForConfiguredReadiness");async function de(r){let e=r.locator("canvas"),n=(await e.evaluateAll(o=>o.map((s,i)=>{let a=s.getBoundingClientRect();return {index:i,area:Math.max(0,a.width)*Math.max(0,a.height)}}))).sort((o,s)=>s.area-o.area)[0];if(n===void 0||n.area<=0)throw new Error("Published page has no visible renderer canvas.");return Buffer.from(await e.nth(n.index).screenshot({type:"png"}))}a(de,"primaryCanvasScreenshot");async function K(r,e,t,n,o,s){let i=ge(n,o),a=await Q(),c=`(() => {
|
|
66
|
+
const runtime = globalThis[Symbol.for(${JSON.stringify(re)})];
|
|
67
|
+
if (!runtime || typeof runtime.configureThreeBlocksShaderCapture !== 'function') {
|
|
68
|
+
throw new Error('@three-blocks/devtools attached shader capture runtime is incompatible.');
|
|
69
|
+
}
|
|
70
|
+
runtime.configureThreeBlocksShaderCapture(${JSON.stringify(i).replaceAll("<","\\u003c")});
|
|
71
|
+
})();`;await r.addInitScript({content:`${a}
|
|
72
|
+
${c}`}),await r.addInitScript({content:J(s)}),await r.route("**/*",async h=>{let f=h.request(),w=new URL(f.url()),u=w.pathname;if(f.method()==="GET"&&n!=="precompiled"&&/^\/three-blocks\/shaders\/[a-z0-9][a-z0-9_-]{0,63}\.json$/u.test(u)){await h.fulfill({status:204});return}if(u===N&&f.method()==="GET"){let p=t.read(w.searchParams.get("scene")??"");await h.fulfill(p===void 0?{status:204}:{status:200,contentType:"application/json",body:JSON.stringify(p)});return}let m=u===ce,d=u===N;if((m||d)&&f.method()==="POST"){let p=f.postDataBuffer()??Buffer.alloc(0);if(p.byteLength>fe){await h.fulfill({status:413,body:"capture payload too large"});return}try{let g=JSON.parse(p.toString("utf8"));d?t.receive(g):e.receive(g),await h.fulfill({status:204});}catch(g){await h.fulfill({status:400,body:g instanceof Error?g.message:String(g)});}return}await h.continue();});}a(K,"configureAttachedContext");var De=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 Ne(r){let e=[`<script src="${me}"></script>`,`<script type="module" src="${he}"></script>`].join(""),t=/<head(?:\s[^>]*)?>/iu.exec(r);return t===null?`${e}${r}`:`${r.slice(0,t.index+t[0].length)}${e}${r.slice(t.index+t[0].length)}`}a(Ne,"injectStaticShaderCaptureHtml");function Ie(r,e){let t=ge(r,e);return [`import { configureThreeBlocksShaderCapture } from ${JSON.stringify(ue)};`,`configureThreeBlocksShaderCapture( ${JSON.stringify(t).replaceAll("<","\\u003c")} );`].join(`
|
|
73
|
+
`)}a(Ie,"staticCaptureBootstrap");function ge(r,e){return {capture:r==="capture",forceLive:r!=="precompiled",settleFrames:e.settleFrames,settleTimeoutMs:e.settleTimeoutMs??3e4,readiness:e.readiness,transform:x$1}}a(ge,"shaderCaptureConfiguration");async function Ue(r,e){let t=await m(r,e,i=>/\.(?:c|m)?js$/u.test(i),16384),n=false,o=false,s;for(let i of t){let a=(await l(r,i,d.texture,"Static application JavaScript")).data.toString("utf8");if(a.includes("nodeBuilderStateProvider")&&(n=true),a.includes("three-blocks.shader-capture.runtime.v1")&&(o=true,s??=i),n&&o)break}if(!n||!o)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,...s===void 0?{}:{id:s}}}a(Ue,"inspectStaticCaptureTransform");async function $e(r,e){let t;try{t=decodeURIComponent(e);}catch{return}if(t.includes("\0"))return;let n=t.replace(/^\/+/u,""),o=k.resolve(r,n.length===0?"index.html":n);if(!h(r,o)||o===r||(await g(o)&&(await lstat(o)).isDirectory()&&(o=k.join(o,"index.html")),!await g(o)&&k.extname(o).length===0&&(o=k.join(r,"index.html")),!await g(o)))return;let s=await l(r,o,d.texture,"Static application asset");return {data:s.data,file:s.path}}a($e,"staticRequestFile");async function He(r,e,t,n,o){let s=await realpath(r.root),i=await realpath(k.resolve(s,r.serve));if(!h(s,i)||i===s)throw new Error("--serve must name a built application directory inside the project root.");let a=await Ue(s,i),c=await O$1(),h$1=Ie(e,t),f=J(v(r.runtime.three)),w=createServer((m,d)=>{(async()=>{if(ye(m,d,n,o,e!=="precompiled"))return;let p=new URL(m.url??"/","http://three-blocks.invalid");if(m.method!=="GET"&&m.method!=="HEAD"){d.statusCode=405,d.end("GET or HEAD required");return}let g=p.pathname===ue?c:p.pathname===he?h$1:p.pathname===me?f:void 0;if(g!==void 0){d.statusCode=200,d.setHeader("Content-Type","text/javascript; charset=utf-8"),d.setHeader("Cache-Control","no-store"),d.end(m.method==="HEAD"?void 0:g);return}let y=await $e(i,p.pathname);if(y===void 0){d.statusCode=404,d.end("Not found");return}let v=k.extname(y.file).toLowerCase(),C=v===".html"?Buffer.from(Ne(y.data.toString("utf8"))):y.data;d.statusCode=200,d.setHeader("Content-Type",De[v]??"application/octet-stream"),d.setHeader("Content-Length",String(C.byteLength)),d.setHeader("Cache-Control","no-store"),d.end(m.method==="HEAD"?void 0:C);})().catch(p=>{if(d.headersSent)return d.destroy(p instanceof Error?p:void 0);d.statusCode=500,d.end(p instanceof Error?p.message:String(p));});});await new Promise((m,d)=>{w.once("error",d),w.listen(0,"127.0.0.1",()=>{w.off("error",d),m();});});let u=w.address();if(!u||typeof u=="string")throw new Error("Static capture server did not expose an ephemeral TCP address.");return {server:w,baseUrl:`http://127.0.0.1:${u.port}`,transform:a}}a(He,"startStaticShaderServer");function Ve(r,e,t){return r===e?true:t&&r!==void 0&&r!=="capture"&&e!=="capture"}a(Ve,"canReuseShaderBrowserSession");function le(r){let e=r instanceof Error?r.message:String(r);return e.includes("Execution context was destroyed")&&e.includes("navigation")||/^launch: Timeout \d+ms exceeded\./u.test(e)}a(le,"isRetryableShaderObservationNavigation");var M=class{static{a(this,"PlaywrightShaderDriver");}#e;#t=new q;#n=new G;#h;#m;#i;#a;#r;#s;#f;#l;#p;#c=0;#u;constructor(e){this.#e=e;}#d(){return this.#h?.status??this.#m??{seen:false,applied:false,alreadyPresent:false}}async#w(e){if(this.#r?.isConnected()===true)return;this.#r=void 0;let t=await xe();this.#u??=await mkdtemp(k.join(tmpdir(),"three-blocks-shader-cache-")),this.#r=await t.launch({headless:te(this.#e.headed===true),args:[...ee(),`--disk-cache-dir=${this.#u}`],timeout:e.timeoutMs}),this.#c=0;}async#o(e,t,n){let o;try{return await Promise.race([n(),new Promise((s,i)=>{o=setTimeout(()=>i(new Error(`launch: Timeout ${t.timeoutMs}ms exceeded.`)),t.timeoutMs);})])}catch(s){throw this.#r===e&&(this.#r=void 0),await E(()=>e.close()),s}finally{o!==void 0&&clearTimeout(o);}}async#y(e,t){let n=this.#i!==void 0||this.#a!==void 0||this.#e.url!==void 0&&this.#s!==void 0,o=this.#a!==void 0?this.#l===e:Ve(this.#l,e,t.bridge.legacyLab);if(n&&o){this.#l=e,await this.#w(t);return}if(n&&await this.close(),this.#l=e,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.#s=s.href,this.#m={seen:true,applied:true,alreadyPresent:false,captureApplied:true,id:"attached-application"},await this.#w(t);return}if(this.#e.serve!==void 0)try{let s=await He({root:this.#e.root,runtime:this.#e.runtime,serve:this.#e.serve,...this.#e.headed===void 0?{}:{headed:this.#e.headed}},e,t,this.#t,this.#n);this.#a=s.server,this.#m=s.transform,this.#s=s.baseUrl,await this.#w(t);return}catch(s){throw await this.close(),s}this.#h=T(this.#e.runtime.three,{disableTimestampQueries:b.env.THREE_BLOCKS_SOFTWARE_WEBGPU==="1",...t.bridge.legacyLab?{}:{capture:{capture:e==="capture",forceLive:e!=="precompiled",settleFrames:t.settleFrames,settleTimeoutMs:t.settleTimeoutMs??3e4,readiness:t.readiness}}}),this.#f={THREE_BLOCKS_SHADER_TOOL:b.env.THREE_BLOCKS_SHADER_TOOL,THREE_BLOCKS_PRECOMPILE_CAPTURE_SERVER:b.env.THREE_BLOCKS_PRECOMPILE_CAPTURE_SERVER},b.env.THREE_BLOCKS_SHADER_TOOL="1",b.env.THREE_BLOCKS_PRECOMPILE_CAPTURE_SERVER="1";try{let s=await Oe(this.#e.root);this.#i=await s({root:this.#e.root,logLevel:"error",plugins:[this.#h.plugin,Fe(this.#t,this.#n,e!=="precompiled",v(this.#e.runtime.three))],server:{host:"127.0.0.1",port:0}}),await this.#i.listen();let i=this.#i.httpServer?.address();if(!i||typeof i=="string")throw new Error("Vite did not expose an ephemeral TCP address.");this.#s=`http://127.0.0.1:${i.port}`,await this.#w(t);}catch(s){throw await this.close(),s}}async capture(e,t){let n=Date.now();if(await this.#y("capture",t),!this.#r||!this.#s)throw new Error("Shader browser driver did not start.");let o=this.#r,s=await this.#o(o,t,()=>o.newContext({viewport:t.viewport}));this.#e.url!==void 0&&await this.#o(o,t,()=>K(s,this.#t,this.#n,"capture",t,v(this.#e.runtime.three)));let i=await this.#o(o,t,()=>s.newPage()),a$2=V(i);this.#n.clear(e.key);let c=this.#t.wait(e.key,t.timeoutMs),h=Promise.race([c,a$2.first.then(m=>Promise.reject(m))]),f=a(()=>{},"resolveDisconnected"),w=new Promise(m=>{f=m;}),u=a(()=>f(new Error("Shader capture browser disconnected before posting a manifest.")),"onDisconnected");o.on("disconnected",u);try{let m=i.goto(se(this.#s,e,{threeBlocksShaderCapture:"1",capture:"1",captureId:e.key,captureFrames:String(Math.max(4,t.settleFrames)),settleFrames:String(t.settleFrames)}),{waitUntil:"domcontentloaded",timeout:t.timeoutMs}),d=await Me(m,Promise.race([h,w.then(g=>Promise.reject(g))]));U(this.#d());let p=[...a$2.page,...a$2.console];if(p.length>0)throw new Error(`Capture browser errors:
|
|
74
|
+
- ${p.join(`
|
|
75
|
+
- `)}`);return a$1(d)?{...d,timing:{...a$1(d.timing)?d.timing:{},launch:n,...this.#n.firstRequest(e.key)===void 0?{}:{firstRequest:this.#n.firstRequest(e.key)},posted:Date.now()}}:d}catch(m){let d=m instanceof Error?m:new Error(String(m));this.#t.cancel(e.key,d),await c.catch(()=>{});let p=this.#n.read(e.key);if(d.message.includes("timed out")){let g=await ie(()=>i.evaluate(()=>{let y=globalThis,v=y.__threeBlocksShaderTools,C=v&&typeof v=="object"?v:void 0,_=y.document,T=Reflect.get(y,Symbol.for("three-blocks.shader-capture.cache-value.v1")),j=y.location,Se=j!==null&&typeof j=="object"&&typeof Reflect.get(j,"href")=="string"?String(Reflect.get(j,"href")):"http://three-blocks.invalid/",be=new URL(Se).searchParams.get("captureId")??"default",z=T!==null&&typeof T=="object"&&typeof Reflect.get(T,"registrations")=="function"?Reflect.apply(Reflect.get(T,"registrations"),T,[be]):void 0;return {documentReadyState:_?.readyState??null,parityTargetFrame:Number(y.__threeBlocksParityTargetFrame??0),parityCompletedFrame:Number(y.__threeBlocksParityCompletedFrame??0),readiness:C?.readiness??null,captureCache:T!==null&&typeof T=="object"?{activeScene:Reflect.get(T,"activeScene")??null,registrations:Array.isArray(z)?z.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"))}}));throw new Error(`${d.message} Last capture state for "${e.key}": ${JSON.stringify({page:g,telemetry:p??null,transform:this.#d()})}`)}throw d}finally{o.off("disconnected",u),await E(()=>s.close()),this.#c++,(!o.isConnected()||this.#c>=(t.browserRelaunchScenes??8))&&(this.#r===o&&(this.#r=void 0),await E(()=>o.close()),this.#c=0);}}async observe(e,t,n,o){for(let s=0;s<2;s++)try{return await this.#g(e,t,n,o)}catch(i){if(s===0&&le(i))continue;throw i}throw new Error(`Shader observation retry was exhausted for scene "${e.key}".`)}async#g(e,t,n,o){if(await this.#y(t,n),!this.#r||!this.#s)throw new Error("Shader browser driver did not start.");let s=this.#r,i=await this.#o(s,n,()=>s.newContext({viewport:n.viewport}));this.#e.url!==void 0&&await this.#o(s,n,()=>K(i,this.#t,this.#n,t,n,v(this.#e.runtime.three)));let a=await this.#o(s,n,()=>i.newPage()),c=V(a);this.#n.clear(e.key);try{await a.goto(se(this.#s,e,{threeBlocksShaderCapture:"1",threeBlocksShaderMode:t,captureId:e.key,...t==="live"?{precompiled:"0"}:{}}),{waitUntil:"domcontentloaded",timeout:n.timeoutMs}),await Promise.race([a.waitForFunction(n.bridge.legacyLab?"globalThis.__threeBlocks?.compileEnd === true":"globalThis.__threeBlocksShaderTools?.readiness?.compileEnd === true",void 0,{timeout:n.timeoutMs}),c.first.then(d=>Promise.reject(d))]),A(await D(a,n.bridge.legacyLab),e,n.bridge.legacyLab,this.#d(),v(this.#e.runtime.three)),await ae(a,n,c),await Promise.race([a.waitForFunction(n.bridge.legacyLab?"true":"globalThis.__threeBlocksShaderTools?.readiness?.firstFrame === true",void 0,{timeout:n.timeoutMs}),c.first.then(d=>Promise.reject(d))]),await O(a,n,1);let h=Buffer.from(await a.screenshot({type:"png"})),f=e.parityFrames??n.parity.frames,w=await O(a,n,f,o),u=Buffer.from(await a.screenshot({type:"png"}));e.parityFrames!==void 0&&f<n.parity.frames&&await O(a,n,n.parity.frames-f);let m=A(await D(a,n.bridge.legacyLab),e,n.bridge.legacyLab,this.#d(),v(this.#e.runtime.three));return this.#p===void 0&&(this.#p=await a.evaluate(async()=>{let d=Reflect.get(navigator,"gpu"),p=typeof d=="object"&&d!==null?Reflect.get(d,"requestAdapter"):void 0,g=typeof p=="function"?await Reflect.apply(p,d,[]):void 0,y=typeof g=="object"&&g!==null?Reflect.get(g,"info"):void 0,v=["description","device","architecture","vendor"].flatMap(C=>{let _=typeof y=="object"&&y!==null?Reflect.get(y,C):void 0;return typeof _=="string"&&_.length>0?[_]:[]});return {adapter:[...new Set(v)].join(" \xB7 ")||"WebGPU adapter",platform:navigator.platform||navigator.userAgent}})),{scene:e.key,mode:t,...m,frame:w,firstFrameScreenshot:h,screenshot:u,errors:[...c.page,...c.console]}}catch(h){let f=h instanceof Error?h:new Error(String(h));if(/(?:timed?\s*out|timeout)/iu.test(f.message)){let w=this.#n.read(e.key),u=await ie(()=>a.evaluate(()=>{let m=globalThis,d=m.__threeBlocksShaderTools,p=d&&typeof d=="object"?d:void 0;return {documentReadyState:m.document?.readyState??null,parityTargetFrame:Number(m.__threeBlocksParityTargetFrame??0),parityCompletedFrame:Number(m.__threeBlocksParityCompletedFrame??0),readiness:p?.readiness??null,threeRuntimeResources:performance.getEntriesByType("resource").map(y=>y.name).filter(y=>y.includes("three.webgpu"))}}));throw new Error(`${f.message} Last ${t} state for "${e.key}": ${JSON.stringify({page:u,telemetry:w??null})}`)}throw f}finally{await E(()=>i.close());}}async observePublished(e,t){for(let n=0;n<2;n++)try{return await this.#S(e,t)}catch(o){if(n===0&&le(o))continue;throw o}throw new Error(`Published shader observation retry was exhausted for scene "${e.key}".`)}async#S(e,t){if(await this.#y("precompiled",t),!this.#r||!this.#s)throw new Error("Shader browser driver did not start.");let n=this.#r,o=await this.#o(n,t,()=>n.newContext({viewport:t.viewport}));this.#e.url!==void 0&&await this.#o(n,t,()=>K(o,this.#t,this.#n,"precompiled",t,v(this.#e.runtime.three)));let s=await this.#o(n,t,()=>o.newPage()),i=V(s);this.#n.clear(e.key);try{await s.goto(Le(this.#s,e),{waitUntil:"domcontentloaded",timeout:t.timeoutMs}),await Promise.race([s.waitForFunction(t.bridge.legacyLab?"globalThis.__threeBlocks?.compileEnd === true":"globalThis.__threeBlocksShaderTools?.readiness?.compileEnd === true",void 0,{timeout:t.timeoutMs}),i.first.then(w=>Promise.reject(w))]),await ae(s,t,i),A(await D(s,t.bridge.legacyLab),e,t.bridge.legacyLab,this.#d(),v(this.#e.runtime.three)),await O(s,t,2);let a=await de(s),c=await O(s,t,120),h=await de(s),f=A(await D(s,t.bridge.legacyLab),e,t.bridge.legacyLab,this.#d(),v(this.#e.runtime.three));return {scene:e.key,mode:"precompiled",...f,frame:c,firstFrameScreenshot:a,beforeScreenshot:a,screenshot:h,errors:[...i.page,...i.console]}}finally{await E(()=>o.close());}}timingEnvironment(){return this.#p??{adapter:"WebGPU adapter",platform:`${b.platform}/${b.arch}`}}async close(){this.#t.rejectAll(new Error("Shader browser driver closed.")),this.#r&&await E(()=>this.#r?.close()??Promise.resolve());let e=this.#i?.httpServer,t=e?Reflect.get(e,"closeAllConnections"):void 0;if(e&&typeof t=="function"&&Reflect.apply(t,e,[]),this.#i&&await E(()=>this.#i?.close()??Promise.resolve()),this.#a){let n=this.#a;n.closeAllConnections(),await E(()=>new Promise(o=>{n.close(()=>o());}));}if(this.#r=void 0,this.#i=void 0,this.#a=void 0,this.#s=void 0,this.#h=void 0,this.#m=void 0,this.#l=void 0,this.#p=void 0,this.#c=0,this.#u!==void 0&&(await rm(this.#u,{recursive:true,force:true}),this.#u=void 0),this.#f){for(let[n,o]of Object.entries(this.#f))o===void 0?delete b.env[n]:b.env[n]=o;this.#f=void 0;}}};function lt(r){return new M(r)}a(lt,"createPlaywrightShaderDriver");function ct(r){return new M(r)}a(ct,"createStaticPlaywrightShaderDriver");function ut(r){return new M(r)}a(ut,"createAttachedPlaywrightShaderDriver");
|
|
76
|
+
export{ve as a,We as b,ee as c,te as d,Me as e,je as f,J as g,Ve as h,le as i,lt as j,ct as k,ut as l};
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {b,c}from'./chunk-NE7SC2BX.js';import {a as a$3}from'./chunk-ZT6T2W4B.js';import {a as a$2,c as c$2}from'./chunk-ZDNZCQUQ.js';import {a as a$1,c as c$1,d,f,e,i,j,k}from'./chunk-5L2VS3BN.js';import {a}from'./chunk-HOZDD6PW.js';import _ from'process';import {createServer}from'http';import {createRequire}from'module';import {mkdtemp,rm,lstat,readFile,unlink,mkdir,readdir,realpath}from'fs/promises';import g from'path';import {tmpdir}from'os';import {pathToFileURL}from'url';import {THREE_WEBGPU_R185_COMPATIBILITY,THREE_R186DEV_VERSION,THREE_WEBGPU_R186DEV_COMPATIBILITY,parsePrecompiledManifest,SHADER_HYDRATION_SCHEMA_VERSION,SHADER_RECIPE_SCHEMA_VERSION,SHADER_ADDRESS_SCHEMA_VERSION,PRECOMPILED_MANIFEST_VERSION}from'three-blocks/shaders';import {transformThreeWebgpuProviderHooks,transformThreeWebgpuCaptureInstrumentation}from'three-blocks/vite';function v(r){if(/^0\.185\./u.test(r))return THREE_WEBGPU_R185_COMPATIBILITY;if(r===THREE_R186DEV_VERSION)return THREE_WEBGPU_R186DEV_COMPATIBILITY;throw new Error(`Three.js ${r} is outside the supported shader compatibility contracts.`)}a(v,"shaderCompatibilityForThree");var I=52,Ae="timing.local.json",je="timing.json",de="parity.json",Q=4096,lr=4096;function se(r,e,t=8192){if(typeof r!="string"||r.length===0||r.length>t||/[\u0000\u007f]/u.test(r))throw new Error(`${e} must be a bounded non-empty string.`);return r}a(se,"boundedString");function S(r,e,t=true){if(typeof r!="number"||!Number.isFinite(r)||r<0||t&&!Number.isSafeInteger(r))throw new Error(`${e} must be a non-negative ${t?"integer":"finite number"}.`);return r}a(S,"nonNegativeNumber");function mr(r){if(!a$2(r))throw new Error("Shader capture stats are missing.");let e={buildCalls:S(r.buildCalls,"capture stats.buildCalls"),renderBuilds:S(r.renderBuilds,"capture stats.renderBuilds"),computeBuilds:S(r.computeBuilds,"capture stats.computeBuilds"),registeredBuilds:S(r.registeredBuilds,"capture stats.registeredBuilds"),registeredRenderBuilds:S(r.registeredRenderBuilds,"capture stats.registeredRenderBuilds"),registeredComputeBuilds:S(r.registeredComputeBuilds,"capture stats.registeredComputeBuilds"),buildMs:S(r.buildMs,"capture stats.buildMs",false),syncBuildMs:S(r.syncBuildMs,"capture stats.syncBuildMs",false),asyncBuildElapsedMs:S(r.asyncBuildElapsedMs,"capture stats.asyncBuildElapsedMs",false),precompiledSetupMs:S(r.precompiledSetupMs,"capture stats.precompiledSetupMs",false),maxSyncBuildMs:S(r.maxSyncBuildMs??r.syncBuildMs,"capture stats.maxSyncBuildMs",false),maxPrecompiledSetupMs:S(r.maxPrecompiledSetupMs??r.precompiledSetupMs,"capture stats.maxPrecompiledSetupMs",false),hydrationMs:S(r.hydrationMs??0,"capture stats.hydrationMs",false),maxHydrationMs:S(r.maxHydrationMs??r.hydrationMs??0,"capture stats.maxHydrationMs",false),injected:S(r.injected,"capture stats.injected"),injectedRender:S(r.injectedRender,"capture stats.injectedRender"),injectedCompute:S(r.injectedCompute,"capture stats.injectedCompute"),missed:S(r.missed,"capture stats.missed"),missedRender:S(r.missedRender,"capture stats.missedRender"),missedCompute:S(r.missedCompute,"capture stats.missedCompute"),...Array.isArray(r.missedKeys)&&r.missedKeys.every(t=>typeof t=="string")?{missedKeys:r.missedKeys.slice(0,Q)}:{}};if(e.renderBuilds+e.computeBuilds!==e.buildCalls||e.registeredRenderBuilds+e.registeredComputeBuilds!==e.registeredBuilds||e.injectedRender+e.injectedCompute!==e.injected||e.missedRender+e.missedCompute!==e.missed||e.registeredBuilds>e.buildCalls||Math.abs(e.syncBuildMs+e.asyncBuildElapsedMs-e.buildMs)>.001||e.maxSyncBuildMs>e.syncBuildMs+.001||e.maxPrecompiledSetupMs>e.precompiledSetupMs+.001||e.maxHydrationMs>e.hydrationMs+.001)throw new Error("Shader capture stats totals are inconsistent.");return e}a(mr,"captureStats");function pr(r){if(!Array.isArray(r)||r.length>Q)throw new Error("Shader capture skipped builds are invalid.");return r.map((e,t)=>{if(!a$2(e)||e.kind!=="render"&&e.kind!=="compute")throw new Error(`Shader capture skipped build ${t} is invalid.`);return {kind:e.kind,name:se(e.name,`skipped build ${t} name`,512),reason:se(e.reason,`skipped build ${t} reason`)}})}a(pr,"skippedBuilds");function hr(r){let e=0,t=0,n=0,s=0;for(let i of Object.values(r.entries)){let a=r.states[i];a!==void 0&&((a.vertex!==null||a.fragment!==null)&&e++,a.vertex!==null&&t++,a.fragment!==null&&n++,a.compute!==null&&s++);}return {render:e,vertex:t,fragment:n,compute:s}}a(hr,"shaderCoverage");function it(r,e){if(!a$2(r))throw new Error("Shader capture payload must be an object.");if(r.scene!==e.scene)throw new Error(`Shader capture scene does not match "${e.scene}".`);if(r.protocolVersion!==2)throw new Error("Shader capture protocolVersion must be 2.");let t=v(e.runtime.three);if(r.compatibility!==t)throw new Error(`Shader capture compatibility must be "${t}".`);if(!a$2(r.entries))throw new Error("Shader capture entries must be an object.");if(typeof r.requiresSetup!="boolean")throw new Error("Shader capture requiresSetup must be boolean.");let n=Object.keys(r.entries).length;if(n===0||n>Q)throw new Error(`Shader capture must contain 1...${Q} entries.`);if(!Array.isArray(r.errors)||r.errors.length>lr)throw new Error("Shader capture errors are invalid.");let s=r.errors.map((m,d)=>se(m,`capture error ${d}`,64*1024));if(s.length>0)throw new Error(`Shader capture failed:
|
|
3
|
+
- ${s.join(`
|
|
4
|
+
- `)}`);let i=pr(r.skipped),a=mr(r.stats),o=a$2(r.timing)?r.timing:void 0,l=o===void 0?void 0:Object.fromEntries(["launch","firstRequest","readiness","lastBuild","settled","posted"].flatMap(m=>{let d=o[m];if(d===void 0)return [];if(typeof d!="number"||!Number.isFinite(d)||d<0)throw new Error(`Shader capture timing.${m} is invalid.`);return [[m,d]]})),h;if(r.provenance!==void 0){if(!a$2(r.provenance)||typeof r.provenance.userAgent!="string"||r.provenance.userAgent.length>1024||typeof r.provenance.adapter!="string"||r.provenance.adapter.length>1024||!Array.isArray(r.provenance.features)||r.provenance.features.length>256||!r.provenance.features.every(m=>typeof m=="string"&&m.length<=128))throw new Error("Shader capture provenance is invalid.");h={userAgent:r.provenance.userAgent,adapter:r.provenance.adapter,features:[...new Set(r.provenance.features)].sort()};}let p=parsePrecompiledManifest({version:PRECOMPILED_MANIFEST_VERSION,scene:e.scene,three:e.runtime.three,threeBlocks:e.runtime.threeBlocks,runtime:{id:t,address:SHADER_ADDRESS_SCHEMA_VERSION,recipe:SHADER_RECIPE_SCHEMA_VERSION,hydration:SHADER_HYDRATION_SCHEMA_VERSION},...r.automatic===void 0?{}:{automatic:r.automatic},requiresSetup:r.requiresSetup,modules:r.modules,nodes:r.nodes,layouts:r.layouts,attributePlans:r.attributePlans,updatePlans:r.updatePlans,requirementPlans:r.requirementPlans,states:r.states,entries:r.entries}),f=hr(p);if(a.registeredRenderBuilds<f.render||a.registeredComputeBuilds<f.compute)throw new Error("Shader capture did not live-build every distinct registered render/compute entry.");return {scene:e.scene,manifest:p,skipped:i,stats:a,coverage:f,...l===void 0?{}:{timing:l},...h===void 0?{}:{provenance:h}}}a(it,"validateShaderCapture");function C(r,e=0){let t=" ".repeat(e),n=" ".repeat(e+1);if(Array.isArray(r))return r.length===0?"[]":r.every(i=>i===null||["number","string","boolean"].includes(typeof i))?JSON.stringify(r):`[
|
|
5
|
+
${r.map(i=>`${n}${C(i,e+1)}`).join(`,
|
|
6
|
+
`)}
|
|
7
|
+
${t}]`;if(r!==null&&typeof r=="object"){let i=r,a=Object.keys(i).sort();return a.length===0?"{}":`{
|
|
8
|
+
${a.map(o=>{let l=i[o];return `${n}${JSON.stringify(o)}: ${C(l,e+1)}`}).join(`,
|
|
9
|
+
`)}
|
|
10
|
+
${t}}`}let s=JSON.stringify(r);if(s===void 0)throw new Error("Shader artifact contains a non-serializable value.");return s}a(C,"stableStringify");function fr(r){return ["// GENERATED FILE \u2014 do not edit by hand.","// Produced by @three-blocks/devtools.","import type { PrecompiledManifest } from 'three-blocks/shaders';","",`export default ${C(r)} satisfies PrecompiledManifest;`,""].join(`
|
|
11
|
+
`)}a(fr,"serializeShaderManifest");function ve(r,e){if(typeof r!="string"||r.length===0||r.length>256||/[\u0000-\u001f\u007f]/u.test(r))throw new Error(`${e} is invalid.`);return r}a(ve,"timingLabel");function ae(r){if(!a$2(r)||r.schemaVersion!==3||r.source!=="latest-local-capture"&&r.source!=="committed-capture"||typeof r.receiptHash!="string"||!/^[a-f0-9]{64}$/u.test(r.receiptHash)||typeof r.measuredAt!="string"||!Number.isFinite(Date.parse(r.measuredAt))||!a$2(r.scenes))throw new Error("Shader timing is invalid.");let e={};for(let[n,s]of Object.entries(r.scenes)){if(n.length===0||n.length>128||!a$2(s))throw new Error("Shader timing scene is invalid.");let i={builds:S(s.builds,`timing ${n}.builds`),setupMeasured:s.setupMeasured===true,liveBuildMs:S(s.liveBuildMs,`timing ${n}.liveBuildMs`,false),precompiledBuildMs:S(s.precompiledBuildMs,`timing ${n}.precompiledBuildMs`,false),avoidedBuildMs:S(s.avoidedBuildMs,`timing ${n}.avoidedBuildMs`,false),runs:S(s.runs,`timing ${n}.runs`),spreadMs:S(s.spreadMs,`timing ${n}.spreadMs`,false)};if(i.runs<1)throw new Error(`Shader timing runs are invalid for scene "${n}".`);if(Math.abs(i.avoidedBuildMs-Math.max(0,i.liveBuildMs-i.precompiledBuildMs))>.001)throw new Error(`Shader timing delta is inconsistent for scene "${n}".`);e[n]=i;}if(Object.keys(e).length===0)throw new Error("Shader timing contains no scenes.");let t={schemaVersion:3,receiptHash:r.receiptHash,measuredAt:r.measuredAt,scenes:e};return r.source==="latest-local-capture"?{...t,source:"latest-local-capture"}:{...t,source:"committed-capture",adapter:ve(r.adapter,"Shader timing adapter"),platform:ve(r.platform,"Shader timing platform")}}a(ae,"parseShaderTiming");function X(r){return /^[a-z0-9][a-z0-9_-]{0,63}$/u.test(r)}a(X,"validParityScene");function Pe(r){return typeof r=="string"&&Number.isFinite(Date.parse(r))}a(Pe,"validParityTimestamp");function ce(r){if(!a$2(r))throw new Error("Shader parity evidence is invalid.");if(r.schemaVersion===1){if(typeof r.receiptHash!="string"||!/^[a-f0-9]{64}$/u.test(r.receiptHash)||!Pe(r.verifiedAt)||!Array.isArray(r.scenes)||r.scenes.length===0||r.scenes.length>64||!r.scenes.every(n=>typeof n=="string"&&X(n)))throw new Error("Shader parity evidence is invalid.");return {schemaVersion:1,receiptHash:r.receiptHash,verifiedAt:r.verifiedAt,scenes:[...new Set(r.scenes)].sort()}}if(r.schemaVersion!==2||!a$2(r.scenes))throw new Error("Shader parity evidence is invalid.");let e=Object.entries(r.scenes);if(e.length===0||e.length>64)throw new Error("Shader parity evidence is invalid.");let t={};for(let[n,s]of e.sort(([i],[a])=>i.localeCompare(a))){if(!X(n)||!a$2(s)||typeof s.fingerprint!="string"||!/^[a-f0-9]{64}$/u.test(s.fingerprint)||!Pe(s.verifiedAt))throw new Error("Shader parity evidence is invalid.");t[n]={fingerprint:s.fingerprint,verifiedAt:s.verifiedAt};}return {schemaVersion:2,scenes:t}}a(ce,"parseShaderParityEvidence");function oe(r,e){let t=r.scenes[e];if(t===void 0)throw new Error(`Shader receipt has no scene "${e}" for parity evidence.`);return c$1(C({runtime:{three:r.runtime.three,threeBlocks:r.runtime.threeBlocks,threeBlocksShaderClosure:r.runtime.threeBlocksShaderClosure},...r.tool===void 0?{}:{tool:r.tool},scene:t}))}a(oe,"shaderSceneParityFingerprint");async function ke(r,e,t,n){let s=g.join(r,t);try{if(!await d(s))return;let i=await lstat(s);if(i.isSymbolicLink()||!i.isFile()||i.size>1024*1024)return;let a=ae(JSON.parse(await readFile(s,"utf8")));return a.source===n&&a.receiptHash===c$1(e)?a:void 0}catch{return}}a(ke,"readShaderTimingFile");async function st(r,e){return await ke(r,e,Ae,"latest-local-capture")??await ke(r,e,je,"committed-capture")}a(st,"readShaderTiming");async function Oe(r,e){let t=g.join(r,de);try{if(!await d(t))return;let n=await lstat(t);if(n.isSymbolicLink()||!n.isFile()||n.size>1024*1024)return;let s=ce(JSON.parse(await readFile(t,"utf8"))),i=c$2(JSON.parse(Buffer.from(e).toString("utf8"))),a={};if(s.schemaVersion===1){if(s.receiptHash!==c$1(e))return;for(let o of s.scenes)i.scenes[o]!==void 0&&(a[o]={fingerprint:oe(i,o),verifiedAt:s.verifiedAt});}else for(let[o,l]of Object.entries(s.scenes))i.scenes[o]===void 0||l.fingerprint!==oe(i,o)||(a[o]=l);return Object.keys(a).length===0?void 0:{schemaVersion:2,scenes:a}}catch{return}}a(Oe,"readShaderParityEvidence");async function Ie(r,e,t){let n=await Z(r),s=g.join(n,"meta.json"),i=await lstat(s);if(i.isSymbolicLink()||!i.isFile())throw new Error("Shader receipt must be a regular file before timing.");let a=await readFile(s),o=new Date().toISOString(),l=Object.fromEntries(Object.entries(e).sort(([f],[m])=>f.localeCompare(m))),h=ae({schemaVersion:3,receiptHash:c$1(a),measuredAt:o,source:"latest-local-capture",scenes:l});if(await f(g.join(n,Ae),`${C(h)}
|
|
12
|
+
`),t===void 0)return {local:h};let p=ae({schemaVersion:3,receiptHash:c$1(a),measuredAt:o,source:"committed-capture",adapter:t.adapter,platform:t.platform,scenes:l});return await f(g.join(n,je),`${C(p)}
|
|
13
|
+
`),{local:h,committed:p}}a(Ie,"writeShaderTimings");async function at(r,e){return (await Ie(r,e)).local}a(at,"writeShaderLocalTiming");async function ot(r,e,t){if(e.length===0||e.length>64||e.some(m=>!X(m)))throw new Error("Shader parity evidence must contain 1...64 valid scene keys.");let n=await Z(r),s=g.join(n,"meta.json"),i=await lstat(s);if(i.isSymbolicLink()||!i.isFile())throw new Error("Shader receipt must be a regular file before parity evidence.");let a=await readFile(s);if(t!==void 0&&c$1(a)!==c$1(t))throw new Error("Shader receipt changed during browser parity verification; completed observations were not attached to the new receipt.");let o=c$2(JSON.parse(a.toString("utf8"))),l=await Oe(n,a),h=new Date().toISOString(),p={...l?.scenes};for(let m of [...new Set(e)].sort())p[m]={fingerprint:oe(o,m),verifiedAt:h};let f$1=ce({schemaVersion:2,scenes:p});return await f(g.join(n,de),`${C(f$1)}
|
|
14
|
+
`),f$1}a(ot,"writeShaderParityEvidence");async function dt(r,e,t){if(e.length===0||e.length>64||e.some(p=>!X(p)))throw new Error("Shader parity invalidation must contain 1...64 valid scene keys.");let n=await Z(r),s=await readFile(g.join(n,"meta.json"));if(c$1(s)!==c$1(t))throw new Error("Shader receipt changed before prior parity evidence could be invalidated.");let i=await Oe(n,s);if(i===void 0)return;let a=new Set(e),o=Object.fromEntries(Object.entries(i.scenes).filter(([p])=>!a.has(p))),l=g.join(n,de);if(Object.keys(o).length===0){await unlink(l).catch(p=>{if(!a$2(p)||p.code!=="ENOENT")throw p});return}let h=ce({schemaVersion:2,scenes:o});await f(l,`${C(h)}
|
|
15
|
+
`);}a(dt,"removeShaderParityEvidence");async function ct(r,e,t){let n=await Ie(r,e,t);if(n.committed===void 0)throw new Error("Committed shader timing was not written.");return {local:n.local,committed:n.committed}}a(ct,"writeShaderTimingTwins");async function Ce(r){if(!await d(r)){await mkdir(r);return}let e=await lstat(r);if(e.isSymbolicLink()||!e.isDirectory())throw new Error(`Shader artifact path is not a real directory: ${r}.`)}a(Ce,"assertDirectory");async function Z(r){let e=g.resolve(r),t=g.join(e,".three-blocks");await Ce(t);let n=g.join(t,"shaders");return await Ce(n),n}a(Z,"artifactRoot");async function ut(r){let e$1=await Z(r.root),t=v(r.runtime.three),n=g.resolve(r.root),s=g.resolve(n,r.publicDirectory??"public");if(!e(n,s)||s===n)throw new Error("Shader public directory must stay inside the project root.");let i$1=g.join(s,"three-blocks","shaders");await mkdir(i$1,{recursive:true}),await i(n,i$1,"Shader static-asset directory");let a={},o=[];for(let d of [...r.scenes].sort((u,y)=>u.key.localeCompare(y.key))){let u=r.captures.get(d.key),y=r.inputs.get(d.key);if(y===void 0)throw new Error(`Shader input matrix is missing scene "${d.key}".`);if(u===void 0){let R=r.previousReceipt?.scenes[d.key];if(R===void 0)throw new Error(`Capture matrix is missing scene "${d.key}".`);let N=await readFile(g.join(e$1,R.artifact));if(c$1(N)!==R.artifactHash)throw new Error(`Preserved shader artifact checksum differs for scene "${d.key}".`);if(R.asset!==void 0&&R.assetHash!==void 0){let H=await readFile(g.join(s,R.asset));if(c$1(H)!==R.assetHash)throw new Error(`Preserved static shader manifest checksum differs for scene "${d.key}".`)}a[d.key]={...R,inputs:Object.fromEntries(Object.entries(y).sort(([H],[z])=>H.localeCompare(z)))},o.push(R.artifact),R.asset!==void 0&&o.push(g.relative(n,g.join(s,R.asset)).split(g.sep).join("/"));continue}if(u.scene!==d.key||u.manifest.scene!==d.key)throw new Error(`Capture matrix scene "${d.key}" is inconsistent.`);let b=`${d.key}.webgpu.ts`,w=fr(u.manifest);await f(g.join(e$1,b),w),o.push(b);let P=`three-blocks/shaders/${d.key}.json`,B=`${C(u.manifest)}
|
|
16
|
+
`;await f(g.join(s,P),B),o.push(g.relative(n,g.join(s,P)).split(g.sep).join("/"));let M=u.skipped.filter(R=>R.kind==="render").length,k=u.skipped.length-M;a[d.key]={artifact:b,artifactHash:c$1(w),asset:P,assetHash:c$1(B),inputs:Object.fromEntries(Object.entries(y).sort(([R],[N])=>R.localeCompare(N))),coverage:u.coverage,bytes:Buffer.byteLength(w),skipped:{render:M,compute:k}};}let l=[...r.captures.values()].find(d=>d.provenance!==void 0)?.provenance??r.previousReceipt?.runtime.capture,h={schemaVersion:2,runtime:{...r.runtime,...l===void 0?{}:{capture:l}},tool:{name:"@three-blocks/devtools",version:a$3,compatibility:t,transform:I,address:SHADER_ADDRESS_SCHEMA_VERSION,recipe:SHADER_RECIPE_SCHEMA_VERSION,hydration:SHADER_HYDRATION_SCHEMA_VERSION},scenes:a},p=new Set(o);for(let d of await readdir(e$1,{withFileTypes:true}))if(!(!d.name.endsWith(".webgpu.ts")||p.has(d.name))){if(d.isSymbolicLink()||!d.isFile())throw new Error(`Orphan shader artifact is not a regular file: ${d.name}.`);await unlink(g.join(e$1,d.name));}let f$1=new Set(r.scenes.map(d=>`${d.key}.json`)),m=new Set(Object.values(r.previousReceipt?.scenes??{}).map(d=>d.asset===void 0?void 0:g.posix.basename(d.asset)).filter(d=>d!==void 0));try{let d=c$2(JSON.parse(await readFile(g.join(e$1,"meta.json"),"utf8")));for(let u of Object.values(d.scenes))u.asset!==void 0&&m.add(g.posix.basename(u.asset));}catch{}for(let d of await readdir(i$1,{withFileTypes:true}))if(!(!d.name.endsWith(".json")||f$1.has(d.name))&&m.has(d.name)){if(d.isSymbolicLink()||!d.isFile())throw new Error(`Orphan shader static asset is not a regular file: ${d.name}.`);await unlink(g.join(i$1,d.name));}return await f(g.join(e$1,"meta.json"),`${C(h)}
|
|
17
|
+
`),o.push("meta.json"),{directory:e$1,receipt:h,files:o}}a(ut,"writeShaderArtifacts");var Le="three-blocks.shader-capture.runtime.v1";var W;async function F(){W===void 0&&(W=(async()=>{let e=createRequire(g.join(process.cwd(),"package.json")).resolve("@three-blocks/devtools/browser/shader-capture"),t=g.resolve(g.dirname(e),"../..");return (await j(t,e,a$1.metadata,"Shader capture browser runtime")).data.toString("utf8")})());let r=W;try{return await r}catch(e){throw W===r&&(W=void 0),e}}a(F,"loadShaderCaptureRuntimeSource");var De="virtual:three-blocks-shader-capture-client",$e="\0three-blocks:shader-capture-client",le="virtual:three-blocks-shader-capture-runtime",Fe="\0three-blocks:shader-capture-runtime";async function He(){let r=await F(),e=r.replace(/\bexport\{[^{}]*\};?\s*$/u,"");if(e===r)throw new Error("Shader capture browser runtime no longer has the expected final ESM export list.");return e}a(He,"loadShaderCaptureRuntimeScriptSource");function br(r){let e=r.split("?",1)[0];return e===void 0?false:e.split(g.sep).join("/").endsWith("/build/three.webgpu.js")}a(br,"isThreeWebGPUModule");function Ue(r){let e=/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/u.exec(r);return e?.[1]==="0"&&e[2]==="185"}a(Ue,"supportedVersion");function Er(r,e,t={}){if(!Ue(e))throw new Error(`Shader provider transform ${THREE_WEBGPU_R185_COMPATIBILITY} supports Three.js 0.185.x; received "${e}".`);let n=transformThreeWebgpuProviderHooks(r,{threeVersion:e,...t.threeRevision===void 0?{}:{threeRevision:t.threeRevision},id:"three/build/three.webgpu.js"}),s=n.state==="already-applied",i=n.code;return t.instrumentCapture&&(i=transformThreeWebgpuCaptureInstrumentation(i,{...t.captureRuntimeImport===void 0?{}:{runtimeImport:t.captureRuntimeImport}}).code),{code:i,alreadyPresent:s,captureApplied:t.instrumentCapture===true}}a(Er,"applyShaderProviderTransform");var Rr=/this\.trackTimestamp\s*=\s*\(\s*parameters\.trackTimestamp\s*===\s*true\s*\);/gu,Tr="Object.defineProperty( this, 'trackTimestamp', { get: () => false, set: () => {} } );";function Ve(r,e={}){if(!Ue(r))throw new Error(`Shader provider transform ${THREE_WEBGPU_R185_COMPATIBILITY} supports Three.js 0.185.x; received "${r}".`);let t={seen:false,applied:false,alreadyPresent:false};return {plugin:{name:"three-blocks:shader-provider-transform",enforce:"pre",config(){return {optimizeDeps:{exclude:["three","three/webgpu","three/tsl"]},resolve:{dedupe:["three"]}}},resolveId(s){return e.capture&&s===De?$e:e.capture&&s===le?Fe:null},async load(s){return e.capture?s===Fe?F():s===$e?[`export * from '${le}';`,`import { configureThreeBlocksShaderCapture } from '${le}';`,`configureThreeBlocksShaderCapture( ${JSON.stringify({capture:e.capture.capture,forceLive:e.capture.forceLive,settleFrames:e.capture.settleFrames,settleTimeoutMs:e.capture.settleTimeoutMs,visibilityGuard:e.capture.visibilityGuard,captureId:e.capture.captureId,sessionKey:e.capture.sessionKey,token:e.capture.token,readiness:e.capture.readiness??{},transform:I})} );`].join(`
|
|
18
|
+
`):null:null},transform(s,i){if(!br(i))return null;t.seen=true,t.id=i;try{let a=Er(s,r,{instrumentCapture:e.capture!==void 0,...e.capture!==void 0?{captureRuntimeImport:De}:{}}),o=e.disableTimestampQueries===!0?a.code.replace(Rr,Tr):a.code;if(e.disableTimestampQueries===!0&&o===a.code)throw new Error("Three.js timestamp tracking anchor drifted; refusing software WebGPU capture.");return t.applied=!0,t.alreadyPresent=a.alreadyPresent,t.captureApplied=a.captureApplied,o===s?null:{code:o,map:null}}catch(a){throw t.error=a instanceof Error?a.message:String(a),a}}},status:t}}a(Ve,"createShaderProviderTransform");function me(r){if(r.error)throw new Error(r.error);if(!r.seen||!r.applied)throw new Error(`The version-gated shader provider transform was not applied (${r.seen?"module seen":"three/webgpu not seen"}).`)}a(me,"assertShaderProviderTransform");var Qe="/__three-blocks/shaders/capture",te="/__three-blocks/shaders/telemetry",Xe="/__three-blocks/shaders/runtime.js",Ze="/__three-blocks/shaders/bootstrap.js",er="/__three-blocks/shaders/bridge.js",rr=a$1.manifest*2,fe=/^[a-z0-9][a-z0-9_-]{0,63}$/u,tr=64,nr=2e3,xr=[/is not valid JSON/iu,/WebGPU is experimental/iu];async function Ar(){try{return (await import('playwright')).chromium}catch(r){throw new Error('Shader browser work requires the optional "playwright" package. Install it in the project and run `npx playwright install chromium`.',{cause:r})}}a(Ar,"loadChromium");async function jr(r){let e;try{e=createRequire(g.join(r,"package.json")).resolve("vite");}catch(n){throw new Error("Shader capture requires Vite in the target project.",{cause:n})}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(jr,"loadProjectCreateServer");var ye=class{static{a(this,"CaptureInbox");}#e=new Map;#r=new Map;wait(e,t){let n=this.#r.get(e);if(n!==void 0)return this.#r.delete(e),Promise.resolve(n);if(this.#e.has(e))throw new Error(`A shader capture is already waiting for scene "${e}".`);return new Promise((s,i)=>{let a=setTimeout(()=>{this.#e.delete(e),i(new Error(`Shader capture "${e}" timed out after ${t}ms.`));},t);this.#e.set(e,{resolve:s,reject:i,timer:a});})}receive(e){if(!a$2(e)||typeof e.scene!="string"||!fe.test(e.scene))throw new Error("Capture POST has no safe scene key.");if(!this.#r.has(e.scene)&&!this.#e.has(e.scene)&&this.#r.size>=tr)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.#r.set(e.scene,e);}cancel(e,t){let n=this.#e.get(e);n&&(clearTimeout(n.timer),this.#e.delete(e),n.reject(t));}rejectAll(e){for(let t of this.#e.values())clearTimeout(t.timer),t.reject(e);this.#e.clear(),this.#r.clear();}};async function Or(r,e){let t=await Promise.race([e.then(n=>({kind:"capture",value:n})),r.then(()=>({kind:"navigation"}))]);return t.kind==="capture"?t.value:e}a(Or,"waitForShaderCaptureAcrossNavigation");var ge=class{static{a(this,"TelemetryHub");}#e=new Map;#r=new Map;markFirstRequest(e){fe.test(e)&&!this.#r.has(e)&&this.#r.set(e,Date.now());}firstRequest(e){return this.#r.get(e)}receive(e){if(!a$2(e)||typeof e.scene!="string"||!fe.test(e.scene))throw new Error("Shader telemetry has no bounded scene key.");if(!this.#e.has(e.scene)&&this.#e.size>=tr)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.#r.delete(e);}},Ir=a(async(r,e,t,n,s)=>{let i=0;for(;r.__threeBlocksParityUsesAnimationLoop!==true&&i<e;)await n(),i+=1;if(r.__threeBlocksParityUsesAnimationLoop===true){let a=Number(r.__threeBlocksParityCompletedFrame||0),o=Number(t),l=Number.isSafeInteger(o)&&o>=a?o:a+e;for(r.__threeBlocksParityTargetFrame=l;Number(r.__threeBlocksParityCompletedFrame||0)<l;)await n();}return await s(),Number(r.__threeBlocksParityCompletedFrame||0)},"settleShaderParityFrames");function Se(r){return `(() => {
|
|
19
|
+
const root = globalThis;
|
|
20
|
+
const scene = new URL(location.href).searchParams.get('captureId')
|
|
21
|
+
|| 'default';
|
|
22
|
+
const randomSeed = (value) => {
|
|
23
|
+
let state = 2166136261;
|
|
24
|
+
for (let index = 0; index < value.length; index++) state = Math.imul(state ^ value.charCodeAt(index), 16777619) >>> 0;
|
|
25
|
+
return state === 0 ? 0x9e3779b9 : state;
|
|
26
|
+
};
|
|
27
|
+
const advanceRandom = (state) => {
|
|
28
|
+
state ^= state << 13;
|
|
29
|
+
state ^= state >>> 17;
|
|
30
|
+
state ^= state << 5;
|
|
31
|
+
return state >>> 0;
|
|
32
|
+
};
|
|
33
|
+
const parityMode = new URL(location.href).searchParams.get('threeBlocksShaderMode');
|
|
34
|
+
if (parityMode === 'live' || parityMode === 'precompiled') {
|
|
35
|
+
root.__threeBlocksParityEpoch = 1700000000000;
|
|
36
|
+
root.__threeBlocksParityTime = 0;
|
|
37
|
+
Date.now = () => root.__threeBlocksParityEpoch + Number(root.__threeBlocksParityTime || 0);
|
|
38
|
+
}
|
|
39
|
+
const randomStreams = new Map();
|
|
40
|
+
Math.random = () => {
|
|
41
|
+
const stackLine = String(new Error().stack || '').split('\\n')[2] || 'unknown';
|
|
42
|
+
const originIndex = stackLine.indexOf(location.origin);
|
|
43
|
+
const callsite = (originIndex >= 0 ? stackLine.slice(0, originIndex) : stackLine).trim() || 'anonymous';
|
|
44
|
+
const next = advanceRandom(randomStreams.get(callsite) ?? randomSeed(scene + '|' + callsite));
|
|
45
|
+
randomStreams.set(callsite, next);
|
|
46
|
+
return next / 4294967296;
|
|
47
|
+
};
|
|
48
|
+
const readiness = { workerReady: false, assetsReady: false, textReady: false, compileEnd: false, firstFrame: false };
|
|
49
|
+
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: [] };
|
|
50
|
+
const settleParityFrames = ${Ir.toString()};
|
|
51
|
+
const settle = (frames, requestedTarget) => settleParityFrames(
|
|
52
|
+
root,
|
|
53
|
+
frames,
|
|
54
|
+
requestedTarget,
|
|
55
|
+
() => new Promise((resolve) => requestAnimationFrame(resolve)),
|
|
56
|
+
() => new Promise((resolve) => setTimeout(resolve, 100)),
|
|
57
|
+
);
|
|
58
|
+
const bridge = { protocolVersion: 1, compatibility: ${JSON.stringify(r)}, transform: ${I}, readiness, stats, settle };
|
|
59
|
+
root.__threeBlocksShaderTools = bridge;
|
|
60
|
+
requestAnimationFrame(() => requestAnimationFrame(() => { readiness.firstFrame = true; }));
|
|
61
|
+
const poll = async () => {
|
|
62
|
+
try {
|
|
63
|
+
const response = await fetch('/__three-blocks/shaders/telemetry?scene=' + encodeURIComponent(scene), { cache: 'no-store' });
|
|
64
|
+
if (response.status !== 204 && response.ok) {
|
|
65
|
+
const payload = await response.json();
|
|
66
|
+
if (payload.protocolVersion !== 1 || payload.compatibility !== bridge.compatibility || payload.transform !== bridge.transform) throw new Error('incompatible shader telemetry');
|
|
67
|
+
Object.assign(stats, payload.stats);
|
|
68
|
+
readiness.workerReady = true;
|
|
69
|
+
if (payload.settled === true) {
|
|
70
|
+
readiness.assetsReady = true;
|
|
71
|
+
readiness.textReady = true;
|
|
72
|
+
readiness.compileEnd = true;
|
|
73
|
+
}
|
|
74
|
+
const smoke = root.__threeBlocksSmoke && typeof root.__threeBlocksSmoke === 'object' ? root.__threeBlocksSmoke : { protocolVersion: 1, worker: { offscreenCanvas: true, visible: true }, readiness: {} };
|
|
75
|
+
smoke.readiness = { ...(smoke.readiness || {}), ...readiness };
|
|
76
|
+
root.__threeBlocksSmoke = smoke;
|
|
77
|
+
}
|
|
78
|
+
} catch {}
|
|
79
|
+
setTimeout(poll, 40);
|
|
80
|
+
};
|
|
81
|
+
void poll();
|
|
82
|
+
})();`}a(Se,"publicBridgeScript");function ir(r,e,t,n,s=false){let i=new URL(r.url??"/","http://three-blocks.invalid"),a=i.pathname;if(s&&r.method==="GET"&&/^\/three-blocks\/shaders\/[a-z0-9][a-z0-9_-]{0,63}\.json$/u.test(a))return e.statusCode=204,e.end(),true;if(a===te&&r.method==="GET"){let m=i.searchParams.get("scene")??"",d=n.read(m);return d===void 0?(e.statusCode=204,e.end()):(e.statusCode=200,e.setHeader("Content-Type","application/json"),e.end(JSON.stringify(d))),true}let o=a===Qe,l=a===te;if(!o&&!l)return false;if(r.method!=="POST")return e.statusCode=405,e.end("POST required"),true;let h=[],p=0,f=false;return r.on("data",m=>{p+=m.byteLength,p>rr?f=true:h.push(m);}),r.on("end",()=>{if(f){e.statusCode=413,e.end("capture payload too large");return}try{let m=JSON.parse(Buffer.concat(h).toString("utf8"));l?n.receive(m):t.receive(m),e.statusCode=204,e.end();}catch(m){e.statusCode=400,e.end(m instanceof Error?m.message:String(m));}}),true}a(ir,"handleCaptureEndpoint");function Lr(r,e,t,n){return {name:"three-blocks:shader-capture-endpoint",transformIndexHtml(){return [{tag:"script",children:Se(n),injectTo:"head-prepend"}]},configureServer(s){s.middlewares.use((i,a,o)=>{let h=new URL(i.url??"/","http://three-blocks.invalid").searchParams.get("captureId");h!==null&&e.markFirstRequest(h),!ir(i,a,r,e,t)&&o();});}}}a(Lr,"captureEndpointPlugin");function We(r,e,t){let n=new URL(e.url,r);for(let[s,i]of Object.entries(t))n.searchParams.set(s,i);return n.href}a(We,"browserUrl");function Dr(r,e){let t=new URL(e.url,r);for(let n of ["capture","precompiled"])t.searchParams.delete(n);return t.searchParams.set("captureId",e.key),t.searchParams.set("threeBlocksShaderMode","precompiled"),t.searchParams.set("tbStats","1"),t.href}a(Dr,"publishedBrowserUrl");function qe(r){return xr.some(e=>e.test(r))}a(qe,"knownNoise");async function L(r){let e;try{await Promise.race([r(),new Promise(t=>{e=setTimeout(t,nr);})]);}catch{}finally{e&&clearTimeout(e);}}a(L,"closeBrowserResource");async function Ke(r){let e;try{return await Promise.race([r().catch(()=>null),new Promise(t=>{e=setTimeout(()=>t(null),nr);})])}finally{e!==void 0&&clearTimeout(e);}}a(Ke,"readPageDiagnostic");function pe(r){let e=a(()=>{},"resolveFirst"),t=new Promise(a=>{e=a;}),n={console:[],page:[],first:t},s=false,i=a(a=>{s||(s=true,e(new Error(a)));},"report");return r.on("console",a=>{let o=a.type()==="warning"&&/\[three-blocks\/shaders\].*(?:has no entry|manifest miss|hydration)/iu.test(a.text());if(a.type()!=="error"&&!o||qe(a.text()))return;let l=a.location().url,h=l.length>0?`${a.text()} (${l})`:a.text();n.console.push(h),i(`Browser console ${o?"warning":"error"}: ${h}`);}),r.on("pageerror",a=>{if(qe(a.message))return;let o=a.stack||a.message;n.page.push(o),i(`Browser page error: ${o}`);}),r.on("crash",()=>i("Browser page crashed before shader capture completed.")),r.on("close",()=>i("Browser page closed before shader capture completed.")),n}a(pe,"collectErrors");function q(r,e,t=false){return typeof r[e]=="boolean"?r[e]:t}a(q,"booleanField");function $r(r){if(!a$2(r))throw new Error("Browser shader stats are unavailable.");let e=a((t,n=true)=>{let s=r[t];if(typeof s!="number"||!Number.isFinite(s)||s<0||n&&!Number.isSafeInteger(s))throw new Error(`Browser shader stats.${t} is invalid.`);return s},"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(r.missedKeys)&&r.missedKeys.every(t=>typeof t=="string")?{missedKeys:r.missedKeys}:{}}}a($r,"parseStats");function ee(r,e,t,n,s){if(!a$2(r))throw new Error("The page did not expose the public shader devtools bridge.");if(!t&&r.protocolVersion!==1)throw new Error(`Scene "${e.key}" exposed an unsupported shader bridge protocol.`);let i=r.readiness;if(!a$2(i))throw new Error("The shader bridge readiness snapshot is invalid.");let a={workerReady:q(i,"workerReady"),assetsReady:q(i,"assetsReady"),textReady:e.requiresText?q(i,"textReady"):true,compileEnd:q(i,"compileEnd"),firstFrame:q(i,"firstFrame",t)};if(!a.workerReady||!a.assetsReady||!a.textReady||!a.compileEnd)throw new Error(`Scene "${e.key}" did not reach worker/assets/text/compile readiness.`);let o=t?s:r.compatibility,l=t?I:r.transform;if(o!==s||l!==I)throw new Error(`Scene "${e.key}" exposed incompatible shader bridge metadata.`);return me(n),{compatibility:s,transform:l,readiness:a,stats:$r(r.stats)}}a(ee,"parseBridge");async function re(r,e){return r.evaluate(t=>{let n=globalThis;if(!t)return n.__threeBlocksShaderTools??null;let s=n.__threeBlocks,i=n.__threeBlocksTslStats;if(!s||typeof s!="object")return null;let a=s;return {readiness:{workerReady:a.workerReady===true,assetsReady:a.loadEnd===true||a.assetsReady===true,textReady:a.textReady===true,compileEnd:a.compileEnd===true,firstFrame:true},stats:i}},e)}a(re,"readBridge");async function K(r,e,t,n){let s=r.evaluate(async a$1=>{let l=globalThis.__threeBlocksShaderTools;if(l&&typeof l=="object"){let f=Reflect.get(l,"settle");if(typeof f=="function"){let m=await f(a$1.frames,a$1.targetFrame);return typeof m=="number"&&Number.isSafeInteger(m)?m:0}}if(!a$1.legacy||!a$1.modulePath)throw new Error("The public shader bridge does not provide deterministic settle().");let h=await import(a$1.modulePath);if(!h.store||typeof h.store!="object")throw new Error("Legacy deterministic store is unavailable.");let p=h.store;return p.recordFrameCount=0,p.recordFrameRate=60,p.recordTotalFrames=a$1.frames,p.recording=true,await new Promise((f,m)=>{let d=Date.now(),u=a(()=>{if(p.recording===false)return f();if(Date.now()-d>a$1.timeoutMs)return m(new Error("Legacy deterministic settle timed out."));setTimeout(u,25);},"poll");u();}),0},{frames:t,targetFrame:n,legacy:e.bridge.legacyLab,modulePath:e.bridge.deterministicModule??null,timeoutMs:e.timeoutMs}),i;try{return await Promise.race([s,new Promise((a,o)=>{i=setTimeout(()=>o(new Error(`Shader parity settle timed out after ${e.timeoutMs}ms.`)),e.timeoutMs);})])}finally{i!==void 0&&clearTimeout(i);}}a(K,"settlePage");async function Je(r,e,t){e.readiness.selector===void 0&&e.readiness.global===void 0||await Promise.race([r.waitForFunction(n=>{let s=globalThis;if(n.selector!==void 0&&s.document?.querySelector(n.selector)==null)return false;if(n.global===void 0)return true;let i=s;for(let l of n.global.split(".")){if((typeof i!="object"||i===null)&&typeof i!="function")return false;i=Reflect.get(i,l);}if(i===true)return true;if(typeof i!="object"||i===null||typeof Reflect.get(i,"then")!="function")return false;let a=s.__threeBlocksReadinessState,o=a instanceof Map?a:new Map;return a instanceof Map||(s.__threeBlocksReadinessState=o),o.has(i)||(o.set(i,false),Promise.resolve(i).then(()=>o.set(i,true),()=>o.set(i,false))),o.get(i)===true},e.readiness,{timeout:e.timeoutMs}),t.first.then(n=>Promise.reject(n))]);}a(Je,"waitForConfiguredReadiness");async function ze(r){let e=r.locator("canvas"),n=(await e.evaluateAll(s=>s.map((i,a)=>{let o=i.getBoundingClientRect();return {index:a,area:Math.max(0,o.width)*Math.max(0,o.height)}}))).sort((s,i)=>i.area-s.area)[0];if(n===void 0||n.area<=0)throw new Error("Published page has no visible renderer canvas.");return Buffer.from(await e.nth(n.index).screenshot({type:"png"}))}a(ze,"primaryCanvasScreenshot");async function he(r,e,t,n,s,i){let a=sr(n,s),o=await He(),l=`(() => {
|
|
83
|
+
const runtime = globalThis[Symbol.for(${JSON.stringify(Le)})];
|
|
84
|
+
if (!runtime || typeof runtime.configureThreeBlocksShaderCapture !== 'function') {
|
|
85
|
+
throw new Error('@three-blocks/devtools attached shader capture runtime is incompatible.');
|
|
86
|
+
}
|
|
87
|
+
runtime.configureThreeBlocksShaderCapture(${JSON.stringify(a).replaceAll("<","\\u003c")});
|
|
88
|
+
})();`;await r.addInitScript({content:`${o}
|
|
89
|
+
${l}`}),await r.addInitScript({content:Se(i)}),await r.route("**/*",async h=>{let p=h.request(),f=new URL(p.url()),m=f.pathname;if(p.method()==="GET"&&n!=="precompiled"&&/^\/three-blocks\/shaders\/[a-z0-9][a-z0-9_-]{0,63}\.json$/u.test(m)){await h.fulfill({status:204});return}if(m===te&&p.method()==="GET"){let y=t.read(f.searchParams.get("scene")??"");await h.fulfill(y===void 0?{status:204}:{status:200,contentType:"application/json",body:JSON.stringify(y)});return}let d=m===Qe,u=m===te;if((d||u)&&p.method()==="POST"){let y=p.postDataBuffer()??Buffer.alloc(0);if(y.byteLength>rr){await h.fulfill({status:413,body:"capture payload too large"});return}try{let b=JSON.parse(y.toString("utf8"));u?t.receive(b):e.receive(b),await h.fulfill({status:204});}catch(b){await h.fulfill({status:400,body:b instanceof Error?b.message:String(b)});}return}await h.continue();});}a(he,"configureAttachedContext");var Fr=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 Nr(r){let e=[`<script src="${er}"></script>`,`<script type="module" src="${Ze}"></script>`].join(""),t=/<head(?:\s[^>]*)?>/iu.exec(r);return t===null?`${e}${r}`:`${r.slice(0,t.index+t[0].length)}${e}${r.slice(t.index+t[0].length)}`}a(Nr,"injectStaticShaderCaptureHtml");function Hr(r,e){let t=sr(r,e);return [`import { configureThreeBlocksShaderCapture } from ${JSON.stringify(Xe)};`,`configureThreeBlocksShaderCapture( ${JSON.stringify(t).replaceAll("<","\\u003c")} );`].join(`
|
|
90
|
+
`)}a(Hr,"staticCaptureBootstrap");function sr(r,e){return {capture:r==="capture",forceLive:r!=="precompiled",settleFrames:e.settleFrames,settleTimeoutMs:e.settleTimeoutMs??3e4,readiness:e.readiness,transform:I}}a(sr,"shaderCaptureConfiguration");async function Ur(r,e){let t=await k(r,e,a=>/\.(?:c|m)?js$/u.test(a),16384),n=false,s=false,i;for(let a of t){let o=(await j(r,a,a$1.texture,"Static application JavaScript")).data.toString("utf8");if(o.includes("nodeBuilderStateProvider")&&(n=true),o.includes("three-blocks.shader-capture.runtime.v1")&&(s=true,i??=a),n&&s)break}if(!n||!s)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,...i===void 0?{}:{id:i}}}a(Ur,"inspectStaticCaptureTransform");async function Vr(r,e$1){let t;try{t=decodeURIComponent(e$1);}catch{return}if(t.includes("\0"))return;let n=t.replace(/^\/+/u,""),s=g.resolve(r,n.length===0?"index.html":n);if(!e(r,s)||s===r||(await d(s)&&(await lstat(s)).isDirectory()&&(s=g.join(s,"index.html")),!await d(s)&&g.extname(s).length===0&&(s=g.join(r,"index.html")),!await d(s)))return;let i=await j(r,s,a$1.texture,"Static application asset");return {data:i.data,file:i.path}}a(Vr,"staticRequestFile");async function Gr(r,e$1,t,n,s){let i=await realpath(r.root),a=await realpath(g.resolve(i,r.serve));if(!e(i,a)||a===i)throw new Error("--serve must name a built application directory inside the project root.");let o=await Ur(i,a),l=await F(),h=Hr(e$1,t),p=Se(v(r.runtime.three)),f=createServer((d,u)=>{(async()=>{if(ir(d,u,n,s,e$1!=="precompiled"))return;let y=new URL(d.url??"/","http://three-blocks.invalid");if(d.method!=="GET"&&d.method!=="HEAD"){u.statusCode=405,u.end("GET or HEAD required");return}let b=y.pathname===Xe?l:y.pathname===Ze?h:y.pathname===er?p:void 0;if(b!==void 0){u.statusCode=200,u.setHeader("Content-Type","text/javascript; charset=utf-8"),u.setHeader("Cache-Control","no-store"),u.end(d.method==="HEAD"?void 0:b);return}let w=await Vr(a,y.pathname);if(w===void 0){u.statusCode=404,u.end("Not found");return}let P=g.extname(w.file).toLowerCase(),B=P===".html"?Buffer.from(Nr(w.data.toString("utf8"))):w.data;u.statusCode=200,u.setHeader("Content-Type",Fr[P]??"application/octet-stream"),u.setHeader("Content-Length",String(B.byteLength)),u.setHeader("Cache-Control","no-store"),u.end(d.method==="HEAD"?void 0:B);})().catch(y=>{if(u.headersSent)return u.destroy(y instanceof Error?y:void 0);u.statusCode=500,u.end(y instanceof Error?y.message:String(y));});});await new Promise((d,u)=>{f.once("error",u),f.listen(0,"127.0.0.1",()=>{f.off("error",u),d();});});let m=f.address();if(!m||typeof m=="string")throw new Error("Static capture server did not expose an ephemeral TCP address.");return {server:f,baseUrl:`http://127.0.0.1:${m.port}`,transform:o}}a(Gr,"startStaticShaderServer");function Wr(r,e,t){return r===e?true:t&&r!==void 0&&r!=="capture"&&e!=="capture"}a(Wr,"canReuseShaderBrowserSession");function Ye(r){let e=r instanceof Error?r.message:String(r);return e.includes("Execution context was destroyed")&&e.includes("navigation")||/^launch: Timeout \d+ms exceeded\./u.test(e)}a(Ye,"isRetryableShaderObservationNavigation");var J=class{static{a(this,"PlaywrightShaderDriver");}#e;#r=new ye;#n=new ge;#m;#p;#a;#o;#t;#i;#h;#c;#f;#u=0;#l;constructor(e){this.#e=e;}#d(){return this.#m?.status??this.#p??{seen:false,applied:false,alreadyPresent:false}}async#y(e){if(this.#t?.isConnected()===true)return;this.#t=void 0;let t=await Ar();this.#l??=await mkdtemp(g.join(tmpdir(),"three-blocks-shader-cache-")),this.#t=await t.launch({headless:c(this.#e.headed===true),args:[...b(),`--disk-cache-dir=${this.#l}`],timeout:e.timeoutMs}),this.#u=0;}async#s(e,t,n){let s;try{return await Promise.race([n(),new Promise((i,a)=>{s=setTimeout(()=>a(new Error(`launch: Timeout ${t.timeoutMs}ms exceeded.`)),t.timeoutMs);})])}catch(i){throw this.#t===e&&(this.#t=void 0),await L(()=>e.close()),i}finally{s!==void 0&&clearTimeout(s);}}async#g(e,t){let n=this.#a!==void 0||this.#o!==void 0||this.#e.url!==void 0&&this.#i!==void 0,s=this.#o!==void 0?this.#c===e:Wr(this.#c,e,t.bridge.legacyLab);if(n&&s){this.#c=e,await this.#y(t);return}if(n&&await this.close(),this.#c=e,this.#e.url!==void 0){let i=new URL(this.#e.url);if(!["http:","https:"].includes(i.protocol)||i.username||i.password||i.hash)throw new Error("Attached shader URL must be an HTTP(S) URL without credentials or a fragment.");this.#i=i.href,this.#p={seen:true,applied:true,alreadyPresent:false,captureApplied:true,id:"attached-application"},await this.#y(t);return}if(this.#e.serve!==void 0)try{let i=await Gr({root:this.#e.root,runtime:this.#e.runtime,serve:this.#e.serve,...this.#e.headed===void 0?{}:{headed:this.#e.headed}},e,t,this.#r,this.#n);this.#o=i.server,this.#p=i.transform,this.#i=i.baseUrl,await this.#y(t);return}catch(i){throw await this.close(),i}this.#m=Ve(this.#e.runtime.three,{disableTimestampQueries:_.env.THREE_BLOCKS_SOFTWARE_WEBGPU==="1",...t.bridge.legacyLab?{}:{capture:{capture:e==="capture",forceLive:e!=="precompiled",settleFrames:t.settleFrames,settleTimeoutMs:t.settleTimeoutMs??3e4,readiness:t.readiness}}}),this.#h={THREE_BLOCKS_SHADER_TOOL:_.env.THREE_BLOCKS_SHADER_TOOL,THREE_BLOCKS_PRECOMPILE_CAPTURE_SERVER:_.env.THREE_BLOCKS_PRECOMPILE_CAPTURE_SERVER},_.env.THREE_BLOCKS_SHADER_TOOL="1",_.env.THREE_BLOCKS_PRECOMPILE_CAPTURE_SERVER="1";try{let i=await jr(this.#e.root);this.#a=await i({root:this.#e.root,logLevel:"error",plugins:[this.#m.plugin,Lr(this.#r,this.#n,e!=="precompiled",v(this.#e.runtime.three))],server:{host:"127.0.0.1",port:0}}),await this.#a.listen();let a=this.#a.httpServer?.address();if(!a||typeof a=="string")throw new Error("Vite did not expose an ephemeral TCP address.");this.#i=`http://127.0.0.1:${a.port}`,await this.#y(t);}catch(i){throw await this.close(),i}}async capture(e,t){let n=Date.now();if(await this.#g("capture",t),!this.#t||!this.#i)throw new Error("Shader browser driver did not start.");let s=this.#t,i=await this.#s(s,t,()=>s.newContext({viewport:t.viewport}));this.#e.url!==void 0&&await this.#s(s,t,()=>he(i,this.#r,this.#n,"capture",t,v(this.#e.runtime.three)));let a$1=await this.#s(s,t,()=>i.newPage()),o=pe(a$1);this.#n.clear(e.key);let l=this.#r.wait(e.key,t.timeoutMs),h=Promise.race([l,o.first.then(d=>Promise.reject(d))]),p=a(()=>{},"resolveDisconnected"),f=new Promise(d=>{p=d;}),m=a(()=>p(new Error("Shader capture browser disconnected before posting a manifest.")),"onDisconnected");s.on("disconnected",m);try{let d=a$1.goto(We(this.#i,e,{threeBlocksShaderCapture:"1",capture:"1",captureId:e.key,captureFrames:String(Math.max(4,t.settleFrames)),settleFrames:String(t.settleFrames)}),{waitUntil:"domcontentloaded",timeout:t.timeoutMs}),u=await Or(d,Promise.race([h,f.then(b=>Promise.reject(b))]));me(this.#d());let y=[...o.page,...o.console];if(y.length>0)throw new Error(`Capture browser errors:
|
|
91
|
+
- ${y.join(`
|
|
92
|
+
- `)}`);return a$2(u)?{...u,timing:{...a$2(u.timing)?u.timing:{},launch:n,...this.#n.firstRequest(e.key)===void 0?{}:{firstRequest:this.#n.firstRequest(e.key)},posted:Date.now()}}:u}catch(d){let u=d instanceof Error?d:new Error(String(d));this.#r.cancel(e.key,u),await l.catch(()=>{});let y=this.#n.read(e.key);if(u.message.includes("timed out")){let b=await Ke(()=>a$1.evaluate(()=>{let w=globalThis,P=w.__threeBlocksShaderTools,B=P&&typeof P=="object"?P:void 0,M=w.document,k=Reflect.get(w,Symbol.for("three-blocks.shader-capture.cache-value.v1")),R=w.location,N=R!==null&&typeof R=="object"&&typeof Reflect.get(R,"href")=="string"?String(Reflect.get(R,"href")):"http://three-blocks.invalid/",H=new URL(N).searchParams.get("captureId")??"default",z=k!==null&&typeof k=="object"&&typeof Reflect.get(k,"registrations")=="function"?Reflect.apply(Reflect.get(k,"registrations"),k,[H]):void 0;return {documentReadyState:M?.readyState??null,parityTargetFrame:Number(w.__threeBlocksParityTargetFrame??0),parityCompletedFrame:Number(w.__threeBlocksParityCompletedFrame??0),readiness:B?.readiness??null,captureCache:k!==null&&typeof k=="object"?{activeScene:Reflect.get(k,"activeScene")??null,registrations:Array.isArray(z)?z.slice(0,16).map(x=>x!==null&&typeof x=="object"?{key:Reflect.get(x,"key")??null,kind:Reflect.get(x,"kind")??null}:null):null}:null,threeRuntimeResources:performance.getEntriesByType("resource").map(x=>x.name).filter(x=>x.includes("three.webgpu"))}}));throw new Error(`${u.message} Last capture state for "${e.key}": ${JSON.stringify({page:b,telemetry:y??null,transform:this.#d()})}`)}throw u}finally{s.off("disconnected",m),await L(()=>i.close()),this.#u++,(!s.isConnected()||this.#u>=(t.browserRelaunchScenes??8))&&(this.#t===s&&(this.#t=void 0),await L(()=>s.close()),this.#u=0);}}async observe(e,t,n,s){for(let i=0;i<2;i++)try{return await this.#S(e,t,n,s)}catch(a){if(i===0&&Ye(a))continue;throw a}throw new Error(`Shader observation retry was exhausted for scene "${e.key}".`)}async#S(e,t,n,s){if(await this.#g(t,n),!this.#t||!this.#i)throw new Error("Shader browser driver did not start.");let i=this.#t,a=await this.#s(i,n,()=>i.newContext({viewport:n.viewport}));this.#e.url!==void 0&&await this.#s(i,n,()=>he(a,this.#r,this.#n,t,n,v(this.#e.runtime.three)));let o=await this.#s(i,n,()=>a.newPage()),l=pe(o);this.#n.clear(e.key);try{await o.goto(We(this.#i,e,{threeBlocksShaderCapture:"1",threeBlocksShaderMode:t,captureId:e.key,...t==="live"?{precompiled:"0"}:{}}),{waitUntil:"domcontentloaded",timeout:n.timeoutMs}),await Promise.race([o.waitForFunction(n.bridge.legacyLab?"globalThis.__threeBlocks?.compileEnd === true":"globalThis.__threeBlocksShaderTools?.readiness?.compileEnd === true",void 0,{timeout:n.timeoutMs}),l.first.then(u=>Promise.reject(u))]),ee(await re(o,n.bridge.legacyLab),e,n.bridge.legacyLab,this.#d(),v(this.#e.runtime.three)),await Je(o,n,l),await Promise.race([o.waitForFunction(n.bridge.legacyLab?"true":"globalThis.__threeBlocksShaderTools?.readiness?.firstFrame === true",void 0,{timeout:n.timeoutMs}),l.first.then(u=>Promise.reject(u))]),await K(o,n,1);let h=Buffer.from(await o.screenshot({type:"png"})),p=e.parityFrames??n.parity.frames,f=await K(o,n,p,s),m=Buffer.from(await o.screenshot({type:"png"}));e.parityFrames!==void 0&&p<n.parity.frames&&await K(o,n,n.parity.frames-p);let d=ee(await re(o,n.bridge.legacyLab),e,n.bridge.legacyLab,this.#d(),v(this.#e.runtime.three));return this.#f===void 0&&(this.#f=await o.evaluate(async()=>{let u=Reflect.get(navigator,"gpu"),y=typeof u=="object"&&u!==null?Reflect.get(u,"requestAdapter"):void 0,b=typeof y=="function"?await Reflect.apply(y,u,[]):void 0,w=typeof b=="object"&&b!==null?Reflect.get(b,"info"):void 0,P=["description","device","architecture","vendor"].flatMap(B=>{let M=typeof w=="object"&&w!==null?Reflect.get(w,B):void 0;return typeof M=="string"&&M.length>0?[M]:[]});return {adapter:[...new Set(P)].join(" \xB7 ")||"WebGPU adapter",platform:navigator.platform||navigator.userAgent}})),{scene:e.key,mode:t,...d,frame:f,firstFrameScreenshot:h,screenshot:m,errors:[...l.page,...l.console]}}catch(h){let p=h instanceof Error?h:new Error(String(h));if(/(?:timed?\s*out|timeout)/iu.test(p.message)){let f=this.#n.read(e.key),m=await Ke(()=>o.evaluate(()=>{let d=globalThis,u=d.__threeBlocksShaderTools,y=u&&typeof u=="object"?u:void 0;return {documentReadyState:d.document?.readyState??null,parityTargetFrame:Number(d.__threeBlocksParityTargetFrame??0),parityCompletedFrame:Number(d.__threeBlocksParityCompletedFrame??0),readiness:y?.readiness??null,threeRuntimeResources:performance.getEntriesByType("resource").map(w=>w.name).filter(w=>w.includes("three.webgpu"))}}));throw new Error(`${p.message} Last ${t} state for "${e.key}": ${JSON.stringify({page:m,telemetry:f??null})}`)}throw p}finally{await L(()=>a.close());}}async observePublished(e,t){for(let n=0;n<2;n++)try{return await this.#w(e,t)}catch(s){if(n===0&&Ye(s))continue;throw s}throw new Error(`Published shader observation retry was exhausted for scene "${e.key}".`)}async#w(e,t){if(await this.#g("precompiled",t),!this.#t||!this.#i)throw new Error("Shader browser driver did not start.");let n=this.#t,s=await this.#s(n,t,()=>n.newContext({viewport:t.viewport}));this.#e.url!==void 0&&await this.#s(n,t,()=>he(s,this.#r,this.#n,"precompiled",t,v(this.#e.runtime.three)));let i=await this.#s(n,t,()=>s.newPage()),a=pe(i);this.#n.clear(e.key);try{await i.goto(Dr(this.#i,e),{waitUntil:"domcontentloaded",timeout:t.timeoutMs}),await Promise.race([i.waitForFunction(t.bridge.legacyLab?"globalThis.__threeBlocks?.compileEnd === true":"globalThis.__threeBlocksShaderTools?.readiness?.compileEnd === true",void 0,{timeout:t.timeoutMs}),a.first.then(f=>Promise.reject(f))]),await Je(i,t,a),ee(await re(i,t.bridge.legacyLab),e,t.bridge.legacyLab,this.#d(),v(this.#e.runtime.three)),await K(i,t,2);let o=await ze(i),l=await K(i,t,120),h=await ze(i),p=ee(await re(i,t.bridge.legacyLab),e,t.bridge.legacyLab,this.#d(),v(this.#e.runtime.three));return {scene:e.key,mode:"precompiled",...p,frame:l,firstFrameScreenshot:o,beforeScreenshot:o,screenshot:h,errors:[...a.page,...a.console]}}finally{await L(()=>s.close());}}timingEnvironment(){return this.#f??{adapter:"WebGPU adapter",platform:`${_.platform}/${_.arch}`}}async close(){this.#r.rejectAll(new Error("Shader browser driver closed.")),this.#t&&await L(()=>this.#t?.close()??Promise.resolve());let e=this.#a?.httpServer,t=e?Reflect.get(e,"closeAllConnections"):void 0;if(e&&typeof t=="function"&&Reflect.apply(t,e,[]),this.#a&&await L(()=>this.#a?.close()??Promise.resolve()),this.#o){let n=this.#o;n.closeAllConnections(),await L(()=>new Promise(s=>{n.close(()=>s());}));}if(this.#t=void 0,this.#a=void 0,this.#o=void 0,this.#i=void 0,this.#m=void 0,this.#p=void 0,this.#c=void 0,this.#f=void 0,this.#u=0,this.#l!==void 0&&(await rm(this.#l,{recursive:true,force:true}),this.#l=void 0),this.#h){for(let[n,s]of Object.entries(this.#h))s===void 0?delete _.env[n]:_.env[n]=s;this.#h=void 0;}}};function Ut(r){return new J(r)}a(Ut,"createPlaywrightShaderDriver");function Vt(r){return new J(r)}a(Vt,"createStaticPlaywrightShaderDriver");function Gt(r){return new J(r)}a(Gt,"createAttachedPlaywrightShaderDriver");
|
|
93
|
+
export{v as a,I as b,it as c,C as d,st as e,at as f,ot as g,dt as h,ct as i,ut as j,Or as k,Ir as l,Se as m,Wr as n,Ye as o,Ut as p,Vt as q,Gt as r};
|