@gasm-compiler/core 0.4.0 → 0.5.0

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.
@@ -0,0 +1,9 @@
1
+ import{A as pe,B as me,C as ge,H as B,I as P,J as j,K as H,L as Z,M as K,N as J,P as Q,T as he,U as ye,a as S,c as oe,d as C,e as D,f as V,g as z,h as T,j as N,k as q,n as ie,p as se,q as ae,r as ce,s as ue,t as le,y as de,z as fe}from"./chunk-MBWDLAL5.js";import{a as h}from"./chunk-STDXBN5E.js";import{resolve as We}from"node:path";import{stat as De,readFile as mt,writeFile as gt,unlink as ht,mkdir as yt}from"node:fs/promises";import{spawn as bt}from"node:child_process";import{dirname as wt}from"node:path";function be(e){let n=e.functions.map(r=>!("parallelLoopInfo"in r)||!r.parallelLoopInfo?r:Pe(r));return{...e,functions:n}}function Pe(e){let n=e.parallelLoopInfo.loopLocalIndex,{writes:r}=Le(e.body,n);if(r>0){let t=M(e.body,n);return{...e,body:t}}return e}function Le(e,n){let r=0,t=0;function o(s){switch(s.kind){case"simple":if(s.instructions)for(let i of s.instructions)i.opcode==="local.get"&&i.immediates?.[0]===n&&r++,(i.opcode==="local.set"||i.opcode==="local.tee")&&i.immediates?.[0]===n&&t++;break;case"block":for(let i of s.children)o(i);break;case"loop":o(s.body);break;case"if":o(s.thenBranch),s.elseBranch&&o(s.elseBranch);break;case"parallel_loop":o(s.body),s.epilogue&&o(s.epilogue);break;case"return":case"break":case"continue":break}}return o(e),{reads:r,writes:t}}function M(e,n){switch(e.kind){case"simple":{if(!e.instructions)return e;let r=e.instructions.filter(t=>!((t.opcode==="local.set"||t.opcode==="local.tee")&&t.immediates?.[0]===n));return r.length===0?{kind:"block",children:[]}:{...e,instructions:r}}case"block":{let r=e.children.map(t=>M(t,n)).filter(t=>!Ue(t));return{...e,children:r}}case"loop":return{...e,body:M(e.body,n)};case"if":return{...e,thenBranch:M(e.thenBranch,n),elseBranch:e.elseBranch?M(e.elseBranch,n):void 0};case"parallel_loop":return{...e,body:M(e.body,n),epilogue:e.epilogue?M(e.epilogue,n):void 0};case"return":case"break":case"continue":return e}}function Ue(e){return e.kind==="block"&&e.children.length===0||e.kind==="simple"&&(!e.instructions||e.instructions.length===0)}function we(e){let n=e.functions.map(r=>Fe(r));return{...e,functions:n}}function Fe(e){let n=E(e.body,e);return{...e,body:n}}function E(e,n){switch(e.kind){case"loop":{let r=Ge(e.body),t=[],o=Se(e.body,r,t,n);return t.length===0?{...e,body:E(e.body,n)}:{kind:"block",children:[{kind:"simple",instructions:t},{...e,body:E(o,n)}],label:void 0}}case"block":return{...e,children:e.children.map(r=>E(r,n))};case"if":return{...e,thenBranch:E(e.thenBranch,n),elseBranch:e.elseBranch?E(e.elseBranch,n):void 0};case"simple":return e;default:return e}}function Ge(e){let n=new Set;function r(t){if(t.kind==="simple"&&t.instructions){for(let o of t.instructions)if(o.id!==void 0&&n.add(o.id),(o.opcode==="local.set"||o.opcode==="local.tee")&&o.immediates){let s=o.immediates[0];n.add(-s-1)}}t.kind==="block"&&t.children.forEach(r),t.kind==="loop"&&r(t.body),t.kind==="if"&&(r(t.thenBranch),t.elseBranch&&r(t.elseBranch))}return r(e),n}function Se(e,n,r,t){switch(e.kind){case"simple":{if(!e.instructions||e.instructions.length===0)return e;let o=[],s=new Set;for(let i of e.instructions)ze(i,n,s)?(r.push(i),i.id!==void 0&&s.add(i.id)):(o.push(i),i.id!==void 0&&s.add(i.id));return{...e,instructions:o}}case"block":{let o=e.children.map(s=>Se(s,n,r,t));return{...e,children:o}}case"loop":return e;case"if":return e;default:return e}}function ze(e,n,r){if(!Te(e.opcode))return!1;if(e.opcode==="local.get"&&e.immediates){let o=-e.immediates[0]-1;if(n.has(o))return!1}if(e.args){for(let t of e.args)if(n.has(t))return!1}return!0}function Te(e){return new Set(["i32.const","i64.const","f32.const","f64.const","local.get","i32.add","i32.sub","i32.mul","i32.div_s","i32.div_u","i32.rem_s","i32.rem_u","i64.add","i64.sub","i64.mul","i64.div_s","i64.div_u","i64.rem_s","i64.rem_u","f32.add","f32.sub","f32.mul","f32.div","f64.add","f64.sub","f64.mul","f64.div","i32.and","i32.or","i32.xor","i32.shl","i32.shr_s","i32.shr_u","i32.rotl","i32.rotr","i64.and","i64.or","i64.xor","i64.shl","i64.shr_s","i64.shr_u","i64.rotl","i64.rotr","i32.eqz","i32.eq","i32.ne","i32.lt_s","i32.lt_u","i32.gt_s","i32.gt_u","i32.le_s","i32.le_u","i32.ge_s","i32.ge_u","i64.eqz","i64.eq","i64.ne","i64.lt_s","i64.lt_u","i64.gt_s","i64.gt_u","i64.le_s","i64.le_u","i64.ge_s","i64.ge_u","f32.eq","f32.ne","f32.lt","f32.gt","f32.le","f32.ge","f64.eq","f64.ne","f64.lt","f64.gt","f64.le","f64.ge","i32.wrap_i64","i64.extend_i32_s","i64.extend_i32_u","f32.convert_i32_s","f32.convert_i32_u","f32.convert_i64_s","f32.convert_i64_u","f32.demote_f64","f64.convert_i32_s","f64.convert_i32_u","f64.convert_i64_s","f64.convert_i64_u","f64.promote_f32","i32.reinterpret_f32","i64.reinterpret_f64","f32.reinterpret_i32","f64.reinterpret_i64","i32.clz","i32.ctz","i32.popcnt","i64.clz","i64.ctz","i64.popcnt","f32.abs","f32.neg","f32.ceil","f32.floor","f32.trunc","f32.nearest","f32.sqrt","f64.abs","f64.neg","f64.ceil","f64.floor","f64.trunc","f64.nearest","f64.sqrt","f32.min","f32.max","f32.copysign","f64.min","f64.max","f64.copysign"]).has(e)}function Ie(e){for(let n of e.functions)Ne(n);return e}function Ne(e){A(e.body,e)}function A(e,n){switch(e.kind){case"simple":qe(e,n);break;case"block":for(let r of e.children)A(r,n);break;case"loop":A(e.body,n);break;case"if":A(e.thenBranch,n),e.elseBranch&&A(e.elseBranch,n);break;case"parallel_loop":A(e.body,n),e.epilogue&&A(e.epilogue,n);break}}function qe(e,n){let r=Ze(e.instructions,n);r.length>0&&Je(e,n,r);let t=Ke(e.instructions,n);t.length>0&&Qe(e,n,t)}function ve(e,n){let r=U(e,n);if(!r)return null;if(r.opcode==="i32.shr_u"&&r.args.length===2){if(L(r.args[1],n)!==2)return null;let o=r.args[0];return je(o,n)}return He(e,n)}function je(e,n){let r=U(e,n);if(!r)return{baseVar:e,wordOffset:0};if(r.opcode==="i32.add"&&r.args.length===2){let t=L(r.args[1],n);if(t!==null&&t>=0&&t%4===0)return{baseVar:r.args[0],wordOffset:t/4};let o=L(r.args[0],n);return o!==null&&o>=0&&o%4===0?{baseVar:r.args[1],wordOffset:o/4}:null}return{baseVar:e,wordOffset:0}}function He(e,n){let r=U(e,n);if(!r)return{baseVar:e,wordOffset:0};if(r.opcode==="i32.add"&&r.args.length===2){let t=L(r.args[1],n);if(t!==null&&t>=0)return{baseVar:r.args[0],wordOffset:t}}return{baseVar:e,wordOffset:0}}function U(e,n){if(n.inlinedExpressionMap){let r=n.inlinedExpressionMap.get(e);if(r)return r}return $(n.body,e)}function $(e,n){switch(e.kind){case"simple":for(let r of e.instructions)if(r.id===n)return r;return null;case"block":for(let r of e.children){let t=$(r,n);if(t)return t}return null;case"loop":return $(e.body,n);case"if":{let r=$(e.thenBranch,n);return r||(e.elseBranch?$(e.elseBranch,n):null)}case"parallel_loop":{let r=$(e.body,n);return r||(e.epilogue?$(e.epilogue,n):null)}default:return null}}function L(e,n){let r=U(e,n);return r&&r.opcode==="i32.const"&&r.immediates&&r.immediates.length>0?r.immediates[0]:null}function Ze(e,n){let r=[],t=[];for(let s=0;s<e.length;s++){let i=e[s];if(i.opcode==="wgsl.store_f32"&&i.args.length===2){let a=ve(i.args[0],n);a&&t.push({index:s,addr:a,valueArg:i.args[1]})}}let o=new Map;for(let s of t){let i=o.get(s.addr.baseVar)||[];i.push(s),o.set(s.addr.baseVar,i)}for(let[s,i]of o){if(i.length<3)continue;i.sort((c,u)=>c.addr.wordOffset-u.addr.wordOffset);let a=0;for(;a<i.length;){let c=a;for(;c+1<i.length&&i[c+1].addr.wordOffset===i[c].addr.wordOffset+1;)c++;let u=c-a+1;if(u>=3){let p=u>=4?4:3,d=i.slice(a,a+p),f=d.map(g=>g.index);ke(f,e)&&r.push({instrIndices:f,baseVar:s,valueArgs:d.map(g=>g.valueArg),components:p})}a=c+1}}return r}function Ke(e,n){let r=[],t=[];for(let s=0;s<e.length;s++){let i=e[s];if(i.opcode==="wgsl.load_f32"&&i.args.length===1&&i.id!==void 0){let a=ve(i.args[0],n);a&&t.push({index:s,addr:a,resultVar:i.id})}}let o=new Map;for(let s of t){let i=o.get(s.addr.baseVar)||[];i.push(s),o.set(s.addr.baseVar,i)}for(let[s,i]of o){if(i.length<3)continue;i.sort((c,u)=>c.addr.wordOffset-u.addr.wordOffset);let a=0;for(;a<i.length;){let c=a;for(;c+1<i.length&&i[c+1].addr.wordOffset===i[c].addr.wordOffset+1;)c++;let u=c-a+1;if(u>=3){let p=u>=4?4:3,d=i.slice(a,a+p),f=d.map(g=>g.index);ke(f,e)&&r.push({instrIndices:f,baseVar:s,resultVars:d.map(g=>g.resultVar),components:p})}a=c+1}}return r}function ke(e,n){if(e.length<3)return!1;let r=Math.min(...e),t=Math.max(...e),o=e.length*4;if(t-r>=o)return!1;for(let s=r;s<=t;s++)if(n[s].opcode.startsWith("wgsl.store")&&!e.includes(s))return!1;return!0}function Je(e,n,r){r.sort((t,o)=>o.instrIndices[0]-t.instrIndices[0]);for(let t of r){let o=t.components===4?"wgsl.store_vec4f":"wgsl.store_vec3f",s=e.instructions[t.instrIndices[0]].args[0],i={type:"instr",opcode:o,args:[s,...t.valueArgs],synthetic:!0},a=[...t.instrIndices].sort((c,u)=>c-u);for(let c=a.length-1;c>=0;c--)e.instructions.splice(a[c],1);e.instructions.splice(a[0],0,i)}}function Qe(e,n,r){r.sort((t,o)=>o.instrIndices[0]-t.instrIndices[0]);for(let t of r){let o=t.components===4?"wgsl.load_vec4f":"wgsl.load_vec3f",s=0;for(let d of n.vars.keys())d>s&&(s=d);let i=s+1;n.vars.set(i,{id:i,type:"v128"});let a=e.instructions[t.instrIndices[0]].args[0],c={type:"instr",id:i,opcode:o,args:[a],synthetic:!0},u=t.resultVars.map((d,f)=>({type:"instr",id:d,opcode:"wgsl.extract_f32",args:[i],immediates:[f],synthetic:!0})),p=[...t.instrIndices].sort((d,f)=>d-f);for(let d=p.length-1;d>=0;d--)e.instructions.splice(p[d],1);e.instructions.splice(p[0],0,c,...u)}}function X(e,n){let r={valid:!0,mathImports:[],errors:[],requiredLevel:null},t=n===!0||n==="M0"||n==="M1"||n==="M2",o=n===!0?"M2":n==="M0"||n==="M1"||n==="M2"?n:null,s=["M0","M1","M2"],i=0;for(let a of e.imports){if(a.kind!=="func")continue;let c=i++;if(!N(a.module,a.name))continue;let u=a.typeIndex;if(u===void 0){r.errors.push(S(`Math import ${a.name} has no type index`,{functionName:a.name})),r.valid=!1;continue}let p=e.types[u];if(!p){r.errors.push(S(`Math import ${a.name} references invalid type index ${u}`,{functionName:a.name})),r.valid=!1;continue}let d=q(a.name);if(!d){r.errors.push(S(`Unknown math intrinsic: ${a.name}`,{functionName:a.name})),r.valid=!1;continue}let f={funcIndex:c,module:a.module,name:a.name,level:d.level,params:p.params,results:p.results};if(r.mathImports.push(f),(r.requiredLevel===null||s.indexOf(d.level)>s.indexOf(r.requiredLevel))&&(r.requiredLevel=d.level),!t){r.errors.push(S(`Math intrinsic ${a.name} requires mathExtension option to be enabled`,{functionName:a.name})),r.valid=!1;continue}if(o&&!ie(a.name,o)){r.errors.push(S(`Math intrinsic ${a.name} requires level ${d.level}, but only ${o} is enabled`,{functionName:a.name})),r.valid=!1;continue}let g=se(a.name,p.params,p.results);g&&(r.errors.push(S(g,{functionName:a.name})),r.valid=!1)}return r}import{readFileSync as Xe}from"node:fs";var xe,Me;async function Ye(e=ee()){let n=await tt(e),r=await WebAssembly.instantiate($e(n),{});return Z(r.instance.exports)}function Y(e=ee()){return Me??=Ye(e),Me}function et(e=ee()){let n=nt(e),r=new WebAssembly.Module($e(n)),t=new WebAssembly.Instance(r,{});return Z(t.exports)}function Ae(e,n={}){return xe??=et(),xe.compile(e,n)}function ee(){let e=globalThis.Deno,n=new URL("./gasm_core_rs.wasm",import.meta.url);if(e){let r=new URL("../../core-rs/target/wasm32-unknown-unknown/debug/gasm_core_rs.wasm",import.meta.url);try{return e.statSync(r),r}catch{}let t=new URL("../../core-rs/target/wasm32-unknown-unknown/release/gasm_core_rs.wasm",import.meta.url);try{return e.statSync(t),t}catch{}try{return e.statSync(n),n}catch{}}return new URL("../../core-rs/target/wasm32-unknown-unknown/debug/gasm_core_rs.wasm",import.meta.url)}async function tt(e){let n=globalThis.Deno;return n?await n.readFile(e):await(await import("node:fs/promises")).readFile(e)}function nt(e){let n=globalThis.Deno;return n?n.readFileSync(e):Xe(e)}function $e(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}var _e={};for(let[e,n]of Object.entries(oe))_e[n]=e.replace(/_/g,".");function rt(e){let n=[];n.push("(module");for(let t of e.memories)n.push(` (memory ${t.min}${t.max!==void 0?` ${t.max}`:""})`);for(let t of e.imports)if(t.kind==="func"&&t.typeIndex!==void 0){let o=e.types[t.typeIndex];if(o){let s=o.params.map((a,c)=>`(param $${c} ${a})`).join(" "),i=o.results.map(a=>`(result ${a})`).join(" ");n.push(` (import "${t.module}" "${t.name}" (func ${s}${i?" "+i:""}))`)}}let r=new Set;for(let t of e.globals){if(t.kind==="import")continue;let o=t.mutable?"(mut ":"",s=t.mutable?")":"",i="";t.initValue!==void 0&&(t.type==="i32"||t.type==="i64"?i=`${t.type}.const ${t.initValue}`:(t.type==="f32"||t.type==="f64")&&(i=`${t.type}.const ${t.initValue}`)),n.push(` (global $${t.index} ${o}${t.type}${s} ${i?`(${i})`:""})`)}for(let t of e.data){let o=Array.from(t.data.slice(0,Math.min(32,t.data.length))).map(i=>`\\${i.toString(16).padStart(2,"0")}`).join(""),s=t.data.length>32?"...":"";n.push(` (data (i32.const ${t.memoryIndex}) "${o}${s}") ;; ${t.data.length} bytes`)}for(let t of e.functions)n.push(""),n.push(...ot(t,e));if(e.exports.length>0){n.push("");for(let t of e.exports)t.kind==="func"?n.push(` (export "${t.name}" (func $${t.index}))`):t.kind==="mem"?n.push(` (export "${t.name}" (memory ${t.index}))`):t.kind==="global"&&n.push(` (export "${t.name}" (global ${t.index}))`)}return e.startFunctionIndex!==void 0&&n.push(` (start $${e.startFunctionIndex})`),n.push(")"),n.join(`
2
+ `)}function ot(e,n){let r=[],t=e.params.map((i,a)=>`(param $${a} ${i})`).join(" "),o=e.results.map(i=>`(result ${i})`).join(" ");if(r.push(` (func $${e.index} ${t}${o?" "+o:""}`),e.locals.length>0){let i=new Map;for(let a of e.locals)i.set(a.type,(i.get(a.type)||0)+1);for(let[a,c]of i)r.push(` (local ${a} (;${c}x;))`)}let s=it(e.body,2);return r.push(...s),r.push(" )"),r}function it(e,n){let r=[],t=" ".repeat(n);for(let o of e){let s=st(o,n);r.push(`${t}${s}`)}return r}function st(e,n){if(!e||typeof e!="object")return";; Error: Invalid instruction";let{opcode:r,immediates:t}=e,o=_e[r]||`unknown_0x${r.toString(16)}`;if(!t||t.length===0)return o;switch(o){case"local.get":case"local.set":case"local.tee":return`${o} $${t[0]}`;case"global.get":case"global.set":return`${o} $${t[0]}`;case"i32.const":case"i64.const":return`${o} ${t[0]}`;case"f32.const":case"f64.const":return`${o} ${t[0]}`;case"call":return`${o} $${t[0]}`;case"call_indirect":return`${o} (type ${t[0]})`;case"br":case"br_if":return`${o} ${t[0]}`;case"br_table":let s=t[0].join(" "),i=t[1];return`${o} ${s} ${i}`;case"if":case"block":case"loop":let a=t[0];return`${o} ${a!==void 0&&a!=="void"?`(result ${a})`:""}`;case"i32.load":case"i64.load":case"f32.load":case"f64.load":case"i32.load8_s":case"i32.load8_u":case"i32.load16_s":case"i32.load16_u":case"i64.load8_s":case"i64.load8_u":case"i64.load16_s":case"i64.load16_u":case"i64.load32_s":case"i64.load32_u":case"i32.store":case"i64.store":case"f32.store":case"f64.store":case"i32.store8":case"i32.store16":case"i64.store8":case"i64.store16":case"i64.store32":let c=t[0],u=t[1],p=[];return u!==0&&p.push(`offset=${u}`),c!==void 0&&p.push(`align=${1<<c}`),`${o}${p.length>0?" "+p.join(" "):""}`;case"memory.size":case"memory.grow":return o;default:if(o.startsWith("v128.")){if(o.includes("load")||o.includes("store")){let d=t[0],f=t[1],g=[];return f!==0&&g.push(`offset=${f}`),d!==void 0&&g.push(`align=${1<<d}`),`${o}${g.length>0?" "+g.join(" "):""}`}if(o.includes("const")){let d=t.join(" ");return`${o} ${d}`}return o.includes("extract_lane")||o.includes("replace_lane")?`${o} ${t[0]}`:`${o}${t.length>0?" "+t.join(" "):""}`}return`${o}${t.length>0?" "+t.join(" "):""}`}}var Ut=globalThis.gpu,at=globalThis.navigator?.gpu,te=class{constructor(n={}){this.config=n}device=null;queue=null;initialized=!1;buffers=new Map;async ensureInitialized(){if(!this.initialized)try{let n=await at?.requestAdapter?.();if(!n)throw new h("No GPU adapter available","compilation","navigator.gpu.requestAdapter() returned null");if(this.device=await n.requestDevice?.(),!this.device)throw new h("Failed to request GPU device","compilation","adapter.requestDevice() returned null");this.queue=this.device.queue,this.initialized=!0}catch(n){throw n instanceof h?n:new h(`GPU initialization failed: ${n instanceof Error?n.message:String(n)}`,"compilation",String(n))}}createBuffer(n,r,t){if(!this.device)throw new h("Device not initialized","binding","Call ensureInitialized() first");let o=this.device.createBuffer({label:n,size:r.byteLength,usage:t});return this.queue.writeBuffer(o,0,r.buffer,r.byteOffset,r.byteLength),o}async readBuffer(n,r,t){if(!this.device||!this.queue)throw new h("Device not initialized","readback","Call ensureInitialized() first");let o=Math.max(4,Math.ceil(r/4)*4),s=this.device.createBuffer({size:o,usage:9}),i=this.device.createCommandEncoder();i.copyBufferToBuffer(n,0,s,0,Math.min(r,o)),this.queue.submit([i.finish()]);try{await s.mapAsync(1)}catch(u){throw s.destroy(),new h(`Failed to map staging buffer: ${u instanceof Error?u.message:String(u)}`,"readback",String(u))}let a=s.getMappedRange(),c;return t==="f32"?c=new Float32Array(new Uint8Array(a).buffer).slice():t==="i32"?c=new Int32Array(new Uint8Array(a).buffer).slice():c=new Uint32Array(new Uint8Array(a).buffer).slice(),s.unmap(),s.destroy(),{data:c,type:t}}async execute(n,r,t,o={}){let s=o.workgroupSize??[1,1,1],i=o.workgroupCount??[1,1,1],a=o.timeout??5e3;if(await this.ensureInitialized(),!this.device||!this.queue)throw new h("Device initialization failed","compilation");try{let c;try{let l=o.shaderLabel||"Gasm Compiler Compute Shader";c=this.device.createShaderModule({code:n,label:l});let m=await c.getCompilationInfo?.();if(m&&m.messages.length>0){let y=m.messages.filter(w=>w.type==="error");if(y.length>0){let w=y.map(x=>`${x.message} at ${x.lineNum}:${x.linePos}`).join("; ");throw new h(`WGSL compilation failed: ${w}`,"compilation")}}}catch(l){throw l instanceof h?l:new h(`Failed to create shader module: ${l instanceof Error?l.message:String(l)}`,"compilation",String(l))}let u=[],p=0,d=new Map,f=Object.entries(r).sort((l,m)=>l[0]==="memory"?-1:m[0]==="memory"?1:l[0].localeCompare(m[0]));for(let[l,{data:m,type:y}]of f){let w=this.createBuffer(`input_${l}`,m,140);d.set(l,w),u.push({binding:p++,resource:{buffer:w}})}let g=new Map,v=new Map;for(let l of t){if(d.has(l)){let Be=d.get(l),re=r[l];g.set(l,Be),v.set(l,{size:re.data.byteLength,type:re.type});continue}let m=o.outputBuffers?.[l]??{type:"f32",size:1},y=m.size??1,w=y*4,x=this.device.createBuffer({label:`output_${l}`,size:w,usage:140}),_;m.type==="f32"?_=new Float32Array(y).fill(0):m.type==="i32"?_=new Int32Array(y).fill(0):_=new Uint32Array(y).fill(0),this.queue.writeBuffer(x,0,_.buffer,_.byteOffset,_.byteLength),g.set(l,x),v.set(l,{size:w,type:m.type}),u.push({binding:p++,resource:{buffer:x}})}let b=Object.keys(r).length,k=this.device.createBindGroupLayout({entries:u.map((l,m)=>{let y=m===0&&r.memory!==void 0,w=m>=b;return{binding:m,visibility:4,buffer:{type:!y&&!w?"read-only-storage":"storage"}}})}),I=this.device.createBindGroup({layout:k,entries:u}),R=this.device.createPipelineLayout({bindGroupLayouts:[k]}),O;try{O=this.device.createComputePipeline({layout:R,compute:{module:c,entryPoint:"main"}})}catch(l){throw new h(`Failed to create compute pipeline: ${l instanceof Error?l.message:String(l)}`,"binding",String(l))}try{let l=this.device.createCommandEncoder(),m=l.beginComputePass();m.setPipeline(O),m.setBindGroup(0,I),m.dispatchWorkgroups(i[0],i[1],i[2]),m.end(),this.queue.submit([l.finish()])}catch(l){throw new h(`Compute shader dispatch failed: ${l instanceof Error?l.message:String(l)}`,"dispatch",String(l))}let W={};try{for(let l of t){let m=g.get(l),y=v.get(l);if(!m||!y)throw new h(`Output buffer "${l}" not found`,"readback");W[l]=await this.readBuffer(m,y.size,y.type)}}catch(l){throw l instanceof h?l:new h(`Failed to read back results: ${l instanceof Error?l.message:String(l)}`,"readback",String(l))}finally{let l=new Set;d.forEach(m=>{m.destroy(),l.add(m)}),g.forEach(m=>{l.has(m)||m.destroy()})}return W}catch(c){throw c instanceof h?c:new h(`Unexpected error during execution: ${c instanceof Error?c.message:String(c)}`,"dispatch",String(c))}}async destroy(){this.buffers.forEach(n=>n.destroy()),this.buffers.clear(),this.device&&typeof this.device.destroy=="function"&&this.device.destroy(),this.device=null,this.queue=null,this.initialized=!1}};function F(e,n={}){let r=G()?Ce(e,n):ne(e,n);return j(r.diagnostics),r}function lt(e,n={}){let r,t=s=>{r=s},o=G()?Ce(e,n,t):ne(e,n,t);if(!o.ok)return o;if(!r)throw new Error("Compiler succeeded without a validated Wasm module");return{...o,metadata:Q(r,{options:n,dispatchInfo:o.dispatchInfo})}}function _n(e,n={}){let r=ye(e,n);if(r.errors.length>0){let o=P();return o.advisories.push(...r.advisories),o.errors.push(...r.errors),{ok:!1,diagnostics:o}}let t=lt(r.wasmBytes,r.compileOptions);return t.diagnostics.advisories.push(...r.advisories),t.ok?{...t,bindings:t.metadata.bindings,...r.mutableGlobalsInit?{mutableGlobalsInit:r.mutableGlobalsInit}:{}}:t}async function Cn(){G()&&await Y()}async function dt(e,n={}){let r=G()?await ft(e,n):ne(e,n);return j(r.diagnostics),r}function ne(e,n={},r){let t=P(),o=B(n),s=n.strictConformance||o,i=D(e);if(V(i))return t.errors.push({severity:"error",code:i.code??C.ERR_PARSE,message:i.message,functionName:i.functionName}),{ok:!1,diagnostics:t};let a=i,c=z(a,{strictConformance:s});if(T(c))return t.errors.push({severity:"error",code:c.code??C.ERR_VALIDATION,message:c.message,functionName:c.functionName}),{ok:!1,diagnostics:t};let u=c;if(Re(t,u,n),n.mathExtension){let b=X(a,n.mathExtension);if(!b.valid){for(let k of b.errors)t.errors.push({severity:"error",code:"ERR_MATH_VALIDATION",message:k.message,functionName:k.functionName});return{ok:!1,diagnostics:t}}}let p=H(u,n);if(t.warnings.push(...p.diagnostics.warnings),t.errors.push(...p.diagnostics.errors),t.demotions.push(...p.diagnostics.demotions),t.featuresUsed=p.diagnostics.featuresUsed,t.errors.length>0)return{ok:!1,diagnostics:t};r?.(u);let d=fe(u);n.optimize!==!1&&(d=me(d,{verbose:n.verbose??!1}));let f=ge(d);f=ae(f),n.optimize!==!1&&(f=ce(f)),n.vectorPromotion&&(f=Ie(f));let g=ue();if(n.optimize!==!1){let b=le(f);f=b.module,g=b.dispatchInfo,f=be(f),f=we(f)}return{ok:!0,wgsl:pe(f,n,e,g),diagnostics:t,dispatchInfo:g}}function G(){let n=globalThis.Deno?.env?.get("GASM_CORE_BACKEND")?.toLowerCase();return n!=="typescript"&&n!=="ts"}function Ce(e,n,r){let t=Ee(e,n);if(!t.ok)return{ok:!1,diagnostics:t.diagnostics};r?.(t.module);let o=Ae(e,n);return o.ok?{ok:!0,wgsl:Oe(o.wgsl,n,e,t.module),diagnostics:t.diagnostics,dispatchInfo:K(o.dispatchInfo)}:(t.diagnostics.errors.push(...J(o.diagnostics).errors),{ok:!1,diagnostics:t.diagnostics})}async function ft(e,n){let r=Ee(e,n);if(!r.ok)return{ok:!1,diagnostics:r.diagnostics};let o=(await Y()).compile(e,n);return o.ok?{ok:!0,wgsl:Oe(o.wgsl,n,e,r.module),diagnostics:r.diagnostics,dispatchInfo:K(o.dispatchInfo)}:(r.diagnostics.errors.push(...J(o.diagnostics).errors),{ok:!1,diagnostics:r.diagnostics})}function Ee(e,n){let r=P(),t=D(e);if(V(t))return r.errors.push({severity:"error",code:t.code??C.ERR_PARSE,message:t.message,functionName:t.functionName}),{ok:!1,diagnostics:r};let o=B(n),s=n.strictConformance||o,i=z(t,{strictConformance:s});if(T(i))return r.errors.push({severity:"error",code:i.code??C.ERR_VALIDATION,message:i.message,functionName:i.functionName}),{ok:!1,diagnostics:r};if(Re(r,i,n),n.mathExtension){let c=X(t,n.mathExtension);if(!c.valid){for(let u of c.errors)r.errors.push({severity:"error",code:"ERR_MATH_VALIDATION",message:u.message,functionName:u.functionName});return{ok:!1,diagnostics:r}}}let a=H(i,n);return r.warnings.push(...a.diagnostics.warnings),r.errors.push(...a.diagnostics.errors),r.demotions.push(...a.diagnostics.demotions),r.featuresUsed=a.diagnostics.featuresUsed,r.errors.length>0?{ok:!1,diagnostics:r}:{ok:!0,diagnostics:r,module:i}}function Re(e,n,r){B(r)&&he(n,r)&&(e.warnings.some(t=>t.code==="WARN_WORKGROUP_SIZE_OVERRIDE")||e.warnings.push({severity:"warning",code:"WARN_WORKGROUP_SIZE_OVERRIDE",message:"CompileOptions.workgroupSize overrides gasm.workgroup_size custom-section declarations"}))}function Oe(e,n,r,t){let o=e;if(o=pt(o,n,r,t),n.compilerMetadata&&(o=o.replace(/(\/\/ Generated: .*\n)/,`$1// Metadata: ${n.compilerMetadata}
3
+ `)),n.workgroupSize){let[s,i,a]=n.workgroupSize;o=o.replace(/@compute @workgroup_size\(\d+, \d+, \d+\)/g,`@compute @workgroup_size(${s}, ${i}, ${a})`)}return o}function pt(e,n,r,t){if(n.stripComments||n.releaseMode)return e;let s=de(r,n.sourceMapping);if(!s)return e;let i=s.generateHeaderComment(),a=i?e.replace(/(\/\/ Generated: .*\n)/,`$1${i}
4
+ `):e,c=0;return a=a.replace(/^fn ([A-Za-z_][A-Za-z0-9_]*)\(/gm,(u,p)=>{let d=t.functions[c],f=s.commentForFunction(d?.index??c,p);if(c+=1,!f)return u;let g=n.sourceMapping==="minimal"?"":`
5
+ // [WAT] rust backend instruction mapping`;return`${f}${g}
6
+ ${u}`}),a}function En(e,n={}){let r=F(e,n);if(!r.ok){let t=r.diagnostics.errors[0];throw S(t?.message??"Compilation failed",{functionName:t?.functionName,instructionName:t?.code,code:t?.code})}return r.wgsl}async function Rn(e,n={}){let r=await dt(e,n);if(!r.ok){let t=r.diagnostics.errors[0];throw S(t?.message??"Compilation failed",{functionName:t?.functionName,instructionName:t?.code,code:t?.code})}return r.wgsl}function Ve(e,n){for(let r of e.warnings){let t=r.functionName?` (${r.functionName})`:"";console.error(`warning${t}: ${r.message}`)}if(n&&e.demotions.length>0){let r=new Map;for(let o of e.demotions)r.set(o.kind,(r.get(o.kind)??0)+1);let t=[...r.entries()].map(([o,s])=>`${o} (${s})`);console.error(`demotions: ${t.join(", ")}`)}}function St(e,n){return new Promise(r=>{let t=bt(e,n,{stdio:["ignore","pipe","pipe"]}),o="",s="";t.stdout.on("data",i=>{o+=String(i)}),t.stderr.on("data",i=>{s+=String(i)}),t.on("close",i=>{r({success:i===0,stdout:o,stderr:s})}),t.on("error",i=>{r({success:!1,stdout:o,stderr:`${s}
7
+ ${i.message}`})})})}async function ct(e,n={}){let{output:r,verbose:t=!1,keepWasm:o=!1,optimize:s=!1,denyF64Demotion:i=!1,allowI64Demotion:a=!1,warningsAsErrors:c=!1}=n;try{t&&console.log(`[1/4] Validating input file: ${e}`);let u=We(e);if(!(await De(u)).isFile())throw new Error(`Not a file: ${e}`);let d=u.endsWith(".wasm");!d&&!u.endsWith(".as")&&!u.endsWith(".ts")&&console.warn("Warning: Input file does not have .as, .ts, or .wasm extension");let f=u.replace(/\.(as|ts)$/,".wasm");if(d)t&&console.log("[2/4] Input is WASM, skipping compilation..."),f=u;else{t&&console.log("[2/4] Compiling AssemblyScript to WASM...");let I=await It(),{success:R,stdout:O,stderr:W}=await St(I,[u,"-o",f]);if(!R)throw new Error(`AssemblyScript compilation failed:
8
+ ${W}`);t&&O&&console.log(O)}t&&console.log("[3/4] Reading WASM binary...");let g=await mt(f);t&&(console.log(` WASM size: ${g.length} bytes`),console.log("[4/4] Compiling WASM to WGSL using Gasm..."));let v={};i&&(v.f64="deny"),a&&(v.i64="allow-lossy");let b=F(g,{optimize:s,demotionPolicy:v,warningsAsErrors:c});if(Ve(b.diagnostics,t),!b.ok){let I=b.diagnostics.errors[0];throw new Error(I?.message??"Compilation failed")}let k=b.wgsl;if(r){let I=We(r),R=wt(I);await yt(R,{recursive:!0}),await gt(I,k,"utf-8"),console.log(t?`
9
+ \u2713 Successfully compiled to: ${I}`:`\u2713 Compiled to: ${r}`)}if(!o&&!d)try{await ht(f),t&&console.log(" Cleaned up intermediate WASM file")}catch{}return k}catch(u){throw u instanceof Error?u:new Error(`Unknown error: ${String(u)}`)}}function ut(e,n={}){let{verbose:r=!1,optimize:t=!1,denyF64Demotion:o=!1,allowI64Demotion:s=!1,warningsAsErrors:i=!1}=n,a={};o&&(a.f64="deny"),s&&(a.i64="allow-lossy");let c=F(e,{optimize:t,demotionPolicy:a,warningsAsErrors:i});if(Ve(c.diagnostics,r),!c.ok){let u=c.diagnostics.errors[0];throw new Error(u?.message??"Compilation failed")}return c.wgsl}async function It(){let e=["node_modules/.bin/asc","./examples/node_modules/.bin/asc","../app/node_modules/.bin/asc","./node_modules/assemblyscript/bin/asc.js"];for(let n of e)try{if((await De(n)).isFile())return n}catch{}return"asc"}export{rt as a,te as b,ct as c,ut as d,F as e,lt as f,_n as g,Cn as h,dt as i,En as j,Rn as k};
package/dist/compiler.js CHANGED
@@ -1 +1 @@
1
- import{h as a,i as b}from"./chunk-NQJKL2KQ.js";import"./chunk-R6SXLNEJ.js";import"./chunk-IZGS3OS2.js";import"./chunk-STDXBN5E.js";export{a as compileAssemblyScriptToWGSL,b as compileWasmToWGSL};
1
+ import{c as a,d as b}from"./chunk-TICBJF7F.js";import"./chunk-MBWDLAL5.js";import"./chunk-IZGS3OS2.js";import"./chunk-STDXBN5E.js";export{a as compileAssemblyScriptToWGSL,b as compileWasmToWGSL};
@@ -401,13 +401,23 @@ interface CompileOptions {
401
401
  */
402
402
  specVersion?: SpecVersion;
403
403
  }
404
- type DiagnosticSeverity = "warning" | "error";
404
+ type DiagnosticSeverity = "advisory" | "warning" | "error";
405
+ interface DiagnosticRecovery {
406
+ action: "add_extension" | "set_spec_version" | "set_demotion_policy" | "use_prepare_module" | "refactor_source";
407
+ extension?: string;
408
+ specVersion?: SpecVersion;
409
+ demotionPolicy?: Partial<DemotionPolicy>;
410
+ docsUrl?: string;
411
+ }
405
412
  interface Diagnostic {
406
413
  severity: DiagnosticSeverity;
407
414
  code: string;
408
415
  message: string;
416
+ recovery?: DiagnosticRecovery;
409
417
  functionIndex?: number;
410
418
  functionName?: string;
419
+ instructionName?: string;
420
+ offset?: number;
411
421
  }
412
422
  interface DemotionEvent {
413
423
  kind: "f64->f32" | "i64->i32-lossy";
@@ -424,12 +434,108 @@ interface FeaturesUsed {
424
434
  usesSimdEmulation: boolean;
425
435
  }
426
436
  interface CompileDiagnostics {
437
+ advisories: Diagnostic[];
427
438
  warnings: Diagnostic[];
428
439
  errors: Diagnostic[];
429
440
  demotions: DemotionEvent[];
430
441
  featuresUsed: FeaturesUsed;
431
442
  }
432
443
 
444
+ type GasmBindingRole = "memory" | "atomic_region" | "imported_global" | "mutable_globals" | "workgroup_memory" | "extension_resource";
445
+ interface GasmBinding {
446
+ group: number;
447
+ binding: number;
448
+ kind: "storage" | "uniform" | "texture" | "sampler";
449
+ rw?: "read" | "read_write" | "write";
450
+ role: GasmBindingRole;
451
+ wasmName?: string;
452
+ wgslName?: string;
453
+ type?: "i32" | "i64" | "f32" | "f64" | "u32" | "vec4<u32>" | "external";
454
+ atomic?: boolean;
455
+ }
456
+ declare function buildBindingTable(module: WasmModule): GasmBinding[];
457
+
458
+ interface GasmMetadata {
459
+ specVersion: SpecVersion;
460
+ extensions: string[];
461
+ memory: {
462
+ sizeBytes: number;
463
+ atomicRegion?: {
464
+ offset: number;
465
+ length: number;
466
+ binding: {
467
+ group: number;
468
+ binding: number;
469
+ };
470
+ } | null;
471
+ workgroupMemoryBytes?: number;
472
+ };
473
+ entryPoints: GasmMetadataEntryPoint[];
474
+ bindings: GasmBinding[];
475
+ dataSegments: GasmMetadataDataSegment[];
476
+ atomicDataSegments?: GasmMetadataDataSegment[];
477
+ passiveDataSegments?: GasmMetadataPassiveDataSegment[];
478
+ mutableGlobals?: Array<{
479
+ index: number;
480
+ name?: string;
481
+ type: "i32" | "i64" | "f32" | "f64";
482
+ offset: number;
483
+ byteLength: number;
484
+ initialValue?: string;
485
+ }>;
486
+ extras?: Record<string, unknown>;
487
+ }
488
+ interface GasmMetadataEntryPoint {
489
+ name: string;
490
+ wgslName: string;
491
+ workgroupSize: [number, number, number];
492
+ }
493
+ interface GasmMetadataDataSegment {
494
+ memory: number;
495
+ offset: number;
496
+ byteLength: number;
497
+ dataB64: string;
498
+ }
499
+ interface GasmMetadataPassiveDataSegment {
500
+ index: number;
501
+ byteLength: number;
502
+ dataB64: string;
503
+ dropped: boolean;
504
+ }
505
+ interface MetadataBuildContext {
506
+ options?: CompileOptions;
507
+ dispatchInfo?: DispatchInfo;
508
+ }
509
+ declare function buildGasmMetadata(module: WasmModule, context?: MetadataBuildContext): GasmMetadata;
510
+ declare function validateGasmMetadataSchema(metadata: unknown): {
511
+ valid: true;
512
+ } | {
513
+ valid: false;
514
+ errors: string[];
515
+ };
516
+ declare function assertCustomSectionsAndMetadataAgree(module: WasmModule, metadata: GasmMetadata): void;
517
+ declare function entryWrapperName(exportName: string): string;
518
+
519
+ type PrepareMode = "integrator" | "strict";
520
+ interface PrepareModuleOptions extends CompileOptions {
521
+ mode?: PrepareMode;
522
+ patchWasm?: boolean;
523
+ }
524
+ interface MutableGlobalsInit {
525
+ byteLength: number;
526
+ data: Uint32Array;
527
+ }
528
+ interface PreparedModule {
529
+ wasmBytes: Uint8Array;
530
+ compileOptions: CompileOptions;
531
+ bindings: GasmBinding[];
532
+ mutableGlobalsInit?: MutableGlobalsInit;
533
+ extensions: string[];
534
+ advisories: Diagnostic[];
535
+ errors: Diagnostic[];
536
+ }
537
+ declare function prepareModule(wasmBytes: Uint8Array, options?: PrepareModuleOptions): PreparedModule;
538
+
433
539
  declare function compile(wasmBytes: Uint8Array): WasmModule | ReturnType<typeof createCompileError>;
434
540
  declare function isCompileError(error: unknown): error is ReturnType<typeof createCompileError>;
435
541
 
@@ -478,4 +584,4 @@ declare const ErrorCodes: {
478
584
  };
479
585
  type ErrorCode = typeof ErrorCodes[keyof typeof ErrorCodes];
480
586
 
481
- export { type CompileOptions as C, type DispatchInfo as D, ErrorCodes as E, type MathIntrinsicSpec as M, type SpecVersion as S, type VectorDimension as V, type WasmModule as W, type CompileDiagnostics as a, type CompileError as b, DEFAULT_SPEC_VERSION as c, SPEC_VERSION_V01 as d, SPEC_VERSION_V02 as e, isCompileError$1 as f, compile as g, isCompileError as h, isV02Mode as i, type ErrorCode as j, type MathLevel as k, getIntrinsicsAtLevel as l, getMathSpec as m, getVectorDimension as n, getWgslMapping as o, isMathIntrinsic as p, MATH_INTRINSICS as q, resolveSpecVersion as r, type DebugInfo as s, type SourceLanguage as t, type SourceMappingLevel as u, detectSourceLanguage as v, extractDebugInfo as w, parseNamesSection as x, parseProducersSection as y };
587
+ export { getIntrinsicsAtLevel as A, getMathSpec as B, type CompileDiagnostics as C, type DispatchInfo as D, ErrorCodes as E, getVectorDimension as F, type GasmMetadata as G, getWgslMapping as H, isMathIntrinsic as I, MATH_INTRINSICS as J, type DebugInfo as K, type SourceLanguage as L, type MutableGlobalsInit as M, type SourceMappingLevel as N, detectSourceLanguage as O, type PreparedModule as P, extractDebugInfo as Q, parseNamesSection as R, type SpecVersion as S, parseProducersSection as T, type VectorDimension as V, type WasmModule as W, type GasmBinding as a, type CompileOptions as b, type PrepareModuleOptions as c, type CompileError as d, type DemotionPolicy as e, type Diagnostic as f, type DiagnosticRecovery as g, DEFAULT_SPEC_VERSION as h, isV02Mode as i, SPEC_VERSION_V01 as j, SPEC_VERSION_V02 as k, isCompileError$1 as l, compile as m, isCompileError as n, type ErrorCode as o, prepareModule as p, assertCustomSectionsAndMetadataAgree as q, resolveSpecVersion as r, buildGasmMetadata as s, entryWrapperName as t, type GasmMetadataEntryPoint as u, validateGasmMetadataSchema as v, buildBindingTable as w, type PrepareMode as x, type MathIntrinsicSpec as y, type MathLevel as z };
Binary file
package/dist/mod.d.ts CHANGED
@@ -1,85 +1,10 @@
1
- import { W as WasmModule, C as CompileOptions, D as DispatchInfo, a as CompileDiagnostics } from './error_codes-Cdy_3FNo.js';
2
- export { b as CompileError, c as DEFAULT_SPEC_VERSION, s as DebugInfo, j as ErrorCode, E as ErrorCodes, q as MATH_INTRINSICS, M as MathIntrinsicSpec, k as MathLevel, d as SPEC_VERSION_V01, e as SPEC_VERSION_V02, t as SourceLanguage, u as SourceMappingLevel, S as SpecVersion, V as VectorDimension, v as detectSourceLanguage, w as extractDebugInfo, l as getIntrinsicsAtLevel, m as getMathSpec, n as getVectorDimension, o as getWgslMapping, f as isCompileError, p as isMathIntrinsic, h as isParseError, i as isV02Mode, x as parseNamesSection, y as parseProducersSection, g as parseWasmModule, r as resolveSpecVersion } from './error_codes-Cdy_3FNo.js';
1
+ import { W as WasmModule, C as CompileDiagnostics, D as DispatchInfo, G as GasmMetadata, a as GasmBinding, P as PreparedModule, b as CompileOptions, c as PrepareModuleOptions } from './error_codes-5zCZDwFZ.js';
2
+ export { d as CompileError, h as DEFAULT_SPEC_VERSION, K as DebugInfo, e as DemotionPolicy, f as Diagnostic, g as DiagnosticRecovery, o as ErrorCode, E as ErrorCodes, u as GasmMetadataEntryPoint, J as MATH_INTRINSICS, y as MathIntrinsicSpec, z as MathLevel, M as MutableGlobalsInit, x as PrepareMode, j as SPEC_VERSION_V01, k as SPEC_VERSION_V02, L as SourceLanguage, N as SourceMappingLevel, S as SpecVersion, V as VectorDimension, q as assertCustomSectionsAndMetadataAgree, w as buildBindingTable, s as buildGasmMetadata, O as detectSourceLanguage, t as entryWrapperName, Q as extractDebugInfo, A as getIntrinsicsAtLevel, B as getMathSpec, F as getVectorDimension, H as getWgslMapping, l as isCompileError, I as isMathIntrinsic, n as isParseError, i as isV02Mode, R as parseNamesSection, T as parseProducersSection, m as parseWasmModule, p as prepareModule, r as resolveSpecVersion, v as validateGasmMetadataSchema } from './error_codes-5zCZDwFZ.js';
3
3
  import { IGPUExecutor, ExecutorConfig, BufferData, ExecuteOptions } from './executor.js';
4
4
  export { ExecutionError, OutputBufferSpec, isExecutionError } from './executor.js';
5
5
  export { BrowserGPUExecutor } from './browser-executor.js';
6
6
  export { CompileOptions as NodeCompilerOptions, compileAssemblyScriptToWGSL, compileWasmToWGSL } from './compiler.js';
7
7
 
8
- type GasmBindingRole = "memory" | "atomic_region" | "imported_global" | "mutable_globals" | "workgroup_memory" | "extension_resource";
9
- interface GasmBinding {
10
- group: number;
11
- binding: number;
12
- kind: "storage" | "uniform" | "texture" | "sampler";
13
- rw?: "read" | "read_write" | "write";
14
- role: GasmBindingRole;
15
- wasmName?: string;
16
- wgslName?: string;
17
- type?: "i32" | "i64" | "f32" | "f64" | "u32" | "vec4<u32>" | "external";
18
- atomic?: boolean;
19
- }
20
- declare function buildBindingTable(module: WasmModule): GasmBinding[];
21
-
22
- interface GasmMetadata {
23
- specVersion: "0.2";
24
- extensions: string[];
25
- memory: {
26
- sizeBytes: number;
27
- atomicRegion?: {
28
- offset: number;
29
- length: number;
30
- binding: {
31
- group: number;
32
- binding: number;
33
- };
34
- } | null;
35
- workgroupMemoryBytes?: number;
36
- };
37
- entryPoints: GasmMetadataEntryPoint[];
38
- bindings: GasmBinding[];
39
- dataSegments: GasmMetadataDataSegment[];
40
- atomicDataSegments?: GasmMetadataDataSegment[];
41
- passiveDataSegments?: GasmMetadataPassiveDataSegment[];
42
- mutableGlobals?: Array<{
43
- index: number;
44
- name?: string;
45
- type: "i32" | "i64" | "f32" | "f64";
46
- offset: number;
47
- byteLength: number;
48
- initialValue?: string;
49
- }>;
50
- extras?: Record<string, unknown>;
51
- }
52
- interface GasmMetadataEntryPoint {
53
- name: string;
54
- wgslName: string;
55
- workgroupSize: [number, number, number];
56
- }
57
- interface GasmMetadataDataSegment {
58
- memory: number;
59
- offset: number;
60
- byteLength: number;
61
- dataB64: string;
62
- }
63
- interface GasmMetadataPassiveDataSegment {
64
- index: number;
65
- byteLength: number;
66
- dataB64: string;
67
- dropped: boolean;
68
- }
69
- interface MetadataBuildContext {
70
- options?: CompileOptions;
71
- dispatchInfo?: DispatchInfo;
72
- }
73
- declare function buildGasmMetadata(module: WasmModule, context?: MetadataBuildContext): GasmMetadata;
74
- declare function validateGasmMetadataSchema(metadata: unknown): {
75
- valid: true;
76
- } | {
77
- valid: false;
78
- errors: string[];
79
- };
80
- declare function assertCustomSectionsAndMetadataAgree(module: WasmModule, metadata: GasmMetadata): void;
81
- declare function entryWrapperName(exportName: string): string;
82
-
83
8
  /**
84
9
  * WAT Disassembler
85
10
  *
@@ -170,11 +95,24 @@ type CompileArtifactResult = {
170
95
  ok: false;
171
96
  diagnostics: CompileDiagnostics;
172
97
  };
98
+ type CompileWithRuntimeInfoResult = {
99
+ ok: true;
100
+ wgsl: string;
101
+ diagnostics: CompileDiagnostics;
102
+ dispatchInfo: DispatchInfo;
103
+ bindings: GasmBinding[];
104
+ metadata: GasmMetadata;
105
+ mutableGlobalsInit?: PreparedModule["mutableGlobalsInit"];
106
+ } | {
107
+ ok: false;
108
+ diagnostics: CompileDiagnostics;
109
+ };
173
110
  declare function compileWithDiagnostics(wasmBytes: Uint8Array, options?: CompileOptions): CompileWithDiagnosticsResult;
174
111
  declare function compileToArtifact(wasmBytes: Uint8Array, options?: CompileOptions): CompileArtifactResult;
112
+ declare function compileWithRuntimeInfo(wasmBytes: Uint8Array, options?: PrepareModuleOptions): CompileWithRuntimeInfoResult;
175
113
  declare function preloadCompiler(): Promise<void>;
176
114
  declare function compileWithDiagnosticsAsync(wasmBytes: Uint8Array, options?: CompileOptions): Promise<CompileWithDiagnosticsResult>;
177
115
  declare function compile(wasmBytes: Uint8Array, options?: CompileOptions): string;
178
116
  declare function compileAsync(wasmBytes: Uint8Array, options?: CompileOptions): Promise<string>;
179
117
 
180
- export { BufferData, type CompileArtifactResult, CompileDiagnostics, CompileOptions, type CompileWithDiagnosticsResult, DenoGPUExecutor, DispatchInfo, ExecuteOptions, ExecutorConfig, type GasmBinding, type GasmMetadata, type GasmMetadataEntryPoint, IGPUExecutor, assertCustomSectionsAndMetadataAgree, buildBindingTable, buildGasmMetadata, compile, compileAsync, compileToArtifact, compileWithDiagnostics, compileWithDiagnosticsAsync, disassembleToWAT, entryWrapperName, preloadCompiler, validateGasmMetadataSchema };
118
+ export { BufferData, type CompileArtifactResult, CompileDiagnostics, CompileOptions, type CompileWithDiagnosticsResult, type CompileWithRuntimeInfoResult, DenoGPUExecutor, DispatchInfo, ExecuteOptions, ExecutorConfig, GasmBinding, GasmMetadata, IGPUExecutor, PrepareModuleOptions, PreparedModule, compile, compileAsync, compileToArtifact, compileWithDiagnostics, compileWithDiagnosticsAsync, compileWithRuntimeInfo, disassembleToWAT, preloadCompiler };
package/dist/mod.js CHANGED
@@ -1 +1 @@
1
- import{a as t,b as u,c as v,d as w,e as x,f as y,g as C,h as D,i as E,j as F,k as G,l as H,m as I,n as J,o as K}from"./chunk-NQJKL2KQ.js";import{D as o,E as p,F as q,G as r,H as s,b as a,d as b,e as c,f as d,i as e,j as f,k as g,l as h,m as i,o as j,u as k,v as l,w as m,x as n}from"./chunk-R6SXLNEJ.js";import{a as B}from"./chunk-IZGS3OS2.js";import{a as z,b as A}from"./chunk-STDXBN5E.js";export{B as BrowserGPUExecutor,q as DEFAULT_SPEC_VERSION,C as DenoGPUExecutor,b as ErrorCodes,z as ExecutionError,e as MATH_INTRINSICS,o as SPEC_VERSION_V01,p as SPEC_VERSION_V02,w as assertCustomSectionsAndMetadataAgree,t as buildBindingTable,u as buildGasmMetadata,J as compile,D as compileAssemblyScriptToWGSL,K as compileAsync,G as compileToArtifact,E as compileWasmToWGSL,F as compileWithDiagnostics,I as compileWithDiagnosticsAsync,m as detectSourceLanguage,y as disassembleToWAT,x as entryWrapperName,n as extractDebugInfo,j as getIntrinsicsAtLevel,g as getMathSpec,i as getVectorDimension,h as getWgslMapping,a as isCompileError,A as isExecutionError,f as isMathIntrinsic,d as isParseError,s as isV02Mode,k as parseNamesSection,l as parseProducersSection,c as parseWasmModule,H as preloadCompiler,r as resolveSpecVersion,v as validateGasmMetadataSchema};
1
+ import{a as z,b as D,c as E,d as F,e as G,f as H,g as I,h as J,i as K,j as L,k as M}from"./chunk-TICBJF7F.js";import{D as o,E as p,F as q,G as r,H as s,O as t,P as u,Q as v,R as w,S as x,U as y,b as a,d as b,e as c,f as d,i as e,j as f,k as g,l as h,m as i,o as j,u as k,v as l,w as m,x as n}from"./chunk-MBWDLAL5.js";import{a as C}from"./chunk-IZGS3OS2.js";import{a as A,b as B}from"./chunk-STDXBN5E.js";export{C as BrowserGPUExecutor,q as DEFAULT_SPEC_VERSION,D as DenoGPUExecutor,b as ErrorCodes,A as ExecutionError,e as MATH_INTRINSICS,o as SPEC_VERSION_V01,p as SPEC_VERSION_V02,w as assertCustomSectionsAndMetadataAgree,t as buildBindingTable,u as buildGasmMetadata,L as compile,E as compileAssemblyScriptToWGSL,M as compileAsync,H as compileToArtifact,F as compileWasmToWGSL,G as compileWithDiagnostics,K as compileWithDiagnosticsAsync,I as compileWithRuntimeInfo,m as detectSourceLanguage,z as disassembleToWAT,x as entryWrapperName,n as extractDebugInfo,j as getIntrinsicsAtLevel,g as getMathSpec,i as getVectorDimension,h as getWgslMapping,a as isCompileError,B as isExecutionError,f as isMathIntrinsic,d as isParseError,s as isV02Mode,k as parseNamesSection,l as parseProducersSection,c as parseWasmModule,J as preloadCompiler,y as prepareModule,r as resolveSpecVersion,v as validateGasmMetadataSchema};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gasm-compiler/core",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Gasm Compiler — compile WebAssembly to WGSL (WebGPU Shading Language)",
5
5
  "type": "module",
6
6
  "main": "./dist/mod.js",
@@ -1,9 +0,0 @@
1
- import{A as ye,B as be,C as Se,G as H,H as L,I as K,J as X,K as Y,L as Q,M as ee,a as I,c as O,d as B,e as z,f as P,g as q,h as j,j as Z,k as J,n as ue,p as le,q as de,r as fe,s as me,t as pe,y as ge,z as he}from"./chunk-R6SXLNEJ.js";import{a as h}from"./chunk-STDXBN5E.js";import{resolve as Le}from"node:path";import{stat as Ne,readFile as Pt,writeFile as Lt,unlink as Nt,mkdir as Ut}from"node:fs/promises";import{spawn as Ft}from"node:child_process";import{dirname as Tt}from"node:path";function we(e){let t=e.functions.map(n=>!("parallelLoopInfo"in n)||!n.parallelLoopInfo?n:Te(n));return{...e,functions:t}}function Te(e){let t=e.parallelLoopInfo.loopLocalIndex,{writes:n}=qe(e.body,t);if(n>0){let r=A(e.body,t);return{...e,body:r}}return e}function qe(e,t){let n=0,r=0;function o(s){switch(s.kind){case"simple":if(s.instructions)for(let i of s.instructions)i.opcode==="local.get"&&i.immediates?.[0]===t&&n++,(i.opcode==="local.set"||i.opcode==="local.tee")&&i.immediates?.[0]===t&&r++;break;case"block":for(let i of s.children)o(i);break;case"loop":o(s.body);break;case"if":o(s.thenBranch),s.elseBranch&&o(s.elseBranch);break;case"parallel_loop":o(s.body),s.epilogue&&o(s.epilogue);break;case"return":case"break":case"continue":break}}return o(e),{reads:n,writes:r}}function A(e,t){switch(e.kind){case"simple":{if(!e.instructions)return e;let n=e.instructions.filter(r=>!((r.opcode==="local.set"||r.opcode==="local.tee")&&r.immediates?.[0]===t));return n.length===0?{kind:"block",children:[]}:{...e,instructions:n}}case"block":{let n=e.children.map(r=>A(r,t)).filter(r=>!je(r));return{...e,children:n}}case"loop":return{...e,body:A(e.body,t)};case"if":return{...e,thenBranch:A(e.thenBranch,t),elseBranch:e.elseBranch?A(e.elseBranch,t):void 0};case"parallel_loop":return{...e,body:A(e.body,t),epilogue:e.epilogue?A(e.epilogue,t):void 0};case"return":case"break":case"continue":return e}}function je(e){return e.kind==="block"&&e.children.length===0||e.kind==="simple"&&(!e.instructions||e.instructions.length===0)}function Ie(e){let t=e.functions.map(n=>Ze(n));return{...e,functions:t}}function Ze(e){let t=E(e.body,e);return{...e,body:t}}function E(e,t){switch(e.kind){case"loop":{let n=Je(e.body),r=[],o=ve(e.body,n,r,t);return r.length===0?{...e,body:E(e.body,t)}:{kind:"block",children:[{kind:"simple",instructions:r},{...e,body:E(o,t)}],label:void 0}}case"block":return{...e,children:e.children.map(n=>E(n,t))};case"if":return{...e,thenBranch:E(e.thenBranch,t),elseBranch:e.elseBranch?E(e.elseBranch,t):void 0};case"simple":return e;default:return e}}function Je(e){let t=new Set;function n(r){if(r.kind==="simple"&&r.instructions){for(let o of r.instructions)if(o.id!==void 0&&t.add(o.id),(o.opcode==="local.set"||o.opcode==="local.tee")&&o.immediates){let s=o.immediates[0];t.add(-s-1)}}r.kind==="block"&&r.children.forEach(n),r.kind==="loop"&&n(r.body),r.kind==="if"&&(n(r.thenBranch),r.elseBranch&&n(r.elseBranch))}return n(e),t}function ve(e,t,n,r){switch(e.kind){case"simple":{if(!e.instructions||e.instructions.length===0)return e;let o=[],s=new Set;for(let i of e.instructions)He(i,t,s)?(n.push(i),i.id!==void 0&&s.add(i.id)):(o.push(i),i.id!==void 0&&s.add(i.id));return{...e,instructions:o}}case"block":{let o=e.children.map(s=>ve(s,t,n,r));return{...e,children:o}}case"loop":return e;case"if":return e;default:return e}}function He(e,t,n){if(!Ke(e.opcode))return!1;if(e.opcode==="local.get"&&e.immediates){let o=-e.immediates[0]-1;if(t.has(o))return!1}if(e.args){for(let r of e.args)if(t.has(r))return!1}return!0}function Ke(e){return new Set(["i32.const","i64.const","f32.const","f64.const","local.get","i32.add","i32.sub","i32.mul","i32.div_s","i32.div_u","i32.rem_s","i32.rem_u","i64.add","i64.sub","i64.mul","i64.div_s","i64.div_u","i64.rem_s","i64.rem_u","f32.add","f32.sub","f32.mul","f32.div","f64.add","f64.sub","f64.mul","f64.div","i32.and","i32.or","i32.xor","i32.shl","i32.shr_s","i32.shr_u","i32.rotl","i32.rotr","i64.and","i64.or","i64.xor","i64.shl","i64.shr_s","i64.shr_u","i64.rotl","i64.rotr","i32.eqz","i32.eq","i32.ne","i32.lt_s","i32.lt_u","i32.gt_s","i32.gt_u","i32.le_s","i32.le_u","i32.ge_s","i32.ge_u","i64.eqz","i64.eq","i64.ne","i64.lt_s","i64.lt_u","i64.gt_s","i64.gt_u","i64.le_s","i64.le_u","i64.ge_s","i64.ge_u","f32.eq","f32.ne","f32.lt","f32.gt","f32.le","f32.ge","f64.eq","f64.ne","f64.lt","f64.gt","f64.le","f64.ge","i32.wrap_i64","i64.extend_i32_s","i64.extend_i32_u","f32.convert_i32_s","f32.convert_i32_u","f32.convert_i64_s","f32.convert_i64_u","f32.demote_f64","f64.convert_i32_s","f64.convert_i32_u","f64.convert_i64_s","f64.convert_i64_u","f64.promote_f32","i32.reinterpret_f32","i64.reinterpret_f64","f32.reinterpret_i32","f64.reinterpret_i64","i32.clz","i32.ctz","i32.popcnt","i64.clz","i64.ctz","i64.popcnt","f32.abs","f32.neg","f32.ceil","f32.floor","f32.trunc","f32.nearest","f32.sqrt","f64.abs","f64.neg","f64.ceil","f64.floor","f64.trunc","f64.nearest","f64.sqrt","f32.min","f32.max","f32.copysign","f64.min","f64.max","f64.copysign"]).has(e)}function ke(e){for(let t of e.functions)Xe(t);return e}function Xe(e){$(e.body,e)}function $(e,t){switch(e.kind){case"simple":Ye(e,t);break;case"block":for(let n of e.children)$(n,t);break;case"loop":$(e.body,t);break;case"if":$(e.thenBranch,t),e.elseBranch&&$(e.elseBranch,t);break;case"parallel_loop":$(e.body,t),e.epilogue&&$(e.epilogue,t);break}}function Ye(e,t){let n=tt(e.instructions,t);n.length>0&&rt(e,t,n);let r=nt(e.instructions,t);r.length>0&&ot(e,t,r)}function xe(e,t){let n=U(e,t);if(!n)return null;if(n.opcode==="i32.shr_u"&&n.args.length===2){if(N(n.args[1],t)!==2)return null;let o=n.args[0];return Qe(o,t)}return et(e,t)}function Qe(e,t){let n=U(e,t);if(!n)return{baseVar:e,wordOffset:0};if(n.opcode==="i32.add"&&n.args.length===2){let r=N(n.args[1],t);if(r!==null&&r>=0&&r%4===0)return{baseVar:n.args[0],wordOffset:r/4};let o=N(n.args[0],t);return o!==null&&o>=0&&o%4===0?{baseVar:n.args[1],wordOffset:o/4}:null}return{baseVar:e,wordOffset:0}}function et(e,t){let n=U(e,t);if(!n)return{baseVar:e,wordOffset:0};if(n.opcode==="i32.add"&&n.args.length===2){let r=N(n.args[1],t);if(r!==null&&r>=0)return{baseVar:n.args[0],wordOffset:r}}return{baseVar:e,wordOffset:0}}function U(e,t){if(t.inlinedExpressionMap){let n=t.inlinedExpressionMap.get(e);if(n)return n}return C(t.body,e)}function C(e,t){switch(e.kind){case"simple":for(let n of e.instructions)if(n.id===t)return n;return null;case"block":for(let n of e.children){let r=C(n,t);if(r)return r}return null;case"loop":return C(e.body,t);case"if":{let n=C(e.thenBranch,t);return n||(e.elseBranch?C(e.elseBranch,t):null)}case"parallel_loop":{let n=C(e.body,t);return n||(e.epilogue?C(e.epilogue,t):null)}default:return null}}function N(e,t){let n=U(e,t);return n&&n.opcode==="i32.const"&&n.immediates&&n.immediates.length>0?n.immediates[0]:null}function tt(e,t){let n=[],r=[];for(let s=0;s<e.length;s++){let i=e[s];if(i.opcode==="wgsl.store_f32"&&i.args.length===2){let a=xe(i.args[0],t);a&&r.push({index:s,addr:a,valueArg:i.args[1]})}}let o=new Map;for(let s of r){let i=o.get(s.addr.baseVar)||[];i.push(s),o.set(s.addr.baseVar,i)}for(let[s,i]of o){if(i.length<3)continue;i.sort((c,u)=>c.addr.wordOffset-u.addr.wordOffset);let a=0;for(;a<i.length;){let c=a;for(;c+1<i.length&&i[c+1].addr.wordOffset===i[c].addr.wordOffset+1;)c++;let u=c-a+1;if(u>=3){let m=u>=4?4:3,d=i.slice(a,a+m),l=d.map(p=>p.index);Me(l,e)&&n.push({instrIndices:l,baseVar:s,valueArgs:d.map(p=>p.valueArg),components:m})}a=c+1}}return n}function nt(e,t){let n=[],r=[];for(let s=0;s<e.length;s++){let i=e[s];if(i.opcode==="wgsl.load_f32"&&i.args.length===1&&i.id!==void 0){let a=xe(i.args[0],t);a&&r.push({index:s,addr:a,resultVar:i.id})}}let o=new Map;for(let s of r){let i=o.get(s.addr.baseVar)||[];i.push(s),o.set(s.addr.baseVar,i)}for(let[s,i]of o){if(i.length<3)continue;i.sort((c,u)=>c.addr.wordOffset-u.addr.wordOffset);let a=0;for(;a<i.length;){let c=a;for(;c+1<i.length&&i[c+1].addr.wordOffset===i[c].addr.wordOffset+1;)c++;let u=c-a+1;if(u>=3){let m=u>=4?4:3,d=i.slice(a,a+m),l=d.map(p=>p.index);Me(l,e)&&n.push({instrIndices:l,baseVar:s,resultVars:d.map(p=>p.resultVar),components:m})}a=c+1}}return n}function Me(e,t){if(e.length<3)return!1;let n=Math.min(...e),r=Math.max(...e),o=e.length*4;if(r-n>=o)return!1;for(let s=n;s<=r;s++)if(t[s].opcode.startsWith("wgsl.store")&&!e.includes(s))return!1;return!0}function rt(e,t,n){n.sort((r,o)=>o.instrIndices[0]-r.instrIndices[0]);for(let r of n){let o=r.components===4?"wgsl.store_vec4f":"wgsl.store_vec3f",s=e.instructions[r.instrIndices[0]].args[0],i={type:"instr",opcode:o,args:[s,...r.valueArgs],synthetic:!0},a=[...r.instrIndices].sort((c,u)=>c-u);for(let c=a.length-1;c>=0;c--)e.instructions.splice(a[c],1);e.instructions.splice(a[0],0,i)}}function ot(e,t,n){n.sort((r,o)=>o.instrIndices[0]-r.instrIndices[0]);for(let r of n){let o=r.components===4?"wgsl.load_vec4f":"wgsl.load_vec3f",s=0;for(let d of t.vars.keys())d>s&&(s=d);let i=s+1;t.vars.set(i,{id:i,type:"v128"});let a=e.instructions[r.instrIndices[0]].args[0],c={type:"instr",id:i,opcode:o,args:[a],synthetic:!0},u=r.resultVars.map((d,l)=>({type:"instr",id:d,opcode:"wgsl.extract_f32",args:[i],immediates:[l],synthetic:!0})),m=[...r.instrIndices].sort((d,l)=>d-l);for(let d=m.length-1;d>=0;d--)e.instructions.splice(m[d],1);e.instructions.splice(m[0],0,c,...u)}}function te(e,t){let n={valid:!0,mathImports:[],errors:[],requiredLevel:null},r=t===!0||t==="M0"||t==="M1"||t==="M2",o=t===!0?"M2":t==="M0"||t==="M1"||t==="M2"?t:null,s=["M0","M1","M2"],i=0;for(let a of e.imports){if(a.kind!=="func")continue;let c=i++;if(!Z(a.module,a.name))continue;let u=a.typeIndex;if(u===void 0){n.errors.push(I(`Math import ${a.name} has no type index`,{functionName:a.name})),n.valid=!1;continue}let m=e.types[u];if(!m){n.errors.push(I(`Math import ${a.name} references invalid type index ${u}`,{functionName:a.name})),n.valid=!1;continue}let d=J(a.name);if(!d){n.errors.push(I(`Unknown math intrinsic: ${a.name}`,{functionName:a.name})),n.valid=!1;continue}let l={funcIndex:c,module:a.module,name:a.name,level:d.level,params:m.params,results:m.results};if(n.mathImports.push(l),(n.requiredLevel===null||s.indexOf(d.level)>s.indexOf(n.requiredLevel))&&(n.requiredLevel=d.level),!r){n.errors.push(I(`Math intrinsic ${a.name} requires mathExtension option to be enabled`,{functionName:a.name})),n.valid=!1;continue}if(o&&!ue(a.name,o)){n.errors.push(I(`Math intrinsic ${a.name} requires level ${d.level}, but only ${o} is enabled`,{functionName:a.name})),n.valid=!1;continue}let p=le(a.name,m.params,m.results);p&&(n.errors.push(I(p,{functionName:a.name})),n.valid=!1)}return n}import{readFileSync as it}from"node:fs";var _e,Ae;async function st(e=re()){let t=await ct(e),n=await WebAssembly.instantiate(Ce(t),{});return Y(n.instance.exports)}function ne(e=re()){return Ae??=st(e),Ae}function at(e=re()){let t=ut(e),n=new WebAssembly.Module(Ce(t)),r=new WebAssembly.Instance(n,{});return Y(r.exports)}function $e(e,t={}){return _e??=at(),_e.compile(e,t)}function re(){let e=globalThis.Deno,t=new URL("./gasm_core_rs.wasm",import.meta.url);if(e){let n=new URL("../../core-rs/target/wasm32-unknown-unknown/debug/gasm_core_rs.wasm",import.meta.url);try{return e.statSync(n),n}catch{}let r=new URL("../../core-rs/target/wasm32-unknown-unknown/release/gasm_core_rs.wasm",import.meta.url);try{return e.statSync(r),r}catch{}try{return e.statSync(t),t}catch{}}return new URL("../../core-rs/target/wasm32-unknown-unknown/debug/gasm_core_rs.wasm",import.meta.url)}async function ct(e){let t=globalThis.Deno;return t?await t.readFile(e):await(await import("node:fs/promises")).readFile(e)}function ut(e){let t=globalThis.Deno;return t?t.readFileSync(e):it(e)}function Ce(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}var lt=new Set(["global_invocation_id_x","global_invocation_id_y","global_invocation_id_z","local_invocation_id_x","local_invocation_id_y","local_invocation_id_z","workgroup_id_x","workgroup_id_y","workgroup_id_z","num_workgroups_x","num_workgroups_y","num_workgroups_z"]);function oe(e){let t=[{group:0,binding:0,kind:"storage",rw:"read_write",role:"memory",wgslName:"memory"}],n=1,r=0;for(let i of e.imports){if(i.kind!=="global")continue;let a=r++;i.module==="gasm"&&lt.has(i.name)||t.push({group:0,binding:n++,kind:"uniform",role:"imported_global",wasmName:`${i.module}.${i.name}`,wgslName:`global_${a}`,type:ft(i.globalType)})}return new Set(e.extensions??[]).has("gasm:mutable-globals:1.0")&&e.globals.some(i=>i.kind==="definition"&&i.mutable)&&t.push({group:0,binding:n++,kind:"storage",rw:"read_write",role:"mutable_globals",wgslName:"mutable_globals"}),e.atomicRegion&&t.push({group:0,binding:n++,kind:"storage",rw:"read_write",role:"atomic_region",wgslName:"atomic_region",atomic:!0}),dt(t),t}function dt(e){let t=new Set;for(let n of e){let r=`${n.group}:${n.binding}`;if(t.has(r))throw new Error(`Duplicate Gasm binding: ${r}`);t.add(r)}}function ft(e){if(e==="i32"||e==="i64"||e==="f32"||e==="f64")return e;if(e==="v128")return"vec4<u32>"}function ie(e,t={}){let n=oe(e),r=n.find(u=>u.role==="atomic_region"),o=vt(e),s={specVersion:"0.2",extensions:[...e.extensions??[]],memory:{sizeBytes:yt(e),atomicRegion:It(e.atomicRegion,r)},entryPoints:Be(e).map(u=>({name:u.name,wgslName:Ee(u.name),workgroupSize:ht(e,u.index,t)})),bindings:n,dataSegments:o.memorySegments},i=bt(e);i!==void 0&&(s.memory.workgroupMemoryBytes=i),o.atomicSegments.length>0&&(s.atomicDataSegments=o.atomicSegments);let a=e.data.map((u,m)=>({segment:u,index:m})).filter(({segment:u})=>u.mode==="passive").map(({segment:u,index:m})=>xt(u,m));a.length>0&&(s.passiveDataSegments=a);let c=St(e);return c.length>0&&(s.mutableGlobals=c),s}function mt(e){let t=[],n=_(e);if(!n)return{valid:!1,errors:["metadata must be an object"]};let r=["specVersion","extensions","memory","entryPoints","bindings","dataSegments"];for(let d of r)d in n||t.push(`missing required property: ${d}`);for(let d of Object.keys(n))[...r,"mutableGlobals","passiveDataSegments","atomicDataSegments","extras"].includes(d)||t.push(`unexpected property: ${d}`);n.specVersion!=="0.2"&&t.push("specVersion must be 0.2"),Array.isArray(n.extensions)||t.push("extensions must be an array"),_(n.memory)||t.push("memory must be an object"),(!Array.isArray(n.entryPoints)||n.entryPoints.length===0)&&t.push("entryPoints must be a non-empty array"),Array.isArray(n.bindings)||t.push("bindings must be an array"),Array.isArray(n.dataSegments)||t.push("dataSegments must be an array");let o=Array.isArray(n.bindings)?n.bindings:[],s=new Set;for(let d of o){let l=_(d);if(!l){t.push("binding must be an object");continue}S(l.group)||t.push("binding.group invalid"),S(l.binding)||t.push("binding.binding invalid"),typeof l.kind!="string"&&t.push("binding.kind invalid"),typeof l.role!="string"&&t.push("binding.role invalid");let p=`${l.group}:${l.binding}`;s.has(p)&&t.push(`duplicate binding: ${p}`),s.add(p)}let i=Array.isArray(n.entryPoints)?n.entryPoints:[];for(let d of i){let l=_(d);if(!l){t.push("entryPoint must be an object");continue}(typeof l.name!="string"||l.name.length===0)&&t.push("entryPoint.name invalid"),(typeof l.wgslName!="string"||l.wgslName.length===0)&&t.push("entryPoint.wgslName invalid"),(!Array.isArray(l.workgroupSize)||l.workgroupSize.length!==3||!l.workgroupSize.every(p=>At(p)))&&t.push("entryPoint.workgroupSize invalid")}let a=_(n.memory);a&&!S(a.sizeBytes)&&t.push("memory.sizeBytes invalid"),a&&"workgroupMemoryBytes"in a&&!S(a.workgroupMemoryBytes)&&t.push("memory.workgroupMemoryBytes invalid");let c=Array.isArray(n.dataSegments)?n.dataSegments:[];for(let d of c){let l=_(d);if(!l){t.push("dataSegment must be an object");continue}S(l.memory)||t.push("dataSegment.memory invalid"),S(l.offset)||t.push("dataSegment.offset invalid"),S(l.byteLength)||t.push("dataSegment.byteLength invalid"),typeof l.dataB64!="string"&&t.push("dataSegment.dataB64 invalid")}let u=Array.isArray(n.passiveDataSegments)?n.passiveDataSegments:[];for(let d of u){let l=_(d);if(!l){t.push("passiveDataSegment must be an object");continue}S(l.index)||t.push("passiveDataSegment.index invalid"),S(l.byteLength)||t.push("passiveDataSegment.byteLength invalid"),typeof l.dataB64!="string"&&t.push("passiveDataSegment.dataB64 invalid"),typeof l.dropped!="boolean"&&t.push("passiveDataSegment.dropped invalid")}let m=Array.isArray(n.atomicDataSegments)?n.atomicDataSegments:[];for(let d of m){let l=_(d);if(!l){t.push("atomicDataSegment must be an object");continue}S(l.memory)||t.push("atomicDataSegment.memory invalid"),S(l.offset)||t.push("atomicDataSegment.offset invalid"),S(l.byteLength)||t.push("atomicDataSegment.byteLength invalid"),typeof l.dataB64!="string"&&t.push("atomicDataSegment.dataB64 invalid")}return t.length===0?{valid:!0}:{valid:!1,errors:t}}function pt(e,t){let n=[...e.extensions??[]].sort(),r=[...t.extensions].sort();De(n,r,"extensions");for(let[o,s]of e.workgroupSizes??new Map){let i=Be(e).find(c=>c.index===o);if(!i)continue;let a=t.entryPoints.find(c=>c.name===i.name);if(!a)throw new Error(`metadata missing entry point ${i.name}`);De(s,a.workgroupSize,"workgroupSize")}if(e.atomicRegion){let o=t.memory.atomicRegion;if(!o)throw new Error("metadata missing atomicRegion");$t(e.atomicRegion,o)}}function Be(e){return e.exports.filter(t=>{if(t.kind!=="func")return!1;let n=gt(e,t.index);return!!n&&n.params.length===0&&n.results.length===0})}function Ee(e){let t=_t(e);return t==="main"?"main":`${t}_entry`}function Re(e,t){return!!t.workgroupSize&&(e.workgroupSizes?.size??0)>0}function gt(e,t){let n=e.imports.filter(o=>o.kind==="func");if(t<n.length){let o=n[t].typeIndex;return o===void 0?void 0:e.types[o]}let r=e.functions.find(o=>o.index===t);if(r)return{params:r.params,results:r.results}}function ht(e,t,n){if(n.options?.workgroupSize)return n.options.workgroupSize;let r=e.workgroupSizes?.get(t);if(r)return r;let o=n.dispatchInfo;return o?.isParallelized?[o.workgroupSizeX,o.workgroupSizeY,o.workgroupSizeZ]:H(n.options)==="0.2"?[64,1,1]:[1,1,1]}function yt(e){let t=e.memories[0];return t?t.min*65536:(e.imports.find(r=>r.kind==="mem"&&!(r.module==="gasm"&&r.name==="workgroup_memory"))?.memoryMin??0)*65536}function bt(e){if(!new Set(e.extensions??[]).has("gasm:workgroup-memory:1.0"))return;let n=e.imports.find(r=>r.kind==="mem"&&r.module==="gasm"&&r.name==="workgroup_memory");if(n)return n.memoryMax??n.memoryMin??0}function St(e){if(!(e.extensions??[]).includes("gasm:mutable-globals:1.0"))return[];let t=[],n=0;for(let r of e.globals){if(r.kind!=="definition"||!r.mutable)continue;let o=wt(r.type);t.push({index:r.index,type:r.type,offset:n,byteLength:o,...r.initValue!==void 0?{initialValue:r.initValue.toString()}:{}}),n+=o}return t}function wt(e){return e==="i64"||e==="f64"?8:4}function It(e,t){return e?{offset:e.offset,length:e.length,binding:{group:t?.group??0,binding:t?.binding??0}}:null}function vt(e){let t=[],n=[];for(let r of e.data)r.mode==="active"&&kt(r,e.atomicRegion).forEach(o=>{o.atomic?n.push(o.metadata):t.push(o.metadata)});return{memorySegments:t,atomicSegments:n}}function kt(e,t){let n=Mt(e.offset);if(!t||e.memoryIndex!==t.memoryIndex)return[V(e,n,e.data,!1)];let r=n+e.data.length,o=t.offset,s=t.offset+t.length,i=[];if(n<Math.min(r,o)){let u=Math.min(r,o);i.push(V(e,n,e.data.subarray(0,u-n),!1))}let a=Math.max(n,o),c=Math.min(r,s);if(a<c&&i.push(V(e,a,e.data.subarray(a-n,c-n),!0)),Math.max(n,s)<r){let u=Math.max(n,s);i.push(V(e,u,e.data.subarray(u-n),!1))}return i.length===0&&i.push(V(e,n,e.data,!1)),i}function V(e,t,n,r){return{atomic:r,metadata:{memory:e.memoryIndex,offset:t,byteLength:n.length,dataB64:We(n)}}}function xt(e,t){return{index:t,byteLength:e.data.length,dataB64:We(e.data),dropped:!1}}function Mt(e){let n=e.find(r=>r.opcode===O.i32_const)?.immediates[0];return typeof n=="number"?n:0}function We(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function _t(e){let t="";for(let n=0;n<e.length;n++){let r=e[n],o=r==="_"||/[A-Za-z]/.test(r)||n>0&&/[0-9]/.test(r);t+=o?r:"_"}return(t.length===0||/^[0-9]/.test(t))&&(t=`_${t}`),t}function _(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function S(e){return Number.isInteger(e)&&e>=0}function At(e){return Number.isInteger(e)&&e>=1}function De(e,t,n){if(JSON.stringify(e)!==JSON.stringify(t))throw new Error(`${n} mismatch: ${JSON.stringify(e)} != ${JSON.stringify(t)}`)}function $t(e,t){if(e.offset!==t.offset||e.length!==t.length)throw new Error("atomicRegion mismatch")}var Ve={};for(let[e,t]of Object.entries(O))Ve[t]=e.replace(/_/g,".");function Ct(e){let t=[];t.push("(module");for(let r of e.memories)t.push(` (memory ${r.min}${r.max!==void 0?` ${r.max}`:""})`);for(let r of e.imports)if(r.kind==="func"&&r.typeIndex!==void 0){let o=e.types[r.typeIndex];if(o){let s=o.params.map((a,c)=>`(param $${c} ${a})`).join(" "),i=o.results.map(a=>`(result ${a})`).join(" ");t.push(` (import "${r.module}" "${r.name}" (func ${s}${i?" "+i:""}))`)}}let n=new Set;for(let r of e.globals){if(r.kind==="import")continue;let o=r.mutable?"(mut ":"",s=r.mutable?")":"",i="";r.initValue!==void 0&&(r.type==="i32"||r.type==="i64"?i=`${r.type}.const ${r.initValue}`:(r.type==="f32"||r.type==="f64")&&(i=`${r.type}.const ${r.initValue}`)),t.push(` (global $${r.index} ${o}${r.type}${s} ${i?`(${i})`:""})`)}for(let r of e.data){let o=Array.from(r.data.slice(0,Math.min(32,r.data.length))).map(i=>`\\${i.toString(16).padStart(2,"0")}`).join(""),s=r.data.length>32?"...":"";t.push(` (data (i32.const ${r.memoryIndex}) "${o}${s}") ;; ${r.data.length} bytes`)}for(let r of e.functions)t.push(""),t.push(...Dt(r,e));if(e.exports.length>0){t.push("");for(let r of e.exports)r.kind==="func"?t.push(` (export "${r.name}" (func $${r.index}))`):r.kind==="mem"?t.push(` (export "${r.name}" (memory ${r.index}))`):r.kind==="global"&&t.push(` (export "${r.name}" (global ${r.index}))`)}return e.startFunctionIndex!==void 0&&t.push(` (start $${e.startFunctionIndex})`),t.push(")"),t.join(`
2
- `)}function Dt(e,t){let n=[],r=e.params.map((i,a)=>`(param $${a} ${i})`).join(" "),o=e.results.map(i=>`(result ${i})`).join(" ");if(n.push(` (func $${e.index} ${r}${o?" "+o:""}`),e.locals.length>0){let i=new Map;for(let a of e.locals)i.set(a.type,(i.get(a.type)||0)+1);for(let[a,c]of i)n.push(` (local ${a} (;${c}x;))`)}let s=Bt(e.body,2);return n.push(...s),n.push(" )"),n}function Bt(e,t){let n=[],r=" ".repeat(t);for(let o of e){let s=Et(o,t);n.push(`${r}${s}`)}return n}function Et(e,t){if(!e||typeof e!="object")return";; Error: Invalid instruction";let{opcode:n,immediates:r}=e,o=Ve[n]||`unknown_0x${n.toString(16)}`;if(!r||r.length===0)return o;switch(o){case"local.get":case"local.set":case"local.tee":return`${o} $${r[0]}`;case"global.get":case"global.set":return`${o} $${r[0]}`;case"i32.const":case"i64.const":return`${o} ${r[0]}`;case"f32.const":case"f64.const":return`${o} ${r[0]}`;case"call":return`${o} $${r[0]}`;case"call_indirect":return`${o} (type ${r[0]})`;case"br":case"br_if":return`${o} ${r[0]}`;case"br_table":let s=r[0].join(" "),i=r[1];return`${o} ${s} ${i}`;case"if":case"block":case"loop":let a=r[0];return`${o} ${a!==void 0&&a!=="void"?`(result ${a})`:""}`;case"i32.load":case"i64.load":case"f32.load":case"f64.load":case"i32.load8_s":case"i32.load8_u":case"i32.load16_s":case"i32.load16_u":case"i64.load8_s":case"i64.load8_u":case"i64.load16_s":case"i64.load16_u":case"i64.load32_s":case"i64.load32_u":case"i32.store":case"i64.store":case"f32.store":case"f64.store":case"i32.store8":case"i32.store16":case"i64.store8":case"i64.store16":case"i64.store32":let c=r[0],u=r[1],m=[];return u!==0&&m.push(`offset=${u}`),c!==void 0&&m.push(`align=${1<<c}`),`${o}${m.length>0?" "+m.join(" "):""}`;case"memory.size":case"memory.grow":return o;default:if(o.startsWith("v128.")){if(o.includes("load")||o.includes("store")){let d=r[0],l=r[1],p=[];return l!==0&&p.push(`offset=${l}`),d!==void 0&&p.push(`align=${1<<d}`),`${o}${p.length>0?" "+p.join(" "):""}`}if(o.includes("const")){let d=r.join(" ");return`${o} ${d}`}return o.includes("extract_lane")||o.includes("replace_lane")?`${o} ${r[0]}`:`${o}${r.length>0?" "+r.join(" "):""}`}return`${o}${r.length>0?" "+r.join(" "):""}`}}var hn=globalThis.gpu,Rt=globalThis.navigator?.gpu,se=class{constructor(t={}){this.config=t}device=null;queue=null;initialized=!1;buffers=new Map;async ensureInitialized(){if(!this.initialized)try{let t=await Rt?.requestAdapter?.();if(!t)throw new h("No GPU adapter available","compilation","navigator.gpu.requestAdapter() returned null");if(this.device=await t.requestDevice?.(),!this.device)throw new h("Failed to request GPU device","compilation","adapter.requestDevice() returned null");this.queue=this.device.queue,this.initialized=!0}catch(t){throw t instanceof h?t:new h(`GPU initialization failed: ${t instanceof Error?t.message:String(t)}`,"compilation",String(t))}}createBuffer(t,n,r){if(!this.device)throw new h("Device not initialized","binding","Call ensureInitialized() first");let o=this.device.createBuffer({label:t,size:n.byteLength,usage:r});return this.queue.writeBuffer(o,0,n.buffer,n.byteOffset,n.byteLength),o}async readBuffer(t,n,r){if(!this.device||!this.queue)throw new h("Device not initialized","readback","Call ensureInitialized() first");let o=Math.max(4,Math.ceil(n/4)*4),s=this.device.createBuffer({size:o,usage:9}),i=this.device.createCommandEncoder();i.copyBufferToBuffer(t,0,s,0,Math.min(n,o)),this.queue.submit([i.finish()]);try{await s.mapAsync(1)}catch(u){throw s.destroy(),new h(`Failed to map staging buffer: ${u instanceof Error?u.message:String(u)}`,"readback",String(u))}let a=s.getMappedRange(),c;return r==="f32"?c=new Float32Array(new Uint8Array(a).buffer).slice():r==="i32"?c=new Int32Array(new Uint8Array(a).buffer).slice():c=new Uint32Array(new Uint8Array(a).buffer).slice(),s.unmap(),s.destroy(),{data:c,type:r}}async execute(t,n,r,o={}){let s=o.workgroupSize??[1,1,1],i=o.workgroupCount??[1,1,1],a=o.timeout??5e3;if(await this.ensureInitialized(),!this.device||!this.queue)throw new h("Device initialization failed","compilation");try{let c;try{let f=o.shaderLabel||"Gasm Compiler Compute Shader";c=this.device.createShaderModule({code:t,label:f});let g=await c.getCompilationInfo?.();if(g&&g.messages.length>0){let y=g.messages.filter(w=>w.type==="error");if(y.length>0){let w=y.map(M=>`${M.message} at ${M.lineNum}:${M.linePos}`).join("; ");throw new h(`WGSL compilation failed: ${w}`,"compilation")}}}catch(f){throw f instanceof h?f:new h(`Failed to create shader module: ${f instanceof Error?f.message:String(f)}`,"compilation",String(f))}let u=[],m=0,d=new Map,l=Object.entries(n).sort((f,g)=>f[0]==="memory"?-1:g[0]==="memory"?1:f[0].localeCompare(g[0]));for(let[f,{data:g,type:y}]of l){let w=this.createBuffer(`input_${f}`,g,140);d.set(f,w),u.push({binding:m++,resource:{buffer:w}})}let p=new Map,k=new Map;for(let f of r){if(d.has(f)){let Fe=d.get(f),ce=n[f];p.set(f,Fe),k.set(f,{size:ce.data.byteLength,type:ce.type});continue}let g=o.outputBuffers?.[f]??{type:"f32",size:1},y=g.size??1,w=y*4,M=this.device.createBuffer({label:`output_${f}`,size:w,usage:140}),D;g.type==="f32"?D=new Float32Array(y).fill(0):g.type==="i32"?D=new Int32Array(y).fill(0):D=new Uint32Array(y).fill(0),this.queue.writeBuffer(M,0,D.buffer,D.byteOffset,D.byteLength),p.set(f,M),k.set(f,{size:w,type:g.type}),u.push({binding:m++,resource:{buffer:M}})}let b=Object.keys(n).length,x=this.device.createBindGroupLayout({entries:u.map((f,g)=>{let y=g===0&&n.memory!==void 0,w=g>=b;return{binding:g,visibility:4,buffer:{type:!y&&!w?"read-only-storage":"storage"}}})}),v=this.device.createBindGroup({layout:x,entries:u}),R=this.device.createPipelineLayout({bindGroupLayouts:[x]}),W;try{W=this.device.createComputePipeline({layout:R,compute:{module:c,entryPoint:"main"}})}catch(f){throw new h(`Failed to create compute pipeline: ${f instanceof Error?f.message:String(f)}`,"binding",String(f))}try{let f=this.device.createCommandEncoder(),g=f.beginComputePass();g.setPipeline(W),g.setBindGroup(0,v),g.dispatchWorkgroups(i[0],i[1],i[2]),g.end(),this.queue.submit([f.finish()])}catch(f){throw new h(`Compute shader dispatch failed: ${f instanceof Error?f.message:String(f)}`,"dispatch",String(f))}let G={};try{for(let f of r){let g=p.get(f),y=k.get(f);if(!g||!y)throw new h(`Output buffer "${f}" not found`,"readback");G[f]=await this.readBuffer(g,y.size,y.type)}}catch(f){throw f instanceof h?f:new h(`Failed to read back results: ${f instanceof Error?f.message:String(f)}`,"readback",String(f))}finally{let f=new Set;d.forEach(g=>{g.destroy(),f.add(g)}),p.forEach(g=>{f.has(g)||g.destroy()})}return G}catch(c){throw c instanceof h?c:new h(`Unexpected error during execution: ${c instanceof Error?c.message:String(c)}`,"dispatch",String(c))}}async destroy(){this.buffers.forEach(t=>t.destroy()),this.buffers.clear(),this.device&&typeof this.device.destroy=="function"&&this.device.destroy(),this.device=null,this.queue=null,this.initialized=!1}};function F(e,t={}){return T()?Ge(e,t):ae(e,t)}function Yn(e,t={}){let n,r=s=>{n=s},o=T()?Ge(e,t,r):ae(e,t,r);if(!o.ok)return o;if(!n)throw new Error("Compiler succeeded without a validated Wasm module");return{...o,metadata:ie(n,{options:t,dispatchInfo:o.dispatchInfo})}}async function Qn(){T()&&await ne()}async function Gt(e,t={}){return T()?await Ot(e,t):ae(e,t)}function ae(e,t={},n){let r=K(),o=L(t),s=t.strictConformance||o,i=z(e);if(P(i))return r.errors.push({severity:"error",code:i.code??B.ERR_PARSE,message:i.message,functionName:i.functionName}),{ok:!1,diagnostics:r};let a=i,c=q(a,{strictConformance:s});if(j(c))return r.errors.push({severity:"error",code:c.code??B.ERR_VALIDATION,message:c.message,functionName:c.functionName}),{ok:!1,diagnostics:r};let u=c;if(ze(r,u,t),t.mathExtension){let b=te(a,t.mathExtension);if(!b.valid){for(let x of b.errors)r.errors.push({severity:"error",code:"ERR_MATH_VALIDATION",message:x.message,functionName:x.functionName});return{ok:!1,diagnostics:r}}}let m=X(u,t);if(r.warnings.push(...m.diagnostics.warnings),r.errors.push(...m.diagnostics.errors),r.demotions.push(...m.diagnostics.demotions),r.featuresUsed=m.diagnostics.featuresUsed,r.errors.length>0)return{ok:!1,diagnostics:r};n?.(u);let d=he(u);t.optimize!==!1&&(d=be(d,{verbose:t.verbose??!1}));let l=Se(d);l=de(l),t.optimize!==!1&&(l=fe(l)),t.vectorPromotion&&(l=ke(l));let p=me();if(t.optimize!==!1){let b=pe(l);l=b.module,p=b.dispatchInfo,l=we(l),l=Ie(l)}return{ok:!0,wgsl:ye(l,t,e,p),diagnostics:r,dispatchInfo:p}}function T(){let t=globalThis.Deno?.env?.get("GASM_CORE_BACKEND")?.toLowerCase();return t!=="typescript"&&t!=="ts"}function Ge(e,t,n){let r=Oe(e,t);if(!r.ok)return{ok:!1,diagnostics:r.diagnostics};n?.(r.module);let o=$e(e,t);return o.ok?{ok:!0,wgsl:Pe(o.wgsl,t,e,r.module),diagnostics:r.diagnostics,dispatchInfo:Q(o.dispatchInfo)}:(r.diagnostics.errors.push(...ee(o.diagnostics).errors),{ok:!1,diagnostics:r.diagnostics})}async function Ot(e,t){let n=Oe(e,t);if(!n.ok)return{ok:!1,diagnostics:n.diagnostics};let o=(await ne()).compile(e,t);return o.ok?{ok:!0,wgsl:Pe(o.wgsl,t,e,n.module),diagnostics:n.diagnostics,dispatchInfo:Q(o.dispatchInfo)}:(n.diagnostics.errors.push(...ee(o.diagnostics).errors),{ok:!1,diagnostics:n.diagnostics})}function Oe(e,t){let n=K(),r=z(e);if(P(r))return n.errors.push({severity:"error",code:r.code??B.ERR_PARSE,message:r.message,functionName:r.functionName}),{ok:!1,diagnostics:n};let o=L(t),s=t.strictConformance||o,i=q(r,{strictConformance:s});if(j(i))return n.errors.push({severity:"error",code:i.code??B.ERR_VALIDATION,message:i.message,functionName:i.functionName}),{ok:!1,diagnostics:n};if(ze(n,i,t),t.mathExtension){let c=te(r,t.mathExtension);if(!c.valid){for(let u of c.errors)n.errors.push({severity:"error",code:"ERR_MATH_VALIDATION",message:u.message,functionName:u.functionName});return{ok:!1,diagnostics:n}}}let a=X(i,t);return n.warnings.push(...a.diagnostics.warnings),n.errors.push(...a.diagnostics.errors),n.demotions.push(...a.diagnostics.demotions),n.featuresUsed=a.diagnostics.featuresUsed,n.errors.length>0?{ok:!1,diagnostics:n}:{ok:!0,diagnostics:n,module:i}}function ze(e,t,n){L(n)&&Re(t,n)&&(e.warnings.some(r=>r.code==="WARN_WORKGROUP_SIZE_OVERRIDE")||e.warnings.push({severity:"warning",code:"WARN_WORKGROUP_SIZE_OVERRIDE",message:"CompileOptions.workgroupSize overrides gasm.workgroup_size custom-section declarations"}))}function Pe(e,t,n,r){let o=e;if(o=zt(o,t,n,r),t.compilerMetadata&&(o=o.replace(/(\/\/ Generated: .*\n)/,`$1// Metadata: ${t.compilerMetadata}
3
- `)),t.workgroupSize){let[s,i,a]=t.workgroupSize;o=o.replace(/@compute @workgroup_size\(\d+, \d+, \d+\)/g,`@compute @workgroup_size(${s}, ${i}, ${a})`)}return o}function zt(e,t,n,r){if(t.stripComments||t.releaseMode)return e;let s=ge(n,t.sourceMapping);if(!s)return e;let i=s.generateHeaderComment(),a=i?e.replace(/(\/\/ Generated: .*\n)/,`$1${i}
4
- `):e,c=0;return a=a.replace(/^fn ([A-Za-z_][A-Za-z0-9_]*)\(/gm,(u,m)=>{let d=r.functions[c],l=s.commentForFunction(d?.index??c,m);if(c+=1,!l)return u;let p=t.sourceMapping==="minimal"?"":`
5
- // [WAT] rust backend instruction mapping`;return`${l}${p}
6
- ${u}`}),a}function er(e,t={}){let n=F(e,t);if(!n.ok){let r=n.diagnostics.errors[0];throw I(r?.message??"Compilation failed",{functionName:r?.functionName,instructionName:r?.code,code:r?.code})}return n.wgsl}async function tr(e,t={}){let n=await Gt(e,t);if(!n.ok){let r=n.diagnostics.errors[0];throw I(r?.message??"Compilation failed",{functionName:r?.functionName,instructionName:r?.code,code:r?.code})}return n.wgsl}function Ue(e,t){for(let n of e.warnings){let r=n.functionName?` (${n.functionName})`:"";console.error(`warning${r}: ${n.message}`)}if(t&&e.demotions.length>0){let n=new Map;for(let o of e.demotions)n.set(o.kind,(n.get(o.kind)??0)+1);let r=[...n.entries()].map(([o,s])=>`${o} (${s})`);console.error(`demotions: ${r.join(", ")}`)}}function qt(e,t){return new Promise(n=>{let r=Ft(e,t,{stdio:["ignore","pipe","pipe"]}),o="",s="";r.stdout.on("data",i=>{o+=String(i)}),r.stderr.on("data",i=>{s+=String(i)}),r.on("close",i=>{n({success:i===0,stdout:o,stderr:s})}),r.on("error",i=>{n({success:!1,stdout:o,stderr:`${s}
7
- ${i.message}`})})})}async function Wt(e,t={}){let{output:n,verbose:r=!1,keepWasm:o=!1,optimize:s=!1,denyF64Demotion:i=!1,allowI64Demotion:a=!1,warningsAsErrors:c=!1}=t;try{r&&console.log(`[1/4] Validating input file: ${e}`);let u=Le(e);if(!(await Ne(u)).isFile())throw new Error(`Not a file: ${e}`);let d=u.endsWith(".wasm");!d&&!u.endsWith(".as")&&!u.endsWith(".ts")&&console.warn("Warning: Input file does not have .as, .ts, or .wasm extension");let l=u.replace(/\.(as|ts)$/,".wasm");if(d)r&&console.log("[2/4] Input is WASM, skipping compilation..."),l=u;else{r&&console.log("[2/4] Compiling AssemblyScript to WASM...");let v=await jt(),{success:R,stdout:W,stderr:G}=await qt(v,[u,"-o",l]);if(!R)throw new Error(`AssemblyScript compilation failed:
8
- ${G}`);r&&W&&console.log(W)}r&&console.log("[3/4] Reading WASM binary...");let p=await Pt(l);r&&(console.log(` WASM size: ${p.length} bytes`),console.log("[4/4] Compiling WASM to WGSL using Gasm..."));let k={};i&&(k.f64="deny"),a&&(k.i64="allow-lossy");let b=F(p,{optimize:s,demotionPolicy:k,warningsAsErrors:c});if(Ue(b.diagnostics,r),!b.ok){let v=b.diagnostics.errors[0];throw new Error(v?.message??"Compilation failed")}let x=b.wgsl;if(n){let v=Le(n),R=Tt(v);await Ut(R,{recursive:!0}),await Lt(v,x,"utf-8"),console.log(r?`
9
- \u2713 Successfully compiled to: ${v}`:`\u2713 Compiled to: ${n}`)}if(!o&&!d)try{await Nt(l),r&&console.log(" Cleaned up intermediate WASM file")}catch{}return x}catch(u){throw u instanceof Error?u:new Error(`Unknown error: ${String(u)}`)}}function Vt(e,t={}){let{verbose:n=!1,optimize:r=!1,denyF64Demotion:o=!1,allowI64Demotion:s=!1,warningsAsErrors:i=!1}=t,a={};o&&(a.f64="deny"),s&&(a.i64="allow-lossy");let c=F(e,{optimize:r,demotionPolicy:a,warningsAsErrors:i});if(Ue(c.diagnostics,n),!c.ok){let u=c.diagnostics.errors[0];throw new Error(u?.message??"Compilation failed")}return c.wgsl}async function jt(){let e=["node_modules/.bin/asc","./examples/node_modules/.bin/asc","../app/node_modules/.bin/asc","./node_modules/assemblyscript/bin/asc.js"];for(let t of e)try{if((await Ne(t)).isFile())return t}catch{}return"asc"}export{oe as a,ie as b,mt as c,pt as d,Ee as e,Ct as f,se as g,Wt as h,Vt as i,F as j,Yn as k,Qn as l,Gt as m,er as n,tr as o};