supersonic-scsynth 0.65.0 → 0.67.2

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.
@@ -1,8 +1,8 @@
1
- var B=class i{constructor(e){if(new.target===i)throw new Error("Transport is abstract - use SABTransport or PostMessageTransport");this._config=e,this._disposed=!1}get mode(){return this._config.mode}send(e,t){throw new Error("Abstract method - implement in subclass")}onReply(e){throw new Error("Abstract method - implement in subclass")}onDebug(e){throw new Error("Abstract method - implement in subclass")}onError(e){throw new Error("Abstract method - implement in subclass")}getMetrics(){throw new Error("Abstract method - implement in subclass")}async initialize(){throw new Error("Abstract method - implement in subclass")}createOscChannel(){throw new Error("Abstract method - implement in subclass")}dispose(){this._disposed=!0}get ready(){throw new Error("Abstract method - implement in subclass")}};var he=new Map;function Ve(i){try{return new URL(i,window.location.href).origin!==window.location.origin}catch{return!1}}async function qe(i){if(he.has(i))return he.get(i);let e=await fetch(i);if(!e.ok)throw new Error(`Failed to fetch ${i}: ${e.status} ${e.statusText}`);let t=await e.text(),s=new Blob([t],{type:"application/javascript"}),r=URL.createObjectURL(s);return he.set(i,r),r}async function O(i,e={}){let t=i;return Ve(i)&&(t=await qe(i)),new Worker(t,e)}async function Xe(i,e){let t=e;Ve(e)&&(t=await qe(e)),await i.addModule(t)}function vt(i,e,t){return(t-1-i+e)%t}function Ht({uint8View:i,dataView:e,bufferStart:t,bufferSize:s,head:r,payload:n,sequence:o,messageMagic:a,headerSize:c,sourceId:l=0,headerScratch:u=null,headerScratchView:f=null}){let h=n.length,m=c+h+3&-4,E=s-r;if(m>E){let p=u||new Uint8Array(c),y=f||new DataView(p.buffer);y.setUint32(0,a,!0),y.setUint32(4,m,!0),y.setUint32(8,o,!0),y.setUint32(12,l,!0);let _=t+r,d=t;if(E>=c){i.set(p,_);let M=E-c;M>0&&i.set(n.subarray(0,M),_+c),i.set(n.subarray(M),d)}else{i.set(p.subarray(0,E),_),i.set(p.subarray(E),d);let M=c-E;i.set(n,d+M)}}else{let p=t+r;e.setUint32(p,a,!0),e.setUint32(p+4,m,!0),e.setUint32(p+8,o,!0),e.setUint32(p+12,l,!0),i.set(n,p+c)}return(r+m)%s}function zt(i,e,t=0,s=!1){for(let r=0;r<=t;r++)if(Atomics.compareExchange(i,e,0,1)===0)return!0;if(s){for(let n=0;n<100;n++)if(Atomics.wait(i,e,1,100),Atomics.compareExchange(i,e,0,1)===0)return!0;return console.error("[RingBuffer] Lock acquisition timeout after 10s - possible deadlock"),!1}return!1}function Gt(i,e){Atomics.store(i,e,0),Atomics.notify(i,e,1)}function Ke({atomicView:i,dataView:e,uint8View:t,bufferConstants:s,ringBufferBase:r,controlIndices:n,oscMessage:o,sourceId:a=0,maxSpins:c=0,useWait:l=!1}){let u=o.length,f=s.MESSAGE_HEADER_SIZE+u;if(f>s.IN_BUFFER_SIZE-s.MESSAGE_HEADER_SIZE||!zt(i,n.IN_WRITE_LOCK,c,l))return!1;try{let h=Atomics.load(i,n.IN_HEAD),S=Atomics.load(i,n.IN_TAIL),m=f+3&-4;if(vt(h,S,s.IN_BUFFER_SIZE)<m)return!1;let p=Atomics.add(i,n.IN_SEQUENCE,1),y=Ht({uint8View:t,dataView:e,bufferStart:r+s.IN_BUFFER_START,bufferSize:s.IN_BUFFER_SIZE,head:h,payload:o,sequence:p,messageMagic:s.MESSAGE_MAGIC,headerSize:s.MESSAGE_HEADER_SIZE,sourceId:a});return Atomics.load(i,n.IN_HEAD),Atomics.store(i,n.IN_HEAD,y),Atomics.notify(i,n.IN_HEAD,1),!0}finally{Gt(i,n.IN_WRITE_LOCK)}}function W(i,e){let t=i+e;return{IN_HEAD:(t+0)/4,IN_TAIL:(t+4)/4,IN_SEQUENCE:(t+24)/4,IN_WRITE_LOCK:(t+40)/4,IN_LOG_TAIL:(t+44)/4}}function je(i,e){let t=i+e;return{IN_HEAD:(t+0)/4,IN_TAIL:(t+4)/4,OUT_HEAD:(t+8)/4,OUT_TAIL:(t+12)/4,DEBUG_HEAD:(t+16)/4,DEBUG_TAIL:(t+20)/4,IN_SEQUENCE:(t+24)/4,OUT_SEQUENCE:(t+28)/4,DEBUG_SEQUENCE:(t+32)/4,STATUS_FLAGS:(t+36)/4,IN_WRITE_LOCK:(t+40)/4,IN_LOG_TAIL:(t+44)/4}}function $t(i){return i.length>=8&&i[0]===35&&i[1]===98&&i[2]===117&&i[3]===110&&i[4]===100&&i[5]===108&&i[6]===101&&i[7]===0}var de=.5;function pe(i){if(i.length<16)return null;let e=new DataView(i.buffer,i.byteOffset,i.byteLength);return{ntpSeconds:e.getUint32(8,!1),ntpFraction:e.getUint32(12,!1)}}function A(){return(performance.timeOrigin+performance.now())/1e3+2208988800}function Qe(i,e={}){let{getCurrentNTP:t=A,bypassLookaheadS:s=de}=e;if(!$t(i))return"nonBundle";let r=pe(i);if(!r)return"nonBundle";let{ntpSeconds:n,ntpFraction:o}=r;if(n===0&&o<=1)return"immediate";let a=t();if(a===null||a===0)return"immediate";let l=n+o/4294967296-a;return l<0?"late":l<s?"nearFuture":"farFuture"}function V(i){return i!=="farFuture"}var Yt={nonBundle:38,immediate:39,nearFuture:40,late:41},w=class i{#t;#e;#s;#f;#o;#c;#n;#i;#l;#u;#d;#E;#_;#p;#h;#m;#b;#y;#r;#a={messagesSent:0,bytesSent:0,nonBundle:0,immediate:0,nearFuture:0,late:0,bypassed:0};constructor(e,t){if(this.#t=e,this.#o=t.preschedulerPort||null,this.#n=t.bypassLookaheadS??de,this.#i=t.sourceId??0,this.#l=t.blocking??this.#i!==0,this.#u=t.getCurrentNTP??A,this.#h=1e3,e==="postMessage")this.#e=t.port;else{if(this.#s={sharedBuffer:t.sharedBuffer,ringBufferBase:t.ringBufferBase,bufferConstants:t.bufferConstants,controlIndices:t.controlIndices},this.#g(),t.sharedBuffer&&t.bufferConstants){let s=t.ringBufferBase+t.bufferConstants.METRICS_START;this.#c=new Int32Array(t.sharedBuffer,s,t.bufferConstants.METRICS_SIZE/4)}if(t.sharedBuffer&&t.bufferConstants?.NODE_ID_COUNTER_START!==void 0){let s=t.ringBufferBase+t.bufferConstants.NODE_ID_COUNTER_START;this.#d=new Int32Array(t.sharedBuffer,s,1),this.#w()}}t.nodeIdSource&&(this.#m=t.nodeIdSource,this.#w()),t.nodeIdRange&&(this.#E=t.nodeIdRange.from,this.#_=t.nodeIdRange.to,this.#p=t.nodeIdRange.from),t.nodeIdPort&&(this.#b=t.nodeIdPort,this.#b.onmessage=s=>{s.data.type==="nodeIdRange"&&(this.#y={from:s.data.from,to:s.data.to})},this.#M())}#g(){let e=this.#s.sharedBuffer;this.#f={atomicView:new Int32Array(e),dataView:new DataView(e),uint8View:new Uint8Array(e)}}classify(e){return Qe(e,{getCurrentNTP:this.#u,bypassLookaheadS:this.#n})}#S(e,t=null){if(this.#t==="sab"&&this.#c){if(Atomics.add(this.#c,24,1),Atomics.add(this.#c,25,e),t){let s=Yt[t];s!==void 0&&(Atomics.add(this.#c,s,1),Atomics.add(this.#c,22,1))}}else this.#a.messagesSent++,this.#a.bytesSent+=e,t&&t in this.#a&&(this.#a[t]++,this.#a.bypassed++)}getAndResetMetrics(){let e={...this.#a};return this.#a={messagesSent:0,bytesSent:0,nonBundle:0,immediate:0,nearFuture:0,late:0,bypassed:0},e}getMetrics(){return this.#t==="sab"&&this.#c?{messagesSent:Atomics.load(this.#c,24),bytesSent:Atomics.load(this.#c,25),nonBundle:Atomics.load(this.#c,38),immediate:Atomics.load(this.#c,39),nearFuture:Atomics.load(this.#c,40),late:Atomics.load(this.#c,41),bypassed:Atomics.load(this.#c,22)}:{...this.#a}}#C(e,t=null,s=!0){if(this.#t==="postMessage")return this.#e?(this.#e.postMessage({type:"osc",oscData:e,bypassCategory:t,sourceId:this.#i}),!0):!1;{let r=this.#l,n=Ke({atomicView:this.#f.atomicView,dataView:this.#f.dataView,uint8View:this.#f.uint8View,bufferConstants:this.#s.bufferConstants,ringBufferBase:this.#s.ringBufferBase,controlIndices:this.#s.controlIndices,oscMessage:e,sourceId:this.#i,maxSpins:r?10:0,useWait:r});return!n&&!r&&s&&this.#o?(this.#c&&Atomics.add(this.#c,45,1),this.#o.postMessage({type:"directDispatch",oscData:e,sourceId:this.#i}),!0):n}}#A(e){return this.#o?(this.#o.postMessage({type:"osc",oscData:e,sourceId:this.#i}),!0):(console.error("[OscChannel] No prescheduler port, sending direct"),this.#C(e))}send(e){let t=this.classify(e);if(V(t)){let s=this.#C(e,t);return s&&this.#S(e.length,t),s}else{let s=this.#A(e);return s&&this.#S(e.length,null),s}}sendDirect(e){return this.#C(e)}sendToPrescheduler(e){return this.#A(e)}nextNodeId(){if(this.#d)return Atomics.add(this.#d,0,1);this.#p>=this.#_&&this.#w();let e=this.#p++;return this.#b&&!this.#y&&this.#_-this.#p<=this.#h>>>1&&this.#M(),e}#w(){if(this.#m){let e=this.#m(this.#h);this.#E=e.from,this.#_=e.to,this.#p=e.from}else this.#y?(this.#E=this.#y.from,this.#_=this.#y.to,this.#p=this.#y.from,this.#y=null,this.#M()):this.#b&&(console.warn("[OscChannel] nextNodeId() range exhausted before async refill arrived. IDs may not be unique. Yield to the event loop between large batches of nextNodeId() calls."),this.#M())}#M(){this.#b&&this.#b.postMessage({type:"requestNodeIdRange"})}set getCurrentNTP(e){this.#u=e}get mode(){return this.#t}get transferable(){let e={mode:this.#t,preschedulerPort:this.#o,bypassLookaheadS:this.#n,sourceId:this.#i,blocking:this.#l};if(this.#t==="postMessage"){let t=this.#h*10,s,r;if(this.#m){let n=this.#m(t);s={from:n.from,to:n.to};let o=new MessageChannel,a=this.#m,c=this.#h;o.port1.onmessage=l=>{if(l.data.type==="requestNodeIdRange"){let u=a(c);o.port1.postMessage({type:"nodeIdRange",from:u.from,to:u.to})}},r=o.port2,this.#r=r}return{...e,port:this.#e,nodeIdRange:s,nodeIdPort:r}}else return{...e,sharedBuffer:this.#s.sharedBuffer,ringBufferBase:this.#s.ringBufferBase,bufferConstants:this.#s.bufferConstants,controlIndices:this.#s.controlIndices}}get transferList(){let e=[];return this.#t==="postMessage"&&this.#e&&e.push(this.#e),this.#o&&e.push(this.#o),this.#r&&(e.push(this.#r),this.#r=null),e}close(){this.#t==="postMessage"&&this.#e&&(this.#e.close(),this.#e=null),this.#o&&(this.#o.close(),this.#o=null)}static createPostMessage(e){return e instanceof MessagePort?new i("postMessage",{port:e}):new i("postMessage",e)}static createSAB(e){let t=e.controlIndices;return t||(t=W(e.ringBufferBase,e.bufferConstants.CONTROL_START)),new i("sab",{sharedBuffer:e.sharedBuffer,ringBufferBase:e.ringBufferBase,bufferConstants:e.bufferConstants,controlIndices:t,preschedulerPort:e.preschedulerPort,bypassLookaheadS:e.bypassLookaheadS,sourceId:e.sourceId,blocking:e.blocking})}static fromTransferable(e){return e.mode==="postMessage"?new i("postMessage",{port:e.port,preschedulerPort:e.preschedulerPort,bypassLookaheadS:e.bypassLookaheadS,sourceId:e.sourceId,blocking:e.blocking,nodeIdRange:e.nodeIdRange,nodeIdPort:e.nodeIdPort}):new i("sab",{sharedBuffer:e.sharedBuffer,ringBufferBase:e.ringBufferBase,bufferConstants:e.bufferConstants,controlIndices:e.controlIndices,preschedulerPort:e.preschedulerPort,bypassLookaheadS:e.bypassLookaheadS,sourceId:e.sourceId,blocking:e.blocking})}};var N=class extends B{#t;#e;#s;#f;#o;#c;#n;#i;#l;#u;#d;#E;#_;#p;#h;#m;#b=1;#y=!1;#r;#a=0;#g=0;#S=0;#C=null;constructor(e){if(super({...e,mode:"sab"}),this.#t=e.sharedBuffer,this.#e=e.ringBufferBase,this.#s=e.bufferConstants,this.#E=e.workerBaseURL,this.#r=e.preschedulerCapacity||65536,!(this.#t instanceof SharedArrayBuffer))throw new Error("SABTransport requires a SharedArrayBuffer");this.#A()}async initialize(){if(this.#y)return;let[e,t,s,r]=await Promise.all([O(this.#E+"osc_out_prescheduler_worker.js",{type:"module"}),O(this.#E+"osc_in_worker.js",{type:"module"}),O(this.#E+"debug_worker.js",{type:"module"}),O(this.#E+"osc_out_log_sab_worker.js",{type:"module"})]);this.#i=e,this.#l=t,this.#u=s,this.#d=r,this.#M(),await Promise.all([this.#w(this.#i,"OSC OUT",{maxPendingMessages:this.#r,bypassLookaheadS:this._config.bypassLookaheadS}),this.#w(this.#l,"OSC IN"),this.#w(this.#u,"DEBUG"),this.#w(this.#d,"OSC OUT LOG")]),this.#l.postMessage({type:"start"}),this.#u.postMessage({type:"start"}),this.#d.postMessage({type:"start"}),this.#y=!0}send(e,t){return!this.#y||this._disposed?!1:(this.#i.postMessage({type:"send",oscData:e,sessionId:0,runTag:"",audioTimeS:null,currentTimeS:null}),this.#a++,this.#S+=e.length,!0)}sendWithOptions(e,t={}){if(!this.#y||this._disposed)return!1;let{sessionId:s=0,runTag:r="",audioTimeS:n=null,currentTimeS:o=null}=t;return this.#i.postMessage({type:"send",oscData:e,sessionId:s,runTag:r,audioTimeS:n,currentTimeS:o}),this.#a++,this.#S+=e.length,!0}sendImmediate(e){return!this.#y||this._disposed?!1:(this.#i.postMessage({type:"sendImmediate",oscData:e}),this.#a++,this.#S+=e.length,!0)}createOscChannel(e={}){if(!this.#y)throw new Error("Transport not initialized");let t=e.sourceId??this.#b++,s=new MessageChannel;return this.#i.postMessage({type:"addOscSource"},[s.port1]),w.createSAB({sharedBuffer:this.#t,ringBufferBase:this.#e,bufferConstants:this.#s,controlIndices:this.#n,preschedulerPort:s.port2,bypassLookaheadS:this._config.bypassLookaheadS,sourceId:t,blocking:e.blocking})}cancelSessionTag(e,t){this.#y&&this.#i.postMessage({type:"cancelSessionTag",sessionId:e,runTag:t})}cancelSession(e){this.#y&&this.#i.postMessage({type:"cancelSession",sessionId:e})}cancelTag(e){this.#y&&this.#i.postMessage({type:"cancelTag",runTag:e})}cancelAll(){this.#y&&this.#i.postMessage({type:"cancelAll"})}cancelAllWithAck(){return this.#y?new Promise(e=>{let t=s=>{s.data.type==="cancelAllAck"&&(this.#i.removeEventListener("message",t),e())};this.#i.addEventListener("message",t),this.#i.postMessage({type:"cancelAll",ack:!0})}):Promise.resolve()}onReply(e){this.#_=e}onDebug(e){this.#p=e}onError(e){this.#h=e}onOscLog(e){this.#m=e}handleOscLog(e){this.#m&&this.#m(e)}getMetrics(){return{oscOutMessagesSent:this.#a,oscOutMessagesDropped:this.#g,oscOutBytesSent:this.#S}}get ready(){return this.#y&&!this._disposed}dispose(){this._disposed||(this.#i&&(this.#i.postMessage({type:"stop"}),this.#i.terminate(),this.#i=null),this.#l&&(this.#l.postMessage({type:"stop"}),this.#l.terminate(),this.#l=null),this.#u&&(this.#u.postMessage({type:"stop"}),this.#u.terminate(),this.#u=null),this.#d&&(this.#d.postMessage({type:"stop"}),this.#d.terminate(),this.#d=null),this.#y=!1,super.dispose())}#A(){this.#f=new Int32Array(this.#t),this.#o=new DataView(this.#t),this.#c=new Uint8Array(this.#t),this.#n=W(this.#e,this.#s.CONTROL_START)}#w(e,t,s={}){return new Promise((r,n)=>{let o=setTimeout(()=>{n(new Error(`${t} worker initialization timeout`))},5e3),a=c=>{c.data.type==="initialized"&&(clearTimeout(o),e.removeEventListener("message",a),r())};e.addEventListener("message",a),e.postMessage({type:"init",sharedBuffer:this.#t,ringBufferBase:this.#e,bufferConstants:this.#s,...s})})}#M(){this.#l.onmessage=e=>{let t=e.data;t.type==="messages"&&this.#_?t.messages.forEach(s=>{s.oscData&&this.#_(s.oscData,s.sequence,s.timestamp)}):t.type==="error"&&(console.error("[SABTransport] OSC IN error:",t.error),this.#h&&this.#h(t.error,"oscIn"))},this.#u.onmessage=e=>{let t=e.data;t.type==="debug"&&this.#p?t.messages.forEach(s=>{this.#p(s)}):t.type==="error"&&(console.error("[SABTransport] DEBUG error:",t.error),this.#h&&this.#h(t.error,"debug"))},this.#i.onmessage=e=>{let t=e.data;t.type==="preschedulerMetrics"?this.#C=t.metrics:t.type==="error"&&(console.error("[SABTransport] OSC OUT error:",t.error),this.#g++,this.#h&&this.#h(t.error,"oscOut"))},this.#d.onmessage=e=>{let t=e.data;t.type==="oscLog"&&this.#m?this.#m(t.entries):t.type==="error"&&(console.error("[SABTransport] OSC OUT LOG error:",t.error),this.#h&&this.#h(t.error,"oscOutLog"))}}getPreschedulerMetrics(){return this.#C}};var v=class extends B{#t;#e;#s;#f;#o;#c;#n;#i=1;#l=null;#u=!1;#d;#E;#_=null;#p=0;#h=0;#m=0;#b=0;#y=0;#r=-1;#a=0;#g=0;#S;#C;constructor(e){super({...e,mode:"postMessage"}),this.#s=e.workerBaseURL,this.#d=e.preschedulerCapacity||65536,this.#E=e.snapshotIntervalMs,this.#S=e.getAudioContextTime,this.#C=e.getNTPStartTime}async initialize(e){if(this.#u)return;if(!e)throw new Error("PostMessageTransport requires workletPort");this.#t=e,this.#t.onmessage=s=>{this.#w(s.data)};let t=new MessageChannel;this.#t.postMessage({type:"addOscPort"},[t.port1]),this.#e=await O(this.#s+"osc_out_prescheduler_worker.js",{type:"module"}),this.#e.onmessage=s=>{this.#M(s.data)},await this.#A(t.port2),this.#u=!0}setBufferConstants(e){this.#_=e}send(e,t){return!this.#u||this._disposed?!1:(this.#e.postMessage({type:"send",oscData:e,sessionId:0,runTag:"",audioTimeS:null,currentTimeS:null}),this.#p++,this.#m+=e.length,!0)}sendWithOptions(e,t={}){if(!this.#u||this._disposed)return!1;let{sessionId:s=0,runTag:r="",audioTimeS:n=null,currentTimeS:o=null}=t;return this.#e.postMessage({type:"send",oscData:e,sessionId:s,runTag:r,audioTimeS:n,currentTimeS:o}),this.#p++,this.#m+=e.length,!0}sendImmediate(e,t){return!this.#u||this._disposed?!1:(this.#t.postMessage({type:"osc",oscData:e,bypassCategory:t}),this.#p++,this.#m+=e.length,!0)}createOscChannel(e={}){if(!this.#u)throw new Error("Transport not initialized");let t=e.sourceId??this.#i++,s=new MessageChannel;this.#t.postMessage({type:"addOscPort",sourceId:t},[s.port1]);let r=new MessageChannel;return this.#e.postMessage({type:"addOscSource"},[r.port1]),w.createPostMessage({port:s.port2,preschedulerPort:r.port2,bypassLookaheadS:this._config.bypassLookaheadS,sourceId:t,blocking:e.blocking,nodeIdSource:this._config.nodeIdSource})}cancelSessionTag(e,t){this.#u&&this.#e.postMessage({type:"cancelSessionTag",sessionId:e,runTag:t})}cancelSession(e){this.#u&&this.#e.postMessage({type:"cancelSession",sessionId:e})}cancelTag(e){this.#u&&this.#e.postMessage({type:"cancelTag",runTag:e})}cancelAll(){this.#u&&this.#e.postMessage({type:"cancelAll"})}cancelAllWithAck(){return this.#u?new Promise(e=>{let t=s=>{s.data.type==="cancelAllAck"&&(this.#e.removeEventListener("message",t),e())};this.#e.addEventListener("message",t),this.#e.postMessage({type:"cancelAll",ack:!0})}):Promise.resolve()}onReply(e){this.#f=e}onDebug(e){this.#o=e}onError(e){this.#c=e}onOscLog(e){this.#n=e}handleDebugRaw(e){if(e.messages&&e.count>0&&e.buffer){let t=new TextDecoder("utf-8"),s=new Uint8Array(e.buffer);for(let r=0;r<e.count;r++){let n=e.messages[r];try{let o=s.subarray(n.offset,n.offset+n.length),a=t.decode(o);a.endsWith(`
2
- `)&&(a=a.slice(0,-1)),this.#a++,this.#g+=n.length,this.#o&&this.#o({text:a,timestamp:performance.now(),sequence:n.sequence})}catch(o){console.error("[PostMessageTransport] Failed to decode debug message:",o)}}}}getPreschedulerMetrics(){return this.#l}getMetrics(){return{oscInMessagesReceived:this.#b,oscInBytesReceived:this.#y,oscInMessagesDropped:this.#h,debugMessagesReceived:this.#a,debugBytesReceived:this.#g}}get ready(){return this.#u&&!this._disposed}dispose(){this._disposed||(this.#e&&(this.#e.postMessage({type:"stop"}),this.#e.terminate(),this.#e=null),this.#t=null,this.#u=!1,super.dispose())}#A(e){return new Promise((t,s)=>{let r=setTimeout(()=>{s(new Error("Prescheduler worker initialization timeout"))},5e3),n=o=>{o.data.type==="initialized"&&(clearTimeout(r),this.#e.removeEventListener("message",n),t())};this.#e.addEventListener("message",n),this.#e.postMessage({type:"init",mode:"postMessage",maxPendingMessages:this.#d,snapshotIntervalMs:this.#E,bypassLookaheadS:this._config.bypassLookaheadS,workletPort:e},[e])})}#w(e){switch(e.type){case"oscReplies":if(e.messages&&e.count>0&&e.buffer){let t=new Uint8Array(e.buffer);for(let s=0;s<e.count;s++){let r=e.messages[s],n=t.subarray(r.offset,r.offset+r.length);if(r.sequence!==void 0&&this.#r>=0){let o=this.#r+1&4294967295;if(r.sequence!==o){let a=r.sequence-o+4294967296&4294967295;a<1e3&&(this.#h+=a)}}r.sequence!==void 0&&(this.#r=r.sequence),this.#b++,this.#y+=r.length,this.#f&&this.#f(n,r.sequence,A())}}break;case"metrics":break;case"bufferLoaded":break;case"debugRawBatch":this.handleDebugRaw(e);break;case"oscLog":if(this.#n&&e.count>0&&e.buffer&&e.entries){let t=new Uint8Array(e.buffer),s=[];for(let r=0;r<e.count;r++){let n=e.entries[r],o=t.subarray(n.offset,n.offset+n.length);s.push({oscData:o,sourceId:n.sourceId,sequence:n.sequence,timestamp:A(),truncated:n.length<n.originalLength,originalLength:n.originalLength})}this.#n(s)}break;case"error":console.error("[PostMessageTransport] Worklet error:",e.error),this.#h++,this.#c&&this.#c(e.error,"worklet");break;case"debug":break}}#M(e){switch(e.type){case"preschedulerMetrics":this.#l=e.metrics;break;case"error":console.error("[PostMessageTransport] Prescheduler error:",e.error),this.#h++,this.#c&&this.#c(e.error,"oscOut");break}}};function Je(i,e){if(i==="sab")return new N(e);if(i==="postMessage")return new v(e);throw new Error(`Unknown transport mode: ${i}. Use 'sab' or 'postMessage'`)}var Wt={5120:"i8",5121:"u8",5122:"i16",5123:"u16",5124:"i32",5125:"u32",5126:"f32"};var et={u8:1,u8c:1,i8:1,u16:2,i16:2,u32:4,i32:4,i64:8,u64:8,f32:4,f64:8};var Vt={f32:Float32Array,f64:Float64Array},qt={i8:Int8Array,i16:Int16Array,i32:Int32Array},Xt={u8:Uint8Array,u8c:Uint8ClampedArray,u16:Uint16Array,u32:Uint32Array},Kt={i64:BigInt64Array,u64:BigUint64Array},Zt={...Vt,...qt,...Xt},jt=i=>{let e=Wt[i];return e!==void 0?e:i};function tt(i,...e){let t=Kt[i];return new(t||Zt[jt(i)])(...e)}var H=(i,e)=>(e--,i+e&~e);var st=i=>typeof i=="number";var q=(i,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(i(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var Qt=q(()=>"Assertion failed"),ye=(typeof process<"u"&&process.env!==void 0?process.env.UMBRELLA_ASSERTS:!import.meta.env||import.meta.env.MODE!=="production"||import.meta.env.UMBRELLA_ASSERTS||import.meta.env.VITE_UMBRELLA_ASSERTS)?(i,e)=>{if(typeof i=="function"&&!i()||!i)throw new Qt(typeof e=="function"?e():e)}:()=>{};var Jt=q(()=>"illegal argument(s)"),rt=i=>{throw new Jt(i)};var it=0,nt=1,ot=2,at=3,ct=4,F=5,lt=6,ge=1,Se=2,ut=7*4,Ee=0,_e=1,C=2*4,X=class{buf;start;u8;u32;state;constructor(e={}){if(this.buf=e.buf?e.buf:new ArrayBuffer(e.size||4096),this.start=e.start!=null?H(Math.max(e.start,0),4):0,this.u8=new Uint8Array(this.buf),this.u32=new Uint32Array(this.buf),this.state=new Uint32Array(this.buf,this.start,ut/4),!e.skipInitialization){let t=e.align||8;ye(t>=8,`invalid alignment: ${t}, must be a pow2 and >= 8`);let s=this.initialTop(t),r=e.end!=null?Math.min(e.end,this.buf.byteLength):this.buf.byteLength;s>=r&&rt(`insufficient address range (0x${this.start.toString(16)} - 0x${r.toString(16)})`),this.align=t,this.doCompact=e.compact!==!1,this.doSplit=e.split!==!1,this.minSplit=e.minSplit||16,this.end=r,this.top=s,this._free=0,this._used=0}}stats(){let e=s=>{let r=0,n=0;for(;s;)r++,n+=this.blockSize(s),s=this.blockNext(s);return{count:r,size:n}},t=e(this._free);return{free:t,used:e(this._used),top:this.top,available:this.end-this.top+t.size,total:this.buf.byteLength}}callocAs(e,t,s=0){let r=this.mallocAs(e,t);return r?.fill(s),r}mallocAs(e,t){let s=this.malloc(t*et[e]);return s?tt(e,this.buf,s,t):void 0}calloc(e,t=0){let s=this.malloc(e);return s&&this.u8.fill(t,s,s+e),s}malloc(e){if(e<=0)return 0;let t=H(e+C,this.align),s=this.end,r=this.top,n=this._free,o=0;for(;n;){let a=this.blockSize(n),c=n+a>=r;if(c||a>=t)return this.mallocTop(n,o,a,t,c);o=n,n=this.blockNext(n)}return n=r,r=n+t,r<=s?(this.initBlock(n,t,this._used),this._used=n,this.top=r,z(n)):0}mallocTop(e,t,s,r,n){if(n&&e+r>this.end)return 0;if(t?this.unlinkBlock(t,e):this._free=this.blockNext(e),this.setBlockNext(e,this._used),this._used=e,n)this.top=e+this.setBlockSize(e,r);else if(this.doSplit){let o=s-r;o>=this.minSplit&&this.splitBlock(e,r,o)}return z(e)}realloc(e,t){if(t<=0)return 0;let s=be(e),r=0,n=this._used,o=0;for(;n;){if(n===s){[r,o]=this.reallocBlock(n,t);break}n=this.blockNext(n)}return r&&r!==s&&this.u8.copyWithin(z(r),z(s),o),z(r)}reallocBlock(e,t){let s=this.blockSize(e),r=e+s,n=r>=this.top,o=H(t+C,this.align);if(o<=s){if(this.doSplit){let a=s-o;a>=this.minSplit?this.splitBlock(e,o,a):n&&(this.top=e+o)}else n&&(this.top=e+o);return[e,r]}return n&&e+o<this.end?(this.top=e+this.setBlockSize(e,o),[e,r]):(this.free(e),[be(this.malloc(t)),r])}reallocArray(e,t){if(e.buffer!==this.buf)return;let s=this.realloc(e.byteOffset,t*e.BYTES_PER_ELEMENT);return s?new e.constructor(this.buf,s,t):void 0}free(e){let t;if(st(e))t=e;else{if(e.buffer!==this.buf)return!1;t=e.byteOffset}t=be(t);let s=this._used,r=0;for(;s;){if(s===t)return r?this.unlinkBlock(r,s):this._used=this.blockNext(s),this.insert(s),this.doCompact&&this.compact(),!0;r=s,s=this.blockNext(s)}return!1}freeAll(){this._free=0,this._used=0,this.top=this.initialTop()}release(){return delete this.u8,delete this.u32,delete this.state,delete this.buf,!0}get align(){return this.state[ct]}set align(e){this.state[ct]=e}get end(){return this.state[at]}set end(e){this.state[at]=e}get top(){return this.state[ot]}set top(e){this.state[ot]=e}get _free(){return this.state[it]}set _free(e){this.state[it]=e}get _used(){return this.state[nt]}set _used(e){this.state[nt]=e}get doCompact(){return!!(this.state[F]&ge)}set doCompact(e){e?this.state[F]|=1<<ge-1:this.state[F]&=~ge}get doSplit(){return!!(this.state[F]&Se)}set doSplit(e){e?this.state[F]|=1<<Se-1:this.state[F]&=~Se}get minSplit(){return this.state[lt]}set minSplit(e){ye(e>C,`illegal min split threshold: ${e}, require at least ${C+1}`),this.state[lt]=e}blockSize(e){return this.u32[(e>>2)+Ee]}setBlockSize(e,t){return this.u32[(e>>2)+Ee]=t,t}blockNext(e){return this.u32[(e>>2)+_e]}setBlockNext(e,t){this.u32[(e>>2)+_e]=t}initBlock(e,t,s){let r=e>>>2;return this.u32[r+Ee]=t,this.u32[r+_e]=s,e}unlinkBlock(e,t){this.setBlockNext(e,this.blockNext(t))}splitBlock(e,t,s){this.insert(this.initBlock(e+this.setBlockSize(e,t),s,0)),this.doCompact&&this.compact()}initialTop(e=this.align){return H(this.start+ut+C,e)-C}compact(){let e=this._free,t=0,s=0,r,n=!1;for(;e;){for(r=e,s=this.blockNext(e);s&&r+this.blockSize(r)===s;)r=s,s=this.blockNext(s);if(r!==e){let o=r-e+this.blockSize(r);this.setBlockSize(e,o);let a=this.blockNext(r),c=this.blockNext(e);for(;c&&c!==a;){let l=this.blockNext(c);this.setBlockNext(c,0),c=l}this.setBlockNext(e,a),n=!0}e+this.blockSize(e)>=this.top&&(this.top=e,t?this.unlinkBlock(t,e):this._free=this.blockNext(e)),t=e,e=this.blockNext(e)}return n}insert(e){let t=this._free,s=0;for(;t&&!(e<=t);)s=t,t=this.blockNext(t);s?this.setBlockNext(s,e):this._free=e,this.setBlockNext(e,t)}},z=i=>i>0?i+C:0,be=i=>i>0?i-C:0;var Te=8,ft=65536,K=class{#t=[];#e;#s;#f=0;#o=!1;#c;#n;#i;#l;constructor({buf:e,start:t,size:s,wasmMemory:r=null,maxSize:n,growIncrement:o=32*1024*1024,growFn:a=null,onGrowth:c=null}){this.#e=r,this.#s=o,this.#c=a,this.#n=c,this.#i=t+s,this.#l=t+n,this.#u(e,t,s,0)}malloc(e){for(let t=this.#t.length-1;t>=0;t--){let s=this.#t[t],r=s.pool.malloc(e);if(r!==0)return r+s.baseOffset}return 0}free(e){for(let t of this.#t)if(e>=t.start&&e<t.end)return t.pool.free(e-t.baseOffset);return!1}stats(){let e=0,t=0,s=0,r=0,n=0,o=0,a=0;for(let c of this.#t){let l=c.pool.stats();e+=l.free?.count||0,t+=l.free?.size||0,s+=l.used?.count||0,r+=l.used?.size||0,n+=l.available||0,o+=l.total||0,l.top>a&&(a=l.top)}return{free:{count:e,size:t},used:{count:s,size:r},top:a,available:n,total:o}}canGrow(){return this.#i+Te<this.#l}async grow(e=0){if(this.#o||!this.canGrow())return!1;this.#o=!0;try{let t=this.#l-this.#i,s=Math.min(Math.max(this.#s,e),t);if(s<Te)return!1;let r=Math.ceil(s/ft),n=this.#i,o=Math.min(r*ft,this.#l-n),a;if(this.#e){if(this.#e.grow(r)===-1)return!1;a=this.#e.buffer}else if(this.#c){if(!await this.#c(r))return!1;a=new ArrayBuffer(o)}else return!1;let c=this.#e?0:n,l=this.#e?n:0;return this.#u(a,l,o,c),this.#i=n+o,this.#f++,this.#n&&this.#n({poolIndex:this.#t.length-1,newBytes:o,totalCapacity:this.totalCapacity}),!0}finally{this.#o=!1}}get poolCount(){return this.#t.length}get growthCount(){return this.#f}get totalCapacity(){let e=0;for(let t of this.#t)e+=t.end-t.start;return e}get maxCapacity(){return this.#l-this.#t[0].start}#u(e,t,s,r){let n=new X({buf:e,start:t,size:s,align:Te}),o=t+r;this.#t.push({pool:n,start:o,end:o+s,baseOffset:r})}};function ht(i){if(i.byteLength<12)return!1;let e=new Uint8Array(i,0,12),t=String.fromCharCode(e[0],e[1],e[2],e[3]),s=String.fromCharCode(e[8],e[9],e[10],e[11]);return t==="FORM"&&(s==="AIFF"||s==="AIFC")}function es(i){let e=i[0]>>7&1,t=(i[0]&127)<<8|i[1],s=0;for(let n=2;n<10;n++)s=s*256+i[n];if(t===0)return 0;let r=s*Math.pow(2,t-16383-63);return e?-r:r}function Ae(i,e){let t=12;for(;t<i.byteLength-8;){let s=String.fromCharCode(i.getUint8(t),i.getUint8(t+1),i.getUint8(t+2),i.getUint8(t+3)),r=i.getUint32(t+4,!1);if(s===e)return{offset:t+8,size:r};t+=8+r+r%2}return null}function dt(i){let e=new DataView(i),t=String.fromCharCode(e.getUint8(8),e.getUint8(9),e.getUint8(10),e.getUint8(11)),s=Ae(e,"COMM");if(!s)throw new Error("AIFF file missing COMM chunk");let r=e.getUint16(s.offset,!1),n=e.getUint32(s.offset+2,!1),o=e.getUint16(s.offset+6,!1),a=new Uint8Array(i,s.offset+8,10),c=es(a);if(t==="AIFC"&&s.size>=22){let d=String.fromCharCode(e.getUint8(s.offset+18),e.getUint8(s.offset+19),e.getUint8(s.offset+20),e.getUint8(s.offset+21));if(d!=="NONE"&&d!=="sowt")throw new Error(`AIFC compression type '${d}' is not supported. Only uncompressed AIFF/AIFC files are supported.`);if(d==="sowt")return ts(i,r,n,o,c)}let l=Ae(e,"SSND");if(!l)throw new Error("AIFF file missing SSND chunk");let u=e.getUint32(l.offset,!1),f=l.offset+8+u,h=o/8,S=n*r*h;if(f+S>i.byteLength)throw new Error("AIFF file truncated: not enough audio data");let m=44,E=new ArrayBuffer(m+S),p=new DataView(E),y=new Uint8Array(E);pt(p,{numChannels:r,sampleRate:Math.round(c),bitsPerSample:o,dataSize:S});let _=new Uint8Array(i,f,S);if(h===1)for(let d=0;d<S;d++)y[m+d]=_[d]+128;else if(h===2)for(let d=0;d<S;d+=2)y[m+d]=_[d+1],y[m+d+1]=_[d];else if(h===3)for(let d=0;d<S;d+=3)y[m+d]=_[d+2],y[m+d+1]=_[d+1],y[m+d+2]=_[d];else if(h===4)for(let d=0;d<S;d+=4)y[m+d]=_[d+3],y[m+d+1]=_[d+2],y[m+d+2]=_[d+1],y[m+d+3]=_[d];else throw new Error(`Unsupported bit depth: ${o}`);return E}function ts(i,e,t,s,r){let n=new DataView(i),o=Ae(n,"SSND");if(!o)throw new Error("AIFF file missing SSND chunk");let a=n.getUint32(o.offset,!1),c=o.offset+8+a,l=s/8,u=t*e*l;if(c+u>i.byteLength)throw new Error("AIFF file truncated: not enough audio data");let f=44,h=new ArrayBuffer(f+u),S=new DataView(h),m=new Uint8Array(h);pt(S,{numChannels:e,sampleRate:Math.round(r),bitsPerSample:s,dataSize:u});let E=new Uint8Array(i,c,u);if(l===1)for(let p=0;p<u;p++)m[f+p]=E[p]+128;else m.set(E,f);return h}function pt(i,{numChannels:e,sampleRate:t,bitsPerSample:s,dataSize:r}){let n=t*e*(s/8),o=e*(s/8);i.setUint8(0,82),i.setUint8(1,73),i.setUint8(2,70),i.setUint8(3,70),i.setUint32(4,36+r,!0),i.setUint8(8,87),i.setUint8(9,65),i.setUint8(10,86),i.setUint8(11,69),i.setUint8(12,102),i.setUint8(13,109),i.setUint8(14,116),i.setUint8(15,32),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,e,!0),i.setUint32(24,t,!0),i.setUint32(28,n,!0),i.setUint16(32,o,!0),i.setUint16(34,s,!0),i.setUint8(36,100),i.setUint8(37,97),i.setUint8(38,116),i.setUint8(39,97),i.setUint32(40,r,!0)}var Z=class{#t;#e;#s;#f;#o;#c;#n;#i;#l;#u;#d;constructor(e){let{mode:t="sab",audioContext:s,sharedBuffer:r,bufferPoolConfig:n,sampleBaseURL:o,maxBuffers:a=1024,assetLoader:c=null,workletPort:l=null,wasmMemory:u=null,maxBufferMemory:f=null,bufferGrowIncrement:h=32*1024*1024,onBufferPoolGrowth:S=null,growFn:m=null}=e;if(this.#t=t,!s)throw new Error("BufferManager requires audioContext");if(t==="sab"){if(!r||!(r instanceof SharedArrayBuffer))throw new Error("BufferManager requires sharedBuffer (SharedArrayBuffer) in SAB mode");if(!n||typeof n!="object")throw new Error("BufferManager requires bufferPoolConfig (object with start, size, align)");if(!Number.isFinite(n.start)||n.start<0)throw new Error("bufferPoolConfig.start must be a non-negative number");if(!Number.isFinite(n.size)||n.size<=0)throw new Error("bufferPoolConfig.size must be a positive number")}if(t==="postMessage"&&(!n||typeof n!="object"))throw new Error("BufferManager requires bufferPoolConfig in postMessage mode");if(!Number.isInteger(a)||a<=0)throw new Error("maxBuffers must be a positive integer");this.#f=s,this.#o=r,this.#c=u,this.#e=o,this.#s=c,this.#d=l;let E=f||n.maxSize||n.size,p=t==="sab"?r:new ArrayBuffer(n.start+n.size);this.#n=new K({buf:p,start:n.start,size:n.size,wasmMemory:t==="sab"?u:null,maxSize:E,growIncrement:h,growFn:t==="postMessage"?m:null,onGrowth:S}),this.#i=new Map,this.#l=new Map,this.#u=new Map,this.GUARD_BEFORE=3,this.GUARD_AFTER=1,this.MAX_BUFFERS=a;let y=(n.size/(1024*1024)).toFixed(0),_=(n.start/(1024*1024)).toFixed(0)}async#E(e){let t=e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),s=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(s)).map(r=>r.toString(16).padStart(2,"0")).join("")}async#_({source:e,startFrame:t=0,numFrames:s=0,channels:r=null}){let n,o;if(typeof e=="string"){let p=this.#b(e),y=e.split("/").pop();n=await this.#s.fetch(p,{type:"sample",name:y}),o={type:"file",path:e,startFrame:t,numFrames:s,channels:r}}else n=e instanceof ArrayBuffer?e:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),o=null;let a=await this.#m(n),c=Math.max(0,Math.floor(t||0)),l=a.length-c,u=s&&s>0?Math.min(Math.floor(s),l):l;if(u<=0)throw new Error("No audio frames available");let f=this.#a(r,a.numberOfChannels),h=f.length,S=u*h+(this.GUARD_BEFORE+this.GUARD_AFTER)*h,m=new Float32Array(S),E=this.GUARD_BEFORE*h;for(let p=0;p<u;p++)for(let y=0;y<h;y++){let _=a.getChannelData(f[y]);m[E+p*h+y]=_[c+p]}return{interleaved:m,numFrames:u,numChannels:h,sampleRate:a.sampleRate,sourceInfo:o}}async#p(e){let t=await this.#S(e.length);return await this.#C(t,e),t}async#h(e,t,s,r){let n,o=await this.#r(e,t,async()=>{let[c,l]=await Promise.all([this.#E(s.interleaved),this.#p(s.interleaved)]);return n=c,{ptr:l,sizeBytes:s.interleaved.length*4,numFrames:s.numFrames,numChannels:s.numChannels,sampleRate:s.sampleRate,source:r||null}}),a=this.#i.get(e);return a&&(a.hash=n),{...o,hash:n}}async#m(e){return ht(e)&&(e=dt(e)),this.#f.decodeAudioData(e)}setWorkletPort(e){if(this.#t==="postMessage"){if(!e)throw new Error("BufferManager.setWorkletPort() requires a valid port");this.#d=e}}#b(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid audio path: must be a non-empty string");if(e.includes(".."))throw new Error(`Invalid audio path: path cannot contain '..' (got: ${e})`);if(e.includes("%2e")||e.includes("%2E"))throw new Error(`Invalid audio path: path cannot contain URL-encoded characters (got: ${e})`);if(e.includes("\\"))throw new Error(`Invalid audio path: use forward slashes only (got: ${e})`);if(e.includes("://")||e.startsWith("/")||e.startsWith("./"))return e;if(!this.#e)throw new Error(`sampleBaseURL not configured. Please set it in SuperSonic constructor options.
1
+ var B=class i{constructor(e){if(new.target===i)throw new Error("Transport is abstract - use SABTransport or PostMessageTransport");this._config=e,this._disposed=!1}get mode(){return this._config.mode}send(e,t){throw new Error("Abstract method - implement in subclass")}onReply(e){throw new Error("Abstract method - implement in subclass")}onDebug(e){throw new Error("Abstract method - implement in subclass")}onError(e){throw new Error("Abstract method - implement in subclass")}getMetrics(){throw new Error("Abstract method - implement in subclass")}async initialize(){throw new Error("Abstract method - implement in subclass")}createOscChannel(){throw new Error("Abstract method - implement in subclass")}dispose(){this._disposed=!0}get ready(){throw new Error("Abstract method - implement in subclass")}};var me=new Map;function Ke(i){try{return new URL(i,window.location.href).origin!==window.location.origin}catch{return!1}}async function je(i){if(me.has(i))return me.get(i);let e=await fetch(i);if(!e.ok)throw new Error(`Failed to fetch ${i}: ${e.status} ${e.statusText}`);let t=await e.text(),s=new Blob([t],{type:"application/javascript"}),r=URL.createObjectURL(s);return me.set(i,r),r}async function I(i,e={}){let t=i;return Ke(i)&&(t=await je(i)),new Worker(t,e)}async function Qe(i,e){let t=e;Ke(e)&&(t=await je(e)),await i.addModule(t)}function Vt(i,e,t){return(t-1-i+e)%t}function qt({uint8View:i,dataView:e,bufferStart:t,bufferSize:s,head:r,payload:n,sequence:o,messageMagic:a,headerSize:c,sourceId:u=0,headerScratch:l=null,headerScratchView:f=null}){let h=n.length,p=c+h+3&-4,d=s-r;if(p>d){let m=l||new Uint8Array(c),g=f||new DataView(m.buffer);g.setUint32(0,a,!0),g.setUint32(4,p,!0),g.setUint32(8,o,!0),g.setUint32(12,u,!0);let _=t+r,w=t;if(d>=c){i.set(m,_);let C=d-c;for(let E=0;E<C;E++)i[_+c+E]=n[E];for(let E=C;E<h;E++)i[w+E-C]=n[E]}else{for(let E=0;E<d;E++)i[_+E]=m[E];for(let E=d;E<c;E++)i[w+E-d]=m[E];let C=c-d;i.set(n,w+C)}}else{let m=t+r;e.setUint32(m,a,!0),e.setUint32(m+4,p,!0),e.setUint32(m+8,o,!0),e.setUint32(m+12,u,!0),i.set(n,m+c)}return(r+p)%s}function Je({uint8View:i,dataView:e,bufferStart:t,bufferSize:s,head:r,tail:n,messageMagic:o,paddingMagic:a,headerSize:c,maxMessages:u=1/0,onMessage:l,onCorruption:f}){let h=n,y=0,p=d=>{let m=d;if(m+4<=s)return e.getUint32(t+m,!0);let g=0;for(let _=0;_<4;_++)g|=i[t+(m+_)%s]<<_*8;return g};for(;h!==r&&y<u;){let d=s-h,m;if(d>=4?m=e.getUint32(t+h,!0):m=p(h),m===a){h=0;continue}if(m!==o){f&&f(h),h=(h+1)%s;continue}let g=p((h+4)%s),_=p((h+8)%s),w=p((h+12)%s);if(g<c||g>s){f&&f(h),h=(h+1)%s;continue}let C=g-c,E=t+(h+c)%s;l(E,C,_,w),h=(h+g)%s,y++}return{newTail:h,messagesRead:y}}function Xt(i,e,t=0,s=!1){for(let r=0;r<=t;r++)if(Atomics.compareExchange(i,e,0,1)===0)return!0;if(s){for(let n=0;n<100;n++)if(Atomics.wait(i,e,1,100),Atomics.compareExchange(i,e,0,1)===0)return!0;return console.error("[RingBuffer] Lock acquisition timeout after 10s - possible deadlock"),!1}return!1}function Zt(i,e){Atomics.store(i,e,0),Atomics.notify(i,e,1)}function et({atomicView:i,dataView:e,uint8View:t,bufferConstants:s,ringBufferBase:r,controlIndices:n,oscMessage:o,sourceId:a=0,maxSpins:c=0,useWait:u=!1,headerScratch:l=null,headerScratchView:f=null}){let h=o.length,y=s.MESSAGE_HEADER_SIZE+h;if(y>s.IN_BUFFER_SIZE-s.MESSAGE_HEADER_SIZE||!Xt(i,n.IN_WRITE_LOCK,c,u))return!1;try{let p=Atomics.load(i,n.IN_HEAD),d=Atomics.load(i,n.IN_TAIL),m=y+3&-4;if(Vt(p,d,s.IN_BUFFER_SIZE)<m)return!1;let _=Atomics.add(i,n.IN_SEQUENCE,1),w=qt({uint8View:t,dataView:e,bufferStart:r+s.IN_BUFFER_START,bufferSize:s.IN_BUFFER_SIZE,head:p,payload:o,sequence:_,messageMagic:s.MESSAGE_MAGIC,headerSize:s.MESSAGE_HEADER_SIZE,sourceId:a,headerScratch:l,headerScratchView:f});return Atomics.load(i,n.IN_HEAD),Atomics.store(i,n.IN_HEAD,w),Atomics.notify(i,n.IN_HEAD,1),!0}finally{Zt(i,n.IN_WRITE_LOCK)}}function st(i,e,t,s){let r=i+e+s*t;return{controlBase:r,headIndex:(r+0)/4,tailIndex:(r+4)/4,activeIndex:(r+8)/4,dropsIndex:(r+12)/4}}function X(i,e){let t=i+e;return{IN_HEAD:(t+0)/4,IN_TAIL:(t+4)/4,IN_SEQUENCE:(t+24)/4,IN_WRITE_LOCK:(t+40)/4,IN_LOG_TAIL:(t+44)/4}}function rt(i,e){let t=i+e;return{IN_HEAD:(t+0)/4,IN_TAIL:(t+4)/4,OUT_HEAD:(t+8)/4,OUT_TAIL:(t+12)/4,DEBUG_HEAD:(t+16)/4,DEBUG_TAIL:(t+20)/4,IN_SEQUENCE:(t+24)/4,OUT_SEQUENCE:(t+28)/4,DEBUG_SEQUENCE:(t+32)/4,STATUS_FLAGS:(t+36)/4,IN_WRITE_LOCK:(t+40)/4,IN_LOG_TAIL:(t+44)/4}}function Kt(i){return i.length>=8&&i[0]===35&&i[1]===98&&i[2]===117&&i[3]===110&&i[4]===100&&i[5]===108&&i[6]===101&&i[7]===0}var ye=.5;function Se(i){if(i.length<16)return null;let e=new DataView(i.buffer,i.byteOffset,i.byteLength);return{ntpSeconds:e.getUint32(8,!1),ntpFraction:e.getUint32(12,!1)}}function M(){return(performance.timeOrigin+performance.now())/1e3+2208988800}function it(i,e={}){let{getCurrentNTP:t=M,bypassLookaheadS:s=ye}=e;if(!Kt(i))return"nonBundle";let r=Se(i);if(!r)return"nonBundle";let{ntpSeconds:n,ntpFraction:o}=r;if(n===0&&o<=1)return"immediate";let a=t();if(a===null||a===0)return"immediate";let u=n+o/4294967296-a,l=128/48e3;return u<-l?"late":u<s?"nearFuture":"farFuture"}function Z(i){return i!=="farFuture"}var jt={nonBundle:38,immediate:39,nearFuture:40,late:41},O=class i{#s;#e;#r;#l;#o;#a;#i;#n;#c;#f;#m;#S;#E;#d;#g;#p;#_;#T;#t;#u;#h=-1;#y;#b;#A;#M;#w;#B=[];#R;#I;#O={messagesSent:0,bytesSent:0,nonBundle:0,immediate:0,nearFuture:0,late:0,bypassed:0};constructor(e,t){if(this.#s=e,this.#o=t.preschedulerPort||null,this.#i=t.bypassLookaheadS??ye,this.#n=t.sourceId??0,this.#c=t.blocking??this.#n!==0,this.#f=t.getCurrentNTP??M,this.#g=1e3,e==="postMessage")this.#e=t.port;else{if(this.#r={sharedBuffer:t.sharedBuffer,ringBufferBase:t.ringBufferBase,bufferConstants:t.bufferConstants,controlIndices:t.controlIndices},this.#D(),this.#b=t.replyNotifier||null,t.sharedBuffer&&t.bufferConstants){let s=t.ringBufferBase+t.bufferConstants.METRICS_START;this.#a=new Int32Array(t.sharedBuffer,s,t.bufferConstants.METRICS_SIZE/4)}if(t.sharedBuffer&&t.bufferConstants?.NODE_ID_COUNTER_START!==void 0){let s=t.ringBufferBase+t.bufferConstants.NODE_ID_COUNTER_START;this.#m=new Int32Array(t.sharedBuffer,s,1),this.#L()}}t.nodeIdSource&&(this.#p=t.nodeIdSource,this.#L()),t.nodeIdRange&&(this.#S=t.nodeIdRange.from,this.#E=t.nodeIdRange.to,this.#d=t.nodeIdRange.from),t.replyWorkletPort&&(this.#R=t.replyWorkletPort),t.nodeIdPort&&(this.#_=t.nodeIdPort,this.#_.onmessage=s=>{s.data.type==="nodeIdRange"&&(this.#T={from:s.data.from,to:s.data.to})},this.#k())}#D(){let e=this.#r.sharedBuffer,t=this.#r.bufferConstants.MESSAGE_HEADER_SIZE||16,s=new Uint8Array(t);this.#l={atomicView:new Int32Array(e),dataView:new DataView(e),uint8View:new Uint8Array(e),headerScratch:s,headerScratchView:new DataView(s.buffer)}}classify(e){return it(e,{getCurrentNTP:this.#f,bypassLookaheadS:this.#i})}#P(e,t=null){if(this.#s==="sab"&&this.#a){if(Atomics.add(this.#a,24,1),Atomics.add(this.#a,25,e),t){let s=jt[t];s!==void 0&&(Atomics.add(this.#a,s,1),Atomics.add(this.#a,22,1))}}else this.#O.messagesSent++,this.#O.bytesSent+=e,t&&t in this.#O&&(this.#O[t]++,this.#O.bypassed++)}getAndResetMetrics(){let e={...this.#O};return this.#O={messagesSent:0,bytesSent:0,nonBundle:0,immediate:0,nearFuture:0,late:0,bypassed:0},e}getMetrics(){return this.#s==="sab"&&this.#a?{messagesSent:Atomics.load(this.#a,24),bytesSent:Atomics.load(this.#a,25),nonBundle:Atomics.load(this.#a,38),immediate:Atomics.load(this.#a,39),nearFuture:Atomics.load(this.#a,40),late:Atomics.load(this.#a,41),bypassed:Atomics.load(this.#a,22)}:{...this.#O}}#U(e,t=null,s=!0){if(this.#s==="postMessage")return this.#e?(this.#e.postMessage({type:"osc",oscData:e,bypassCategory:t,sourceId:this.#n}),!0):!1;{let r=this.#c,n=et({atomicView:this.#l.atomicView,dataView:this.#l.dataView,uint8View:this.#l.uint8View,bufferConstants:this.#r.bufferConstants,ringBufferBase:this.#r.ringBufferBase,controlIndices:this.#r.controlIndices,oscMessage:e,sourceId:this.#n,maxSpins:r?10:0,useWait:r,headerScratch:this.#l.headerScratch,headerScratchView:this.#l.headerScratchView});return!n&&!r&&s&&this.#o?(this.#a&&Atomics.add(this.#a,45,1),this.#o.postMessage({type:"directDispatch",oscData:e,sourceId:this.#n}),!0):n}}#x(e){return this.#o?(this.#o.postMessage({type:"osc",oscData:e,sourceId:this.#n}),!0):(console.error("[OscChannel] No prescheduler port, sending direct"),this.#U(e))}send(e){let t=this.classify(e);if(Z(t)){let s=this.#U(e,t);return s&&this.#P(e.length,t),s}else{let s=this.#x(e);return s&&this.#P(e.length,null),s}}sendDirect(e){return this.#U(e)}sendToPrescheduler(e){return this.#x(e)}nextNodeId(){if(this.#m)return Atomics.add(this.#m,0,1);this.#d>=this.#E&&this.#L();let e=this.#d++;return this.#_&&!this.#T&&this.#E-this.#d<=this.#g>>>1&&this.#k(),e}#L(){if(this.#p){let e=this.#p(this.#g);this.#S=e.from,this.#E=e.to,this.#d=e.from}else if(this.#T)this.#S=this.#T.from,this.#E=this.#T.to,this.#d=this.#T.from,this.#T=null,this.#k();else if(this.#_)throw new Error("[OscChannel] Node ID range exhausted before async refill arrived. Yield to the event loop between large batches of nextNodeId() calls.")}#k(){this.#_&&this.#_.postMessage({type:"requestNodeIdRange"})}set getCurrentNTP(e){this.#f=e}get mode(){return this.#s}get replyDrops(){if(!(this.#s!=="sab"||this.#h<0))return Atomics.load(this.#l.atomicView,this.#I.dropsIndex)}get transferable(){let e={mode:this.#s,preschedulerPort:this.#o,bypassLookaheadS:this.#i,sourceId:this.#n,blocking:this.#c};if(this.#s==="postMessage"){let t=this.#g*10,s,r;if(this.#p){let n=this.#p(t);s={from:n.from,to:n.to};let o=new MessageChannel,a=this.#p,c=this.#g;o.port1.onmessage=u=>{if(u.data.type==="requestNodeIdRange"){let l=a(c);o.port1.postMessage({type:"nodeIdRange",from:l.from,to:l.to})}},r=o.port2,this.#t=r}return{...e,port:this.#e,nodeIdRange:s,nodeIdPort:r}}else return{...e,sharedBuffer:this.#r.sharedBuffer,ringBufferBase:this.#r.ringBufferBase,bufferConstants:this.#r.bufferConstants,controlIndices:this.#r.controlIndices}}get transferList(){let e=[];return this.#s==="postMessage"&&this.#e&&e.push(this.#e),this.#o&&e.push(this.#o),this.#t&&(e.push(this.#t),this.#t=null),e}activateReplies(){this.#s==="sab"?this.#H():this.#N()}deactivateReplies(){this.#s==="sab"?this.#F():this.#$()}setReplyHandler(e){this.#u=e,this.activateReplies(),this.#z()}clearReplyHandler(){this.#u=null,this.deactivateReplies()}pollReplies(e){let t=e||this.#u;return t?this.#s==="sab"?this.#h<0?0:this.#Y(t):this.#w?this.#v(t):0:0}#H(){if(this.#h>=0)return;let e=this.#r.bufferConstants;if(!e.REPLY_CHANNEL_COUNT)throw new Error("WASM does not support reply channels");let t=this.#l.atomicView;for(let s=0;s<e.REPLY_CHANNEL_COUNT;s++){let r=st(this.#r.ringBufferBase,e.REPLY_CHANNELS_CONTROL_START,e.REPLY_CHANNEL_CONTROL_SIZE,s);if(Atomics.store(t,r.headIndex,0),Atomics.store(t,r.tailIndex,0),Atomics.store(t,r.dropsIndex,0),Atomics.compareExchange(t,r.activeIndex,0,1)===0){this.#I=r,this.#h=s;return}}throw new Error("All "+e.REPLY_CHANNEL_COUNT+" reply channel slots are in use \u2014 cannot register for replies")}#z(){this.#A||this.#M||this.#y||typeof AudioWorkletGlobalScope<"u"||this.#s==="sab"&&(this.#b?(this.#A=()=>this.pollReplies(),this.#b.subscribe(this.#A)):typeof Atomics<"u"&&typeof Atomics.waitAsync=="function"?this.#G():this.#y=setInterval(()=>this.pollReplies(),5))}#F(){this.#h<0||(Atomics.store(this.#l.atomicView,this.#I.activeIndex,0),this.#y&&(clearInterval(this.#y),this.#y=null),this.#A&&this.#b&&(this.#b.unsubscribe(this.#A),this.#A=null),this.#M=!1,this.#h=-1,this.#I=null)}#G(){let e=this.#l.atomicView,{headIndex:t,tailIndex:s}=this.#I;this.#M=!0;let r=()=>{if(!this.#M)return;let n=Atomics.load(e,t),o=Atomics.load(e,s);if(n!==o&&this.pollReplies(),!this.#M)return;let a=Atomics.load(e,t),c=Atomics.waitAsync(e,t,a);c.async?c.value.then(()=>{this.#M&&(this.pollReplies(),r())}):(this.pollReplies(),setTimeout(r,0))};r()}#Y(e){let t=this.#l.atomicView,{headIndex:s,tailIndex:r}=this.#I,n=Atomics.load(t,s),o=Atomics.load(t,r);if(n===o)return 0;let a=this.#r.bufferConstants,c=this.#r.ringBufferBase+a.REPLY_CHANNELS_BUFFER_START+this.#h*a.REPLY_CHANNEL_BUFFER_SIZE,u=a.REPLY_CHANNEL_BUFFER_SIZE,l=this.#l.uint8View,{newTail:f,messagesRead:h}=Je({uint8View:l,dataView:this.#l.dataView,bufferStart:c,bufferSize:u,head:n,tail:o,messageMagic:a.MESSAGE_MAGIC,paddingMagic:a.PADDING_MAGIC,headerSize:a.MESSAGE_HEADER_SIZE||16,maxMessages:64,onMessage:(y,p,d)=>{e(l,y,p,d)}});return h>0&&Atomics.store(t,r,f),h}#N(){if(this.#w)return;let e=this.#R||this.#e;if(!e)throw new Error("No port available for reply registration");let t=new MessageChannel;e.postMessage({type:"addReplyPort",sourceId:this.#n},[t.port1]),this.#w=t.port2;let s=typeof AudioWorkletGlobalScope<"u";this.#w.onmessage=r=>{if(r.data.type!=="oscReplies"||!r.data.count)return;let{count:n,buffer:o,messages:a}=r.data;if(!a||!o)return;let c=new Uint8Array(o);if(s)for(let u=0;u<n;u++){let l=a[u];if(!l)continue;let f=c.slice(l.offset,l.offset+l.length);this.#B.push({oscData:f,sequence:l.sequence})}else{let u=this.#u;if(!u)return;for(let l=0;l<n;l++){let f=a[l];if(!f)continue;let h=c.slice(f.offset,f.offset+f.length);u(h,f.sequence)}}}}#$(){if(this.#w){let e=this.#R||this.#e;e&&e.postMessage({type:"removeReplyPort",sourceId:this.#n}),this.#w.close(),this.#w=null}this.#B.length=0}#v(e){let t=this.#B,s=t.length;if(s===0)return 0;for(let r=0;r<s;r++)e(t[r].oscData,t[r].sequence);return t.length=0,s}close(){this.clearReplyHandler(),this.#s==="postMessage"&&this.#e&&(this.#e.close(),this.#e=null),this.#o&&(this.#o.close(),this.#o=null)}static createPostMessage(e){return e instanceof MessagePort?new i("postMessage",{port:e}):new i("postMessage",e)}static createSAB(e){let t=e.controlIndices;return t||(t=X(e.ringBufferBase,e.bufferConstants.CONTROL_START)),new i("sab",{sharedBuffer:e.sharedBuffer,ringBufferBase:e.ringBufferBase,bufferConstants:e.bufferConstants,controlIndices:t,preschedulerPort:e.preschedulerPort,bypassLookaheadS:e.bypassLookaheadS,sourceId:e.sourceId,blocking:e.blocking,replyNotifier:e.replyNotifier})}static fromTransferable(e){return e.mode==="postMessage"?new i("postMessage",{port:e.port,preschedulerPort:e.preschedulerPort,bypassLookaheadS:e.bypassLookaheadS,sourceId:e.sourceId,blocking:e.blocking,nodeIdRange:e.nodeIdRange,nodeIdPort:e.nodeIdPort}):new i("sab",{sharedBuffer:e.sharedBuffer,ringBufferBase:e.ringBufferBase,bufferConstants:e.bufferConstants,controlIndices:e.controlIndices,preschedulerPort:e.preschedulerPort,bypassLookaheadS:e.bypassLookaheadS,sourceId:e.sourceId,blocking:e.blocking})}};var z=class extends B{#s;#e;#r;#l;#o;#a;#i;#n;#c;#f;#m;#S;#E;#d=[];#g;#p;#_;#T=1;#t=!1;#u;#h=0;#y=0;#b=0;#A=null;constructor(e){if(super({...e,mode:"sab"}),this.#s=e.sharedBuffer,this.#e=e.ringBufferBase,this.#r=e.bufferConstants,this.#S=e.workerBaseURL,this.#u=e.preschedulerCapacity||65536,!(this.#s instanceof SharedArrayBuffer))throw new Error("SABTransport requires a SharedArrayBuffer");this.#M()}async initialize(){if(this.#t)return;let[e,t,s,r]=await Promise.all([I(this.#S+"osc_out_prescheduler_worker.js",{type:"module"}),I(this.#S+"osc_in_worker.js",{type:"module"}),I(this.#S+"debug_worker.js",{type:"module"}),I(this.#S+"osc_out_log_sab_worker.js",{type:"module"})]);this.#n=e,this.#c=t,this.#f=s,this.#m=r,this.#B(),await Promise.all([this.#w(this.#n,"OSC OUT",{maxPendingMessages:this.#u,bypassLookaheadS:this._config.bypassLookaheadS}),this.#w(this.#c,"OSC IN"),this.#w(this.#f,"DEBUG"),this.#w(this.#m,"OSC OUT LOG")]),this.#c.postMessage({type:"start"}),this.#f.postMessage({type:"start"}),this.#m.postMessage({type:"start"}),this.#t=!0}send(e,t){return!this.#t||this._disposed?!1:(this.#n.postMessage({type:"send",oscData:e,sessionId:0,runTag:"",audioTimeS:null,currentTimeS:null}),this.#h++,this.#b+=e.length,!0)}sendWithOptions(e,t={}){if(!this.#t||this._disposed)return!1;let{sessionId:s=0,runTag:r="",audioTimeS:n=null,currentTimeS:o=null}=t;return this.#n.postMessage({type:"send",oscData:e,sessionId:s,runTag:r,audioTimeS:n,currentTimeS:o}),this.#h++,this.#b+=e.length,!0}sendImmediate(e){return!this.#t||this._disposed?!1:(this.#n.postMessage({type:"sendImmediate",oscData:e}),this.#h++,this.#b+=e.length,!0)}createOscChannel(e={}){if(!this.#t)throw new Error("Transport not initialized");let t=e.sourceId??this.#T++,s=new MessageChannel;this.#n.postMessage({type:"addOscSource"},[s.port1]);let r=this.#d;return O.createSAB({sharedBuffer:this.#s,ringBufferBase:this.#e,bufferConstants:this.#r,controlIndices:this.#i,preschedulerPort:s.port2,bypassLookaheadS:this._config.bypassLookaheadS,sourceId:t,blocking:e.blocking,replyNotifier:{subscribe(n){r.push(n)},unsubscribe(n){let o=r.indexOf(n);o>=0&&r.splice(o,1)}}})}cancelSessionTag(e,t){this.#t&&this.#n.postMessage({type:"cancelSessionTag",sessionId:e,runTag:t})}cancelSession(e){this.#t&&this.#n.postMessage({type:"cancelSession",sessionId:e})}cancelTag(e){this.#t&&this.#n.postMessage({type:"cancelTag",runTag:e})}cancelAll(){this.#t&&this.#n.postMessage({type:"cancelAll"})}cancelAllWithAck(){return this.#t?new Promise(e=>{let t=s=>{s.data.type==="cancelAllAck"&&(this.#n.removeEventListener("message",t),e())};this.#n.addEventListener("message",t),this.#n.postMessage({type:"cancelAll",ack:!0})}):Promise.resolve()}onReply(e){this.#E=e}onDebug(e){this.#g=e}onError(e){this.#p=e}onOscLog(e){this.#_=e}handleOscLog(e){this.#_&&this.#_(e)}getMetrics(){return{oscOutMessagesSent:this.#h,oscOutMessagesDropped:this.#y,oscOutBytesSent:this.#b}}get ready(){return this.#t&&!this._disposed}dispose(){this._disposed||(this.#n&&(this.#n.postMessage({type:"stop"}),this.#n.terminate(),this.#n=null),this.#c&&(this.#c.postMessage({type:"stop"}),this.#c.terminate(),this.#c=null),this.#f&&(this.#f.postMessage({type:"stop"}),this.#f.terminate(),this.#f=null),this.#m&&(this.#m.postMessage({type:"stop"}),this.#m.terminate(),this.#m=null),this.#t=!1,super.dispose())}#M(){this.#l=new Int32Array(this.#s),this.#o=new DataView(this.#s),this.#a=new Uint8Array(this.#s),this.#i=X(this.#e,this.#r.CONTROL_START)}#w(e,t,s={}){return new Promise((r,n)=>{let o=setTimeout(()=>{n(new Error(`${t} worker initialization timeout`))},5e3),a=c=>{c.data.type==="initialized"&&(clearTimeout(o),e.removeEventListener("message",a),r())};e.addEventListener("message",a),e.postMessage({type:"init",sharedBuffer:this.#s,ringBufferBase:this.#e,bufferConstants:this.#r,...s})})}#B(){this.#c.onmessage=e=>{let t=e.data;if(t.type==="messages"){this.#E&&t.messages.forEach(s=>{s.oscData&&this.#E(s.oscData,s.sequence,s.timestamp)});for(let s=0;s<this.#d.length;s++)this.#d[s]()}else t.type==="error"&&(console.error("[SABTransport] OSC IN error:",t.error),this.#p&&this.#p(t.error,"oscIn"))},this.#f.onmessage=e=>{let t=e.data;t.type==="debug"&&this.#g?t.messages.forEach(s=>{this.#g(s)}):t.type==="error"&&(console.error("[SABTransport] DEBUG error:",t.error),this.#p&&this.#p(t.error,"debug"))},this.#n.onmessage=e=>{let t=e.data;t.type==="preschedulerMetrics"?this.#A=t.metrics:t.type==="error"&&(console.error("[SABTransport] OSC OUT error:",t.error),this.#y++,this.#p&&this.#p(t.error,"oscOut"))},this.#m.onmessage=e=>{let t=e.data;t.type==="oscLog"&&this.#_?this.#_(t.entries):t.type==="error"&&(console.error("[SABTransport] OSC OUT LOG error:",t.error),this.#p&&this.#p(t.error,"oscOutLog"))}}getPreschedulerMetrics(){return this.#A}};var G=class extends B{#s;#e;#r;#l;#o;#a;#i;#n=1;#c=null;#f=!1;#m;#S;#E=null;#d=0;#g=0;#p=0;#_=0;#T=0;#t=-1;#u=0;#h=0;#y;#b;constructor(e){super({...e,mode:"postMessage"}),this.#r=e.workerBaseURL,this.#m=e.preschedulerCapacity||65536,this.#S=e.snapshotIntervalMs,this.#y=e.getAudioContextTime,this.#b=e.getNTPStartTime}async initialize(e){if(this.#f)return;if(!e)throw new Error("PostMessageTransport requires workletPort");this.#s=e,this.#s.onmessage=s=>{this.#M(s.data)};let t=new MessageChannel;this.#s.postMessage({type:"addOscPort"},[t.port1]),this.#e=await I(this.#r+"osc_out_prescheduler_worker.js",{type:"module"}),this.#e.onmessage=s=>{this.#w(s.data)},await this.#A(t.port2),this.#f=!0}setBufferConstants(e){this.#E=e}send(e,t){return!this.#f||this._disposed?!1:(this.#e.postMessage({type:"send",oscData:e,sessionId:0,runTag:"",audioTimeS:null,currentTimeS:null}),this.#d++,this.#p+=e.length,!0)}sendWithOptions(e,t={}){if(!this.#f||this._disposed)return!1;let{sessionId:s=0,runTag:r="",audioTimeS:n=null,currentTimeS:o=null}=t;return this.#e.postMessage({type:"send",oscData:e,sessionId:s,runTag:r,audioTimeS:n,currentTimeS:o}),this.#d++,this.#p+=e.length,!0}sendImmediate(e,t){return!this.#f||this._disposed?!1:(this.#s.postMessage({type:"osc",oscData:e,bypassCategory:t}),this.#d++,this.#p+=e.length,!0)}createOscChannel(e={}){if(!this.#f)throw new Error("Transport not initialized");let t=e.sourceId??this.#n++,s=new MessageChannel;this.#s.postMessage({type:"addOscPort",sourceId:t},[s.port1]);let r=new MessageChannel;return this.#e.postMessage({type:"addOscSource"},[r.port1]),O.createPostMessage({port:s.port2,preschedulerPort:r.port2,bypassLookaheadS:this._config.bypassLookaheadS,sourceId:t,blocking:e.blocking,nodeIdSource:this._config.nodeIdSource,replyWorkletPort:this.#s})}cancelSessionTag(e,t){this.#f&&this.#e.postMessage({type:"cancelSessionTag",sessionId:e,runTag:t})}cancelSession(e){this.#f&&this.#e.postMessage({type:"cancelSession",sessionId:e})}cancelTag(e){this.#f&&this.#e.postMessage({type:"cancelTag",runTag:e})}cancelAll(){this.#f&&this.#e.postMessage({type:"cancelAll"})}cancelAllWithAck(){return this.#f?new Promise(e=>{let t=s=>{s.data.type==="cancelAllAck"&&(this.#e.removeEventListener("message",t),e())};this.#e.addEventListener("message",t),this.#e.postMessage({type:"cancelAll",ack:!0})}):Promise.resolve()}onReply(e){this.#l=e}onDebug(e){this.#o=e}onError(e){this.#a=e}onOscLog(e){this.#i=e}handleDebugRaw(e){if(e.messages&&e.count>0&&e.buffer){let t=new TextDecoder("utf-8"),s=new Uint8Array(e.buffer);for(let r=0;r<e.count;r++){let n=e.messages[r];try{let o=s.subarray(n.offset,n.offset+n.length),a=t.decode(o);a.endsWith(`
2
+ `)&&(a=a.slice(0,-1)),this.#u++,this.#h+=n.length,this.#o&&this.#o({text:a,timestamp:performance.now(),sequence:n.sequence})}catch(o){console.error("[PostMessageTransport] Failed to decode debug message:",o)}}}}getPreschedulerMetrics(){return this.#c}getMetrics(){return{oscInMessagesReceived:this.#_,oscInBytesReceived:this.#T,oscInMessagesDropped:this.#g,debugMessagesReceived:this.#u,debugBytesReceived:this.#h}}get ready(){return this.#f&&!this._disposed}dispose(){this._disposed||(this.#e&&(this.#e.postMessage({type:"stop"}),this.#e.terminate(),this.#e=null),this.#s=null,this.#f=!1,super.dispose())}#A(e){return new Promise((t,s)=>{let r=setTimeout(()=>{s(new Error("Prescheduler worker initialization timeout"))},5e3),n=o=>{o.data.type==="initialized"&&(clearTimeout(r),this.#e.removeEventListener("message",n),t())};this.#e.addEventListener("message",n),this.#e.postMessage({type:"init",mode:"postMessage",maxPendingMessages:this.#m,snapshotIntervalMs:this.#S,bypassLookaheadS:this._config.bypassLookaheadS,workletPort:e},[e])})}#M(e){switch(e.type){case"oscReplies":if(e.messages&&e.count>0&&e.buffer){let t=new Uint8Array(e.buffer);for(let s=0;s<e.count;s++){let r=e.messages[s],n=t.subarray(r.offset,r.offset+r.length);if(r.sequence!==void 0&&this.#t>=0){let o=this.#t+1&4294967295;if(r.sequence!==o){let a=r.sequence-o+4294967296&4294967295;a<1e3&&(this.#g+=a)}}r.sequence!==void 0&&(this.#t=r.sequence),this.#_++,this.#T+=r.length,this.#l&&this.#l(n,r.sequence,M())}}break;case"metrics":break;case"bufferLoaded":break;case"debugRawBatch":this.handleDebugRaw(e);break;case"oscLog":if(this.#i&&e.count>0&&e.buffer&&e.entries){let t=new Uint8Array(e.buffer),s=[];for(let r=0;r<e.count;r++){let n=e.entries[r],o=t.subarray(n.offset,n.offset+n.length);s.push({oscData:o,sourceId:n.sourceId,sequence:n.sequence,timestamp:M(),truncated:n.length<n.originalLength,originalLength:n.originalLength})}this.#i(s)}break;case"error":console.error("[PostMessageTransport] Worklet error:",e.error),this.#g++,this.#a&&this.#a(e.error,"worklet");break;case"debug":break}}#w(e){switch(e.type){case"preschedulerMetrics":this.#c=e.metrics;break;case"error":console.error("[PostMessageTransport] Prescheduler error:",e.error),this.#g++,this.#a&&this.#a(e.error,"oscOut");break}}};function nt(i,e){if(i==="sab")return new z(e);if(i==="postMessage")return new G(e);throw new Error(`Unknown transport mode: ${i}. Use 'sab' or 'postMessage'`)}var Qt={5120:"i8",5121:"u8",5122:"i16",5123:"u16",5124:"i32",5125:"u32",5126:"f32"};var ot={u8:1,u8c:1,i8:1,u16:2,i16:2,u32:4,i32:4,i64:8,u64:8,f32:4,f64:8};var Jt={f32:Float32Array,f64:Float64Array},es={i8:Int8Array,i16:Int16Array,i32:Int32Array},ts={u8:Uint8Array,u8c:Uint8ClampedArray,u16:Uint16Array,u32:Uint32Array},ss={i64:BigInt64Array,u64:BigUint64Array},rs={...Jt,...es,...ts},is=i=>{let e=Qt[i];return e!==void 0?e:i};function at(i,...e){let t=ss[i];return new(t||rs[is(i)])(...e)}var Y=(i,e)=>(e--,i+e&~e);var ct=i=>typeof i=="number";var K=(i,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(i(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var ns=K(()=>"Assertion failed"),Ee=(typeof process<"u"&&process.env!==void 0?process.env.UMBRELLA_ASSERTS:!import.meta.env||import.meta.env.MODE!=="production"||import.meta.env.UMBRELLA_ASSERTS||import.meta.env.VITE_UMBRELLA_ASSERTS)?(i,e)=>{if(typeof i=="function"&&!i()||!i)throw new ns(typeof e=="function"?e():e)}:()=>{};var os=K(()=>"illegal argument(s)"),lt=i=>{throw new os(i)};var ut=0,ft=1,ht=2,dt=3,pt=4,v=5,mt=6,_e=1,be=2,yt=7*4,Ae=0,Te=1,R=2*4,j=class{buf;start;u8;u32;state;constructor(e={}){if(this.buf=e.buf?e.buf:new ArrayBuffer(e.size||4096),this.start=e.start!=null?Y(Math.max(e.start,0),4):0,this.u8=new Uint8Array(this.buf),this.u32=new Uint32Array(this.buf),this.state=new Uint32Array(this.buf,this.start,yt/4),!e.skipInitialization){let t=e.align||8;Ee(t>=8,`invalid alignment: ${t}, must be a pow2 and >= 8`);let s=this.initialTop(t),r=e.end!=null?Math.min(e.end,this.buf.byteLength):this.buf.byteLength;s>=r&&lt(`insufficient address range (0x${this.start.toString(16)} - 0x${r.toString(16)})`),this.align=t,this.doCompact=e.compact!==!1,this.doSplit=e.split!==!1,this.minSplit=e.minSplit||16,this.end=r,this.top=s,this._free=0,this._used=0}}stats(){let e=s=>{let r=0,n=0;for(;s;)r++,n+=this.blockSize(s),s=this.blockNext(s);return{count:r,size:n}},t=e(this._free);return{free:t,used:e(this._used),top:this.top,available:this.end-this.top+t.size,total:this.buf.byteLength}}callocAs(e,t,s=0){let r=this.mallocAs(e,t);return r?.fill(s),r}mallocAs(e,t){let s=this.malloc(t*ot[e]);return s?at(e,this.buf,s,t):void 0}calloc(e,t=0){let s=this.malloc(e);return s&&this.u8.fill(t,s,s+e),s}malloc(e){if(e<=0)return 0;let t=Y(e+R,this.align),s=this.end,r=this.top,n=this._free,o=0;for(;n;){let a=this.blockSize(n),c=n+a>=r;if(c||a>=t)return this.mallocTop(n,o,a,t,c);o=n,n=this.blockNext(n)}return n=r,r=n+t,r<=s?(this.initBlock(n,t,this._used),this._used=n,this.top=r,$(n)):0}mallocTop(e,t,s,r,n){if(n&&e+r>this.end)return 0;if(t?this.unlinkBlock(t,e):this._free=this.blockNext(e),this.setBlockNext(e,this._used),this._used=e,n)this.top=e+this.setBlockSize(e,r);else if(this.doSplit){let o=s-r;o>=this.minSplit&&this.splitBlock(e,r,o)}return $(e)}realloc(e,t){if(t<=0)return 0;let s=we(e),r=0,n=this._used,o=0;for(;n;){if(n===s){[r,o]=this.reallocBlock(n,t);break}n=this.blockNext(n)}return r&&r!==s&&this.u8.copyWithin($(r),$(s),o),$(r)}reallocBlock(e,t){let s=this.blockSize(e),r=e+s,n=r>=this.top,o=Y(t+R,this.align);if(o<=s){if(this.doSplit){let a=s-o;a>=this.minSplit?this.splitBlock(e,o,a):n&&(this.top=e+o)}else n&&(this.top=e+o);return[e,r]}return n&&e+o<this.end?(this.top=e+this.setBlockSize(e,o),[e,r]):(this.free(e),[we(this.malloc(t)),r])}reallocArray(e,t){if(e.buffer!==this.buf)return;let s=this.realloc(e.byteOffset,t*e.BYTES_PER_ELEMENT);return s?new e.constructor(this.buf,s,t):void 0}free(e){let t;if(ct(e))t=e;else{if(e.buffer!==this.buf)return!1;t=e.byteOffset}t=we(t);let s=this._used,r=0;for(;s;){if(s===t)return r?this.unlinkBlock(r,s):this._used=this.blockNext(s),this.insert(s),this.doCompact&&this.compact(),!0;r=s,s=this.blockNext(s)}return!1}freeAll(){this._free=0,this._used=0,this.top=this.initialTop()}release(){return delete this.u8,delete this.u32,delete this.state,delete this.buf,!0}get align(){return this.state[pt]}set align(e){this.state[pt]=e}get end(){return this.state[dt]}set end(e){this.state[dt]=e}get top(){return this.state[ht]}set top(e){this.state[ht]=e}get _free(){return this.state[ut]}set _free(e){this.state[ut]=e}get _used(){return this.state[ft]}set _used(e){this.state[ft]=e}get doCompact(){return!!(this.state[v]&_e)}set doCompact(e){e?this.state[v]|=1<<_e-1:this.state[v]&=~_e}get doSplit(){return!!(this.state[v]&be)}set doSplit(e){e?this.state[v]|=1<<be-1:this.state[v]&=~be}get minSplit(){return this.state[mt]}set minSplit(e){Ee(e>R,`illegal min split threshold: ${e}, require at least ${R+1}`),this.state[mt]=e}blockSize(e){return this.u32[(e>>2)+Ae]}setBlockSize(e,t){return this.u32[(e>>2)+Ae]=t,t}blockNext(e){return this.u32[(e>>2)+Te]}setBlockNext(e,t){this.u32[(e>>2)+Te]=t}initBlock(e,t,s){let r=e>>>2;return this.u32[r+Ae]=t,this.u32[r+Te]=s,e}unlinkBlock(e,t){this.setBlockNext(e,this.blockNext(t))}splitBlock(e,t,s){this.insert(this.initBlock(e+this.setBlockSize(e,t),s,0)),this.doCompact&&this.compact()}initialTop(e=this.align){return Y(this.start+yt+R,e)-R}compact(){let e=this._free,t=0,s=0,r,n=!1;for(;e;){for(r=e,s=this.blockNext(e);s&&r+this.blockSize(r)===s;)r=s,s=this.blockNext(s);if(r!==e){let o=r-e+this.blockSize(r);this.setBlockSize(e,o);let a=this.blockNext(r),c=this.blockNext(e);for(;c&&c!==a;){let u=this.blockNext(c);this.setBlockNext(c,0),c=u}this.setBlockNext(e,a),n=!0}e+this.blockSize(e)>=this.top&&(this.top=e,t?this.unlinkBlock(t,e):this._free=this.blockNext(e)),t=e,e=this.blockNext(e)}return n}insert(e){let t=this._free,s=0;for(;t&&!(e<=t);)s=t,t=this.blockNext(t);s?this.setBlockNext(s,e):this._free=e,this.setBlockNext(e,t)}},$=i=>i>0?i+R:0,we=i=>i>0?i-R:0;var Ce=8,St=65536,Q=class{#s=[];#e;#r;#l=0;#o=!1;#a;#i;#n;#c;constructor({buf:e,start:t,size:s,wasmMemory:r=null,maxSize:n,growIncrement:o=32*1024*1024,growFn:a=null,onGrowth:c=null}){this.#e=r,this.#r=o,this.#a=a,this.#i=c,this.#n=t+s,this.#c=t+n,this.#f(e,t,s,0)}malloc(e){for(let t=this.#s.length-1;t>=0;t--){let s=this.#s[t],r=s.pool.malloc(e);if(r!==0)return r+s.baseOffset}return 0}free(e){for(let t of this.#s)if(e>=t.start&&e<t.end)return t.pool.free(e-t.baseOffset);return!1}stats(){let e=0,t=0,s=0,r=0,n=0,o=0,a=0;for(let c of this.#s){let u=c.pool.stats();e+=u.free?.count||0,t+=u.free?.size||0,s+=u.used?.count||0,r+=u.used?.size||0,n+=u.available||0,o+=u.total||0,u.top>a&&(a=u.top)}return{free:{count:e,size:t},used:{count:s,size:r},top:a,available:n,total:o}}canGrow(){return this.#n+Ce<this.#c}async grow(e=0){if(this.#o||!this.canGrow())return!1;this.#o=!0;try{let t=this.#c-this.#n,s=Math.min(Math.max(this.#r,e),t);if(s<Ce)return!1;let r=Math.ceil(s/St),n=this.#n,o=Math.min(r*St,this.#c-n),a;if(this.#e){if(this.#e.grow(r)===-1)return!1;a=this.#e.buffer}else if(this.#a){if(!await this.#a(r))return!1;a=new ArrayBuffer(o)}else return!1;let c=this.#e?0:n,u=this.#e?n:0;return this.#f(a,u,o,c),this.#n=n+o,this.#l++,this.#i&&this.#i({poolIndex:this.#s.length-1,newBytes:o,totalCapacity:this.totalCapacity}),!0}finally{this.#o=!1}}get poolCount(){return this.#s.length}get growthCount(){return this.#l}get totalCapacity(){let e=0;for(let t of this.#s)e+=t.end-t.start;return e}get maxCapacity(){return this.#c-this.#s[0].start}#f(e,t,s,r){let n=new j({buf:e,start:t,size:s,align:Ce}),o=t+r;this.#s.push({pool:n,start:o,end:o+s,baseOffset:r})}};function gt(i){if(i.byteLength<12)return!1;let e=new Uint8Array(i,0,12),t=String.fromCharCode(e[0],e[1],e[2],e[3]),s=String.fromCharCode(e[8],e[9],e[10],e[11]);return t==="FORM"&&(s==="AIFF"||s==="AIFC")}function as(i){let e=i[0]>>7&1,t=(i[0]&127)<<8|i[1],s=0;for(let n=2;n<10;n++)s=s*256+i[n];if(t===0)return 0;let r=s*Math.pow(2,t-16383-63);return e?-r:r}function Et(i,e){let t=12;for(;t<i.byteLength-8;){let s=String.fromCharCode(i.getUint8(t),i.getUint8(t+1),i.getUint8(t+2),i.getUint8(t+3)),r=i.getUint32(t+4,!1);if(s===e)return{offset:t+8,size:r};t+=8+r+r%2}return null}function _t(i){let e=new DataView(i),t=String.fromCharCode(e.getUint8(8),e.getUint8(9),e.getUint8(10),e.getUint8(11)),s=Et(e,"COMM");if(!s)throw new Error("AIFF file missing COMM chunk");let r=e.getUint16(s.offset,!1),n=e.getUint32(s.offset+2,!1),o=e.getUint16(s.offset+6,!1),a=new Uint8Array(i,s.offset+8,10),c=as(a);if(t==="AIFC"&&s.size>=22){let d=String.fromCharCode(e.getUint8(s.offset+18),e.getUint8(s.offset+19),e.getUint8(s.offset+20),e.getUint8(s.offset+21));if(d!=="NONE"&&d!=="sowt")throw new Error(`AIFC compression type '${d}' is not supported. Only uncompressed AIFF/AIFC files are supported.`);if(d==="sowt")return cs(i,r,n,o,c)}let{wavBuffer:u,wavBytes:l,srcBytes:f,audioDataSize:h,bytesPerSample:y,wavHeaderSize:p}=bt(i,r,n,o,c);if(y===1)for(let d=0;d<h;d++)l[p+d]=f[d]+128;else if(y===2)for(let d=0;d<h;d+=2)l[p+d]=f[d+1],l[p+d+1]=f[d];else if(y===3)for(let d=0;d<h;d+=3)l[p+d]=f[d+2],l[p+d+1]=f[d+1],l[p+d+2]=f[d];else if(y===4)for(let d=0;d<h;d+=4)l[p+d]=f[d+3],l[p+d+1]=f[d+2],l[p+d+2]=f[d+1],l[p+d+3]=f[d];else throw new Error(`Unsupported bit depth: ${o}`);return u}function bt(i,e,t,s,r){let n=new DataView(i),o=Et(n,"SSND");if(!o)throw new Error("AIFF file missing SSND chunk");let a=n.getUint32(o.offset,!1),c=o.offset+8+a,u=s/8,l=t*e*u;if(c+l>i.byteLength)throw new Error("AIFF file truncated: not enough audio data");let f=44,h=new ArrayBuffer(f+l),y=new DataView(h),p=new Uint8Array(h);ls(y,{numChannels:e,sampleRate:Math.round(r),bitsPerSample:s,dataSize:l});let d=new Uint8Array(i,c,l);return{wavBuffer:h,wavBytes:p,srcBytes:d,audioDataSize:l,bytesPerSample:u,wavHeaderSize:f}}function cs(i,e,t,s,r){let{wavBuffer:n,wavBytes:o,srcBytes:a,audioDataSize:c,bytesPerSample:u,wavHeaderSize:l}=bt(i,e,t,s,r);if(u===1)for(let f=0;f<c;f++)o[l+f]=a[f]+128;else o.set(a,l);return n}function ls(i,{numChannels:e,sampleRate:t,bitsPerSample:s,dataSize:r}){let n=t*e*(s/8),o=e*(s/8);i.setUint8(0,82),i.setUint8(1,73),i.setUint8(2,70),i.setUint8(3,70),i.setUint32(4,36+r,!0),i.setUint8(8,87),i.setUint8(9,65),i.setUint8(10,86),i.setUint8(11,69),i.setUint8(12,102),i.setUint8(13,109),i.setUint8(14,116),i.setUint8(15,32),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,e,!0),i.setUint32(24,t,!0),i.setUint32(28,n,!0),i.setUint16(32,o,!0),i.setUint16(34,s,!0),i.setUint8(36,100),i.setUint8(37,97),i.setUint8(38,116),i.setUint8(39,97),i.setUint32(40,r,!0)}var J=class{#s;#e;#r;#l;#o;#a;#i;#n;#c;#f;#m;constructor(e){let{mode:t="sab",audioContext:s,sharedBuffer:r,bufferPoolConfig:n,sampleBaseURL:o,maxBuffers:a=1024,assetLoader:c=null,workletPort:u=null,wasmMemory:l=null,maxBufferMemory:f=null,bufferGrowIncrement:h=32*1024*1024,onBufferPoolGrowth:y=null,growFn:p=null}=e;if(this.#s=t,!s)throw new Error("BufferManager requires audioContext");if(t==="sab"){if(!r||!(r instanceof SharedArrayBuffer))throw new Error("BufferManager requires sharedBuffer (SharedArrayBuffer) in SAB mode");if(!n||typeof n!="object")throw new Error("BufferManager requires bufferPoolConfig (object with start, size, align)");if(!Number.isFinite(n.start)||n.start<0)throw new Error("bufferPoolConfig.start must be a non-negative number");if(!Number.isFinite(n.size)||n.size<=0)throw new Error("bufferPoolConfig.size must be a positive number")}if(t==="postMessage"&&(!n||typeof n!="object"))throw new Error("BufferManager requires bufferPoolConfig in postMessage mode");if(!Number.isInteger(a)||a<=0)throw new Error("maxBuffers must be a positive integer");this.#l=s,this.#o=r,this.#a=l,this.#e=o,this.#r=c,this.#m=u;let d=f||n.maxSize||n.size,m=t==="sab"?r:new ArrayBuffer(n.start+n.size);this.#i=new Q({buf:m,start:n.start,size:n.size,wasmMemory:t==="sab"?l:null,maxSize:d,growIncrement:h,growFn:t==="postMessage"?p:null,onGrowth:y}),this.#n=new Map,this.#c=new Map,this.#f=new Map,this.GUARD_BEFORE=3,this.GUARD_AFTER=1,this.MAX_BUFFERS=a;let g=(n.size/(1024*1024)).toFixed(0),_=(n.start/(1024*1024)).toFixed(0)}async#S(e){let t=e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),s=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(s)).map(r=>r.toString(16).padStart(2,"0")).join("")}async#E({source:e,startFrame:t=0,numFrames:s=0,channels:r=null}){let n,o;if(typeof e=="string"){let m=this.#_(e),g=e.split("/").pop();n=await this.#r.fetch(m,{type:"sample",name:g}),o={type:"file",path:e,startFrame:t,numFrames:s,channels:r}}else n=e instanceof ArrayBuffer?e:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),o=null;let a=await this.#p(n),c=Math.max(0,Math.floor(t||0)),u=a.length-c,l=s&&s>0?Math.min(Math.floor(s),u):u;if(l<=0)throw new Error("No audio frames available");let f=this.#u(r,a.numberOfChannels),h=f.length,y=l*h+(this.GUARD_BEFORE+this.GUARD_AFTER)*h,p=new Float32Array(y),d=this.GUARD_BEFORE*h;for(let m=0;m<l;m++)for(let g=0;g<h;g++){let _=a.getChannelData(f[g]);p[d+m*h+g]=_[c+m]}return{interleaved:p,numFrames:l,numChannels:h,sampleRate:a.sampleRate,sourceInfo:o}}async#d(e){let t=await this.#y(e.length);return await this.#b(t,e),t}async#g(e,t,s,r){let n,o=await this.#t(e,t,async()=>{let[c,u]=await Promise.all([this.#S(s.interleaved),this.#d(s.interleaved)]);return n=c,{ptr:u,sizeBytes:s.interleaved.length*4,numFrames:s.numFrames,numChannels:s.numChannels,sampleRate:s.sampleRate,source:r||null}}),a=this.#n.get(e);return a&&(a.hash=n),{...o,hash:n}}async#p(e){return gt(e)&&(e=_t(e)),this.#l.decodeAudioData(e)}setWorkletPort(e){if(this.#s==="postMessage"){if(!e)throw new Error("BufferManager.setWorkletPort() requires a valid port");this.#m=e}}#_(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid audio path: must be a non-empty string");if(e.includes(".."))throw new Error(`Invalid audio path: path cannot contain '..' (got: ${e})`);if(e.includes("%2e")||e.includes("%2E"))throw new Error(`Invalid audio path: path cannot contain URL-encoded characters (got: ${e})`);if(e.includes("\\"))throw new Error(`Invalid audio path: use forward slashes only (got: ${e})`);if(e.includes("://")||e.startsWith("/")||e.startsWith("./"))return e;if(!this.#e)throw new Error(`sampleBaseURL not configured. Please set it in SuperSonic constructor options.
3
3
  Example: new SuperSonic({ sampleBaseURL: "./dist/samples/" })
4
4
  Or use CDN: new SuperSonic({ sampleBaseURL: "https://unpkg.com/supersonic-scsynth-samples@latest/samples/" })
5
- Or install: npm install supersonic-scsynth-samples`);return this.#e+e}#y(e){if(!Number.isInteger(e)||e<0||e>=this.MAX_BUFFERS)throw new Error(`Invalid buffer number ${e} (must be 0-${this.MAX_BUFFERS-1})`)}async#r(e,t,s){let r=null,n=null,o=!1,a=await this.#M(e),c=!1;try{await this.#O(e);let{ptr:l,sizeBytes:u,numFrames:f,numChannels:h,sampleRate:S,source:m,...E}=await s();r=l;let{uuid:p,allocationComplete:y}=this.#w(e,t);n=p,this.#R(e,r,u,p,y,{numFrames:f,numChannels:h,sampleRate:S,source:m}),o=!0;let _=this.#I(e,p,y);return a(),c=!0,{ptr:r,uuid:p,allocationComplete:_,numFrames:f,numChannels:h,sampleRate:S,...E}}catch(l){throw o&&n?this.#B(e,n,!1):r&&this.#n.free(r),l}finally{c||a()}}async prepareFromBlob(e){let{bufnum:t,blob:s,startFrame:r=0,numFrames:n=0,channels:o=null}=e;if(this.#y(t),!s||!(s instanceof ArrayBuffer||ArrayBuffer.isView(s)))throw new Error("/b_allocFile requires audio data as ArrayBuffer or typed array");let a=await this.#_({source:s,startFrame:r,numFrames:n,channels:o});return this.#h(t,3e4,a,null)}async prepareFromFile(e){let{bufnum:t,path:s,startFrame:r=0,numFrames:n=0,channels:o=null}=e;this.#y(t);let a=await this.#_({source:s,startFrame:r,numFrames:n,channels:o});return this.#h(t,6e4,a,a.sourceInfo)}async prepareEmpty(e){let{bufnum:t,numFrames:s,numChannels:r=1,sampleRate:n=null}=e;if(this.#y(t),!Number.isFinite(s)||s<=0)throw new Error(`/b_alloc requires a positive number of frames (got ${s})`);if(!Number.isFinite(r)||r<=0)throw new Error(`/b_alloc requires a positive channel count (got ${r})`);let o=Math.floor(s),a=Math.floor(r),c=o*a+(this.GUARD_BEFORE+this.GUARD_AFTER)*a,u={interleaved:new Float32Array(c),numFrames:o,numChannels:a,sampleRate:n||this.#f.sampleRate};return this.#h(t,5e3,u,null)}#a(e,t){return!e||e.length===0?Array.from({length:t},(s,r)=>r):(e.forEach(s=>{if(!Number.isInteger(s)||s<0||s>=t)throw new Error(`Channel ${s} is out of range (file has ${t} channels)`)}),e)}async#g(e){let t=this.#n.malloc(e);return t===0&&this.#n.canGrow()&&await this.#n.grow(e)&&(t=this.#n.malloc(e)),t}async#S(e){let t=e*4,s=await this.#g(t);if(s===0){let r=this.#n.stats(),n=((r.available||0)/(1024*1024)).toFixed(2),o=((r.total||0)/(1024*1024)).toFixed(2),a=((this.#n.maxCapacity||0)/(1024*1024)).toFixed(2),c=(t/(1024*1024)).toFixed(2);throw new Error(`Buffer pool allocation failed: requested ${c}MB, available ${n}MB of ${o}MB total (max ${a}MB)`)}return s}async#C(e,t){if(this.#t==="sab"){let s=this.#c?.buffer||this.#o;new Float32Array(s,e,t.length).set(t)}else{let s=crypto.randomUUID(),r=new Promise((o,a)=>{let c=setTimeout(()=>{a(new Error("Buffer copy to WASM memory timed out"))},1e4),l=u=>{let f=u.data;f.type==="bufferCopied"&&f.copyId===s&&(this.#d.removeEventListener("message",l),clearTimeout(c),f.success?o():a(new Error(f.error||"Buffer copy failed")))};this.#d.addEventListener("message",l)}),n=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);this.#d.postMessage({type:"copyBufferData",copyId:s,ptr:e,data:n},[n]),await r}}#A(e,t,s){return new Promise((r,n)=>{let o=setTimeout(()=>{this.#l.delete(e),n(new Error(`Buffer ${t} allocation timeout (${s}ms)`))},s);this.#l.set(e,{resolve:r,reject:n,timeout:o})})}#w(e,t){let s=crypto.randomUUID(),r=this.#A(s,e,t);return{uuid:s,allocationComplete:r}}async#M(e){let t=this.#u.get(e)||Promise.resolve(),s,r=new Promise(n=>{s=n});return this.#u.set(e,t.then(()=>r)),await t,()=>{s&&(s(),s=null),this.#u.get(e)===r&&this.#u.delete(e)}}#R(e,t,s,r,n,o={}){let a=this.#i.get(e),c={ptr:t,size:s,numFrames:o.numFrames||0,numChannels:o.numChannels||1,sampleRate:o.sampleRate||48e3,pendingToken:r,pendingPromise:n,previousAllocation:a?{ptr:a.ptr,size:a.size}:null,source:o.source||null};return this.#i.set(e,c),c}async#O(e){let t=this.#i.get(e);if(t&&t.pendingToken&&t.pendingPromise)try{await t.pendingPromise}catch{}}#I(e,t,s){return!s||typeof s.then!="function"?(this.#B(e,t,!0),Promise.resolve()):s.then(r=>(this.#B(e,t,!0),r)).catch(r=>{throw this.#B(e,t,!1),r})}#B(e,t,s){let r=this.#i.get(e);if(!r||r.pendingToken!==t)return;let n=r.previousAllocation;if(s){r.pendingToken=null,r.pendingPromise=null,r.previousAllocation=null,n?.ptr&&this.#n.free(n.ptr);return}r.ptr&&this.#n.free(r.ptr),r.pendingPromise=null,n?.ptr?this.#i.set(e,{ptr:n.ptr,size:n.size,pendingToken:null,previousAllocation:null}):this.#i.delete(e)}handleBufferFreed(e){let t=typeof e[0]=="bigint"?Number(e[0]):e[0],s=typeof e[1]=="bigint"?Number(e[1]):e[1],r=this.#i.get(t);if(!r){typeof s=="number"&&s!==0&&this.#n.free(s);return}if(typeof s=="number"&&s===r.ptr){this.#n.free(r.ptr),this.#i.delete(t);return}if(typeof s=="number"&&r.previousAllocation&&r.previousAllocation.ptr===s){this.#n.free(s),r.previousAllocation=null;return}this.#n.free(r.ptr),this.#i.delete(t)}handleBufferAllocated(e){let t=e[0],s=e[1],r=this.#l.get(t);r&&(clearTimeout(r.timeout),r.resolve({bufnum:s}),this.#l.delete(t))}async allocate(e){return this.#g(e*4)}free(e){return this.#n.free(e)}getView(e,t){let s=this.#c?.buffer||this.#o;return new Float32Array(s,e,t)}getStats(){return this.#n?this.#n.stats():{total:0,available:0,used:0,allocations:0}}getGrowthStats(){return this.#n?{totalCapacity:this.#n.totalCapacity,maxCapacity:this.#n.maxCapacity,growthCount:this.#n.growthCount,poolCount:this.#n.poolCount}:{totalCapacity:0,maxCapacity:0,growthCount:0,poolCount:0}}async sampleInfo({source:e,startFrame:t=0,numFrames:s=0,channels:r=null}){let n=await this.#_({source:e,startFrame:t,numFrames:s,channels:r});return{hash:await this.#E(n.interleaved),source:n.sourceInfo?.path||null,numFrames:n.numFrames,numChannels:n.numChannels,sampleRate:n.sampleRate,duration:n.sampleRate>0?n.numFrames/n.sampleRate:0}}getAllocatedBuffers(){let e=[];for(let[t,s]of this.#i.entries())!s||!s.ptr||e.push({bufnum:t,ptr:s.ptr,numFrames:s.numFrames,numChannels:s.numChannels,sampleRate:s.sampleRate,source:s.source||null,hash:s.hash||null});return e}updateAudioContext(e){if(!e)throw new Error("BufferManager.updateAudioContext requires audioContext");this.#f=e}destroy(){for(let[e,t]of this.#l.entries())clearTimeout(t.timeout),t.reject(new Error("BufferManager destroyed"));this.#l.clear();for(let[e,t]of this.#i.entries())t.ptr&&this.#n.free(t.ptr);this.#i.clear(),this.#u.clear()}};var j=class{#t;#e;#s;#f;constructor(e={}){let{onLoadingEvent:t=null,maxRetries:s=3,baseDelay:r=1e3,skipHeadRequests:n=!1}=e;this.#t=t,this.#e=s,this.#s=r,this.#f=n}async fetch(e,{type:t,name:s}){let r=this.#c(e);if(this.#f)this.#t?.("loading:start",{type:t,name:s});else{let a=await this.#o(e);this.#t?.("loading:start",{type:t,name:s,...a!=null&&{size:a}})}let o=await(await r).arrayBuffer();return this.#t?.("loading:complete",{type:t,name:s,size:o.byteLength}),o}async#o(e){try{let t=await fetch(e,{method:"HEAD"});if(t.ok){let s=t.headers.get("Content-Length");return s?parseInt(s,10):null}return null}catch{return null}}async#c(e){let t;for(let s=0;s<=this.#e;s++)try{let r=await fetch(e);if(r.status>=400&&r.status<500)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);if(!r.ok)throw new Error(`Server error fetching ${e}: ${r.status} ${r.statusText}`);return r}catch(r){if(t=r,r.message.includes("Failed to fetch")&&r.message.includes("4"))throw r;if(s<this.#e){let n=this.#s*Math.pow(2,s);await this.#n(n)}}throw t}#n(e){return new Promise(t=>setTimeout(t,e))}};var Q=class{#t;#e;constructor({bufferManager:e,getDefaultSampleRate:t}){if(!e)throw new Error("OSCRewriter requires bufferManager");if(typeof t!="function")throw new Error("OSCRewriter requires getDefaultSampleRate callback");this.#t=e,this.#e=t}async rewritePacket(e){if(Array.isArray(e)){let{message:t,changed:s}=await this.#s(e);return{packet:t,changed:s}}if(this.#l(e)){let t=await Promise.all(e.packets.map(n=>this.rewritePacket(n)));if(!t.some(n=>n.changed))return{packet:e,changed:!1};let r=t.map(n=>n.packet);return{packet:{timeTag:e.timeTag,packets:r},changed:!0}}return{packet:e,changed:!1}}async#s(e){let t=e[0],s=e.slice(1);switch(t){case"/b_alloc":return{message:await this.#f(s),changed:!0};case"/b_allocRead":return{message:await this.#o(s),changed:!0};case"/b_allocReadChannel":return{message:await this.#c(s),changed:!0};case"/b_allocFile":return{message:await this.#n(s),changed:!0};default:return{message:e,changed:!1}}}async#f(e){let t=this.#E(e,0,"/b_alloc requires a buffer number"),s=this.#E(e,1,"/b_alloc requires a frame count"),r=2,n=1,o=this.#e();Number.isFinite(this.#u(e,r))&&(n=Math.max(1,this.#_(e,r,1)),r++),(Array.isArray(e)?e[r]:void 0)?.type==="b"&&r++;let a=this.#u(e,r);Number.isFinite(a)&&(o=a);let c=await this.#t.prepareEmpty({bufnum:t,numFrames:s,numChannels:n,sampleRate:o});return this.#m(c.allocationComplete,`/b_alloc ${t}`),this.#i(t,c)}async#o(e){let t=this.#E(e,0,"/b_allocRead requires a buffer number"),s=this.#p(e,1,"/b_allocRead requires a file path"),r=this.#_(e,2,0),n=this.#_(e,3,0),o=await this.#t.prepareFromFile({bufnum:t,path:s,startFrame:r,numFrames:n});return this.#m(o.allocationComplete,`/b_allocRead ${t}`),this.#i(t,o)}async#c(e){let t=this.#E(e,0,"/b_allocReadChannel requires a buffer number"),s=this.#p(e,1,"/b_allocReadChannel requires a file path"),r=this.#_(e,2,0),n=this.#_(e,3,0),o=[];for(let c=4;c<(e?.length||0);c++){let l=this.#u(e,c);if(!Number.isFinite(l))break;o.push(Math.floor(l))}let a=await this.#t.prepareFromFile({bufnum:t,path:s,startFrame:r,numFrames:n,channels:o.length>0?o:null});return this.#m(a.allocationComplete,`/b_allocReadChannel ${t}`),this.#i(t,a)}async#n(e){let t=this.#E(e,0,"/b_allocFile requires a buffer number"),s=this.#h(e,1,"/b_allocFile requires audio file data as blob"),r=await this.#t.prepareFromBlob({bufnum:t,blob:s});return this.#m(r.allocationComplete,`/b_allocFile ${t}`),this.#i(t,r)}#i(e,t){return["/b_allocPtr",Math.floor(e),Math.floor(t.ptr),Math.floor(t.numFrames),Math.floor(t.numChannels),t.sampleRate,String(t.uuid)]}#l(e){return e&&e.timeTag!==void 0&&Array.isArray(e.packets)}#u(e,t){let s=Array.isArray(e)?e[t]:void 0;if(s!=null)return typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"value")?s.value:s}#d(e,t,s,r){let n=this.#u(e,t);if(!s(n))throw new Error(r);return n}#E(e,t,s){return Math.floor(this.#d(e,t,Number.isFinite,s))}#_(e,t,s=0){let r=this.#u(e,t);return Number.isFinite(r)?Math.floor(r):s}#p(e,t,s){return this.#d(e,t,r=>typeof r=="string",s)}#h(e,t,s){return this.#d(e,t,r=>r instanceof Uint8Array||r instanceof ArrayBuffer,s)}#m(e,t){!e||typeof e.catch!="function"||e.catch(s=>{console.error(`[OSCRewriter] ${t} allocation failed:`,s)})}};function x(i){if(!i)return null;if(typeof i=="string")return(i.split("/").filter(Boolean).pop()||i).replace(/\.scsyndef$/i,"");let e=i instanceof ArrayBuffer?new Uint8Array(i):i;if(!(e instanceof Uint8Array)||e.length<11||e[0]!==83||e[1]!==67||e[2]!==103||e[3]!==102)return null;let s=(e[4]<<24|e[5]<<16|e[6]<<8|e[7])>=3?14:10;if(s>=e.length)return null;let r=e[s];if(r===0||s+1+r>e.length)return null;try{return new TextDecoder().decode(e.slice(s+1,s+1+r))}catch{return null}}var J=class{#t=new Map;on(e,t){if(typeof t!="function")throw new Error("Callback must be a function");return this.#t.has(e)||this.#t.set(e,new Set),this.#t.get(e).add(t),()=>this.off(e,t)}off(e,t){let s=this.#t.get(e);return s&&s.delete(t),this}once(e,t){let s=(...r)=>{this.off(e,s),t(...r)};return this.on(e,s)}removeAllListeners(e){return e===void 0?this.#t.clear():this.#t.delete(e),this}hasListeners(e){let t=this.#t.get(e);return t?t.size>0:!1}emit(e,...t){let s=this.#t.get(e);if(s)for(let r of s)try{r(...t)}catch(n){console.error(`[EventEmitter] Error in ${e} listener:`,n)}}async emitAsync(e,...t){let s=this.#t.get(e);if(s)for(let r of s)try{await r(...t)}catch(n){console.error(`[EventEmitter] Error in ${e} listener:`,n)}}clearAllListeners(){this.#t.clear()}};var ee=class{#t;#e;#s;#f;#o;#c;#n;#i=null;#l=new Uint32Array(70);#u=new DataView(this.#l.buffer);constructor(e={}){this.#f=e.mode||"sab",this.#t=e.sharedBuffer||null,this.#e=e.ringBufferBase||0,this.#s=e.bufferConstants||null}initSharedViews(e,t,s){if(this.#t=e,this.#e=t,this.#s=s,this.#f==="sab"&&e&&s){this.#o=new Int32Array(e),this.#n=je(t,s.CONTROL_START);let r=t+s.METRICS_START;this.#c=new Uint32Array(e,r,s.METRICS_SIZE/4)}}updateSnapshot(e){this.#i=e}getSnapshotBuffer(){return this.#i}getMetricsView(){return this.#c}addMetric(e,t=1){if(!this.#c)return;let r={oscOutMessagesSent:24,oscOutBytesSent:25,preschedulerBypassed:22,bypassNonBundle:38,bypassImmediate:39,bypassNearFuture:40,bypassLate:41}[e];r!==void 0&&Atomics.add(this.#c,r,t)}overlayPreschedulerMetrics(e){if(!this.#i||!e)return;let t=new Uint32Array(this.#i,0,46),s=9,r=13;t.set(e.subarray(s,s+r),s),t[23]=e[23]}gatherMetrics(e={}){this.updateMergedArray(e);let t=this.#l,s={scsynthProcessCount:t[0],scsynthMessagesProcessed:t[1],scsynthMessagesDropped:t[2],scsynthSchedulerDepth:t[3],scsynthSchedulerPeakDepth:t[4],scsynthSchedulerDropped:t[5],scsynthSequenceGaps:t[6],scsynthSchedulerLates:t[8],scsynthSchedulerMaxLateMs:t[42],scsynthSchedulerLastLateMs:t[43],scsynthSchedulerLastLateTick:t[44],preschedulerPending:t[9],preschedulerPendingPeak:t[10],preschedulerDispatched:t[12],preschedulerRetriesSucceeded:t[16],preschedulerRetriesFailed:t[17],preschedulerBundlesScheduled:t[11],preschedulerEventsCancelled:t[13],preschedulerTotalDispatches:t[21],preschedulerMessagesRetried:t[20],preschedulerRetryQueueSize:t[18],preschedulerRetryQueuePeak:t[19],preschedulerBypassed:t[22],preschedulerMinHeadroomMs:t[14],preschedulerLates:t[15],preschedulerMaxLateMs:t[23],oscInMessagesReceived:t[26],oscInMessagesDropped:t[28],oscInBytesReceived:t[27],debugMessagesReceived:t[30],debugBytesReceived:t[31],oscOutMessagesSent:t[24],oscOutBytesSent:t[25],scsynthWasmErrors:t[7],oscInCorrupted:t[29],ringBufferDirectWriteFails:t[45],bypassNonBundle:t[38],bypassImmediate:t[39],bypassNearFuture:t[40],bypassLate:t[41],mode:this.#f},r=this.#s;return t[32]!==void 0&&r&&(s.inBufferUsed={bytes:t[32],percentage:t[32]/r.IN_BUFFER_SIZE*100,peakBytes:t[35],peakPercentage:t[35]/r.IN_BUFFER_SIZE*100,capacity:r.IN_BUFFER_SIZE},s.outBufferUsed={bytes:t[33],percentage:t[33]/r.OUT_BUFFER_SIZE*100,peakBytes:t[36],peakPercentage:t[36]/r.OUT_BUFFER_SIZE*100,capacity:r.OUT_BUFFER_SIZE},s.debugBufferUsed={bytes:t[34],percentage:t[34]/r.DEBUG_BUFFER_SIZE*100,peakBytes:t[37],peakPercentage:t[37]/r.DEBUG_BUFFER_SIZE*100,capacity:r.DEBUG_BUFFER_SIZE}),r?.scheduler_slot_count!==void 0&&(s.scsynthSchedulerCapacity=r.scheduler_slot_count),e.driftOffsetMs!==void 0&&(s.driftOffsetMs=e.driftOffsetMs),e.ntpStartTime!==void 0&&(s.ntpStartTime=e.ntpStartTime),e.clockOffsetMs!==void 0&&(s.clockOffsetMs=e.clockOffsetMs),e.audioContextState&&(s.audioContextState=e.audioContextState),e.bufferPoolStats&&(s.bufferPoolUsedBytes=e.bufferPoolStats.used.size,s.bufferPoolAvailableBytes=e.bufferPoolStats.available,s.bufferPoolAllocations=e.bufferPoolStats.used.count),e.bufferPoolGrowthStats&&(s.bufferPoolTotalCapacity=e.bufferPoolGrowthStats.totalCapacity,s.bufferPoolMaxCapacity=e.bufferPoolGrowthStats.maxCapacity,s.bufferPoolGrowthCount=e.bufferPoolGrowthStats.growthCount,s.bufferPoolPoolCount=e.bufferPoolGrowthStats.poolCount),e.loadedSynthDefsCount!==void 0&&(s.loadedSynthDefs=e.loadedSynthDefsCount),e.preschedulerCapacity!==void 0&&(s.preschedulerCapacity=e.preschedulerCapacity),s.audioHealthPct=e.audioHealthPct??100,s.hasPlaybackStats=!!e.playbackStats,e.playbackStats?(s.glitchCount=e.playbackStats.fallbackFramesEvents??0,s.glitchDurationMs=Math.round((e.playbackStats.fallbackFramesDuration??0)*1e3),s.averageLatencyUs=Math.round((e.playbackStats.averageLatency??0)*1e6),s.maxLatencyUs=Math.round((e.playbackStats.maximumLatency??0)*1e6),s.totalFramesDurationMs=Math.round((e.playbackStats.totalFramesDuration??0)*1e3)):(s.glitchCount=0,s.glitchDurationMs=0,s.averageLatencyUs=0,s.maxLatencyUs=0,s.totalFramesDurationMs=0),this.#f==="postMessage"&&e.transportMetrics&&Object.assign(s,e.transportMetrics),s}updateMergedArray(e={}){let t=this.#l;if(this.#f==="postMessage"){if(e.preschedulerMetrics&&this.overlayPreschedulerMetrics(e.preschedulerMetrics),this.#i){let a=new Uint32Array(this.#i,0,46);t.set(a)}e.transportMetrics&&(e.transportMetrics.oscOutMessagesSent!==void 0&&(t[24]=e.transportMetrics.oscOutMessagesSent),e.transportMetrics.oscOutBytesSent!==void 0&&(t[25]=e.transportMetrics.oscOutBytesSent),e.transportMetrics.preschedulerBypassed!==void 0&&(t[22]=e.transportMetrics.preschedulerBypassed),e.transportMetrics.bypassNonBundle!==void 0&&(t[38]=e.transportMetrics.bypassNonBundle),e.transportMetrics.bypassImmediate!==void 0&&(t[39]=e.transportMetrics.bypassImmediate),e.transportMetrics.bypassNearFuture!==void 0&&(t[40]=e.transportMetrics.bypassNearFuture),e.transportMetrics.bypassLate!==void 0&&(t[41]=e.transportMetrics.bypassLate))}else this.#c&&t.set(this.#c);let s=this.#u;s.setInt32(46*4,e.driftOffsetMs??0,!0),s.setInt32(47*4,e.clockOffsetMs??0,!0);let r=e.audioContextState||"unknown",n={unknown:0,running:1,suspended:2,closed:3,interrupted:4};t[48]=n[r]??0,e.bufferPoolStats&&(t[49]=e.bufferPoolStats.used?.size??0,t[50]=e.bufferPoolStats.available??0,t[51]=e.bufferPoolStats.used?.count??0),t[52]=e.loadedSynthDefsCount??0;let o=this.#s;t[53]=o?.scheduler_slot_count??0,t[54]=e.preschedulerCapacity??0,t[55]=o?.IN_BUFFER_SIZE??0,t[56]=o?.OUT_BUFFER_SIZE??0,t[57]=o?.DEBUG_BUFFER_SIZE??0,t[58]=this.#f==="sab"?0:1,t[65]=e.playbackStats?1:0,e.playbackStats&&(t[59]=e.playbackStats.fallbackFramesEvents??0,t[60]=Math.round((e.playbackStats.fallbackFramesDuration??0)*1e3),t[61]=Math.round((e.playbackStats.averageLatency??0)*1e6),t[62]=Math.round((e.playbackStats.maximumLatency??0)*1e6),t[64]=Math.round((e.playbackStats.totalFramesDuration??0)*1e3)),t[63]=e.audioHealthPct??100,e.bufferPoolGrowthStats&&(t[66]=e.bufferPoolGrowthStats.totalCapacity??0,t[67]=e.bufferPoolGrowthStats.maxCapacity??0,t[68]=e.bufferPoolGrowthStats.growthCount??0,t[69]=e.bufferPoolGrowthStats.poolCount??0)}getMergedArray(){return this.#l}get bufferConstants(){return this.#s}get ringBufferBase(){return this.#e}get sharedBuffer(){return this.#t}};function Me(i){return i/1e3+2208988800}function bt(i,e){return i-e}function or(i,e){let t=i-e;return Math.round(t*1e3)}var te=class{#t;#e;#s;#f;#o;#c;#n;#i;#l;#u=0;#d=0;#E=null;constructor(e={}){this.#t=e.mode||"sab",this.#e=e.audioContext,this.#s=e.workletPort||null}initSharedViews(e,t,s){this.#o=t,this.#f=s,this.#t==="sab"&&e&&s&&(this.#c=new Float64Array(e,t+s.NTP_START_TIME_START,1),this.#n=new Int32Array(e,t+s.DRIFT_OFFSET_START,1),this.#i=new Int32Array(e,t+s.GLOBAL_OFFSET_START,1))}updateAudioContext(e){this.#e=e}async initialize(){if(!this.#e)return;let e;for(;e=this.#e.getOutputTimestamp(),!(e.contextTime>0);)await new Promise(o=>setTimeout(o,50));e=this.#e.getOutputTimestamp();let t=performance.timeOrigin+e.performanceTime,s=Me(t),r=e.contextTime,n=bt(s,r);this.#t==="sab"&&this.#c?this.#c[0]=n:this.#s&&this.#s.postMessage({type:"setNTPStartTime",ntpStartTime:n}),this.#l=n,await new Promise(o=>setTimeout(o,500)),this.updateDriftOffset()}updateDriftOffset(){if(!this.#e||this.#l===void 0)return;let e=this.#e.getOutputTimestamp(),t=performance.timeOrigin+e.performanceTime,r=Me(t)-this.#l,n=or(r,e.contextTime);this.#u=n,this.#t==="sab"&&this.#n?Atomics.store(this.#n,0,n):this.#s&&this.#s.postMessage({type:"setDriftOffset",driftOffsetMs:n})}resync(){if(!this.#e)return;let e=this.#e.getOutputTimestamp();if(!e||e.contextTime<=0)return;let t=performance.timeOrigin+e.performanceTime,s=Me(t),r=bt(s,e.contextTime);this.#t==="sab"&&this.#c?this.#c[0]=r:this.#s&&this.#s.postMessage({type:"setNTPStartTime",ntpStartTime:r}),this.#l=r,this.updateDriftOffset()}startDriftTimer(){this.stopDriftTimer(),this.#E=setInterval(()=>{this.updateDriftOffset()},1e3)}stopDriftTimer(){this.#E&&(clearInterval(this.#E),this.#E=null)}getDriftOffset(){return this.#n?Atomics.load(this.#n,0):this.#u}getNTPStartTime(){return this.#c?this.#c[0]:this.#l??0}getClockOffset(){return this.#i?Atomics.load(this.#i,0):this.#d}setClockOffset(e){let t=Math.round(e*1e3);this.#d=t,this.#t==="sab"&&this.#i?Atomics.store(this.#i,0,t):this.#s&&this.#s.postMessage({type:"setClockOffset",clockOffsetMs:t})}reset(){this.stopDriftTimer(),this.#l=void 0,this.#u=0,this.#d=0,this.#c=null,this.#n=null,this.#i=null}};var se=class i{#t;#e=0;#s=0;#f=100;static#o=1e3;constructor({audioContext:e}){this.#t=e}update(){if(this.#t.state!=="running")return this.#f;let e=performance.now(),t=this.#t.currentTime;if(this.#s===0)return this.#s=e,this.#e=t,this.#f;let s=e-this.#s;if(s<i.#o)return this.#f;let r=s/1e3,n=t-this.#e;return this.#f=Math.min(100,Math.round(n/r*100)),this.#s=e,this.#e=t,this.#f}getHealth(){return{healthPct:this.#f}}reset(){this.#e=0,this.#s=0,this.#f=100}};var re=class{#t;#e;#s;constructor(e={}){this.#t=e.sharedBuffer||null,this.#e=e.bufferConstants||null,this.#s=e.ringBufferBase||0}update(e,t,s){this.#t=e,this.#s=t,this.#e=s}isAvailable(){return!!(this.#t&&this.#e)}start(){if(!this.isAvailable())throw new Error("AudioCapture not initialized");let e=this.#e,t=this.#s+e.AUDIO_CAPTURE_START,s=new Uint32Array(this.#t,t,4);Atomics.store(s,1,0),Atomics.store(s,0,1)}stop(){if(!this.isAvailable())throw new Error("AudioCapture not initialized");let e=this.#e,t=this.#s+e.AUDIO_CAPTURE_START,s=new Uint32Array(this.#t,t,4);Atomics.store(s,0,0);let r=Atomics.load(s,1),n=s[2],o=s[3],a=t+e.AUDIO_CAPTURE_HEADER_SIZE,c=new Float32Array(this.#t,a,r*o),l=new Float32Array(r),u=o>1?new Float32Array(r):null;for(let f=0;f<r;f++)l[f]=c[f*o],u&&(u[f]=c[f*o+1]);return{sampleRate:n,channels:o,frames:r,left:l,right:u}}isEnabled(){if(!this.isAvailable())return!1;let e=this.#e,t=this.#s+e.AUDIO_CAPTURE_START,s=new Uint32Array(this.#t,t,1);return Atomics.load(s,0)===1}getFrameCount(){if(!this.isAvailable())return 0;let e=this.#e,t=this.#s+e.AUDIO_CAPTURE_START,s=new Uint32Array(this.#t,t,2);return Atomics.load(s,1)}getMaxDuration(){if(!this.#e)return 0;let e=this.#e;return e.AUDIO_CAPTURE_FRAMES/(e.AUDIO_CAPTURE_SAMPLE_RATE||48e3)}};function Tt(i,e,t){let s=t,r=new Uint32Array(i,e,3),n=r[0],o=r[1],a=r[2],c=e+s.NODE_TREE_HEADER_SIZE,l=s.NODE_TREE_MIRROR_MAX_NODES,u=s.NODE_TREE_ENTRY_SIZE,f=s.NODE_TREE_DEF_NAME_SIZE,h=new DataView(i,c,l*u),S=new TextDecoder("utf-8"),m=[],E=0;for(let p=0;p<l&&E<n;p++){let y=p*u,_=h.getInt32(y,!0);if(_===-1)continue;E++;let d=c+y+24,M=new Uint8Array(i,d,f),ue=new Uint8Array(f);ue.set(M);let fe=ue.indexOf(0);fe===-1&&(fe=f);let Nt=S.decode(ue.subarray(0,fe));m.push({id:_,parentId:h.getInt32(y+4,!0),isGroup:h.getInt32(y+8,!0)===1,prevId:h.getInt32(y+12,!0),nextId:h.getInt32(y+16,!0),headId:h.getInt32(y+20,!0),defName:Nt})}return{nodeCount:n,version:o,droppedCount:a,nodes:m}}var xe=new Uint8Array(2097152),At=new DataView(xe.buffer),g=xe,T=At,Be=new Map,ar=1e3,cr=new TextDecoder,lr=new TextEncoder,Oe=[null,0],Ne=2208988800,oe=4294967296,ve=new Uint8Array([35,98,117,110,100,108,101,0]),wt=44,Ue=105,Ie=102,De=115,Pe=98,Le=84,ke=70,Ct=104,Mt=100,Bt=116,Ot=117;function ie(i,e,t=0){let s=i.length+4;s+=e.length-t+4;for(let r=t;r<e.length;r++){let n=e[r];if(n instanceof Uint8Array)s+=4+n.length+3;else if(n instanceof ArrayBuffer)s+=4+n.byteLength+3;else if(typeof n=="string")s+=n.length*3+4;else if(n&&n.type==="string")s+=n.value.length*3+4;else if(n&&n.type==="blob"){let o=n.value,a=o instanceof Uint8Array?o.length:o.byteLength;s+=4+a+3}else n&&n.type==="uuid"?s+=16:s+=8}return s}function Rt(i){let e=16;for(let t of i)e+=4,Array.isArray(t)?e+=ie(t[0],t,1):t.packets!==void 0?e+=Rt(t.packets):e+=ie(t.address,t.args||[]);return e}function He(i){if(i<=2097152){g=xe,T=At;return}g=new Uint8Array(i),T=new DataView(g.buffer)}function Ut(i,e=[]){let t=ie(i,e);He(t);let s=0;s=ze(i,s),s=Ge(e,s);for(let r=0;r<e.length;r++)s=ae(e[r],s);return g.subarray(0,s)}function It(i,e){let t=Rt(e);He(t);let s=0;g.set(ve,s),s+=8,s=ce(i,s);for(let r=0;r<e.length;r++){let n=e[r],o=s;s+=4;let a=s;Array.isArray(n)?s=ne(n[0],n,s,1):n.packets!==void 0?s=Pt(n.timeTag,n.packets,s):s=ne(n.address,n.args||[],s);let c=s-a;T.setUint32(o,c,!1)}return g.subarray(0,s)}function Dt(i,e,t=[]){let s=20+ie(e,t);He(s);let r=0;g.set(ve,r),r+=8,r=ce(i,r);let n=r;r+=4;let o=r;r=ze(e,r),r=Ge(t,r);for(let a=0;a<t.length;a++)r=ae(t[a],r);return T.setUint32(n,r-o,!1),g.subarray(0,r)}function ne(i,e,t,s=0){t=ze(i,t),t=Ge(e,t,s);for(let r=s;r<e.length;r++)t=ae(e[r],t);return t}function Pt(i,e,t){g.set(ve,t),t+=8,t=ce(i,t);for(let s=0;s<e.length;s++){let r=e[s],n=t;t+=4;let o=t;Array.isArray(r)?t=ne(r[0],r,t,1):r.packets!==void 0?t=Pt(r.timeTag,r.packets,t):t=ne(r.address,r.args||[],t),T.setUint32(n,t-o,!1)}return t}function ze(i,e){let t=Be.get(i);if(t)return g.set(t,e),e+t.length;let s=e;if(e=Fe(i,e),Be.size<ar){let r=g.slice(s,e);Be.set(i,r)}return e}function Fe(i,e){let t=!1;for(let s=0;s<i.length;s++)if(i.charCodeAt(s)>=128){t=!0;break}if(t){let s=lr.encodeInto(i,g.subarray(e));e+=s.written}else for(let s=0;s<i.length;s++)g[e++]=i.charCodeAt(s);for(g[e++]=0;e&3;)g[e++]=0;return e}function Ge(i,e,t=0){g[e++]=wt;for(let s=t;s<i.length;s++){let r=i[s],n=typeof r;if(n==="number")g[e++]=Number.isInteger(r)?Ue:Ie;else if(n==="string")g[e++]=De;else if(n==="boolean")g[e++]=r?Le:ke;else if(r instanceof Uint8Array||r instanceof ArrayBuffer)g[e++]=Pe;else if(r&&r.type==="int")g[e++]=Ue;else if(r&&r.type==="float")g[e++]=Ie;else if(r&&r.type==="string")g[e++]=De;else if(r&&r.type==="blob")g[e++]=Pe;else if(r&&r.type==="bool")g[e++]=r.value?Le:ke;else if(r&&r.type==="int64")g[e++]=Ct;else if(r&&r.type==="double")g[e++]=Mt;else if(r&&r.type==="timetag")g[e++]=Bt;else if(r&&r.type==="uuid")g[e++]=Ot;else throw r==null?new Error(`OSC argument at index ${s} is ${r}`):new Error(`Unknown OSC argument type at index ${s}: ${n}`)}for(g[e++]=0;e&3;)g[e++]=0;return e}function ae(i,e){let t=typeof i;if(t==="number")return Number.isInteger(i)?(T.setInt32(e,i,!1),e+4):(T.setFloat32(e,i,!1),e+4);if(t==="string")return Fe(i,e);if(t==="boolean")return e;if(i instanceof Uint8Array){let s=i.length;for(T.setUint32(e,s,!1),e+=4,g.set(i,e),e+=s;e&3;)g[e++]=0;return e}if(i instanceof ArrayBuffer)return ae(new Uint8Array(i),e);if(i&&i.type==="int")return T.setInt32(e,i.value,!1),e+4;if(i&&i.type==="float")return T.setFloat32(e,i.value,!1),e+4;if(i&&i.type==="string")return Fe(i.value,e);if(i&&i.type==="blob"){let s=i.value instanceof Uint8Array?i.value:new Uint8Array(i.value),r=s.length;for(T.setUint32(e,r,!1),e+=4,g.set(s,e),e+=r;e&3;)g[e++]=0;return e}return i&&i.type==="bool"?e:i&&i.type==="int64"?(T.setBigInt64(e,BigInt(i.value),!1),e+8):i&&i.type==="double"?(T.setFloat64(e,i.value,!1),e+8):i&&i.type==="timetag"?ce(i.value,e):i&&i.type==="uuid"?(g.set(i.value,e),e+16):e}function ce(i,e){if(i===1||i===null||i===void 0)return T.setUint32(e,0,!1),T.setUint32(e+4,1,!1),e+8;if(Array.isArray(i)){if(i.length!==2)throw new Error(`TimeTag array must have exactly 2 elements [seconds, fraction], got ${i.length}`);return T.setUint32(e,i[0]>>>0,!1),T.setUint32(e+4,i[1]>>>0,!1),e+8}if(typeof i!="number")throw new TypeError(`TimeTag must be a number, array, null, or undefined, got ${typeof i}`);i>1&&i<Ne&&console.warn(`TimeTag ${i} looks like a Unix timestamp (< NTP_EPOCH_OFFSET). Did you mean to add NTP_EPOCH_OFFSET (2208988800)?`);let t=i>>>0,s=(i-Math.floor(i))*oe>>>0;return T.setUint32(e,t,!1),T.setUint32(e+4,s,!1),e+8}function G(i){return i instanceof Uint8Array||(i=new Uint8Array(i)),i[0]===35&&i[1]===98?fr(i):ur(i)}function ur(i){i instanceof Uint8Array||(i=new Uint8Array(i));let e=new DataView(i.buffer,i.byteOffset,i.byteLength),t=0,[s,r]=Re(i,t);if(t=r,t>=i.length||i[t]!==wt)return[s];let[n,o]=Re(i,t);t=o;let a=[s];for(let c=1;c<n.length;c++)switch(n.charCodeAt(c)){case Ue:a.push(e.getInt32(t,!1)),t+=4;break;case Ie:a.push(e.getFloat32(t,!1)),t+=4;break;case De:let[u,f]=Re(i,t);a.push(u),t=f;break;case Pe:let h=e.getUint32(t,!1);t+=4,a.push(i.slice(t,t+h)),t+=h,t=t+3&-4;break;case Ct:a.push(e.getBigInt64(t,!1)),t+=8;break;case Mt:a.push(e.getFloat64(t,!1)),t+=8;break;case Le:a.push(!0);break;case ke:a.push(!1);break;case Bt:let S=e.getUint32(t,!1),m=e.getUint32(t+4,!1);a.push(S+m/oe),t+=8;break;case Ot:a.push({type:"uuid",value:i.slice(t,t+16)}),t+=16;break}return a}function fr(i){i instanceof Uint8Array||(i=new Uint8Array(i));let e=new DataView(i.buffer,i.byteOffset,i.byteLength),t=8,s=e.getUint32(t,!1),r=e.getUint32(t+4,!1),n=s+r/oe;t+=8;let o=[];for(;t<i.length;){let a=e.getUint32(t,!1);if(t+=4,a>0&&t+a<=i.length){let c=i.subarray(t,t+a);o.push(G(c))}t+=a}return{timeTag:n,packets:o}}function Re(i,e){let t=e;for(;t<i.length&&i[t]!==0;)t++;let s=cr.decode(i.subarray(e,t));return t++,t=t+3&-4,Oe[0]=s,Oe[1]=t,Oe}function le(i){return i.slice()}function hr(i){return!i||i.length<8?!1:i[0]===35&&i[1]===98}function $e(i){if(!hr(i))return null;let e=new DataView(i.buffer,i.byteOffset,i.byteLength),t=e.getUint32(8,!1),s=e.getUint32(12,!1);return t+s/oe}var $={totalPages:368,ringBufferReserved:3145728,bufferPoolOffset:19922944,bufferPoolSize:4194304,maxBufferPoolSize:268435456,get totalMemory(){return this.bufferPoolOffset+this.bufferPoolSize},get maxTotalMemory(){return this.bufferPoolOffset+this.maxBufferPoolSize},get wasmHeapSize(){return this.bufferPoolOffset-this.ringBufferReserved}};var Lt={numBuffers:1024,maxNodes:1024,maxGraphDefs:1024,maxWireBufs:64,numAudioBusChannels:128,numInputBusChannels:2,numOutputBusChannels:2,numControlBusChannels:4096,bufLength:128,realTimeMemorySize:8192,numRGens:64,realTime:!1,memoryLocking:!1,loadGraphDefs:0,preferredSampleRate:0,verbosity:0};var pr=1e4,mr=5e3,yr=150,gr=new Set(["/b_alloc","/b_allocRead","/b_allocReadChannel","/b_allocFile"]),b=[];for(let i=0;i<256;i++)b[i]=i.toString(16).padStart(2,"0");function Sr(i){return b[i[0]]+b[i[1]]+b[i[2]]+b[i[3]]+"-"+b[i[4]]+b[i[5]]+"-"+b[i[6]]+b[i[7]]+"-"+b[i[8]]+b[i[9]]+"-"+b[i[10]]+b[i[11]]+b[i[12]]+b[i[13]]+b[i[14]]+b[i[15]]}function Ft(i){return"\u2026"+b[i[13]]+b[i[14]]+b[i[15]]}function kt(i,e){if(i&&i.type==="uuid"&&i.value)return Ft(i.value);if(i instanceof Uint8Array||i instanceof ArrayBuffer)return`<${i.byteLength||i.length} bytes>`;let t=JSON.stringify(i);return e&&t.length>e?t.slice(0,e)+"...":t}function Y(i){return String(i).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function xt(i,e,t){if(i&&i.type==="uuid"&&i.value)return`<span class="supersonic-scsynth-string" title="${Sr(i.value)}">${Ft(i.value)}</span>`;let s=i,r=null;if(typeof i=="object"&&i!==null&&i.value!==void 0&&(s=i.value,r=i.type),r==="b"||s instanceof Uint8Array||s instanceof ArrayBuffer)return`<span class="supersonic-scsynth-binary">&lt;${s.byteLength??s.length??"?"} bytes&gt;</span>`;let n=r==="f"||r===null&&typeof s=="number"&&!Number.isInteger(s),o=r==="i"||r===null&&Number.isInteger(s),c=e==="/s_new"&&t>=4&&(t-4)%2===0&&typeof s=="string";return n?`<span class="supersonic-scsynth-float">${parseFloat(s.toFixed(3))}</span>`:o?`<span class="supersonic-scsynth-int">${s}</span>`:c?`<span class="supersonic-scsynth-param">${Y(s)}</span>`:typeof s=="string"?`<span class="supersonic-scsynth-string">${Y(JSON.stringify(s))}</span>`:`<span class="supersonic-scsynth-string">${Y(s)}</span>`}function Ye(i,e,t,s,r){let n=i[0],o=i.slice(1),a=s&&t?(t-s).toFixed(2):"",c=`<span class="supersonic-scsynth-seq">[${e}]</span>`;if(a&&(c+=` <span class="supersonic-scsynth-time">${a}</span>`),r!==void 0&&(c+=` <span class="supersonic-scsynth-source">ch${r}</span>`),c+=` <span class="supersonic-scsynth-address">${Y(n)}</span>`,o.length>0){let l=o.map((u,f)=>xt(u,n,f)).join(", ");c+=" "+l}return c}function Er(i,e,t,s,r){if(!i.packets)return Ye(i,e,t,s,r);if(i.packets.length===1)return Ye(i.packets[0],e,t,s,r);let n=s&&t?(t-s).toFixed(2):"",o=`<span class="supersonic-scsynth-seq">[${e}]</span>`;n&&(o+=` <span class="supersonic-scsynth-time">${n}</span>`),r!==void 0&&(o+=` <span class="supersonic-scsynth-source">ch${r}</span>`),o+=` <span class="supersonic-scsynth-bundle">Bundle (${i.packets.length})</span>`;for(let a of i.packets){let c=a[0],l=a.slice(1);o+=`<br><span class="supersonic-scsynth-address">${Y(c)}</span>`,l.length>0&&(o+=" "+l.map((u,f)=>xt(u,c,f)).join(", "))}return o}var We=class i{static osc={encodeMessage:(e,t)=>le(Ut(e,t)),encodeBundle:(e,t)=>le(It(e,t)),decode:e=>G(e),encodeSingleBundle:(e,t,s)=>le(Dt(e,t,s)),readTimetag:e=>pe(e),ntpNow:()=>A(),NTP_EPOCH_OFFSET:Ne};static#t=null;static getMetricsSchema(){return this.#t??={metrics:{scsynthProcessCount:{offset:0,type:"counter",unit:"count",description:"Audio process() calls"},scsynthMessagesProcessed:{offset:1,type:"counter",unit:"count",description:"OSC messages processed by scsynth"},scsynthMessagesDropped:{offset:2,type:"counter",unit:"count",description:"Messages dropped (ring buffer full)"},scsynthSchedulerDepth:{offset:3,type:"gauge",unit:"count",description:"Current scheduler queue depth"},scsynthSchedulerPeakDepth:{offset:4,type:"gauge",unit:"count",description:"Peak scheduler queue depth (high water mark)"},scsynthSchedulerDropped:{offset:5,type:"counter",unit:"count",description:"Scheduled events dropped"},scsynthSequenceGaps:{offset:6,type:"counter",unit:"count",description:"Messages lost in transit from JS to scsynth"},scsynthWasmErrors:{offset:7,type:"counter",unit:"count",description:"WASM execution errors in audio worklet"},scsynthSchedulerLates:{offset:8,type:"counter",unit:"count",description:"Bundles executed after their scheduled time"},preschedulerPending:{offset:9,type:"gauge",unit:"count",description:"Events waiting to be scheduled"},preschedulerPendingPeak:{offset:10,type:"gauge",unit:"count",description:"Peak pending events"},preschedulerBundlesScheduled:{offset:11,type:"counter",unit:"count",description:"Bundles scheduled"},preschedulerDispatched:{offset:12,type:"counter",unit:"count",description:"Events sent to worklet"},preschedulerEventsCancelled:{offset:13,type:"counter",unit:"count",description:"Events cancelled"},preschedulerMinHeadroomMs:{offset:14,type:"gauge",unit:"ms",description:"Smallest time gap between JS prescheduler dispatch and scsynth scheduler execution"},preschedulerLates:{offset:15,type:"counter",unit:"count",description:"Bundles dispatched after their scheduled execution time"},preschedulerRetriesSucceeded:{offset:16,type:"counter",unit:"count",description:"Retries that succeeded"},preschedulerRetriesFailed:{offset:17,type:"counter",unit:"count",description:"Retries that failed"},preschedulerRetryQueueSize:{offset:18,type:"gauge",unit:"count",description:"Current retry queue size"},preschedulerRetryQueuePeak:{offset:19,type:"gauge",unit:"count",description:"Peak retry queue size"},preschedulerMessagesRetried:{offset:20,type:"counter",unit:"count",description:"Messages that needed retry"},preschedulerTotalDispatches:{offset:21,type:"counter",unit:"count",description:"Total dispatch attempts"},preschedulerBypassed:{offset:22,type:"counter",unit:"count",description:"Messages sent directly from JS to scsynth, bypassing prescheduler (aggregate)"},preschedulerMaxLateMs:{offset:23,type:"gauge",unit:"ms",description:"Maximum lateness at prescheduler (ms)"},oscOutMessagesSent:{offset:24,type:"counter",unit:"count",description:"OSC messages sent from JS to scsynth"},oscOutBytesSent:{offset:25,type:"counter",unit:"bytes",description:"Total bytes sent from JS to scsynth"},oscInMessagesReceived:{offset:26,type:"counter",unit:"count",description:"OSC replies received from scsynth to JS"},oscInBytesReceived:{offset:27,type:"counter",unit:"bytes",description:"Total bytes received from scsynth to JS"},oscInMessagesDropped:{offset:28,type:"counter",unit:"count",description:"Replies lost in transit from scsynth to JS"},oscInCorrupted:{offset:29,type:"counter",unit:"count",description:"Corrupted messages detected from scsynth to JS"},debugMessagesReceived:{offset:30,type:"counter",unit:"count",description:"Debug messages from scsynth"},debugBytesReceived:{offset:31,type:"counter",unit:"bytes",description:"Debug bytes received"},inBufferUsedBytes:{offset:32,type:"gauge",unit:"bytes",description:"Bytes used in IN ring buffer"},outBufferUsedBytes:{offset:33,type:"gauge",unit:"bytes",description:"Bytes used in OUT ring buffer"},debugBufferUsedBytes:{offset:34,type:"gauge",unit:"bytes",description:"Bytes used in DEBUG ring buffer"},inBufferPeakBytes:{offset:35,type:"gauge",unit:"bytes",description:"Peak bytes used in IN ring buffer"},outBufferPeakBytes:{offset:36,type:"gauge",unit:"bytes",description:"Peak bytes used in OUT ring buffer"},debugBufferPeakBytes:{offset:37,type:"gauge",unit:"bytes",description:"Peak bytes used in DEBUG ring buffer"},bypassNonBundle:{offset:38,type:"counter",unit:"count",description:"Plain OSC messages (not bundles) that bypassed prescheduler"},bypassImmediate:{offset:39,type:"counter",unit:"count",description:"Bundles with timetag 0 or 1 that bypassed prescheduler"},bypassNearFuture:{offset:40,type:"counter",unit:"count",description:"Bundles within bypass lookahead threshold that bypassed prescheduler"},bypassLate:{offset:41,type:"counter",unit:"count",description:"Timestamped OSC bundles arriving late into SuperSonic bypassing prescheduler"},scsynthSchedulerMaxLateMs:{offset:42,type:"gauge",unit:"ms",description:"Maximum lateness observed in scsynth scheduler (ms)"},scsynthSchedulerLastLateMs:{offset:43,type:"gauge",unit:"ms",description:"Most recent late magnitude in scsynth scheduler (ms)"},scsynthSchedulerLastLateTick:{offset:44,type:"gauge",unit:"count",description:"Process count when last scsynth late occurred"},ringBufferDirectWriteFails:{offset:45,type:"counter",unit:"count",description:"SAB mode only: optimistic direct writes attempted but failed due to ring buffer lock not being available (delivered via prescheduler instead)"},driftOffsetMs:{offset:46,type:"gauge",unit:"ms",signed:!0,description:"Clock drift between AudioContext and wall clock"},clockOffsetMs:{offset:47,type:"gauge",unit:"ms",signed:!0,description:"Clock offset for multi-system sync"},audioContextState:{offset:48,type:"enum",values:["unknown","running","suspended","closed","interrupted"],description:"AudioContext state"},bufferPoolUsedBytes:{offset:49,type:"gauge",unit:"bytes",description:"Buffer pool bytes used"},bufferPoolAvailableBytes:{offset:50,type:"gauge",unit:"bytes",description:"Buffer pool bytes available"},bufferPoolAllocations:{offset:51,type:"counter",unit:"count",description:"Total buffer allocations"},loadedSynthDefs:{offset:52,type:"gauge",unit:"count",description:"Number of loaded synthdefs"},scsynthSchedulerCapacity:{offset:53,type:"constant",unit:"count",description:"Maximum scheduler queue size"},preschedulerCapacity:{offset:54,type:"constant",unit:"count",description:"Maximum pending events in prescheduler"},inBufferCapacity:{offset:55,type:"constant",unit:"bytes",description:"IN ring buffer capacity"},outBufferCapacity:{offset:56,type:"constant",unit:"bytes",description:"OUT ring buffer capacity"},debugBufferCapacity:{offset:57,type:"constant",unit:"bytes",description:"DEBUG ring buffer capacity"},mode:{offset:58,type:"enum",values:["sab","postMessage"],description:"Transport mode"},glitchCount:{offset:59,type:"counter",unit:"count",description:"Chrome only: audio underrun/glitch events"},glitchDurationMs:{offset:60,type:"gauge",unit:"ms",description:"Chrome only: total silence from audio underruns"},averageLatencyUs:{offset:61,type:"gauge",unit:"us",description:"Chrome only: average audio output latency"},maxLatencyUs:{offset:62,type:"gauge",unit:"us",description:"Chrome only: maximum audio output latency"},audioHealthPct:{offset:63,type:"gauge",unit:"%",description:"Cross-browser: fraction of expected audio frames delivered (100% = no issues)"},totalFramesDurationMs:{offset:64,type:"counter",unit:"ms",description:"Chrome only: total audio rendered duration"},hasPlaybackStats:{offset:65,type:"gauge",unit:"bool",description:"1 if Chrome playbackStats API is available, 0 otherwise"},bufferPoolTotalCapacity:{offset:66,type:"gauge",unit:"bytes",description:"Buffer pool committed capacity (grows on demand)"},bufferPoolMaxCapacity:{offset:67,type:"gauge",unit:"bytes",description:"Buffer pool hard ceiling"},bufferPoolGrowthCount:{offset:68,type:"counter",unit:"count",description:"Number of buffer pool growth events"},bufferPoolPoolCount:{offset:69,type:"gauge",unit:"count",description:"Number of buffer pool segments"}},layout:{panels:[{title:"OSC Out",rows:[{label:"sent",cells:[{key:"oscOutMessagesSent"}]},{label:"bytes",cells:[{key:"oscOutBytesSent",kind:"muted",format:"bytes"}]},{label:"bypass",cells:[{key:"preschedulerBypassed",kind:"green"}]},{label:"lost",cells:[{key:"scsynthSequenceGaps",kind:"error"}]}]},{title:"Bypass",rows:[{label:"msg",cells:[{key:"bypassNonBundle",kind:"muted"}]},{label:"imm",cells:[{key:"bypassImmediate",kind:"muted"}]},{label:"near",cells:[{key:"bypassNearFuture",kind:"muted"}]},{label:"late",cells:[{key:"bypassLate",kind:"muted"}]}]},{title:"OSC In",rows:[{label:"received",cells:[{key:"oscInMessagesReceived"}]},{label:"bytes",cells:[{key:"oscInBytesReceived",kind:"muted",format:"bytes"}]},{label:"dropped",cells:[{key:"oscInMessagesDropped",kind:"error"}]},{label:"corrupted",cells:[{key:"oscInCorrupted",kind:"error"}]}]},{title:"Presched Flow",rows:[{label:"pending",tooltip:"Current pending events | peak pending events",cells:[{key:"preschedulerPending"},{sep:" | "},{key:"preschedulerPendingPeak",kind:"muted"}]},{label:"scheduled",cells:[{key:"preschedulerBundlesScheduled"}]},{label:"dispatched",cells:[{key:"preschedulerDispatched",kind:"dim"}]},{label:"min slack",cells:[{key:"preschedulerMinHeadroomMs",kind:"dim",format:"headroom"},{text:" ms",kind:"muted"}]}]},{title:"Presched Health",rows:[{label:"lates",tooltip:"Bundles dispatched after their scheduled time (count and max lateness in ms)",cells:[{key:"preschedulerLates",kind:"error"},{sep:" ("},{key:"preschedulerMaxLateMs",kind:"dim"},{text:" ms max)",kind:"muted"}]},{label:"cancelled",cells:[{key:"preschedulerEventsCancelled",kind:"error"}]},{label:"retried",tooltip:"Messages retried | succeeded | failed",cells:[{key:"preschedulerMessagesRetried",kind:"dim"},{sep:" | "},{key:"preschedulerRetriesSucceeded",kind:"green"},{sep:" | "},{key:"preschedulerRetriesFailed",kind:"error"}]},{label:"retry queue",tooltip:"Current retry queue size | peak size",cells:[{key:"preschedulerRetryQueueSize"},{sep:" | "},{key:"preschedulerRetryQueuePeak",kind:"muted"}]}]},{title:"scsynth Scheduler",rows:[{label:"queue",tooltip:"Current scheduler queue depth | peak depth",cells:[{key:"scsynthSchedulerDepth"},{sep:" | "},{key:"scsynthSchedulerPeakDepth",kind:"muted"}]},{label:"dropped",cells:[{key:"scsynthSchedulerDropped",kind:"error"}]},{label:"lates",cells:[{key:"scsynthSchedulerLates",kind:"error"}]},{label:"max | last",tooltip:"Maximum lateness observed | most recent late magnitude (ms)",cells:[{key:"scsynthSchedulerMaxLateMs",kind:"error"},{sep:" | "},{key:"scsynthSchedulerLastLateMs",kind:"dim"},{text:" ms",kind:"muted"}]}]},{title:"scsynth",rows:[{label:"ticks",tooltip:"Audio process() callback count and OSC messages processed",cells:[{key:"scsynthProcessCount",kind:"dim"},{sep:" | "},{key:"scsynthMessagesProcessed",kind:"muted"},{text:" msgs",kind:"muted"}]},{label:"dropped",cells:[{key:"scsynthMessagesDropped",kind:"error"}]},{label:"drift",cells:[{key:"driftOffsetMs",format:"signed"},{text:" ms",kind:"muted"}]},{label:"debug",tooltip:"Debug messages from scsynth (count and bytes)",cells:[{key:"debugMessagesReceived",kind:"muted"},{text:" ("},{key:"debugBytesReceived",kind:"muted",format:"bytes"},{text:")"}]}]},{title:"Ring Buffer Level",class:"wide",rows:[{type:"bar",label:"in",usedKey:"inBufferUsedBytes",peakKey:"inBufferPeakBytes",capacityKey:"inBufferCapacity",color:"blue"},{type:"bar",label:"out",usedKey:"outBufferUsedBytes",peakKey:"outBufferPeakBytes",capacityKey:"outBufferCapacity",color:"green"},{type:"bar",label:"dbg",usedKey:"debugBufferUsedBytes",peakKey:"debugBufferPeakBytes",capacityKey:"debugBufferCapacity",color:"purple"},{label:"direct write fails",cells:[{key:"ringBufferDirectWriteFails",kind:"error"}]}]},{title:"Buffers & SynthDefs",rows:[{label:"buf used",cells:[{key:"bufferPoolUsedBytes",format:"bytes"}]},{label:"buf free",cells:[{key:"bufferPoolAvailableBytes",kind:"green",format:"bytes"}]},{label:"buf allocs",cells:[{key:"bufferPoolAllocations",kind:"dim"}]},{label:"synthdefs",cells:[{key:"loadedSynthDefs"}]}]},{title:"AudioWorklet",rows:[{label:"health",tooltip:"AudioContext state and audio health percentage (fraction of expected frames delivered)",cells:[{key:"audioContextState",kind:"green",format:"enum"},{sep:" | "},{key:"audioHealthPct",kind:"green",format:"percent"},{text:" %",kind:"muted"}]},{label:"glitches",tooltip:"Chrome only: audio underrun/glitch events and total silence duration",cells:[{key:"glitchCount",kind:"error",format:"chromeOnly"},{sep:" ("},{key:"glitchDurationMs",kind:"error",format:"chromeOnly"},{text:" ms)",kind:"muted"}]},{label:"latency",tooltip:"Chrome only: avg | max audio output latency in ms",cells:[{key:"averageLatencyUs",kind:"dim",format:"chromeLatencyUs"},{sep:" | "},{key:"maxLatencyUs",kind:"dim",format:"chromeLatencyUs"},{text:" ms",kind:"muted"}]},{label:"WASM errors",cells:[{key:"scsynthWasmErrors",kind:"error"}]}]}]},sentinels:{HEADROOM_UNSET:4294967295}}}static getTreeSchema(){return{nodeCount:{type:"number",description:"Total nodes in tree"},version:{type:"number",description:"Increments on any tree change, useful for detecting updates"},droppedCount:{type:"number",description:"Nodes that exceeded mirror capacity (tree may be incomplete)"},root:{type:"object",description:"Root node of the tree (always a group with id 0)",schema:{id:{type:"number",description:"Unique node ID"},type:{type:"string",values:["group","synth"],description:"Node type"},defName:{type:"string",description:"Synthdef name (synths only, empty for groups)"},children:{type:"array",description:"Child nodes (recursive)",itemSchema:"(self)"}}}}}static getRawTreeSchema(){return{nodeCount:{type:"number",description:"Total nodes in tree"},version:{type:"number",description:"Increments on any tree change, useful for detecting updates"},droppedCount:{type:"number",description:"Nodes that exceeded mirror capacity (tree may be incomplete)"},nodes:{type:"array",description:"Flat array of all nodes with internal linkage pointers",itemSchema:{id:{type:"number",description:"Unique node ID"},parentId:{type:"number",description:"Parent node ID (-1 for root)"},isGroup:{type:"boolean",description:"True if group, false if synth"},prevId:{type:"number",description:"Previous sibling node ID (-1 if none)"},nextId:{type:"number",description:"Next sibling node ID (-1 if none)"},headId:{type:"number",description:"First child node ID (groups only, -1 if empty)"},defName:{type:"string",description:"Synthdef name (synths only, empty for groups)"}}}}}#e;#s;#f=null;#o;#c;#n;#i;#l;#u;#d;#E;#_;#p;#h;#m;#b;#y;#r;#a;#g;#S;#C;#A;#w;#M=1e3;#R=null;#O=null;#I=0;#B=[];#D=null;#U=Promise.resolve();#$(e){let t=[["numBuffers",1,65535],["maxNodes",1],["maxGraphDefs",1],["maxWireBufs",1],["numAudioBusChannels",1],["numInputBusChannels",0],["numOutputBusChannels",1,128],["numControlBusChannels",1],["realTimeMemorySize",1],["numRGens",1],["preferredSampleRate",0,384e3],["verbosity",0,4]];for(let[s,r,n]of t){let o=e[s];if(typeof o!="number"||!Number.isFinite(o))throw new Error(`scsynthOptions.${s} must be a finite number, got: ${o}`);if(o<r)throw new Error(`scsynthOptions.${s} must be >= ${r}, got: ${o}`);if(n!==void 0&&o>n)throw new Error(`scsynthOptions.${s} must be <= ${n}, got: ${o}`)}if(e.bufLength!==128)throw new Error(`scsynthOptions.bufLength must be 128 (WebAudio API constraint), got: ${e.bufLength}`);for(let s of["realTime","memoryLocking"])if(typeof e[s]!="boolean")throw new Error(`scsynthOptions.${s} must be a boolean, got: ${typeof e[s]}`);if(e.loadGraphDefs!==0&&e.loadGraphDefs!==1)throw new Error(`scsynthOptions.loadGraphDefs must be 0 or 1, got: ${e.loadGraphDefs}`);if(e.preferredSampleRate!==0&&e.preferredSampleRate<8e3)throw new Error(`scsynthOptions.preferredSampleRate must be 0 (auto) or >= 8000, got: ${e.preferredSampleRate}`)}#Y(e){let t=e?{...$,...e}:{...$};return t.totalMemory=t.bufferPoolOffset+t.bufferPoolSize,t.maxTotalMemory=t.bufferPoolOffset+t.maxBufferPoolSize,t.wasmHeapSize=t.bufferPoolOffset-t.ringBufferReserved,t}constructor(e={}){this.#p=!1,this.#h=!1,this.#m=null,this.#b={},this.#y=null,this.#a=new J,this.#g=new ee({mode:e.mode||"postMessage"}),this.#C=new re({}),this.#e=null,this.#s=null,this.#o=null,this.#n=null,this.loadedSynthDefs=new Map;let t=e.baseURL||null,s=e.coreBaseURL||t,r=e.workerBaseURL||(t?`${t}workers/`:null),n=e.wasmBaseURL||(s?`${s}wasm/`:null);if(!r||!n)throw new Error(`SuperSonic requires explicit URL configuration.
5
+ Or install: npm install supersonic-scsynth-samples`);return this.#e+e}#T(e){if(!Number.isInteger(e)||e<0||e>=this.MAX_BUFFERS)throw new Error(`Invalid buffer number ${e} (must be 0-${this.MAX_BUFFERS-1})`)}async#t(e,t,s){let r=null,n=null,o=!1,a=await this.#w(e),c=!1;try{await this.#R(e);let{ptr:u,sizeBytes:l,numFrames:f,numChannels:h,sampleRate:y,source:p,...d}=await s();r=u;let{uuid:m,allocationComplete:g}=this.#M(e,t);n=m,this.#B(e,r,l,m,g,{numFrames:f,numChannels:h,sampleRate:y,source:p}),o=!0;let _=this.#I(e,m,g);return a(),c=!0,{ptr:r,uuid:m,allocationComplete:_,numFrames:f,numChannels:h,sampleRate:y,...d}}catch(u){throw o&&n?this.#O(e,n,!1):r&&this.#i.free(r),u}finally{c||a()}}async prepareFromBlob(e){let{bufnum:t,blob:s,startFrame:r=0,numFrames:n=0,channels:o=null}=e;if(this.#T(t),!s||!(s instanceof ArrayBuffer||ArrayBuffer.isView(s)))throw new Error("/b_allocFile requires audio data as ArrayBuffer or typed array");let a=await this.#E({source:s,startFrame:r,numFrames:n,channels:o});return this.#g(t,3e4,a,null)}async prepareFromFile(e){let{bufnum:t,path:s,startFrame:r=0,numFrames:n=0,channels:o=null}=e;this.#T(t);let a=await this.#E({source:s,startFrame:r,numFrames:n,channels:o});return this.#g(t,6e4,a,a.sourceInfo)}async prepareEmpty(e){let{bufnum:t,numFrames:s,numChannels:r=1,sampleRate:n=null}=e;if(this.#T(t),!Number.isFinite(s)||s<=0)throw new Error(`/b_alloc requires a positive number of frames (got ${s})`);if(!Number.isFinite(r)||r<=0)throw new Error(`/b_alloc requires a positive channel count (got ${r})`);let o=Math.floor(s),a=Math.floor(r),c=o*a+(this.GUARD_BEFORE+this.GUARD_AFTER)*a,l={interleaved:new Float32Array(c),numFrames:o,numChannels:a,sampleRate:n||this.#l.sampleRate};return this.#g(t,5e3,l,null)}#u(e,t){return!e||e.length===0?Array.from({length:t},(s,r)=>r):(e.forEach(s=>{if(!Number.isInteger(s)||s<0||s>=t)throw new Error(`Channel ${s} is out of range (file has ${t} channels)`)}),e)}async#h(e){let t=this.#i.malloc(e);return t===0&&this.#i.canGrow()&&await this.#i.grow(e)&&(t=this.#i.malloc(e)),t}async#y(e){let t=e*4,s=await this.#h(t);if(s===0){let r=this.#i.stats(),n=((r.available||0)/(1024*1024)).toFixed(2),o=((r.total||0)/(1024*1024)).toFixed(2),a=((this.#i.maxCapacity||0)/(1024*1024)).toFixed(2),c=(t/(1024*1024)).toFixed(2);throw new Error(`Buffer pool allocation failed: requested ${c}MB, available ${n}MB of ${o}MB total (max ${a}MB)`)}return s}async#b(e,t){if(this.#s==="sab"){let s=this.#a?.buffer||this.#o;new Float32Array(s,e,t.length).set(t)}else{let s=crypto.randomUUID(),r=new Promise((o,a)=>{let c=setTimeout(()=>{a(new Error("Buffer copy to WASM memory timed out"))},1e4),u=l=>{let f=l.data;f.type==="bufferCopied"&&f.copyId===s&&(this.#m.removeEventListener("message",u),clearTimeout(c),f.success?o():a(new Error(f.error||"Buffer copy failed")))};this.#m.addEventListener("message",u)}),n=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);this.#m.postMessage({type:"copyBufferData",copyId:s,ptr:e,data:n},[n]),await r}}#A(e,t,s){return new Promise((r,n)=>{let o=setTimeout(()=>{this.#c.delete(e),n(new Error(`Buffer ${t} allocation timeout (${s}ms)`))},s);this.#c.set(e,{resolve:r,reject:n,timeout:o})})}#M(e,t){let s=crypto.randomUUID(),r=this.#A(s,e,t);return{uuid:s,allocationComplete:r}}async#w(e){let t=this.#f.get(e)||Promise.resolve(),s,r=new Promise(n=>{s=n});return this.#f.set(e,t.then(()=>r)),await t,()=>{s&&(s(),s=null),this.#f.get(e)===r&&this.#f.delete(e)}}#B(e,t,s,r,n,o={}){let a=this.#n.get(e),c={ptr:t,size:s,numFrames:o.numFrames||0,numChannels:o.numChannels||1,sampleRate:o.sampleRate||48e3,pendingToken:r,pendingPromise:n,previousAllocation:a?{ptr:a.ptr,size:a.size}:null,source:o.source||null};return this.#n.set(e,c),c}async#R(e){let t=this.#n.get(e);if(t&&t.pendingToken&&t.pendingPromise)try{await t.pendingPromise}catch{}}#I(e,t,s){return!s||typeof s.then!="function"?(this.#O(e,t,!0),Promise.resolve()):s.then(r=>(this.#O(e,t,!0),r)).catch(r=>{throw this.#O(e,t,!1),r})}#O(e,t,s){let r=this.#n.get(e);if(!r||r.pendingToken!==t)return;let n=r.previousAllocation;if(s){r.pendingToken=null,r.pendingPromise=null,r.previousAllocation=null,n?.ptr&&this.#i.free(n.ptr);return}r.ptr&&this.#i.free(r.ptr),r.pendingPromise=null,n?.ptr?this.#n.set(e,{ptr:n.ptr,size:n.size,pendingToken:null,previousAllocation:null}):this.#n.delete(e)}handleBufferFreed(e){let t=typeof e[0]=="bigint"?Number(e[0]):e[0],s=typeof e[1]=="bigint"?Number(e[1]):e[1],r=this.#n.get(t);if(!r){typeof s=="number"&&s!==0&&this.#i.free(s);return}if(typeof s=="number"&&s===r.ptr){this.#i.free(r.ptr),this.#n.delete(t);return}if(typeof s=="number"&&r.previousAllocation&&r.previousAllocation.ptr===s){this.#i.free(s),r.previousAllocation=null;return}this.#i.free(r.ptr),this.#n.delete(t)}handleBufferAllocated(e){let t=e[0],s=e[1],r=this.#c.get(t);r&&(clearTimeout(r.timeout),r.resolve({bufnum:s}),this.#c.delete(t))}async allocate(e){return this.#h(e*4)}free(e){return this.#i.free(e)}getView(e,t){let s=this.#a?.buffer||this.#o;return new Float32Array(s,e,t)}getStats(){return this.#i?this.#i.stats():{total:0,available:0,used:0,allocations:0}}getGrowthStats(){return this.#i?{totalCapacity:this.#i.totalCapacity,maxCapacity:this.#i.maxCapacity,growthCount:this.#i.growthCount,poolCount:this.#i.poolCount}:{totalCapacity:0,maxCapacity:0,growthCount:0,poolCount:0}}async sampleInfo({source:e,startFrame:t=0,numFrames:s=0,channels:r=null}){let n=await this.#E({source:e,startFrame:t,numFrames:s,channels:r});return{hash:await this.#S(n.interleaved),source:n.sourceInfo?.path||null,numFrames:n.numFrames,numChannels:n.numChannels,sampleRate:n.sampleRate,duration:n.sampleRate>0?n.numFrames/n.sampleRate:0}}getAllocatedBuffers(){let e=[];for(let[t,s]of this.#n.entries())!s||!s.ptr||e.push({bufnum:t,ptr:s.ptr,numFrames:s.numFrames,numChannels:s.numChannels,sampleRate:s.sampleRate,source:s.source||null,hash:s.hash||null});return e}updateAudioContext(e){if(!e)throw new Error("BufferManager.updateAudioContext requires audioContext");this.#l=e}destroy(){for(let[e,t]of this.#c.entries())clearTimeout(t.timeout),t.reject(new Error("BufferManager destroyed"));this.#c.clear();for(let[e,t]of this.#n.entries())t.ptr&&this.#i.free(t.ptr);this.#n.clear(),this.#f.clear()}};var ee=class{#s;#e;#r;#l;constructor(e={}){let{onLoadingEvent:t=null,maxRetries:s=3,baseDelay:r=1e3,skipHeadRequests:n=!1}=e;this.#s=t,this.#e=s,this.#r=r,this.#l=n}async fetch(e,{type:t,name:s}){let r=this.#a(e);if(this.#l)this.#s?.("loading:start",{type:t,name:s});else{let a=await this.#o(e);this.#s?.("loading:start",{type:t,name:s,...a!=null&&{size:a}})}let o=await(await r).arrayBuffer();return this.#s?.("loading:complete",{type:t,name:s,size:o.byteLength}),o}async#o(e){try{let t=await fetch(e,{method:"HEAD"});if(t.ok){let s=t.headers.get("Content-Length");return s?parseInt(s,10):null}return null}catch{return null}}async#a(e){let t;for(let s=0;s<=this.#e;s++)try{let r=await fetch(e);if(r.status>=400&&r.status<500)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);if(!r.ok)throw new Error(`Server error fetching ${e}: ${r.status} ${r.statusText}`);return r}catch(r){if(t=r,r.message.match(/Failed to fetch .+: 4\d{2} /))throw r;if(s<this.#e){let n=this.#r*Math.pow(2,s);await this.#i(n)}}throw t}#i(e){return new Promise(t=>setTimeout(t,e))}};var te=class{#s;#e;constructor({bufferManager:e,getDefaultSampleRate:t}){if(!e)throw new Error("OSCRewriter requires bufferManager");if(typeof t!="function")throw new Error("OSCRewriter requires getDefaultSampleRate callback");this.#s=e,this.#e=t}async rewritePacket(e){if(Array.isArray(e)){let{message:t,changed:s}=await this.#r(e);return{packet:t,changed:s}}if(this.#c(e)){let t=await Promise.all(e.packets.map(n=>this.rewritePacket(n)));if(!t.some(n=>n.changed))return{packet:e,changed:!1};let r=t.map(n=>n.packet);return{packet:{timeTag:e.timeTag,packets:r},changed:!0}}return{packet:e,changed:!1}}async#r(e){let t=e[0],s=e.slice(1);switch(t){case"/b_alloc":return{message:await this.#l(s),changed:!0};case"/b_allocRead":return{message:await this.#o(s),changed:!0};case"/b_allocReadChannel":return{message:await this.#a(s),changed:!0};case"/b_allocFile":return{message:await this.#i(s),changed:!0};default:return{message:e,changed:!1}}}async#l(e){let t=this.#S(e,0,"/b_alloc requires a buffer number"),s=this.#S(e,1,"/b_alloc requires a frame count"),r=2,n=1,o=this.#e();Number.isFinite(this.#f(e,r))&&(n=Math.max(1,this.#E(e,r,1)),r++),(Array.isArray(e)?e[r]:void 0)?.type==="b"&&r++;let a=this.#f(e,r);Number.isFinite(a)&&(o=a);let c=await this.#s.prepareEmpty({bufnum:t,numFrames:s,numChannels:n,sampleRate:o});return this.#p(c.allocationComplete,`/b_alloc ${t}`),this.#n(t,c)}async#o(e){let t=this.#S(e,0,"/b_allocRead requires a buffer number"),s=this.#d(e,1,"/b_allocRead requires a file path"),r=this.#E(e,2,0),n=this.#E(e,3,0),o=await this.#s.prepareFromFile({bufnum:t,path:s,startFrame:r,numFrames:n});return this.#p(o.allocationComplete,`/b_allocRead ${t}`),this.#n(t,o)}async#a(e){let t=this.#S(e,0,"/b_allocReadChannel requires a buffer number"),s=this.#d(e,1,"/b_allocReadChannel requires a file path"),r=this.#E(e,2,0),n=this.#E(e,3,0),o=[];for(let c=4;c<(e?.length||0);c++){let u=this.#f(e,c);if(!Number.isFinite(u))break;o.push(Math.floor(u))}let a=await this.#s.prepareFromFile({bufnum:t,path:s,startFrame:r,numFrames:n,channels:o.length>0?o:null});return this.#p(a.allocationComplete,`/b_allocReadChannel ${t}`),this.#n(t,a)}async#i(e){let t=this.#S(e,0,"/b_allocFile requires a buffer number"),s=this.#g(e,1,"/b_allocFile requires audio file data as blob"),r=await this.#s.prepareFromBlob({bufnum:t,blob:s});return this.#p(r.allocationComplete,`/b_allocFile ${t}`),this.#n(t,r)}#n(e,t){return["/b_allocPtr",Math.floor(e),Math.floor(t.ptr),Math.floor(t.numFrames),Math.floor(t.numChannels),t.sampleRate,String(t.uuid)]}#c(e){return e&&e.timeTag!==void 0&&Array.isArray(e.packets)}#f(e,t){let s=Array.isArray(e)?e[t]:void 0;if(s!=null)return typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"value")?s.value:s}#m(e,t,s,r){let n=this.#f(e,t);if(!s(n))throw new Error(r);return n}#S(e,t,s){return Math.floor(this.#m(e,t,Number.isFinite,s))}#E(e,t,s=0){let r=this.#f(e,t);return Number.isFinite(r)?Math.floor(r):s}#d(e,t,s){return this.#m(e,t,r=>typeof r=="string",s)}#g(e,t,s){return this.#m(e,t,r=>r instanceof Uint8Array||r instanceof ArrayBuffer,s)}#p(e,t){!e||typeof e.catch!="function"||e.catch(s=>{console.error(`[OSCRewriter] ${t} allocation failed:`,s)})}};function H(i){if(!i)return null;if(typeof i=="string")return(i.split("/").filter(Boolean).pop()||i).replace(/\.scsyndef$/i,"");let e=i instanceof ArrayBuffer?new Uint8Array(i):i;if(!(e instanceof Uint8Array)||e.length<11||e[0]!==83||e[1]!==67||e[2]!==103||e[3]!==102)return null;let s=(e[4]<<24|e[5]<<16|e[6]<<8|e[7])>=3?14:10;if(s>=e.length)return null;let r=e[s];if(r===0||s+1+r>e.length)return null;try{return new TextDecoder().decode(e.slice(s+1,s+1+r))}catch{return null}}var se=class{#s=new Map;on(e,t){if(typeof t!="function")throw new Error("Callback must be a function");return this.#s.has(e)||this.#s.set(e,new Set),this.#s.get(e).add(t),()=>this.off(e,t)}off(e,t){let s=this.#s.get(e);return s&&s.delete(t),this}once(e,t){let s=(...r)=>{this.off(e,s),t(...r)};return this.on(e,s)}removeAllListeners(e){return e===void 0?this.#s.clear():this.#s.delete(e),this}hasListeners(e){let t=this.#s.get(e);return t?t.size>0:!1}emit(e,...t){let s=this.#s.get(e);if(s)for(let r of s)try{r(...t)}catch(n){console.error(`[EventEmitter] Error in ${e} listener:`,n)}}async emitAsync(e,...t){let s=this.#s.get(e);if(s)for(let r of s)try{await r(...t)}catch(n){console.error(`[EventEmitter] Error in ${e} listener:`,n)}}};var pr={oscOutMessagesSent:24,oscOutBytesSent:25,preschedulerBypassed:22,bypassNonBundle:38,bypassImmediate:39,bypassNearFuture:40,bypassLate:41},re=class{#s;#e;#r;#l;#o;#a;#i;#n=null;#c=new Uint32Array(70);#f=new DataView(this.#c.buffer);constructor(e={}){this.#l=e.mode||"sab",this.#s=e.sharedBuffer||null,this.#e=e.ringBufferBase||0,this.#r=e.bufferConstants||null}initSharedViews(e,t,s){if(this.#s=e,this.#e=t,this.#r=s,this.#l==="sab"&&e&&s){this.#o=new Int32Array(e),this.#i=rt(t,s.CONTROL_START);let r=t+s.METRICS_START;this.#a=new Uint32Array(e,r,s.METRICS_SIZE/4)}}updateSnapshot(e){this.#n=e}getSnapshotBuffer(){return this.#n}getMetricsView(){return this.#a}addMetric(e,t=1){if(!this.#a)return;let s=pr[e];s!==void 0&&Atomics.add(this.#a,s,t)}overlayPreschedulerMetrics(e){if(!this.#n||!e)return;let t=new Uint32Array(this.#n,0,46),s=9,r=13;t.set(e.subarray(s,s+r),s),t[23]=e[23]}gatherMetrics(e={}){this.updateMergedArray(e);let t=this.#c,s={scsynthProcessCount:t[0],scsynthMessagesProcessed:t[1],scsynthMessagesDropped:t[2],scsynthSchedulerDepth:t[3],scsynthSchedulerPeakDepth:t[4],scsynthSchedulerDropped:t[5],scsynthSequenceGaps:t[6],scsynthSchedulerLates:t[8],scsynthSchedulerMaxLateMs:t[42],scsynthSchedulerLastLateMs:t[43],scsynthSchedulerLastLateTick:t[44],preschedulerPending:t[9],preschedulerPendingPeak:t[10],preschedulerDispatched:t[12],preschedulerRetriesSucceeded:t[16],preschedulerRetriesFailed:t[17],preschedulerBundlesScheduled:t[11],preschedulerEventsCancelled:t[13],preschedulerTotalDispatches:t[21],preschedulerMessagesRetried:t[20],preschedulerRetryQueueSize:t[18],preschedulerRetryQueuePeak:t[19],preschedulerBypassed:t[22],preschedulerMinHeadroomMs:t[14],preschedulerLates:t[15],preschedulerMaxLateMs:t[23],oscInMessagesReceived:t[26],oscInMessagesDropped:t[28],oscInBytesReceived:t[27],debugMessagesReceived:t[30],debugBytesReceived:t[31],oscOutMessagesSent:t[24],oscOutBytesSent:t[25],scsynthWasmErrors:t[7],oscInCorrupted:t[29],ringBufferDirectWriteFails:t[45],bypassNonBundle:t[38],bypassImmediate:t[39],bypassNearFuture:t[40],bypassLate:t[41],mode:this.#l},r=this.#r;return t[32]!==void 0&&r&&(s.inBufferUsed={bytes:t[32],percentage:t[32]/r.IN_BUFFER_SIZE*100,peakBytes:t[35],peakPercentage:t[35]/r.IN_BUFFER_SIZE*100,capacity:r.IN_BUFFER_SIZE},s.outBufferUsed={bytes:t[33],percentage:t[33]/r.OUT_BUFFER_SIZE*100,peakBytes:t[36],peakPercentage:t[36]/r.OUT_BUFFER_SIZE*100,capacity:r.OUT_BUFFER_SIZE},s.debugBufferUsed={bytes:t[34],percentage:t[34]/r.DEBUG_BUFFER_SIZE*100,peakBytes:t[37],peakPercentage:t[37]/r.DEBUG_BUFFER_SIZE*100,capacity:r.DEBUG_BUFFER_SIZE}),r?.scheduler_slot_count!==void 0&&(s.scsynthSchedulerCapacity=r.scheduler_slot_count),e.driftOffsetMs!==void 0&&(s.driftOffsetMs=e.driftOffsetMs),e.ntpStartTime!==void 0&&(s.ntpStartTime=e.ntpStartTime),e.clockOffsetMs!==void 0&&(s.clockOffsetMs=e.clockOffsetMs),e.audioContextState&&(s.audioContextState=e.audioContextState),e.bufferPoolStats&&(s.bufferPoolUsedBytes=e.bufferPoolStats.used.size,s.bufferPoolAvailableBytes=e.bufferPoolStats.available,s.bufferPoolAllocations=e.bufferPoolStats.used.count),e.bufferPoolGrowthStats&&(s.bufferPoolTotalCapacity=e.bufferPoolGrowthStats.totalCapacity,s.bufferPoolMaxCapacity=e.bufferPoolGrowthStats.maxCapacity,s.bufferPoolGrowthCount=e.bufferPoolGrowthStats.growthCount,s.bufferPoolPoolCount=e.bufferPoolGrowthStats.poolCount),e.loadedSynthDefsCount!==void 0&&(s.loadedSynthDefs=e.loadedSynthDefsCount),e.preschedulerCapacity!==void 0&&(s.preschedulerCapacity=e.preschedulerCapacity),s.audioHealthPct=e.audioHealthPct??100,s.hasPlaybackStats=!!e.playbackStats,e.playbackStats?(s.glitchCount=e.playbackStats.fallbackFramesEvents??0,s.glitchDurationMs=Math.round((e.playbackStats.fallbackFramesDuration??0)*1e3),s.averageLatencyUs=Math.round((e.playbackStats.averageLatency??0)*1e6),s.maxLatencyUs=Math.round((e.playbackStats.maximumLatency??0)*1e6),s.totalFramesDurationMs=Math.round((e.playbackStats.totalFramesDuration??0)*1e3)):(s.glitchCount=0,s.glitchDurationMs=0,s.averageLatencyUs=0,s.maxLatencyUs=0,s.totalFramesDurationMs=0),this.#l==="postMessage"&&e.transportMetrics&&Object.assign(s,e.transportMetrics),s}updateMergedArray(e={}){let t=this.#c;if(this.#l==="postMessage"){if(e.preschedulerMetrics&&this.overlayPreschedulerMetrics(e.preschedulerMetrics),this.#n){let a=new Uint32Array(this.#n,0,46);t.set(a)}e.transportMetrics&&(e.transportMetrics.oscOutMessagesSent!==void 0&&(t[24]=e.transportMetrics.oscOutMessagesSent),e.transportMetrics.oscOutBytesSent!==void 0&&(t[25]=e.transportMetrics.oscOutBytesSent),e.transportMetrics.preschedulerBypassed!==void 0&&(t[22]=e.transportMetrics.preschedulerBypassed),e.transportMetrics.bypassNonBundle!==void 0&&(t[38]=e.transportMetrics.bypassNonBundle),e.transportMetrics.bypassImmediate!==void 0&&(t[39]=e.transportMetrics.bypassImmediate),e.transportMetrics.bypassNearFuture!==void 0&&(t[40]=e.transportMetrics.bypassNearFuture),e.transportMetrics.bypassLate!==void 0&&(t[41]=e.transportMetrics.bypassLate))}else this.#a&&t.set(this.#a);let s=this.#f;s.setInt32(46*4,e.driftOffsetMs??0,!0),s.setInt32(47*4,e.clockOffsetMs??0,!0);let r=e.audioContextState||"unknown",n={unknown:0,running:1,suspended:2,closed:3,interrupted:4};t[48]=n[r]??0,e.bufferPoolStats&&(t[49]=e.bufferPoolStats.used?.size??0,t[50]=e.bufferPoolStats.available??0,t[51]=e.bufferPoolStats.used?.count??0),t[52]=e.loadedSynthDefsCount??0;let o=this.#r;t[53]=o?.scheduler_slot_count??0,t[54]=e.preschedulerCapacity??0,t[55]=o?.IN_BUFFER_SIZE??0,t[56]=o?.OUT_BUFFER_SIZE??0,t[57]=o?.DEBUG_BUFFER_SIZE??0,t[58]=this.#l==="sab"?0:1,t[65]=e.playbackStats?1:0,e.playbackStats&&(t[59]=e.playbackStats.fallbackFramesEvents??0,t[60]=Math.round((e.playbackStats.fallbackFramesDuration??0)*1e3),t[61]=Math.round((e.playbackStats.averageLatency??0)*1e6),t[62]=Math.round((e.playbackStats.maximumLatency??0)*1e6),t[64]=Math.round((e.playbackStats.totalFramesDuration??0)*1e3)),t[63]=e.audioHealthPct??100,e.bufferPoolGrowthStats&&(t[66]=e.bufferPoolGrowthStats.totalCapacity??0,t[67]=e.bufferPoolGrowthStats.maxCapacity??0,t[68]=e.bufferPoolGrowthStats.growthCount??0,t[69]=e.bufferPoolGrowthStats.poolCount??0)}getMergedArray(){return this.#c}get bufferConstants(){return this.#r}get ringBufferBase(){return this.#e}get sharedBuffer(){return this.#s}};function Re(i){return i/1e3+2208988800}function Rt(i,e){return i-e}function mr(i,e){let t=i-e;return Math.round(t*1e6)}var ie=class{#s;#e;#r;#l;#o;#a;#i;#n;#c;#f=0;#m=0;#S=null;constructor(e={}){this.#s=e.mode||"sab",this.#e=e.audioContext,this.#r=e.workletPort||null}#E(e){this.#a.setFloat64(0,e,!0),this.#i&&Atomics.store(this.#i,0,Atomics.load(this.#i,0))}initSharedViews(e,t,s){this.#o=t,this.#l=s,this.#s==="sab"&&e&&s&&(this.#a=new DataView(e,t+s.NTP_START_TIME_START,8),this.#i=new Int32Array(e,t+s.DRIFT_OFFSET_START,1),this.#n=new Int32Array(e,t+s.GLOBAL_OFFSET_START,1))}updateAudioContext(e){this.#e=e}async initialize(){if(!this.#e)return;let e;for(;e=this.#e.getOutputTimestamp(),!(e.contextTime>0);)await new Promise(o=>setTimeout(o,50));e=this.#e.getOutputTimestamp();let t=performance.timeOrigin+e.performanceTime,s=Re(t),r=e.contextTime,n=Rt(s,r);this.#s==="sab"&&this.#a?this.#E(n):this.#r&&this.#r.postMessage({type:"setNTPStartTime",ntpStartTime:n}),this.#c=n,await new Promise(o=>setTimeout(o,500)),this.updateDriftOffset()}updateDriftOffset(){if(!this.#e||this.#c===void 0)return;let e=this.#e.getOutputTimestamp(),t=performance.timeOrigin+e.performanceTime,r=Re(t)-this.#c,n=mr(r,e.contextTime);this.#f=Math.round(n/1e3),this.#s==="sab"&&this.#i?Atomics.store(this.#i,0,n):this.#r&&this.#r.postMessage({type:"setDriftOffset",driftOffsetUs:n})}resync(){if(!this.#e)return;let e=this.#e.getOutputTimestamp();if(!e||e.contextTime<=0)return;let t=performance.timeOrigin+e.performanceTime,s=Re(t),r=Rt(s,e.contextTime);this.#s==="sab"&&this.#a?this.#E(r):this.#r&&this.#r.postMessage({type:"setNTPStartTime",ntpStartTime:r}),this.#c=r,this.updateDriftOffset()}startDriftTimer(){this.stopDriftTimer(),this.#S=setInterval(()=>{this.updateDriftOffset()},1e3)}stopDriftTimer(){this.#S&&(clearInterval(this.#S),this.#S=null)}getDriftOffset(){return this.#i?Math.round(Atomics.load(this.#i,0)/1e3):this.#f}getNTPStartTime(){return this.#a?this.#a.getFloat64(0,!0):this.#c??0}getClockOffset(){return this.#n?Atomics.load(this.#n,0):this.#m}setClockOffset(e){let t=Math.round(e*1e3);this.#m=t,this.#s==="sab"&&this.#n?Atomics.store(this.#n,0,t):this.#r&&this.#r.postMessage({type:"setClockOffset",clockOffsetMs:t})}reset(){this.stopDriftTimer(),this.#c=void 0,this.#f=0,this.#m=0,this.#a=null,this.#i=null,this.#n=null}};var ne=class i{#s;#e=0;#r=0;#l=100;static#o=1e3;constructor({audioContext:e}){this.#s=e}update(){if(this.#s.state!=="running")return this.#l;let e=performance.now(),t=this.#s.currentTime;if(this.#r===0)return this.#r=e,this.#e=t,this.#l;let s=e-this.#r;if(s<i.#o)return this.#l;let r=s/1e3,n=t-this.#e;return this.#l=Math.min(100,Math.round(n/r*100)),this.#r=e,this.#e=t,this.#l}getHealth(){return{healthPct:this.#l}}reset(){this.#e=0,this.#r=0,this.#l=100}};var oe=class i{#s;#e;#r;constructor(e={}){this.#s=e.sharedBuffer||null,this.#e=e.bufferConstants||null,this.#r=e.ringBufferBase||0}update(e,t,s){this.#s=e,this.#r=t,this.#e=s}isAvailable(){return!!(this.#s&&this.#e)}static#l=0;static#o=1;static#a=2;static#i=4;static#n=5;static#c=8;start(){if(!this.isAvailable())throw new Error("AudioCapture not initialized");let e=this.#e,t=this.#r+e.SHM_AUDIO_START,s=new Uint32Array(this.#s,t,i.#c);Atomics.store(s,i.#l,0),Atomics.store(s,i.#i,0),Atomics.store(s,i.#n,0),Atomics.store(s,i.#l,1)}stop(){if(!this.isAvailable())throw new Error("AudioCapture not initialized");let e=this.#e,t=this.#r+e.SHM_AUDIO_START,s=new Uint32Array(this.#s,t,1);return Atomics.store(s,i.#l,0),this.read()}read(){if(!this.isAvailable())throw new Error("AudioCapture not initialized");let e=this.#e,t=this.#r+e.SHM_AUDIO_START,s=new Uint32Array(this.#s,t,i.#c),r=s[i.#o],n=s[i.#a],o=Atomics.load(s,i.#i),a=Atomics.load(s,i.#n);if(a!==0)throw new Error(`AudioCapture: write_position too large (high=${a})`);let c=o,u=t+e.SHM_AUDIO_HEADER_SIZE,l=new Float32Array(this.#s,u,c*n),f=new Float32Array(c),h=n>1?new Float32Array(c):null;for(let y=0;y<c;y++)f[y]=l[y*n],h&&(h[y]=l[y*n+1]);return{sampleRate:r,channels:n,frames:c,left:f,right:h}}isEnabled(){if(!this.isAvailable())return!1;let e=this.#e,t=this.#r+e.SHM_AUDIO_START,s=new Uint32Array(this.#s,t,1);return Atomics.load(s,i.#l)===1}getFrameCount(){if(!this.isAvailable())return 0;let e=this.#e,t=this.#r+e.SHM_AUDIO_START,s=new Uint32Array(this.#s,t,i.#c);return Atomics.load(s,i.#i)}getMaxDuration(){if(!this.#e)return 0;let e=this.#e;return e.SHM_AUDIO_FRAMES/(e.SHM_AUDIO_SAMPLE_RATE||48e3)}};function Bt(i,e,t){let s=t,r=new Uint32Array(i,e,3),n=r[0],o=r[1],a=r[2],c=e+s.NODE_TREE_HEADER_SIZE,u=s.NODE_TREE_MIRROR_MAX_NODES,l=s.NODE_TREE_ENTRY_SIZE,f=s.NODE_TREE_DEF_NAME_SIZE,h=new DataView(i,c,u*l),y=new TextDecoder("utf-8"),p=[],d=0;for(let m=0;m<u&&d<n;m++){let g=m*l,_=h.getInt32(g,!0);if(_===-1)continue;d++;let w=c+g+24,C=new Uint8Array(i,w,f),E=new Uint8Array(f);E.set(C);let de=E.indexOf(0);de===-1&&(de=f);let $t=y.decode(E.subarray(0,de)),Wt=c+g+56,pe=new Uint8Array(i,Wt,16),Ze=!1;for(let T=0;T<16;T++)if(pe[T]!==0){Ze=!0;break}let q=null;if(Ze){q=new Uint8Array(16);for(let T=0;T<8;T++)q[T]=pe[7-T];for(let T=0;T<8;T++)q[8+T]=pe[15-T]}p.push({id:_,parentId:h.getInt32(g+4,!0),isGroup:h.getInt32(g+8,!0)===1,prevId:h.getInt32(g+12,!0),nextId:h.getInt32(g+16,!0),headId:h.getInt32(g+20,!0),defName:$t,uuid:q})}return{nodeCount:n,version:o,droppedCount:a,nodes:p}}var ve=new Uint8Array(2097152),It=new DataView(ve.buffer),S=ve,A=It,Be=new Map,yr=1e3,Sr=new TextDecoder,gr=new TextEncoder,Ie=[null,0],He=2208988800,le=4294967296,ze=new Uint8Array([35,98,117,110,100,108,101,0]),Ut=44,Pe=105,De=102,Le=115,ke=98,xe=84,Fe=70,Pt=104,Dt=100,Lt=116,kt=117;function ae(i,e,t=0){let s=i.length+4;s+=e.length-t+4;for(let r=t;r<e.length;r++){let n=e[r];if(n instanceof Uint8Array)s+=4+n.length+3;else if(n instanceof ArrayBuffer)s+=4+n.byteLength+3;else if(typeof n=="string")s+=n.length*3+4;else if(n&&n.type==="string")s+=n.value.length*3+4;else if(n&&n.type==="blob"){let o=n.value,a=o instanceof Uint8Array?o.length:o.byteLength;s+=4+a+3}else n&&n.type==="uuid"?s+=16:s+=8}return s}function xt(i){let e=16;for(let t of i)e+=4,Array.isArray(t)?e+=ae(t[0],t,1):t.packets!==void 0?e+=xt(t.packets):e+=ae(t.address,t.args||[]);return e}function Ge(i){if(i<=2097152){S=ve,A=It;return}S=new Uint8Array(i),A=new DataView(S.buffer)}function Ft(i,e=[]){let t=ae(i,e);Ge(t);let s=0;s=Ye(i,s),s=$e(e,s);for(let r=0;r<e.length;r++)s=ue(e[r],s);return S.subarray(0,s)}function Nt(i,e){let t=xt(e);Ge(t);let s=0;S.set(ze,s),s+=8,s=fe(i,s);for(let r=0;r<e.length;r++){let n=e[r],o=s;s+=4;let a=s;Array.isArray(n)?s=ce(n[0],n,s,1):n.packets!==void 0?s=Ht(n.timeTag,n.packets,s):s=ce(n.address,n.args||[],s);let c=s-a;A.setUint32(o,c,!1)}return S.subarray(0,s)}function vt(i,e,t=[]){let s=20+ae(e,t);Ge(s);let r=0;S.set(ze,r),r+=8,r=fe(i,r);let n=r;r+=4;let o=r;r=Ye(e,r),r=$e(t,r);for(let a=0;a<t.length;a++)r=ue(t[a],r);return A.setUint32(n,r-o,!1),S.subarray(0,r)}function ce(i,e,t,s=0){t=Ye(i,t),t=$e(e,t,s);for(let r=s;r<e.length;r++)t=ue(e[r],t);return t}function Ht(i,e,t){S.set(ze,t),t+=8,t=fe(i,t);for(let s=0;s<e.length;s++){let r=e[s],n=t;t+=4;let o=t;Array.isArray(r)?t=ce(r[0],r,t,1):r.packets!==void 0?t=Ht(r.timeTag,r.packets,t):t=ce(r.address,r.args||[],t),A.setUint32(n,t-o,!1)}return t}function Ye(i,e){let t=Be.get(i);if(t)return S.set(t,e),e+t.length;let s=e;if(e=Ne(i,e),Be.size<yr){let r=S.slice(s,e);Be.set(i,r)}return e}function Ne(i,e){let t=!1;for(let s=0;s<i.length;s++)if(i.charCodeAt(s)>=128){t=!0;break}if(t){let s=gr.encodeInto(i,S.subarray(e));e+=s.written}else for(let s=0;s<i.length;s++)S[e++]=i.charCodeAt(s);for(S[e++]=0;e&3;)S[e++]=0;return e}function $e(i,e,t=0){S[e++]=Ut;for(let s=t;s<i.length;s++){let r=i[s],n=typeof r;if(n==="number")S[e++]=Number.isInteger(r)?Pe:De;else if(n==="string")S[e++]=Le;else if(n==="boolean")S[e++]=r?xe:Fe;else if(r instanceof Uint8Array||r instanceof ArrayBuffer)S[e++]=ke;else if(r&&r.type==="int")S[e++]=Pe;else if(r&&r.type==="float")S[e++]=De;else if(r&&r.type==="string")S[e++]=Le;else if(r&&r.type==="blob")S[e++]=ke;else if(r&&r.type==="bool")S[e++]=r.value?xe:Fe;else if(r&&r.type==="int64")S[e++]=Pt;else if(r&&r.type==="double")S[e++]=Dt;else if(r&&r.type==="timetag")S[e++]=Lt;else if(r&&r.type==="uuid")S[e++]=kt;else throw r==null?new Error(`OSC argument at index ${s} is ${r}`):new Error(`Unknown OSC argument type at index ${s}: ${n}`)}for(S[e++]=0;e&3;)S[e++]=0;return e}function ue(i,e){let t=typeof i;if(t==="number")return Number.isInteger(i)?(A.setInt32(e,i,!1),e+4):(A.setFloat32(e,i,!1),e+4);if(t==="string")return Ne(i,e);if(t==="boolean")return e;if(i instanceof Uint8Array){let s=i.length;for(A.setUint32(e,s,!1),e+=4,S.set(i,e),e+=s;e&3;)S[e++]=0;return e}if(i instanceof ArrayBuffer)return ue(new Uint8Array(i),e);if(i&&i.type==="int")return A.setInt32(e,i.value,!1),e+4;if(i&&i.type==="float")return A.setFloat32(e,i.value,!1),e+4;if(i&&i.type==="string")return Ne(i.value,e);if(i&&i.type==="blob"){let s=i.value instanceof Uint8Array?i.value:new Uint8Array(i.value),r=s.length;for(A.setUint32(e,r,!1),e+=4,S.set(s,e),e+=r;e&3;)S[e++]=0;return e}return i&&i.type==="bool"?e:i&&i.type==="int64"?(A.setBigInt64(e,BigInt(i.value),!1),e+8):i&&i.type==="double"?(A.setFloat64(e,i.value,!1),e+8):i&&i.type==="timetag"?fe(i.value,e):i&&i.type==="uuid"?(S.set(i.value,e),e+16):e}function fe(i,e){if(i===1||i===null||i===void 0)return A.setUint32(e,0,!1),A.setUint32(e+4,1,!1),e+8;if(Array.isArray(i)){if(i.length!==2)throw new Error(`TimeTag array must have exactly 2 elements [seconds, fraction], got ${i.length}`);return A.setUint32(e,i[0]>>>0,!1),A.setUint32(e+4,i[1]>>>0,!1),e+8}if(typeof i!="number")throw new TypeError(`TimeTag must be a number, array, null, or undefined, got ${typeof i}`);i>1&&i<He&&console.warn(`TimeTag ${i} looks like a Unix timestamp (< NTP_EPOCH_OFFSET). Did you mean to add NTP_EPOCH_OFFSET (2208988800)?`);let t=i>>>0,s=(i-Math.floor(i))*le>>>0;return A.setUint32(e,t,!1),A.setUint32(e+4,s,!1),e+8}function W(i){return i instanceof Uint8Array||(i=new Uint8Array(i)),i[0]===35&&i[1]===98?_r(i):Er(i)}function Er(i){i instanceof Uint8Array||(i=new Uint8Array(i));let e=new DataView(i.buffer,i.byteOffset,i.byteLength),t=0,[s,r]=Ue(i,t);if(t=r,t>=i.length||i[t]!==Ut)return[s];let[n,o]=Ue(i,t);t=o;let a=[s];for(let c=1;c<n.length;c++)switch(n.charCodeAt(c)){case Pe:a.push(e.getInt32(t,!1)),t+=4;break;case De:a.push(e.getFloat32(t,!1)),t+=4;break;case Le:let[l,f]=Ue(i,t);a.push(l),t=f;break;case ke:let h=e.getUint32(t,!1);t+=4,a.push(i.slice(t,t+h)),t+=h,t=t+3&-4;break;case Pt:a.push(e.getBigInt64(t,!1)),t+=8;break;case Dt:a.push(e.getFloat64(t,!1)),t+=8;break;case xe:a.push(!0);break;case Fe:a.push(!1);break;case Lt:let y=e.getUint32(t,!1),p=e.getUint32(t+4,!1);a.push(y+p/le),t+=8;break;case kt:a.push({type:"uuid",value:i.slice(t,t+16)}),t+=16;break}return a}function _r(i){i instanceof Uint8Array||(i=new Uint8Array(i));let e=new DataView(i.buffer,i.byteOffset,i.byteLength),t=8,s=e.getUint32(t,!1),r=e.getUint32(t+4,!1),n=s+r/le;t+=8;let o=[];for(;t<i.length;){let a=e.getUint32(t,!1);if(t+=4,a>0&&t+a<=i.length){let c=i.subarray(t,t+a);o.push(W(c))}t+=a}return{timeTag:n,packets:o}}function Ue(i,e){let t=e;for(;t<i.length&&i[t]!==0;)t++;let s=Sr.decode(i.subarray(e,t));return t++,t=t+3&-4,Ie[0]=s,Ie[1]=t,Ie}function he(i){return i.slice()}function br(i){return!i||i.length<8?!1:i[0]===35&&i[1]===98}function We(i){if(!br(i))return null;let e=new DataView(i.buffer,i.byteOffset,i.byteLength),t=e.getUint32(8,!1),s=e.getUint32(12,!1);return t+s/le}var U={wasmHeapSize:8388608,ringBufferReserved:3145728,rtPoolSize:33554432,bufferPoolSize:4194304,maxBufferPoolSize:805306368,get rtPoolOffset(){return this.wasmHeapSize+this.ringBufferReserved},get bufferPoolOffset(){return this.rtPoolOffset+this.rtPoolSize},get totalMemory(){return this.bufferPoolOffset+this.bufferPoolSize},get maxTotalMemory(){return this.bufferPoolOffset+this.maxBufferPoolSize},get totalPages(){return Math.ceil(this.totalMemory/65536)}};var Ve={numBuffers:1024,maxNodes:8192,maxGraphDefs:1024,maxWireBufs:64,numAudioBusChannels:128,numInputBusChannels:2,numOutputBusChannels:2,numControlBusChannels:4096,bufLength:128,realTimeMemorySize:8192,numRGens:64,realTime:!1,memoryLocking:!1,loadGraphDefs:0,preferredSampleRate:0,verbosity:0};var Tr=1e4,wr=5e3,Cr=150,Mr=new Set(["/b_alloc","/b_allocRead","/b_allocReadChannel","/b_allocFile"]),b=[];for(let i=0;i<256;i++)b[i]=i.toString(16).padStart(2,"0");function Or(i){return b[i[0]]+b[i[1]]+b[i[2]]+b[i[3]]+"-"+b[i[4]]+b[i[5]]+"-"+b[i[6]]+b[i[7]]+"-"+b[i[8]]+b[i[9]]+"-"+b[i[10]]+b[i[11]]+b[i[12]]+b[i[13]]+b[i[14]]+b[i[15]]}function Gt(i){return"\u2026"+b[i[13]]+b[i[14]]+b[i[15]]}function zt(i,e){if(i&&i.type==="uuid"&&i.value)return Gt(i.value);if(i instanceof Uint8Array||i instanceof ArrayBuffer)return`<${i.byteLength||i.length} bytes>`;let t=JSON.stringify(i);return e&&t.length>e?t.slice(0,e)+"...":t}function V(i){return String(i).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Yt(i,e,t){if(i&&i.type==="uuid"&&i.value)return`<span class="supersonic-scsynth-string" title="${Or(i.value)}">${Gt(i.value)}</span>`;let s=i,r=null;if(typeof i=="object"&&i!==null&&i.value!==void 0&&(s=i.value,r=i.type),r==="b"||s instanceof Uint8Array||s instanceof ArrayBuffer)return`<span class="supersonic-scsynth-binary">&lt;${s.byteLength??s.length??"?"} bytes&gt;</span>`;let n=r==="f"||r===null&&typeof s=="number"&&!Number.isInteger(s),o=r==="i"||r===null&&Number.isInteger(s),c=e==="/s_new"&&t>=4&&(t-4)%2===0&&typeof s=="string";return n?`<span class="supersonic-scsynth-float">${parseFloat(s.toFixed(3))}</span>`:o?`<span class="supersonic-scsynth-int">${s}</span>`:c?`<span class="supersonic-scsynth-param">${V(s)}</span>`:typeof s=="string"?`<span class="supersonic-scsynth-string">${V(JSON.stringify(s))}</span>`:`<span class="supersonic-scsynth-string">${V(s)}</span>`}function qe(i,e,t,s,r){let n=i[0],o=i.slice(1),a=s&&t?(t-s).toFixed(2):"",c=`<span class="supersonic-scsynth-seq">[${e}]</span>`;if(a&&(c+=` <span class="supersonic-scsynth-time">${a}</span>`),r!==void 0&&(c+=` <span class="supersonic-scsynth-source">ch${r}</span>`),c+=` <span class="supersonic-scsynth-address">${V(n)}</span>`,o.length>0){let u=o.map((l,f)=>Yt(l,n,f)).join(", ");c+=" "+u}return c}function Rr(i,e,t,s,r){if(!i.packets)return qe(i,e,t,s,r);if(i.packets.length===1)return qe(i.packets[0],e,t,s,r);let n=s&&t?(t-s).toFixed(2):"",o=`<span class="supersonic-scsynth-seq">[${e}]</span>`;n&&(o+=` <span class="supersonic-scsynth-time">${n}</span>`),r!==void 0&&(o+=` <span class="supersonic-scsynth-source">ch${r}</span>`),o+=` <span class="supersonic-scsynth-bundle">Bundle (${i.packets.length})</span>`;for(let a of i.packets){let c=a[0],u=a.slice(1);o+=`<br><span class="supersonic-scsynth-address">${V(c)}</span>`,u.length>0&&(o+=" "+u.map((l,f)=>Yt(l,c,f)).join(", "))}return o}var Xe=class i{static osc={encodeMessage:(e,t)=>he(Ft(e,t)),encodeBundle:(e,t)=>he(Nt(e,t)),decode:e=>W(e),encodeSingleBundle:(e,t,s)=>he(vt(e,t,s)),readTimetag:e=>Se(e),ntpNow:()=>M(),NTP_EPOCH_OFFSET:He};static#s=null;static getMetricsSchema(){return this.#s??={metrics:{scsynthProcessCount:{offset:0,type:"counter",unit:"count",description:"Audio process() calls"},scsynthMessagesProcessed:{offset:1,type:"counter",unit:"count",description:"OSC messages processed by scsynth"},scsynthMessagesDropped:{offset:2,type:"counter",unit:"count",description:"Messages dropped (ring buffer full)"},scsynthSchedulerDepth:{offset:3,type:"gauge",unit:"count",description:"Current scheduler queue depth"},scsynthSchedulerPeakDepth:{offset:4,type:"gauge",unit:"count",description:"Peak scheduler queue depth (high water mark)"},scsynthSchedulerDropped:{offset:5,type:"counter",unit:"count",description:"Scheduled events dropped"},scsynthSequenceGaps:{offset:6,type:"counter",unit:"count",description:"Messages lost in transit from JS to scsynth"},scsynthWasmErrors:{offset:7,type:"counter",unit:"count",description:"WASM execution errors in audio worklet"},scsynthSchedulerLates:{offset:8,type:"counter",unit:"count",description:"Bundles executed after their scheduled time"},preschedulerPending:{offset:9,type:"gauge",unit:"count",description:"Events waiting to be scheduled"},preschedulerPendingPeak:{offset:10,type:"gauge",unit:"count",description:"Peak pending events"},preschedulerBundlesScheduled:{offset:11,type:"counter",unit:"count",description:"Bundles scheduled"},preschedulerDispatched:{offset:12,type:"counter",unit:"count",description:"Events sent to worklet"},preschedulerEventsCancelled:{offset:13,type:"counter",unit:"count",description:"Events cancelled"},preschedulerMinHeadroomMs:{offset:14,type:"gauge",unit:"ms",description:"Smallest time gap between JS prescheduler dispatch and scsynth scheduler execution"},preschedulerLates:{offset:15,type:"counter",unit:"count",description:"Bundles dispatched after their scheduled execution time"},preschedulerRetriesSucceeded:{offset:16,type:"counter",unit:"count",description:"Retries that succeeded"},preschedulerRetriesFailed:{offset:17,type:"counter",unit:"count",description:"Retries that failed"},preschedulerRetryQueueSize:{offset:18,type:"gauge",unit:"count",description:"Current retry queue size"},preschedulerRetryQueuePeak:{offset:19,type:"gauge",unit:"count",description:"Peak retry queue size"},preschedulerMessagesRetried:{offset:20,type:"counter",unit:"count",description:"Messages that needed retry"},preschedulerTotalDispatches:{offset:21,type:"counter",unit:"count",description:"Total dispatch attempts"},preschedulerBypassed:{offset:22,type:"counter",unit:"count",description:"Messages sent directly from JS to scsynth, bypassing prescheduler (aggregate)"},preschedulerMaxLateMs:{offset:23,type:"gauge",unit:"ms",description:"Maximum lateness at prescheduler (ms)"},oscOutMessagesSent:{offset:24,type:"counter",unit:"count",description:"OSC messages sent from JS to scsynth"},oscOutBytesSent:{offset:25,type:"counter",unit:"bytes",description:"Total bytes sent from JS to scsynth"},oscInMessagesReceived:{offset:26,type:"counter",unit:"count",description:"OSC replies received from scsynth to JS"},oscInBytesReceived:{offset:27,type:"counter",unit:"bytes",description:"Total bytes received from scsynth to JS"},oscInMessagesDropped:{offset:28,type:"counter",unit:"count",description:"Replies lost in transit from scsynth to JS"},oscInCorrupted:{offset:29,type:"counter",unit:"count",description:"Corrupted messages detected from scsynth to JS"},debugMessagesReceived:{offset:30,type:"counter",unit:"count",description:"Debug messages from scsynth"},debugBytesReceived:{offset:31,type:"counter",unit:"bytes",description:"Debug bytes received"},inBufferUsedBytes:{offset:32,type:"gauge",unit:"bytes",description:"Bytes used in IN ring buffer"},outBufferUsedBytes:{offset:33,type:"gauge",unit:"bytes",description:"Bytes used in OUT ring buffer"},debugBufferUsedBytes:{offset:34,type:"gauge",unit:"bytes",description:"Bytes used in DEBUG ring buffer"},inBufferPeakBytes:{offset:35,type:"gauge",unit:"bytes",description:"Peak bytes used in IN ring buffer"},outBufferPeakBytes:{offset:36,type:"gauge",unit:"bytes",description:"Peak bytes used in OUT ring buffer"},debugBufferPeakBytes:{offset:37,type:"gauge",unit:"bytes",description:"Peak bytes used in DEBUG ring buffer"},bypassNonBundle:{offset:38,type:"counter",unit:"count",description:"Plain OSC messages (not bundles) that bypassed prescheduler"},bypassImmediate:{offset:39,type:"counter",unit:"count",description:"Bundles with timetag 0 or 1 that bypassed prescheduler"},bypassNearFuture:{offset:40,type:"counter",unit:"count",description:"Bundles within bypass lookahead threshold that bypassed prescheduler"},bypassLate:{offset:41,type:"counter",unit:"count",description:"Timestamped OSC bundles arriving late into SuperSonic bypassing prescheduler"},scsynthSchedulerMaxLateMs:{offset:42,type:"gauge",unit:"ms",description:"Maximum lateness observed in scsynth scheduler (ms)"},scsynthSchedulerLastLateMs:{offset:43,type:"gauge",unit:"ms",description:"Most recent late magnitude in scsynth scheduler (ms)"},scsynthSchedulerLastLateTick:{offset:44,type:"gauge",unit:"count",description:"Process count when last scsynth late occurred"},ringBufferDirectWriteFails:{offset:45,type:"counter",unit:"count",description:"SAB mode only: optimistic direct writes attempted but failed due to ring buffer lock not being available (delivered via prescheduler instead)"},driftOffsetMs:{offset:46,type:"gauge",unit:"ms",signed:!0,description:"Clock drift between AudioContext and wall clock"},clockOffsetMs:{offset:47,type:"gauge",unit:"ms",signed:!0,description:"Clock offset for multi-system sync"},audioContextState:{offset:48,type:"enum",values:["unknown","running","suspended","closed","interrupted"],description:"AudioContext state"},bufferPoolUsedBytes:{offset:49,type:"gauge",unit:"bytes",description:"Buffer pool bytes used"},bufferPoolAvailableBytes:{offset:50,type:"gauge",unit:"bytes",description:"Buffer pool bytes available"},bufferPoolAllocations:{offset:51,type:"counter",unit:"count",description:"Total buffer allocations"},loadedSynthDefs:{offset:52,type:"gauge",unit:"count",description:"Number of loaded synthdefs"},scsynthSchedulerCapacity:{offset:53,type:"constant",unit:"count",description:"Maximum scheduler queue size"},preschedulerCapacity:{offset:54,type:"constant",unit:"count",description:"Maximum pending events in prescheduler"},inBufferCapacity:{offset:55,type:"constant",unit:"bytes",description:"IN ring buffer capacity"},outBufferCapacity:{offset:56,type:"constant",unit:"bytes",description:"OUT ring buffer capacity"},debugBufferCapacity:{offset:57,type:"constant",unit:"bytes",description:"DEBUG ring buffer capacity"},mode:{offset:58,type:"enum",values:["sab","postMessage"],description:"Transport mode"},glitchCount:{offset:59,type:"counter",unit:"count",description:"Chrome only: audio underrun/glitch events"},glitchDurationMs:{offset:60,type:"gauge",unit:"ms",description:"Chrome only: total silence from audio underruns"},averageLatencyUs:{offset:61,type:"gauge",unit:"us",description:"Chrome only: average audio output latency"},maxLatencyUs:{offset:62,type:"gauge",unit:"us",description:"Chrome only: maximum audio output latency"},audioHealthPct:{offset:63,type:"gauge",unit:"%",description:"Cross-browser: fraction of expected audio frames delivered (100% = no issues)"},totalFramesDurationMs:{offset:64,type:"counter",unit:"ms",description:"Chrome only: total audio rendered duration"},hasPlaybackStats:{offset:65,type:"gauge",unit:"bool",description:"1 if Chrome playbackStats API is available, 0 otherwise"},bufferPoolTotalCapacity:{offset:66,type:"gauge",unit:"bytes",description:"Buffer pool committed capacity (grows on demand)"},bufferPoolMaxCapacity:{offset:67,type:"gauge",unit:"bytes",description:"Buffer pool hard ceiling"},bufferPoolGrowthCount:{offset:68,type:"counter",unit:"count",description:"Number of buffer pool growth events"},bufferPoolPoolCount:{offset:69,type:"gauge",unit:"count",description:"Number of buffer pool segments"}},layout:{panels:[{title:"OSC Out",rows:[{label:"sent",cells:[{key:"oscOutMessagesSent"}]},{label:"bytes",cells:[{key:"oscOutBytesSent",kind:"muted",format:"bytes"}]},{label:"bypass",cells:[{key:"preschedulerBypassed",kind:"green"}]},{label:"lost",cells:[{key:"scsynthSequenceGaps",kind:"error"}]}]},{title:"Bypass",rows:[{label:"msg",cells:[{key:"bypassNonBundle",kind:"muted"}]},{label:"imm",cells:[{key:"bypassImmediate",kind:"muted"}]},{label:"near",cells:[{key:"bypassNearFuture",kind:"muted"}]},{label:"late",cells:[{key:"bypassLate",kind:"muted"}]}]},{title:"OSC In",rows:[{label:"received",cells:[{key:"oscInMessagesReceived"}]},{label:"bytes",cells:[{key:"oscInBytesReceived",kind:"muted",format:"bytes"}]},{label:"dropped",cells:[{key:"oscInMessagesDropped",kind:"error"}]},{label:"corrupted",cells:[{key:"oscInCorrupted",kind:"error"}]}]},{title:"Presched Flow",rows:[{label:"pending",tooltip:"Current pending events | peak pending events",cells:[{key:"preschedulerPending"},{sep:" | "},{key:"preschedulerPendingPeak",kind:"muted"}]},{label:"scheduled",cells:[{key:"preschedulerBundlesScheduled"}]},{label:"dispatched",cells:[{key:"preschedulerDispatched",kind:"dim"}]},{label:"min slack",cells:[{key:"preschedulerMinHeadroomMs",kind:"dim",format:"headroom"},{text:" ms",kind:"muted"}]}]},{title:"Presched Health",rows:[{label:"lates",tooltip:"Bundles dispatched after their scheduled time (count and max lateness in ms)",cells:[{key:"preschedulerLates",kind:"error"},{sep:" ("},{key:"preschedulerMaxLateMs",kind:"dim"},{text:" ms max)",kind:"muted"}]},{label:"cancelled",cells:[{key:"preschedulerEventsCancelled",kind:"error"}]},{label:"retried",tooltip:"Messages retried | succeeded | failed",cells:[{key:"preschedulerMessagesRetried",kind:"dim"},{sep:" | "},{key:"preschedulerRetriesSucceeded",kind:"green"},{sep:" | "},{key:"preschedulerRetriesFailed",kind:"error"}]},{label:"retry queue",tooltip:"Current retry queue size | peak size",cells:[{key:"preschedulerRetryQueueSize"},{sep:" | "},{key:"preschedulerRetryQueuePeak",kind:"muted"}]}]},{title:"scsynth Scheduler",rows:[{label:"queue",tooltip:"Current scheduler queue depth | peak depth",cells:[{key:"scsynthSchedulerDepth"},{sep:" | "},{key:"scsynthSchedulerPeakDepth",kind:"muted"}]},{label:"dropped",cells:[{key:"scsynthSchedulerDropped",kind:"error"}]},{label:"lates",cells:[{key:"scsynthSchedulerLates",kind:"error"}]},{label:"max | last",tooltip:"Maximum lateness observed | most recent late magnitude (ms)",cells:[{key:"scsynthSchedulerMaxLateMs",kind:"error"},{sep:" | "},{key:"scsynthSchedulerLastLateMs",kind:"dim"},{text:" ms",kind:"muted"}]}]},{title:"scsynth",rows:[{label:"ticks",tooltip:"Audio process() callback count and OSC messages processed",cells:[{key:"scsynthProcessCount",kind:"dim"},{sep:" | "},{key:"scsynthMessagesProcessed",kind:"muted"},{text:" msgs",kind:"muted"}]},{label:"dropped",cells:[{key:"scsynthMessagesDropped",kind:"error"}]},{label:"drift",cells:[{key:"driftOffsetMs",format:"signed"},{text:" ms",kind:"muted"}]},{label:"debug",tooltip:"Debug messages from scsynth (count and bytes)",cells:[{key:"debugMessagesReceived",kind:"muted"},{text:" ("},{key:"debugBytesReceived",kind:"muted",format:"bytes"},{text:")"}]}]},{title:"Ring Buffer Level",class:"wide",rows:[{type:"bar",label:"in",usedKey:"inBufferUsedBytes",peakKey:"inBufferPeakBytes",capacityKey:"inBufferCapacity",color:"blue"},{type:"bar",label:"out",usedKey:"outBufferUsedBytes",peakKey:"outBufferPeakBytes",capacityKey:"outBufferCapacity",color:"green"},{type:"bar",label:"dbg",usedKey:"debugBufferUsedBytes",peakKey:"debugBufferPeakBytes",capacityKey:"debugBufferCapacity",color:"purple"},{label:"direct write fails",cells:[{key:"ringBufferDirectWriteFails",kind:"error"}]}]},{title:"Buffers & SynthDefs",rows:[{label:"buf used",cells:[{key:"bufferPoolUsedBytes",format:"bytes"}]},{label:"buf free",cells:[{key:"bufferPoolAvailableBytes",kind:"green",format:"bytes"}]},{label:"buf allocs",cells:[{key:"bufferPoolAllocations",kind:"dim"}]},{label:"synthdefs",cells:[{key:"loadedSynthDefs"}]}]},{title:"AudioWorklet",rows:[{label:"health",tooltip:"AudioContext state and audio health percentage (fraction of expected frames delivered)",cells:[{key:"audioContextState",kind:"green",format:"enum"},{sep:" | "},{key:"audioHealthPct",kind:"green",format:"percent"},{text:" %",kind:"muted"}]},{label:"glitches",tooltip:"Chrome only: audio underrun/glitch events and total silence duration",cells:[{key:"glitchCount",kind:"error",format:"chromeOnly"},{sep:" ("},{key:"glitchDurationMs",kind:"error",format:"chromeOnly"},{text:" ms)",kind:"muted"}]},{label:"latency",tooltip:"Chrome only: avg | max audio output latency in ms",cells:[{key:"averageLatencyUs",kind:"dim",format:"chromeLatencyUs"},{sep:" | "},{key:"maxLatencyUs",kind:"dim",format:"chromeLatencyUs"},{text:" ms",kind:"muted"}]},{label:"WASM errors",cells:[{key:"scsynthWasmErrors",kind:"error"}]}]}]},sentinels:{HEADROOM_UNSET:4294967295}}}static getTreeSchema(){return{nodeCount:{type:"number",description:"Total nodes in tree"},version:{type:"number",description:"Increments on any tree change, useful for detecting updates"},droppedCount:{type:"number",description:"Nodes that exceeded mirror capacity (tree may be incomplete)"},root:{type:"object",description:"Root node of the tree (always a group with id 0)",schema:{id:{type:"number",description:"Unique node ID"},type:{type:"string",values:["group","synth"],description:"Node type"},defName:{type:"string",description:"Synthdef name (synths only, empty for groups)"},children:{type:"array",description:"Child nodes (recursive)",itemSchema:"(self)"}}}}}static getRawTreeSchema(){return{nodeCount:{type:"number",description:"Total nodes in tree"},version:{type:"number",description:"Increments on any tree change, useful for detecting updates"},droppedCount:{type:"number",description:"Nodes that exceeded mirror capacity (tree may be incomplete)"},nodes:{type:"array",description:"Flat array of all nodes with internal linkage pointers",itemSchema:{id:{type:"number",description:"Unique node ID"},parentId:{type:"number",description:"Parent node ID (-1 for root)"},isGroup:{type:"boolean",description:"True if group, false if synth"},prevId:{type:"number",description:"Previous sibling node ID (-1 if none)"},nextId:{type:"number",description:"Next sibling node ID (-1 if none)"},headId:{type:"number",description:"First child node ID (groups only, -1 if empty)"},defName:{type:"string",description:"Synthdef name (synths only, empty for groups)"}}}}}#e;#r;#l=null;#o;#a;#i;#n;#c;#f;#m;#S;#E;#d;#g;#p;#_;#T;#t;#u;#h;#y;#b;#A;#M;#w=1e3;#B=null;#R=null;#I=0;#O=[];#D=null;#P=Promise.resolve();#U=null;#x(e){let t=[["numBuffers",1,65535],["maxNodes",1],["maxGraphDefs",1],["maxWireBufs",1],["numAudioBusChannels",1],["numInputBusChannels",0],["numOutputBusChannels",1,128],["numControlBusChannels",1],["realTimeMemorySize",1],["numRGens",1],["preferredSampleRate",0,384e3],["verbosity",0,4]];for(let[s,r,n]of t){let o=e[s];if(typeof o!="number"||!Number.isFinite(o))throw new Error(`scsynthOptions.${s} must be a finite number, got: ${o}`);if(o<r)throw new Error(`scsynthOptions.${s} must be >= ${r}, got: ${o}`);if(n!==void 0&&o>n)throw new Error(`scsynthOptions.${s} must be <= ${n}, got: ${o}`)}if(e.bufLength!==128)throw new Error(`scsynthOptions.bufLength must be 128 (WebAudio API constraint), got: ${e.bufLength}`);for(let s of["realTime","memoryLocking"])if(typeof e[s]!="boolean")throw new Error(`scsynthOptions.${s} must be a boolean, got: ${typeof e[s]}`);if(e.loadGraphDefs!==0&&e.loadGraphDefs!==1)throw new Error(`scsynthOptions.loadGraphDefs must be 0 or 1, got: ${e.loadGraphDefs}`);if(e.preferredSampleRate!==0&&e.preferredSampleRate<8e3)throw new Error(`scsynthOptions.preferredSampleRate must be 0 (auto) or >= 8000, got: ${e.preferredSampleRate}`)}#L(e,t){let s=e?{...U,...e}:{...U},r=t?.realTimeMemorySize||Ve.realTimeMemorySize;return r&&(s.rtPoolSize=Math.max(s.rtPoolSize,r*1024)),s.rtPoolOffset=(s.wasmHeapSize||U.wasmHeapSize)+(s.ringBufferReserved||U.ringBufferReserved),s.bufferPoolOffset=s.rtPoolOffset+s.rtPoolSize,s.totalMemory=s.bufferPoolOffset+s.bufferPoolSize,s.maxTotalMemory=s.bufferPoolOffset+s.maxBufferPoolSize,s}constructor(e={}){this.#d=!1,this.#g=!1,this.#p=null,this.#_={},this.#T=null,this.#u=new se,this.#h=new re({mode:e.mode||"postMessage"}),this.#b=new oe({}),this.#e=null,this.#r=null,this.#o=null,this.#i=null,this.loadedSynthDefs=new Map;let t=e.baseURL||null,s=e.coreBaseURL||t,r=e.workerBaseURL||(t?`${t}workers/`:null),n=e.wasmBaseURL||(s?`${s}wasm/`:null);if(!r||!n)throw new Error(`SuperSonic requires explicit URL configuration.
6
6
 
7
7
  For CDN usage:
8
8
  import { SuperSonic } from 'https://unpkg.com/supersonic-scsynth@VERSION/dist/supersonic.js';
@@ -14,6 +14,6 @@ For CDN usage:
14
14
  For local usage:
15
15
  new SuperSonic({ baseURL: '/path/to/supersonic/dist/' })
16
16
 
17
- See: https://github.com/samaaron/supersonic#configuration`);let o={...Lt,...e.scsynthOptions};this.#$(o);let a=e.mode||"postMessage";this.#r={mode:a,snapshotIntervalMs:e.snapshotIntervalMs??yr,wasmBytes:e.wasmBytes??null,wasmUrl:e.wasmUrl||n+"scsynth-nrt.wasm",wasmBaseURL:n,workletUrl:e.workletUrl||(s?`${s}workers/scsynth_audio_worklet.js`:r+"scsynth_audio_worklet.js"),workerBaseURL:r,audioContext:e.audioContext||null,autoConnect:e.autoConnect!==!1,audioContextOptions:{latencyHint:"interactive",sampleRate:48e3,...e.audioContextOptions},memory:this.#Y(e.memory),worldOptions:o,preschedulerCapacity:e.preschedulerCapacity||65536,bypassLookaheadMs:e.bypassLookaheadMs??500,activityEvent:{maxLineLength:e.activityEvent?.maxLineLength??200,scsynthMaxLineLength:e.activityEvent?.scsynthMaxLineLength??null,oscInMaxLineLength:e.activityEvent?.oscInMaxLineLength??null,oscOutMaxLineLength:e.activityEvent?.oscOutMaxLineLength??null},debug:e.debug??!1,debugScsynth:e.debugScsynth??!1,debugOscIn:e.debugOscIn??!1,debugOscOut:e.debugOscOut??!1,bufferGrowIncrement:e.bufferGrowIncrement??32*1024*1024},this.#r.effectiveMaxBufferMemory=e.maxBufferMemory||this.#r.memory.maxBufferPoolSize||this.#r.memory.bufferPoolSize,this.#u=e.sampleBaseURL||(t?`${t}samples/`:null),this.#d=e.synthdefBaseURL||(t?`${t}synthdefs/`:null),this.#E={maxRetries:e.fetchMaxRetries??3,baseDelay:e.fetchRetryDelay??1e3},this.#_=new j({onLoadingEvent:(c,l)=>this.#a.emit(c,l),maxRetries:this.#E.maxRetries,baseDelay:this.#E.baseDelay,skipHeadRequests:e.skipHeadRequests??!1}),this.bootStats={initStartTime:null,initDuration:null}}get initialized(){return this.#p}get initializing(){return this.#h}get audioContext(){return this.#e}get mode(){return this.#r.mode}get bufferConstants(){return this.#g.bufferConstants}get ringBufferBase(){return this.#g.ringBufferBase}get sharedBuffer(){return this.#g.sharedBuffer}get node(){return this.#f}get osc(){return this.#o}get initTime(){return this.#S?.getNTPStartTime()??0}on(e,t){return this.#a.on(e,t)}off(e,t){return this.#a.off(e,t),this}once(e,t){return this.#a.once(e,t)}removeAllListeners(e){return this.#a.removeAllListeners(e),this}async init(){if(!this.#p)return this.#m?this.#m:(this.#m=this.#W(),this.#m)}async#W(){this.#h=!0,this.bootStats.initStartTime=performance.now();try{this.#X(),this.#K(),this.#L(),this.#Z(),this.#k();let e=await this.#F();await this.#x(e),await this.#N(),await this.#v()}catch(e){throw this.#h=!1,this.#m=null,console.error("[SuperSonic] Initialization failed:",e),this.#a.emit("error",e),e}}getMetrics(){return this.#P()}getMetricsArray(){return this.#te(),this.#g.getMergedArray()}getSnapshot(){let e=this.#P(),t=i.getMetricsSchema()?.metrics||{},s={};for(let[n,o]of Object.entries(e)){let a=t[n];a?.description?s[n]={value:o,description:a.description}:s[n]={value:o}}let r=null;return typeof performance<"u"&&performance.memory&&(r={usedJSHeapSize:performance.memory.usedJSHeapSize,totalJSHeapSize:performance.memory.totalJSHeapSize,jsHeapSizeLimit:performance.memory.jsHeapSizeLimit}),{timestamp:new Date().toISOString(),metrics:s,nodeTree:this.getRawTree(),memory:r}}getSystemReport(){this.#T("get system report");let e=this.#P(),t=[],s={userAgent:navigator.userAgent,hardwareConcurrency:navigator.hardwareConcurrency??null,deviceMemory:navigator.deviceMemory??null,platform:navigator.platform},r={sampleRate:this.#e.sampleRate,baseLatency:this.#e.baseLatency??null,outputLatency:this.#e.outputLatency??null,state:this.#e.state,channelCount:this.#r.worldOptions.numOutputBusChannels},n=this.#b.playbackStats?this.#e.playbackStats:null,o=n?{glitchCount:n.fallbackFramesEvents,glitchDurationS:n.fallbackFramesDuration,totalDurationS:n.totalFramesDuration,averageLatencyS:n.averageLatency,maximumLatencyS:n.maximumLatency}:null,a=this.#A?.getHealth()?.healthPct??100;a<95&&t.push({severity:a<80?"critical":"warning",message:`Audio health at ${a}% \u2014 audio thread may be falling behind`}),e.scsynthSchedulerLates>0&&t.push({severity:"warning",message:`${e.scsynthSchedulerLates} late bundles in scsynth scheduler`}),e.scsynthWasmErrors>0&&t.push({severity:"error",message:`${e.scsynthWasmErrors} WASM errors detected`}),n?.fallbackFramesEvents>0&&t.push({severity:"warning",message:`${n.fallbackFramesEvents} audio glitch events (${(n.fallbackFramesDuration*1e3).toFixed(1)}ms total silence)`}),e.driftOffsetMs!==void 0&&Math.abs(e.driftOffsetMs)>10&&t.push({severity:"warning",message:`Clock drift: ${e.driftOffsetMs}ms between AudioContext and wall clock`});let c=t.length===0?`Audio health: ${a}% \u2014 no issues detected`:`Audio health: ${a}% \u2014 ${t.length} issue(s): ${t.map(l=>l.message).join("; ")}`;return{timestamp:new Date().toISOString(),system:s,audio:r,playbackStats:o,engine:{mode:this.mode,version:this.#y,bootTimeMs:this.bootStats.initDuration},health:{audioHealthPct:a,issues:t,summary:c},metrics:e}}setClockOffset(e){this.#T("set clock offset"),this.#S?.setClockOffset(e)}async recover(){return this.#p?await this.resume()?!0:await this.reload():!1}async resume(){if(!this.#p||!this.#e)return!1;await this.purge();try{await this.#e.resume()}catch{}this.#S?.startDriftTimer();let e=this.#z();if(e===null){let r=this.#e.state==="running";return r&&(this.#S?.resync(),this.#a.emit("resumed")),r}await new Promise(r=>setTimeout(r,200));let t=this.#z(),s=t!==null&&t>e;return s&&(this.#S?.resync(),this.#a.emit("resumed")),s}async suspend(){if(this.#p){this.#S?.stopDriftTimer();try{await this.#e?.suspend()}catch{}}}async reload(){if(!this.#p)return!1;this.#a.emit("reload:start");let e=new Map(this.loadedSynthDefs),t=this.#n?.getAllocatedBuffers()||[];await this.#V(),await this.#q();for(let[s,r]of e)try{await this.send("/d_recv",r)}catch(n){console.error(`[SuperSonic] Failed to restore synthdef ${s}:`,n)}for(let s of t)try{if(this.#r.mode==="postMessage"&&s.source)s.source.type==="file"&&await this.loadSample(s.bufnum,s.source.path,s.source.startFrame||0,s.source.numFrames||0);else{let r=crypto.randomUUID();await this.send("/b_allocPtr",s.bufnum,s.ptr,s.numFrames,s.numChannels,s.sampleRate,r)}}catch(r){console.error(`[SuperSonic] Failed to restore buffer ${s.bufnum}:`,r)}return(e.size>0||t.length>0)&&await this.sync(),this.#a.emit("reload:complete",{success:!0}),!0}async#V(){this.#S?.stopDriftTimer(),this.#l?.clear(),this.#l=null,this.#o&&(this.#o.cancelAll(),this.#o.dispose(),this.#o=null),this.#s&&(this.#s.disconnect(),this.#s=null),this.#e&&(await this.#e.close(),this.#e=null),this.#p=!1,this.loadedSynthDefs.clear(),this.#m=null,this.#w=null,this.#S?.reset(),this.#A?.reset()}async#q(){this.#h=!0,this.bootStats.initStartTime=performance.now();try{this.#L(),this.#n&&this.#n.updateAudioContext(this.#e),this.#k();let e=await this.#F();await this.#x(e),await this.#N(),await this.#v()}catch(e){throw this.#h=!1,this.#m=null,console.error("[SuperSonic] Partial init failed:",e),this.#a.emit("error",e),e}}getRawTree(){if(!this.#p)return{nodeCount:0,version:0,droppedCount:0,nodes:[]};let e=this.#g.bufferConstants;if(!e)return{nodeCount:0,version:0,droppedCount:0,nodes:[]};let t,s;if(this.#r.mode==="postMessage"){let r=this.#g.getSnapshotBuffer();if(!r)return{nodeCount:0,version:0,droppedCount:0,nodes:[]};t=r,s=e.METRICS_SIZE}else{let r=this.#g.sharedBuffer;if(!r)return{nodeCount:0,version:0,droppedCount:0,nodes:[]};t=r,s=this.#g.ringBufferBase+e.NODE_TREE_START}return Tt(t,s,e)}getTree(){let e=this.getRawTree(),t=n=>({id:n.id,type:n.isGroup?"group":"synth",defName:n.defName,children:[]}),s=new Map;for(let n of e.nodes)s.set(n.id,t(n));let r=null;for(let n of e.nodes){let o=s.get(n.id);if(n.parentId===-1||n.parentId===0&&n.id===0)r=o;else{let a=s.get(n.parentId);a&&a.children.push(o)}}return{nodeCount:e.nodeCount,version:e.version,droppedCount:e.droppedCount,root:r||{id:0,type:"group",defName:"",children:[]}}}startCapture(){this.#T("start capture"),this.#C.start()}stopCapture(){return this.#T("stop capture"),this.#C.stop()}isCaptureEnabled(){return this.#C.isEnabled()}getCaptureFrames(){return this.#C.getFrameCount()}getMaxCaptureDuration(){return this.#C.getMaxDuration()}send(e,...t){this.#T("send OSC messages");let s={"/d_load":"Use loadSynthDef() or send /d_recv with synthdef bytes instead.","/d_loadDir":"Use loadSynthDef() or send /d_recv with synthdef bytes instead.","/b_read":"Use loadSample() to load audio into a buffer.","/b_readChannel":"Use loadSample() to load audio into a buffer.","/b_write":"Writing audio files is not available in the browser.","/b_close":"Writing audio files is not available in the browser.","/clearSched":"Use purge() to clear both the JS prescheduler and WASM scheduler.","/error":"SuperSonic always enables error notifications so you never miss a /fail message.","/quit":"Use destroy() to shut down SuperSonic."};if(s[e])throw new Error(`${e} is not supported in SuperSonic. ${s[e]}`);if(e==="/d_recv"){let o=t[0];if(o instanceof Uint8Array||o instanceof ArrayBuffer){let a=o instanceof ArrayBuffer?new Uint8Array(o):o,c=x(a)||"unknown";this.loadedSynthDefs.set(c,a)}}if(e==="/d_free")for(let o of t)typeof o=="string"&&this.loadedSynthDefs.delete(o);else e==="/d_freeAll"&&this.loadedSynthDefs.clear();let r=t.map(o=>o instanceof ArrayBuffer?new Uint8Array(o):o);if(gr.has(e)){this.#ie(e,r),this.#ne(e,r);return}let n=i.osc.encodeMessage(e,r);this.sendOSC(n)}sendOSC(e,t={}){this.#T("send OSC data");let s=this.#re(e);this.#G(s,t)}cancelTag(e){this.#T("cancel by tag"),this.#o.cancelTag(e)}cancelSession(e){this.#T("cancel by session"),this.#o.cancelSession(e)}cancelSessionTag(e,t){this.#T("cancel by session and tag"),this.#o.cancelSessionTag(e,t)}cancelAll(){this.#T("cancel all scheduled"),this.#o.cancelAll()}async purge(){this.#T("purge");let e=this.#o.cancelAllWithAck(),t=new Promise(s=>{let r=n=>{n.data.type==="clearSchedAck"&&(this.#s.port.removeEventListener("message",r),s())};this.#s.port.addEventListener("message",r),this.#s.port.postMessage({type:"clearSched",ack:!0})});await Promise.all([e,t])}createOscChannel(e={}){return this.#T("create OSC channel"),this.#o.createOscChannel(e)}nextNodeId(){return this.#T("allocate node IDs"),this.#w.nextNodeId()}async loadSynthDef(e){this.#T("load synthdef");let t,s;if(typeof e=="string"){let r;if(this.#se(e))r=e;else{if(!this.#d)throw new Error("synthdefBaseURL not configured.");r=`${this.#d}${e}.scsyndef`}let n=x(r),o=await this.#_.fetch(r,{type:"synthdef",name:n});t=new Uint8Array(o),s=x(t)||n}else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){if(t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=x(t),!s)throw new Error("Could not extract synthdef name from binary data. Make sure it's a valid .scsyndef file.")}else if(e instanceof Blob){let r=await e.arrayBuffer();if(t=new Uint8Array(r),s=x(t),!s)throw new Error("Could not extract synthdef name from file. Make sure it's a valid .scsyndef file.")}else throw new Error("loadSynthDef source must be a name, path/URL string, ArrayBuffer, Uint8Array, or File/Blob");return await this.send("/d_recv",t),{name:s,size:t.length}}async loadSynthDefs(e){this.#T("load synthdefs");let t={};return await Promise.all(e.map(async s=>{try{await this.loadSynthDef(s),t[s]={success:!0}}catch(r){t[s]={success:!1,error:r.message}}})),t}async loadSample(e,t,s=0,r=0){this.#T("load samples");let n;if(typeof t=="string")n=await this.#n.prepareFromFile({bufnum:e,path:t,startFrame:s,numFrames:r});else if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))n=await this.#n.prepareFromBlob({bufnum:e,blob:t,startFrame:s,numFrames:r});else if(t instanceof Blob){let l=await t.arrayBuffer();n=await this.#n.prepareFromBlob({bufnum:e,blob:l,startFrame:s,numFrames:r})}else throw new Error("loadSample source must be a path/URL string, ArrayBuffer, TypedArray, or File/Blob");await this.send("/b_allocPtr",e,n.ptr,n.numFrames,n.numChannels,n.sampleRate,n.uuid),await n.allocationComplete;let{numFrames:o,numChannels:a,sampleRate:c}=n;return{bufnum:e,hash:n.hash,source:typeof t=="string"?t:null,numFrames:o,numChannels:a,sampleRate:c,duration:c>0?o/c:0}}getLoadedBuffers(){return this.#T("get loaded buffers"),(this.#n?.getAllocatedBuffers()||[]).map(({bufnum:t,numFrames:s,numChannels:r,sampleRate:n,source:o,hash:a})=>({bufnum:t,hash:a||null,source:o?.path||o?.name||null,numFrames:s,numChannels:r,sampleRate:n,duration:n>0?s/n:0}))}async sampleInfo(e,t=0,s=0){this.#T("get sample info");let r;if(typeof e=="string")r=e;else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))r=e;else if(e instanceof Blob)r=await e.arrayBuffer();else throw new Error("sampleInfo source must be a path/URL string, ArrayBuffer, TypedArray, or File/Blob");return this.#n.sampleInfo({source:r,startFrame:t,numFrames:s})}async sync(e=Math.floor(Math.random()*2147483647)){this.#T("sync"),await this.#oe();let t=new Promise((s,r)=>{let n=setTimeout(()=>{this.#l?.delete(e),r(new Error("Timeout waiting for /synced response"))},pr),o=()=>{clearTimeout(n),this.#l.delete(e),s()};this.#l||(this.#l=new Map),this.#l.set(e,o)});this.send("/sync",e),await t,this.#r.mode==="postMessage"&&await new Promise(s=>setTimeout(s,this.#r.snapshotIntervalMs*2))}getInfo(){return this.#T("get info"),{sampleRate:this.#e.sampleRate,numBuffers:this.#r.worldOptions.numBuffers,totalMemory:this.#r.memory.totalMemory,wasmHeapSize:this.#r.memory.wasmHeapSize,bufferPoolSize:this.#r.memory.bufferPoolSize,bootTimeMs:this.bootStats.initDuration,capabilities:{...this.#b},version:this.#y}}async shutdown(){!this.#p&&!this.#h||(this.#a.emit("shutdown"),this.#S?.stopDriftTimer(),this.#A?.reset(),this.#A=null,this.#l?.clear(),this.#l=null,this.#o&&(this.#o.cancelAll(),this.#o.dispose(),this.#o=null),this.#s&&(this.#s.disconnect(),this.#s=null),this.#e&&(await this.#e.close(),this.#e=null),this.#n&&(this.#n.destroy(),this.#n=null),this.#i=null,this.#w=null,this.#U=Promise.resolve(),this.#p=!1,this.loadedSynthDefs.clear(),this.#m=null,this.#c=null,this.#S?.reset(),this.#A?.reset(),this.bootStats={initStartTime:null,initDuration:null})}async destroy(){this.#a.emit("destroy"),await this.shutdown(),this.#O=null,this.#a.clearAllListeners()}async reset(){await this.shutdown(),await this.init()}#X(){this.#b={audioWorklet:typeof AudioWorklet<"u",sharedArrayBuffer:typeof SharedArrayBuffer<"u",crossOriginIsolated:window.crossOriginIsolated===!0,atomics:typeof Atomics<"u",webWorker:typeof Worker<"u",playbackStats:typeof AudioContext<"u"&&"playbackStats"in AudioContext.prototype};let e=this.#r.mode,t=["audioWorklet","webWorker"];e==="sab"&&t.push("sharedArrayBuffer","crossOriginIsolated","atomics");let s=t.filter(r=>!this.#b[r]);if(s.length>0){let r=new Error(`Missing required features for ${e} mode: ${s.join(", ")}`);throw e==="sab"&&!this.#b.crossOriginIsolated&&(r.message+=`
17
+ See: https://github.com/samaaron/supersonic#configuration`);let o={...Ve,...e.scsynthOptions};this.#x(o);let a=e.mode||"postMessage";this.#t={mode:a,snapshotIntervalMs:e.snapshotIntervalMs??Cr,wasmBytes:e.wasmBytes??null,wasmUrl:e.wasmUrl||n+"scsynth-nrt.wasm",wasmBaseURL:n,workletUrl:e.workletUrl||(s?`${s}workers/scsynth_audio_worklet.js`:r+"scsynth_audio_worklet.js"),workerBaseURL:r,audioContext:e.audioContext||null,autoConnect:e.autoConnect!==!1,audioContextOptions:{latencyHint:"interactive",sampleRate:48e3,...e.audioContextOptions},memory:this.#L(e.memory,e.scsynthOptions),worldOptions:o,preschedulerCapacity:e.preschedulerCapacity||65536,bypassLookaheadMs:e.bypassLookaheadMs??500,activityEvent:{maxLineLength:e.activityEvent?.maxLineLength??200,scsynthMaxLineLength:e.activityEvent?.scsynthMaxLineLength??null,oscInMaxLineLength:e.activityEvent?.oscInMaxLineLength??null,oscOutMaxLineLength:e.activityEvent?.oscOutMaxLineLength??null},debug:e.debug??!1,debugScsynth:e.debugScsynth??!1,debugOscIn:e.debugOscIn??!1,debugOscOut:e.debugOscOut??!1,bufferGrowIncrement:e.bufferGrowIncrement??32*1024*1024},this.#t.effectiveMaxBufferMemory=e.maxBufferMemory||this.#t.memory.maxBufferPoolSize||this.#t.memory.bufferPoolSize,this.#f=e.sampleBaseURL||(t?`${t}samples/`:null),this.#m=e.synthdefBaseURL||(t?`${t}synthdefs/`:null),this.#S={maxRetries:e.fetchMaxRetries??3,baseDelay:e.fetchRetryDelay??1e3},this.#E=new ee({onLoadingEvent:(c,u)=>this.#u.emit(c,u),maxRetries:this.#S.maxRetries,baseDelay:this.#S.baseDelay,skipHeadRequests:e.skipHeadRequests??!1}),this.bootStats={initStartTime:null,initDuration:null}}get initialized(){return this.#d}get initializing(){return this.#g}isRunning(){return this.#d}getEngineState(){return this.#g?"booting":this.#d?"running":"stopped"}get audioContext(){return this.#e}get mode(){return this.#t.mode}get bufferConstants(){return this.#h.bufferConstants}get ringBufferBase(){return this.#h.ringBufferBase}get sharedBuffer(){return this.#h.sharedBuffer}get node(){return this.#l}get osc(){return this.#o}get initTime(){return this.#y?.getNTPStartTime()??0}on(e,t){return this.#u.on(e,t)}off(e,t){return this.#u.off(e,t),this}once(e,t){return this.#u.once(e,t)}removeAllListeners(e){return this.#u.removeAllListeners(e),this}async init(){if(!this.#d)return this.#p?this.#p:(this.#p=this.#k(),this.#p)}async#k(){this.#g=!0,this.bootStats.initStartTime=performance.now();try{this.#G(),this.#Y(),this.#N(),this.#$(),this.#v();let e=await this.#V();await this.#q(e),await this.#X(),await this.#Z()}catch(e){throw this.#g=!1,this.#p=null,console.error("[SuperSonic] Initialization failed:",e),this.#u.emit("error",e),e}}getMetrics(){return this.#W()}getMetricsArray(){return this.#re(),this.#h.getMergedArray()}getSnapshot(){let e=this.#W(),t=i.getMetricsSchema()?.metrics||{},s={};for(let[n,o]of Object.entries(e)){let a=t[n];a?.description?s[n]={value:o,description:a.description}:s[n]={value:o}}let r=null;return typeof performance<"u"&&performance.memory&&(r={usedJSHeapSize:performance.memory.usedJSHeapSize,totalJSHeapSize:performance.memory.totalJSHeapSize,jsHeapSizeLimit:performance.memory.jsHeapSizeLimit}),{timestamp:new Date().toISOString(),metrics:s,nodeTree:this.getRawTree(),memory:r}}getSystemReport(){this.#C("get system report");let e=this.#W(),t=[],s={userAgent:navigator.userAgent,hardwareConcurrency:navigator.hardwareConcurrency??null,deviceMemory:navigator.deviceMemory??null,platform:navigator.platform},r={sampleRate:this.#e.sampleRate,baseLatency:this.#e.baseLatency??null,outputLatency:this.#e.outputLatency??null,state:this.#e.state,channelCount:this.#t.worldOptions.numOutputBusChannels},n=this.#_.playbackStats?this.#e.playbackStats:null,o=n?{glitchCount:n.fallbackFramesEvents,glitchDurationS:n.fallbackFramesDuration,totalDurationS:n.totalFramesDuration,averageLatencyS:n.averageLatency,maximumLatencyS:n.maximumLatency}:null,a=this.#A?.getHealth()?.healthPct??100;a<95&&t.push({severity:a<80?"critical":"warning",message:`Audio health at ${a}% \u2014 audio thread may be falling behind`}),e.scsynthSchedulerLates>0&&t.push({severity:"warning",message:`${e.scsynthSchedulerLates} late bundles in scsynth scheduler`}),e.scsynthWasmErrors>0&&t.push({severity:"error",message:`${e.scsynthWasmErrors} WASM errors detected`}),n?.fallbackFramesEvents>0&&t.push({severity:"warning",message:`${n.fallbackFramesEvents} audio glitch events (${(n.fallbackFramesDuration*1e3).toFixed(1)}ms total silence)`}),e.driftOffsetMs!==void 0&&Math.abs(e.driftOffsetMs)>10&&t.push({severity:"warning",message:`Clock drift: ${e.driftOffsetMs}ms between AudioContext and wall clock`});let c=t.length===0?`Audio health: ${a}% \u2014 no issues detected`:`Audio health: ${a}% \u2014 ${t.length} issue(s): ${t.map(u=>u.message).join("; ")}`;return{timestamp:new Date().toISOString(),system:s,audio:r,playbackStats:o,engine:{mode:this.mode,version:this.#T,bootTimeMs:this.bootStats.initDuration},health:{audioHealthPct:a,issues:t,summary:c},metrics:e}}setClockOffset(e){this.#C("set clock offset"),this.#y?.setClockOffset(e)}async recover(){return this.#d?await this.resume()?!0:await this.reload():!1}async resume(){if(!this.#d||!this.#e)return!1;await this.purge();try{await this.#e.resume()}catch{}this.#y?.startDriftTimer();let e=this.#j();if(e===null){let r=this.#e.state==="running";return r&&(this.#y?.resync(),this.#u.emit("resumed")),r}await new Promise(r=>setTimeout(r,200));let t=this.#j(),s=t!==null&&t>e;return s&&(this.#y?.resync(),this.#u.emit("resumed")),s}async suspend(){if(this.#d){this.#y?.stopDriftTimer();try{await this.#e?.suspend()}catch{}}}async reload(){if(!this.#d)return!1;this.#u.emit("reload:start");let e=new Map(this.loadedSynthDefs),t=this.#i?.getAllocatedBuffers()||[];await this.#H(),await this.#z();for(let[s,r]of e)try{await this.send("/d_recv",r)}catch(n){console.error(`[SuperSonic] Failed to restore synthdef ${s}:`,n)}for(let s of t)try{if(this.#t.mode==="postMessage"&&s.source)s.source.type==="file"&&await this.loadSample(s.bufnum,s.source.path,s.source.startFrame||0,s.source.numFrames||0);else{let r=crypto.randomUUID();await this.send("/b_allocPtr",s.bufnum,s.ptr,s.numFrames,s.numChannels,s.sampleRate,r)}}catch(r){console.error(`[SuperSonic] Failed to restore buffer ${s.bufnum}:`,r)}return(e.size>0||t.length>0)&&await this.sync(),this.#u.emit("reload:complete",{success:!0}),!0}async#H(){this.#y?.stopDriftTimer(),this.#c?.clear(),this.#c=null,this.#o&&(this.#o.cancelAll(),this.#o.dispose(),this.#o=null),this.#r&&(this.#r.disconnect(),this.#r=null),this.#e&&(await this.#e.close(),this.#e=null),this.#d=!1,this.#U=null,this.loadedSynthDefs.clear(),this.#p=null,this.#M=null,this.#y?.reset(),this.#A?.reset()}async#z(){this.#g=!0,this.bootStats.initStartTime=performance.now();try{this.#N(),this.#i&&this.#i.updateAudioContext(this.#e),this.#v();let e=await this.#V();await this.#q(e),await this.#X(),await this.#Z()}catch(e){throw this.#g=!1,this.#p=null,console.error("[SuperSonic] Partial init failed:",e),this.#u.emit("error",e),e}}getRawTree(){if(!this.#d)return{nodeCount:0,version:0,droppedCount:0,nodes:[]};let e=this.#h.bufferConstants;if(!e)return{nodeCount:0,version:0,droppedCount:0,nodes:[]};let t,s;if(this.#t.mode==="postMessage"){let r=this.#h.getSnapshotBuffer();if(!r)return{nodeCount:0,version:0,droppedCount:0,nodes:[]};t=r,s=e.METRICS_SIZE}else{let r=this.#h.sharedBuffer;if(!r)return{nodeCount:0,version:0,droppedCount:0,nodes:[]};t=r,s=this.#h.ringBufferBase+e.NODE_TREE_START}return Bt(t,s,e)}getTree(){let e=this.getRawTree(),t=new Map,s=null;for(let a of e.nodes){let c={id:a.uuid||a.id,type:a.isGroup?"group":"synth",defName:a.defName,children:[]};t.set(a.id,{raw:a,tree:c}),(a.parentId===-1||a.parentId===0&&a.id===0)&&(s=a)}let r=t.size,n=a=>{let c=t.get(a);if(!c||!c.raw.isGroup)return;let u=c.raw.headId,l=0;for(;u!==-1&&u!==0&&l<r;){let f=t.get(u);if(!f)break;c.tree.children.push(f.tree),f.raw.isGroup&&n(u),u=f.raw.nextId,l++}},o=s?t.get(s.id).tree:null;return s&&n(s.id),{nodeCount:e.nodeCount,version:e.version,droppedCount:e.droppedCount,root:o||{id:0,type:"group",defName:"",children:[]}}}#F(e){this.#U||(this.#U=new Array(this.#h.bufferConstants.SHM_SCOPE_MAX_SCOPES));let t=this.#U[e];if(t)return t;let s=this.#h.bufferConstants,r=this.#h.sharedBuffer,o=this.#h.ringBufferBase+s.SHM_SCOPE_START+s.SHM_SCOPE_HEADER_SIZE+e*s.SHM_SCOPE_SLOT_SIZE,a=s.SHM_SCOPE_FRAMES_PER_SCOPE,c=a*s.SHM_SCOPE_CHANNELS,u=o+s.SHM_SCOPE_SLOT_HEADER_SIZE,l=[];for(let f=0;f<3;f++){let h=new Float32Array(r,u+f*c*4,c);l.push({left:h.subarray(0,a),right:h.subarray(a,a*2)})}return t={meta:new Uint32Array(r,o,4),stage:new Int32Array(r,o+8,1),framesPerScope:a,regions:l},this.#U[e]=t,t}getScope(e){if(!this.#d)return null;let t=this.#h.bufferConstants;if(!t||t.SHM_SCOPE_START==null||t.SHM_SCOPE_MAX_SCOPES==null||e<0||e>=t.SHM_SCOPE_MAX_SCOPES||!this.#h.sharedBuffer)return null;let s=this.#F(e);if(s.meta[0]===0)return null;let r=s.meta[1],n=Atomics.load(s.stage,0);if(n<0||n>2)return null;let o=s.regions[n];return{frames:s.framesPerScope,channels:r,left:o.left,right:r>=2?o.right:null}}getScopes(){if(!this.#d)return[];let e=this.#h.bufferConstants;if(!e||e.SHM_SCOPE_START==null||e.SHM_SCOPE_MAX_SCOPES==null)return[];if(!this.#h.sharedBuffer)return[];let t=[];for(let s=0;s<e.SHM_SCOPE_MAX_SCOPES;s++){let r=this.#F(s);r.meta[0]!==0&&t.push({index:s,channels:r.meta[1]})}return t}static getScopeSchema(){return{maxScopes:32,framesPerScope:1024,channels:2}}startCapture(){if(this.#C("start capture"),!this.#b.isAvailable())throw new Error("Audio capture is only available in SAB mode (set mode: 'sab').");this.#b.start()}stopCapture(){return this.#C("stop capture"),this.#b.stop()}isCaptureEnabled(){return this.#b.isEnabled()}getCaptureFrames(){return this.#b.getFrameCount()}getMaxCaptureDuration(){return this.#b.getMaxDuration()}send(e,...t){this.#C("send OSC messages");let s={"/d_load":"Use loadSynthDef() or send /d_recv with synthdef bytes instead.","/d_loadDir":"Use loadSynthDef() or send /d_recv with synthdef bytes instead.","/b_read":"Use loadSample() to load audio into a buffer.","/b_readChannel":"Use loadSample() to load audio into a buffer.","/b_write":"Writing audio files is not available in the browser.","/b_close":"Writing audio files is not available in the browser.","/clearSched":"Use purge() to clear both the JS prescheduler and WASM scheduler.","/error":"SuperSonic always enables error notifications so you never miss a /fail message.","/quit":"Use destroy() to shut down SuperSonic."};if(s[e])throw new Error(`${e} is not supported in SuperSonic. ${s[e]}`);if(e==="/d_recv"){let o=t[0];if(o instanceof Uint8Array||o instanceof ArrayBuffer){let a=o instanceof ArrayBuffer?new Uint8Array(o):o,c=H(a)||"unknown";this.loadedSynthDefs.set(c,a)}}if(e==="/d_free")for(let o of t)typeof o=="string"&&this.loadedSynthDefs.delete(o);else e==="/d_freeAll"&&this.loadedSynthDefs.clear();let r=t.map(o=>o instanceof ArrayBuffer?new Uint8Array(o):o);if(Mr.has(e)){this.#oe(e,r),this.#ae(e,r);return}let n=i.osc.encodeMessage(e,r);this.sendOSC(n)}sendOSC(e,t={}){this.#C("send OSC data");let s=this.#ne(e);this.#Q(s,t)}cancelTag(e){this.#C("cancel by tag"),this.#o.cancelTag(e)}cancelSession(e){this.#C("cancel by session"),this.#o.cancelSession(e)}cancelSessionTag(e,t){this.#C("cancel by session and tag"),this.#o.cancelSessionTag(e,t)}cancelAll(){this.#C("cancel all scheduled"),this.#o.cancelAll()}async purge(){this.#C("purge");let e=this.#o.cancelAllWithAck(),t=new Promise(s=>{let r=n=>{n.data.type==="clearSchedAck"&&(this.#r.port.removeEventListener("message",r),s())};this.#r.port.addEventListener("message",r),this.#r.port.postMessage({type:"clearSched",ack:!0})});await Promise.all([e,t])}createOscChannel(e={}){return this.#C("create OSC channel"),this.#o.createOscChannel(e)}nextNodeId(){return this.#C("allocate node IDs"),this.#M.nextNodeId()}async loadSynthDef(e){this.#C("load synthdef");let t,s;if(typeof e=="string"){let r;if(this.#ie(e))r=e;else{if(!this.#m)throw new Error("synthdefBaseURL not configured.");r=`${this.#m}${e}.scsyndef`}let n=H(r),o=await this.#E.fetch(r,{type:"synthdef",name:n});t=new Uint8Array(o),s=H(t)||n}else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){if(t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=H(t),!s)throw new Error("Could not extract synthdef name from binary data. Make sure it's a valid .scsyndef file.")}else if(e instanceof Blob){let r=await e.arrayBuffer();if(t=new Uint8Array(r),s=H(t),!s)throw new Error("Could not extract synthdef name from file. Make sure it's a valid .scsyndef file.")}else throw new Error("loadSynthDef source must be a name, path/URL string, ArrayBuffer, Uint8Array, or File/Blob");return await this.send("/d_recv",t),{name:s,size:t.length}}async loadSynthDefs(e){this.#C("load synthdefs");let t={};return await Promise.all(e.map(async s=>{try{await this.loadSynthDef(s),t[s]={success:!0}}catch(r){t[s]={success:!1,error:r.message}}})),t}async loadSample(e,t,s=0,r=0){this.#C("load samples");let n;if(typeof t=="string")n=await this.#i.prepareFromFile({bufnum:e,path:t,startFrame:s,numFrames:r});else if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))n=await this.#i.prepareFromBlob({bufnum:e,blob:t,startFrame:s,numFrames:r});else if(t instanceof Blob){let u=await t.arrayBuffer();n=await this.#i.prepareFromBlob({bufnum:e,blob:u,startFrame:s,numFrames:r})}else throw new Error("loadSample source must be a path/URL string, ArrayBuffer, TypedArray, or File/Blob");await this.send("/b_allocPtr",e,n.ptr,n.numFrames,n.numChannels,n.sampleRate,n.uuid),await n.allocationComplete;let{numFrames:o,numChannels:a,sampleRate:c}=n;return{bufnum:e,hash:n.hash,source:typeof t=="string"?t:null,numFrames:o,numChannels:a,sampleRate:c,duration:c>0?o/c:0}}getLoadedBuffers(){return this.#C("get loaded buffers"),(this.#i?.getAllocatedBuffers()||[]).map(({bufnum:t,numFrames:s,numChannels:r,sampleRate:n,source:o,hash:a})=>({bufnum:t,hash:a||null,source:o?.path||o?.name||null,numFrames:s,numChannels:r,sampleRate:n,duration:n>0?s/n:0}))}async sampleInfo(e,t=0,s=0){this.#C("get sample info");let r;if(typeof e=="string")r=e;else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))r=e;else if(e instanceof Blob)r=await e.arrayBuffer();else throw new Error("sampleInfo source must be a path/URL string, ArrayBuffer, TypedArray, or File/Blob");return this.#i.sampleInfo({source:r,startFrame:t,numFrames:s})}async sync(e=Math.floor(Math.random()*2147483647)){this.#C("sync"),await this.#ce();let t=new Promise((s,r)=>{let n=setTimeout(()=>{this.#c?.delete(e),r(new Error("Timeout waiting for /synced response"))},Tr),o=()=>{clearTimeout(n),this.#c.delete(e),s()};this.#c||(this.#c=new Map),this.#c.set(e,o)});this.send("/sync",e),await t,this.#t.mode==="postMessage"&&await new Promise(s=>setTimeout(s,this.#t.snapshotIntervalMs*2))}getInfo(){return this.#C("get info"),{sampleRate:this.#e.sampleRate,numBuffers:this.#t.worldOptions.numBuffers,totalMemory:this.#t.memory.totalMemory,wasmHeapSize:this.#t.memory.wasmHeapSize,bufferPoolSize:this.#t.memory.bufferPoolSize,bootTimeMs:this.bootStats.initDuration,capabilities:{...this.#_},version:this.#T}}async shutdown(){!this.#d&&!this.#g||(this.#u.emit("shutdown"),this.#y?.stopDriftTimer(),this.#A?.reset(),this.#A=null,this.#c?.clear(),this.#c=null,this.#o&&(this.#o.cancelAll(),this.#o.dispose(),this.#o=null),this.#r&&(this.#r.disconnect(),this.#r=null),this.#e&&(await this.#e.close(),this.#e=null),this.#i&&(this.#i.destroy(),this.#i=null),this.#n=null,this.#M=null,this.#P=Promise.resolve(),this.#d=!1,this.#U=null,this.loadedSynthDefs.clear(),this.#p=null,this.#a=null,this.#y?.reset(),this.bootStats={initStartTime:null,initDuration:null})}async destroy(){this.#u.emit("destroy"),await this.shutdown(),this.#R=null,this.#u.removeAllListeners()}async reset(){await this.shutdown(),await this.init()}#G(){this.#_={audioWorklet:typeof AudioWorklet<"u",sharedArrayBuffer:typeof SharedArrayBuffer<"u",crossOriginIsolated:window.crossOriginIsolated===!0,atomics:typeof Atomics<"u",webWorker:typeof Worker<"u",playbackStats:typeof AudioContext<"u"&&"playbackStats"in AudioContext.prototype};let e=this.#t.mode,t=["audioWorklet","webWorker"];e==="sab"&&t.push("sharedArrayBuffer","crossOriginIsolated","atomics");let s=t.filter(r=>!this.#_[r]);if(s.length>0){let r=new Error(`Missing required features for ${e} mode: ${s.join(", ")}`);throw e==="sab"&&!this.#_.crossOriginIsolated&&(r.message+=`
18
18
 
19
- Consider using mode: 'postMessage' which doesn't require COOP/COEP headers.`),r}if(e!=="sab"&&e!=="postMessage")throw new Error(`Invalid mode: '${e}'. Use 'sab' or 'postMessage'.`)}#K(){let e=this.#r.memory;if(this.#r.mode==="sab"){let s=$.totalPages,r=Math.max(Math.ceil(e.totalMemory/65536),s),n=Math.ceil(e.maxTotalMemory/65536);this.#c=new WebAssembly.Memory({initial:r,maximum:n,shared:!0})}else this.#c=null}#L(){this.#r.audioContext?this.#e=this.#r.audioContext:this.#e=new AudioContext(this.#r.audioContextOptions),this.#e.addEventListener("statechange",()=>{let e=this.#e?.state;if(!e)return;let t=this.#R;this.#R=e,e==="running"&&(t==="suspended"||t==="interrupted")&&this.#S?.resync(),this.#a.emit("audiocontext:statechange",{state:e}),e==="suspended"?(this.#a.emit("audiocontext:suspended"),this.#A?.reset()):e==="running"?(this.#a.emit("audiocontext:resumed"),this.#A?.reset()):e==="interrupted"&&(this.#a.emit("audiocontext:interrupted"),this.#A?.reset())}),this.#A=new se({audioContext:this.#e})}#Z(){let e=this.#r.mode==="sab"?this.#c.buffer:null;this.#n=new Z({mode:this.#r.mode,audioContext:this.#e,sharedBuffer:e,bufferPoolConfig:{start:this.#r.memory.bufferPoolOffset,size:this.#r.memory.bufferPoolSize,maxSize:this.#r.effectiveMaxBufferMemory},sampleBaseURL:this.#u,maxBuffers:this.#r.worldOptions.numBuffers,assetLoader:this.#_,wasmMemory:this.#c,maxBufferMemory:this.#r.effectiveMaxBufferMemory,bufferGrowIncrement:this.#r.bufferGrowIncrement,growFn:this.#r.mode==="postMessage"?t=>this.#J(t):null,onBufferPoolGrowth:t=>{this.#a.emit("buffer:pool:grown",t)}})}#k(){this.#i=new Q({bufferManager:this.#n,getDefaultSampleRate:()=>this.#e?.sampleRate||44100})}async#F(){if(this.#O)return this.#O;let e=this.#r.wasmUrl.split("/").pop();if(this.#r.wasmBytes){let s=this.#r.wasmBytes;return this.#a.emit("loading:start",{type:"wasm",name:e,size:s.byteLength}),this.#a.emit("loading:complete",{type:"wasm",name:e,size:s.byteLength}),this.#O=s,s}let t=await this.#_.fetch(this.#r.wasmUrl,{type:"wasm",name:e});return this.#O=t,t}async#x(e){await Xe(this.#e.audioWorklet,this.#r.workletUrl);let t=this.#r.worldOptions.numOutputBusChannels;if(this.#s=new AudioWorkletNode(this.#e,"scsynth-processor",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[t]}),this.#r.autoConnect){let o=this.#e.destination;t>2&&(o.channelCount=Math.min(t,o.maxChannelCount),o.channelInterpretation="discrete"),this.#s.connect(o)}this.#f=this.#j(),this.#s.port.start(),this.#ee();let s=this.#r.mode,r=s==="sab"?this.#c.buffer:null;this.#s.port.postMessage({type:"init",mode:s,sharedBuffer:r,snapshotIntervalMs:this.#r.snapshotIntervalMs});let n={type:"loadWasm",wasmBytes:e,worldOptions:this.#r.worldOptions,sampleRate:this.#e.sampleRate};if(s==="sab")n.wasmMemory=this.#c;else{let o=$.totalPages;n.memoryPages=Math.max(Math.ceil(this.#r.memory.totalMemory/65536),o),n.maxMemoryPages=Math.ceil(this.#r.memory.maxTotalMemory/65536)}this.#s.port.postMessage(n),await this.#Q(),this.#n.setWorkletPort(this.#s.port)}#j(){let e=this.#s;return Object.freeze({connect:(...t)=>e.connect(...t),disconnect:(...t)=>e.disconnect(...t),get context(){return e.context},get numberOfOutputs(){return e.numberOfOutputs},get numberOfInputs(){return e.numberOfInputs},get channelCount(){return e.channelCount},get input(){return e}})}async#N(){let e=this.#r.mode,t=this.#g.bufferConstants,s=this.#g.ringBufferBase,r=this.#g.sharedBuffer,n={workerBaseURL:this.#r.workerBaseURL,preschedulerCapacity:this.#r.preschedulerCapacity,snapshotIntervalMs:this.#r.snapshotIntervalMs,bypassLookaheadS:this.#r.bypassLookaheadMs/1e3,getAudioContextTime:()=>this.#e?.currentTime??0,getNTPStartTime:()=>this.#S?.getNTPStartTime()??0};if(e==="sab"){if(n.sharedBuffer=r,n.ringBufferBase=s,n.bufferConstants=t,t?.NODE_ID_COUNTER_START!==void 0){let o=s+t.NODE_ID_COUNTER_START,a=new Int32Array(r,o,1);Atomics.store(a,0,1e3)}}else{this.#M=1e3,n.nodeIdSource=u=>{let f=this.#M;return this.#M+=u,{from:f,to:f+u}};let o=1e4,a=n.nodeIdSource(o),c=new MessageChannel,l=n.nodeIdSource;c.port1.onmessage=u=>{if(u.data.type==="requestNodeIdRange"){let f=l(o);c.port1.postMessage({type:"nodeIdRange",from:f.from,to:f.to})}},this.#s.port.postMessage({type:"nodeIdRange",from:a.from,to:a.to},[c.port2])}if(this.#o=Je(e,n),this.#o.onReply((o,a,c)=>{let l=$e(o)||null;this.#a.emit("in:osc",{oscData:o,sequence:a,timestamp:c,scheduledTime:l});try{let u=G(o),f=u[0],h=u.slice(1);if(f==="/supersonic/buffer/freed")this.#n?.handleBufferFreed(h);else if(f==="/supersonic/buffer/allocated")this.#n?.handleBufferAllocated(h);else if(f==="/synced"&&h.length>0){let S=h[0];this.#l?.has(S)&&this.#l.get(S)(u)}if(this.#a.emit("in",u),this.#a.hasListeners("in:text")||this.#r.debug||this.#r.debugOscIn){let S=this.#r.activityEvent.oscInMaxLineLength??this.#r.activityEvent.maxLineLength,m=h.map(p=>kt(p,S)).join(", ")||"",E=`${f}${m?" "+m:""}`;this.#a.emit("in:text",{text:E,sequence:a,timestamp:c})}if(this.#a.hasListeners("in:html")){let S=Ye(u,a,c,this.initTime);this.#a.emit("in:html",{html:S,sequence:a,timestamp:c})}}catch(u){console.error("[SuperSonic] Failed to decode OSC message:",u)}}),this.#o.onDebug(o=>{let a=this.#r.activityEvent.scsynthMaxLineLength??this.#r.activityEvent.maxLineLength;a>0&&o.text?.length>a&&(o={...o,text:o.text.slice(0,a)+"..."}),this.#a.emit("debug",o)}),this.#o.onError((o,a)=>{console.error(`[SuperSonic] ${a} error:`,o),this.#a.emit("error",new Error(`${a}: ${o}`))}),this.#o.onOscLog(o=>{for(let a of o){let c=$e(a.oscData)||null;if(this.#a.emit("out:osc",{oscData:a.oscData,sourceId:a.sourceId,sequence:a.sequence,timestamp:a.timestamp,scheduledTime:c}),this.#a.hasListeners("out")||this.#a.hasListeners("out:text")||this.#a.hasListeners("out:html")||this.#r.debug||this.#r.debugOscOut)try{let u=G(a.oscData);if(this.#a.emit("out",u),this.#a.hasListeners("out:text")||this.#r.debug||this.#r.debugOscOut){let f=this.#r.activityEvent.oscOutMaxLineLength??this.#r.activityEvent.maxLineLength,h=u[0],m=u.slice(1).map(p=>kt(p,f)).join(", "),E=`${h}${m?" "+m:""}`;this.#a.emit("out:text",{text:E,sequence:a.sequence,timestamp:a.timestamp})}if(this.#a.hasListeners("out:html")){let f=Er(u,a.sequence,a.timestamp,this.initTime,a.sourceId);this.#a.emit("out:html",{html:f,sequence:a.sequence,timestamp:a.timestamp})}}catch{}}}),(this.#r.debug||this.#r.debugOscIn)&&this.on("in:text",({text:o})=>console.log(`[\u2190 OSC] ${o}`)),(this.#r.debug||this.#r.debugOscOut)&&this.on("out:text",({text:o})=>console.log(`[OSC \u2192] ${o}`)),(this.#r.debug||this.#r.debugScsynth)&&this.on("debug",o=>console.log(`[synth] ${o.text}`)),e==="sab")await this.#o.initialize();else{if(await this.#o.initialize(this.#s.port),this.#o.setBufferConstants(t),this.#B?.length>0)for(let o of this.#B)this.#o.handleDebugRaw(o);this.#D=o=>this.#o.handleDebugRaw(o),this.#B=[]}this.#w=this.#o.createOscChannel({sourceId:0})}async#v(){this.#p=!0,this.#h=!1,this.bootStats.initDuration=performance.now()-this.bootStats.initStartTime,await this.#a.emitAsync("setup"),this.#a.emit("ready",{capabilities:this.#b,bootStats:this.bootStats})}#Q(){return new Promise((e,t)=>{let s=setTimeout(()=>{t(new Error("AudioWorklet initialization timeout"))},mr),r=async n=>{if(n.data.type==="error"){clearTimeout(s),this.#s.port.removeEventListener("message",r),t(new Error(n.data.error||"AudioWorklet error"));return}if(n.data.type==="initialized")if(clearTimeout(s),this.#s.port.removeEventListener("message",r),n.data.success){let o=n.data.ringBufferBase??0,a=n.data.bufferConstants,c=this.#r.mode==="sab"?this.#c.buffer:null;this.#g.initSharedViews(c,o,a);let l=this.#r.worldOptions?.maxNodes??1024,u=a?.NODE_TREE_MIRROR_MAX_NODES??1024;l>u&&console.warn(`SuperSonic: maxNodes (${l}) exceeds NODE_TREE_MIRROR_MAX_NODES (${u}). The node tree mirror will not show all nodes. Rebuild with NODE_TREE_MIRROR_MAX_NODES=${l} to fix.`),this.#S=new te({mode:this.#r.mode,audioContext:this.#e,workletPort:this.#s.port}),this.#S.initSharedViews(c,o,a),await this.#S.initialize(),this.#S.startDriftTimer(),this.#r.mode==="sab"&&this.#C.update(c,o,a),this.#r.mode==="postMessage"&&n.data.initialSnapshot&&this.#g.updateSnapshot(n.data.initialSnapshot),e()}else t(new Error(n.data.error||"AudioWorklet initialization failed"))};this.#s.port.addEventListener("message",r),this.#s.port.start()})}#J(e){return new Promise(t=>{let s=crypto.randomUUID(),r=n=>{n.data.type==="memoryGrown"&&n.data.growId===s&&(this.#s.port.removeEventListener("message",r),t(n.data.success))};this.#s.port.addEventListener("message",r),this.#s.port.postMessage({type:"growMemory",growId:s,pages:e})})}#ee(){this.#s.port.addEventListener("message",e=>{let{data:t}=e;switch(t.type){case"error":console.error("[Worklet] Error:",t.error),this.#a.emit("error",new Error(t.error));break;case"version":this.#y=t.version;break;case"snapshot":t.buffer&&(this.#g.updateSnapshot(t.buffer),this.#I=t.snapshotsSent);break;case"debugRawBatch":this.#D?this.#D(t):this.#B.push(t);break}})}#H(){return{preschedulerMetrics:this.#o?.getPreschedulerMetrics(),transportMetrics:this.#o?.getMetrics(),driftOffsetMs:this.#S?.getDriftOffset()??0,ntpStartTime:this.#S?.getNTPStartTime()??0,clockOffsetMs:this.#S?.getClockOffset()??0,audioContextState:this.#e?.state||"unknown",bufferPoolStats:this.#n?.getStats(),bufferPoolGrowthStats:this.#n?.getGrowthStats(),loadedSynthDefsCount:this.loadedSynthDefs?.size||0,preschedulerCapacity:this.#r.preschedulerCapacity,audioHealthPct:this.#A?.update()??100,playbackStats:this.#b.playbackStats?this.#e?.playbackStats:null}}#P(){return this.#g.gatherMetrics(this.#H())}#te(){this.#g.updateMergedArray(this.#H())}#z(){if(this.#r.mode==="sab"){let t=this.#g.getMetricsView();return t?t[0]:null}let e=this.#g.getSnapshotBuffer();return e?new Uint32Array(e,0,1)[0]:null}#T(e="perform this operation"){if(!this.#p)throw new Error(`SuperSonic not initialized. Call init() before attempting to ${e}.`)}#se(e){return e.includes("/")||e.includes("://")}#re(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new Error("oscData must be ArrayBuffer or Uint8Array")}#G(e,t={}){let s=this.#w.classify(e);if(V(s))this.#r.mode==="sab"?this.#w.send(e):this.#o.sendImmediate(e,s);else{let r=this.#g.bufferConstants?.scheduler_slot_size;if(r&&e.length>r)throw new Error(`OSC bundle too large to schedule (${e.length} > ${r} bytes). Use immediate timestamp (0 or 1) for large messages, or reduce bundle size.`);this.#o.sendWithOptions(e,t)}}#ie(e,t){let s=(o,a)=>{let c=t[o];if(!Number.isFinite(c))throw new Error(a)},r=(o,a)=>{if(typeof t[o]!="string")throw new Error(a)},n=(o,a)=>{let c=t[o];if(!(c instanceof Uint8Array||c instanceof ArrayBuffer))throw new Error(a)};switch(e){case"/b_alloc":s(0,"/b_alloc requires a buffer number"),s(1,"/b_alloc requires a frame count");break;case"/b_allocRead":s(0,"/b_allocRead requires a buffer number"),r(1,"/b_allocRead requires a file path");break;case"/b_allocReadChannel":s(0,"/b_allocReadChannel requires a buffer number"),r(1,"/b_allocReadChannel requires a file path");break;case"/b_allocFile":s(0,"/b_allocFile requires a buffer number"),n(1,"/b_allocFile requires audio file data as blob");break}}#ne(e,t){this.#U=this.#U.then(async()=>{let s=[e,...t],{packet:r}=await this.#i.rewritePacket(s),n=i.osc.encodeMessage(r[0],r.slice(1));this.#G(n)}).catch(s=>{console.error(`[SuperSonic] Buffer command ${e} failed:`,s),this.#a.emit("error",s)})}#oe(){return this.#U}},Hi=We.osc;export{w as OscChannel,We as SuperSonic,Hi as osc};
19
+ Consider using mode: 'postMessage' which doesn't require COOP/COEP headers.`),r}if(e!=="sab"&&e!=="postMessage")throw new Error(`Invalid mode: '${e}'. Use 'sab' or 'postMessage'.`)}#Y(){let e=this.#t.memory;if(this.#t.mode==="sab"){let s=U.totalPages,r=Math.max(Math.ceil(e.totalMemory/65536),s),n=Math.ceil(e.maxTotalMemory/65536);this.#a=new WebAssembly.Memory({initial:r,maximum:n,shared:!0})}else this.#a=null}#N(){this.#t.audioContext?this.#e=this.#t.audioContext:this.#e=new AudioContext(this.#t.audioContextOptions),this.#e.addEventListener("statechange",()=>{let e=this.#e?.state;if(!e)return;let t=this.#B;this.#B=e,e==="running"&&(t==="suspended"||t==="interrupted")&&this.#y?.resync(),this.#u.emit("audiocontext:statechange",{state:e}),e==="suspended"?(this.#u.emit("audiocontext:suspended"),this.#A?.reset()):e==="running"?(this.#u.emit("audiocontext:resumed"),this.#A?.reset()):e==="interrupted"&&(this.#u.emit("audiocontext:interrupted"),this.#A?.reset())}),this.#A=new ne({audioContext:this.#e})}#$(){let e=this.#t.mode==="sab"?this.#a.buffer:null;this.#i=new J({mode:this.#t.mode,audioContext:this.#e,sharedBuffer:e,bufferPoolConfig:{start:this.#t.memory.bufferPoolOffset,size:this.#t.memory.bufferPoolSize,maxSize:this.#t.effectiveMaxBufferMemory},sampleBaseURL:this.#f,maxBuffers:this.#t.worldOptions.numBuffers,assetLoader:this.#E,wasmMemory:this.#a,maxBufferMemory:this.#t.effectiveMaxBufferMemory,bufferGrowIncrement:this.#t.bufferGrowIncrement,growFn:this.#t.mode==="postMessage"?t=>this.#te(t):null,onBufferPoolGrowth:t=>{this.#u.emit("buffer:pool:grown",t)}})}#v(){this.#n=new te({bufferManager:this.#i,getDefaultSampleRate:()=>this.#e?.sampleRate||44100})}async#V(){if(this.#R)return this.#R;let e=this.#t.wasmUrl.split("/").pop();if(this.#t.wasmBytes){let s=this.#t.wasmBytes;return this.#u.emit("loading:start",{type:"wasm",name:e,size:s.byteLength}),this.#u.emit("loading:complete",{type:"wasm",name:e,size:s.byteLength}),this.#R=s,s}let t=await this.#E.fetch(this.#t.wasmUrl,{type:"wasm",name:e});return this.#R=t,t}async#q(e){await Qe(this.#e.audioWorklet,this.#t.workletUrl);let t=this.#t.worldOptions.numOutputBusChannels;if(this.#r=new AudioWorkletNode(this.#e,"scsynth-processor",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[t]}),this.#t.autoConnect){let o=this.#e.destination;t>2&&(o.channelCount=Math.min(t,o.maxChannelCount),o.channelInterpretation="discrete"),this.#r.connect(o)}this.#l=this.#J(),this.#r.port.start(),this.#se();let s=this.#t.mode,r=s==="sab"?this.#a.buffer:null;this.#r.port.postMessage({type:"init",mode:s,sharedBuffer:r,snapshotIntervalMs:this.#t.snapshotIntervalMs});let n={type:"loadWasm",wasmBytes:e,worldOptions:{...this.#t.worldOptions,rtPoolOffset:this.#t.memory.rtPoolOffset},sampleRate:this.#e.sampleRate};if(s==="sab")n.wasmMemory=this.#a;else{let o=U.totalPages;n.memoryPages=Math.max(Math.ceil(this.#t.memory.totalMemory/65536),o),n.maxMemoryPages=Math.ceil(this.#t.memory.maxTotalMemory/65536)}this.#r.port.postMessage(n),await this.#ee(),this.#i.setWorkletPort(this.#r.port)}#J(){let e=this.#r;return Object.freeze({connect:(...t)=>e.connect(...t),disconnect:(...t)=>e.disconnect(...t),get context(){return e.context},get numberOfOutputs(){return e.numberOfOutputs},get numberOfInputs(){return e.numberOfInputs},get channelCount(){return e.channelCount},get input(){return e}})}async#X(){let e=this.#t.mode,t=this.#h.bufferConstants,s=this.#h.ringBufferBase,r=this.#h.sharedBuffer,n={workerBaseURL:this.#t.workerBaseURL,preschedulerCapacity:this.#t.preschedulerCapacity,snapshotIntervalMs:this.#t.snapshotIntervalMs,bypassLookaheadS:this.#t.bypassLookaheadMs/1e3,getAudioContextTime:()=>this.#e?.currentTime??0,getNTPStartTime:()=>this.#y?.getNTPStartTime()??0};if(e==="sab"){if(n.sharedBuffer=r,n.ringBufferBase=s,n.bufferConstants=t,t?.NODE_ID_COUNTER_START!==void 0){let o=s+t.NODE_ID_COUNTER_START,a=new Int32Array(r,o,1);Atomics.store(a,0,1e3)}}else{this.#w=1e3,n.nodeIdSource=l=>{let f=this.#w;return this.#w+=l,{from:f,to:f+l}};let o=1e4,a=n.nodeIdSource(o),c=new MessageChannel,u=n.nodeIdSource;c.port1.onmessage=l=>{if(l.data.type==="requestNodeIdRange"){let f=u(o);c.port1.postMessage({type:"nodeIdRange",from:f.from,to:f.to})}},this.#r.port.postMessage({type:"nodeIdRange",from:a.from,to:a.to},[c.port2])}if(this.#o=nt(e,n),this.#o.onReply((o,a,c)=>{let u=We(o)||null;this.#u.emit("in:osc",{oscData:o,sequence:a,timestamp:c,scheduledTime:u});try{let l=W(o),f=l[0],h=l.slice(1);if(f==="/supersonic/buffer/freed")this.#i?.handleBufferFreed(h);else if(f==="/supersonic/buffer/allocated")this.#i?.handleBufferAllocated(h);else if(f==="/synced"&&h.length>0){let y=h[0];this.#c?.has(y)&&this.#c.get(y)(l)}if(this.#u.emit("in",l),this.#u.hasListeners("in:text")||this.#t.debug||this.#t.debugOscIn){let y=this.#t.activityEvent.oscInMaxLineLength??this.#t.activityEvent.maxLineLength,p=h.map(m=>zt(m,y)).join(", ")||"",d=`${f}${p?" "+p:""}`;this.#u.emit("in:text",{text:d,sequence:a,timestamp:c})}if(this.#u.hasListeners("in:html")){let y=qe(l,a,c,this.initTime);this.#u.emit("in:html",{html:y,sequence:a,timestamp:c})}}catch(l){console.error("[SuperSonic] Failed to decode OSC message:",l)}}),this.#o.onDebug(o=>{let a=this.#t.activityEvent.scsynthMaxLineLength??this.#t.activityEvent.maxLineLength;a>0&&o.text?.length>a&&(o={...o,text:o.text.slice(0,a)+"..."}),this.#u.emit("debug",o)}),this.#o.onError((o,a)=>{console.error(`[SuperSonic] ${a} error:`,o),this.#u.emit("error",new Error(`${a}: ${o}`))}),this.#o.onOscLog(o=>{for(let a of o){let c=We(a.oscData)||null;if(this.#u.emit("out:osc",{oscData:a.oscData,sourceId:a.sourceId,sequence:a.sequence,timestamp:a.timestamp,scheduledTime:c}),this.#u.hasListeners("out")||this.#u.hasListeners("out:text")||this.#u.hasListeners("out:html")||this.#t.debug||this.#t.debugOscOut)try{let l=W(a.oscData);if(this.#u.emit("out",l),this.#u.hasListeners("out:text")||this.#t.debug||this.#t.debugOscOut){let f=this.#t.activityEvent.oscOutMaxLineLength??this.#t.activityEvent.maxLineLength,h=l[0],p=l.slice(1).map(m=>zt(m,f)).join(", "),d=`${h}${p?" "+p:""}`;this.#u.emit("out:text",{text:d,sequence:a.sequence,timestamp:a.timestamp})}if(this.#u.hasListeners("out:html")){let f=Rr(l,a.sequence,a.timestamp,this.initTime,a.sourceId);this.#u.emit("out:html",{html:f,sequence:a.sequence,timestamp:a.timestamp})}}catch{}}}),(this.#t.debug||this.#t.debugOscIn)&&this.on("in:text",({text:o})=>console.log(`[\u2190 OSC] ${o}`)),(this.#t.debug||this.#t.debugOscOut)&&this.on("out:text",({text:o})=>console.log(`[OSC \u2192] ${o}`)),(this.#t.debug||this.#t.debugScsynth)&&this.on("debug",o=>console.log(`[synth] ${o.text}`)),e==="sab")await this.#o.initialize();else{if(await this.#o.initialize(this.#r.port),this.#o.setBufferConstants(t),this.#O?.length>0)for(let o of this.#O)this.#o.handleDebugRaw(o);this.#D=o=>this.#o.handleDebugRaw(o),this.#O=[]}this.#M=this.#o.createOscChannel({sourceId:0})}async#Z(){this.#d=!0,this.#g=!1,this.bootStats.initDuration=performance.now()-this.bootStats.initStartTime,await this.#u.emitAsync("setup"),this.#u.emit("ready",{capabilities:this.#_,bootStats:this.bootStats})}#ee(){return new Promise((e,t)=>{let s=setTimeout(()=>{t(new Error("AudioWorklet initialization timeout"))},wr),r=async n=>{if(n.data.type==="error"){clearTimeout(s),this.#r.port.removeEventListener("message",r),t(new Error(n.data.error||"AudioWorklet error"));return}if(n.data.type==="initialized")if(clearTimeout(s),this.#r.port.removeEventListener("message",r),n.data.success){let o=n.data.ringBufferBase??0,a=n.data.bufferConstants,c=this.#t.mode==="sab"?this.#a.buffer:null;this.#h.initSharedViews(c,o,a);let u=this.#t.worldOptions?.maxNodes??1024,l=a?.NODE_TREE_MIRROR_MAX_NODES??1024;u>l&&console.warn(`SuperSonic: maxNodes (${u}) exceeds NODE_TREE_MIRROR_MAX_NODES (${l}). The node tree mirror will not show all nodes. Rebuild with NODE_TREE_MIRROR_MAX_NODES=${u} to fix.`),this.#y=new ie({mode:this.#t.mode,audioContext:this.#e,workletPort:this.#r.port}),this.#y.initSharedViews(c,o,a),await this.#y.initialize(),this.#y.startDriftTimer(),this.#t.mode==="sab"&&this.#b.update(c,o,a),this.#t.mode==="postMessage"&&n.data.initialSnapshot&&this.#h.updateSnapshot(n.data.initialSnapshot),e()}else t(new Error(n.data.error||"AudioWorklet initialization failed"))};this.#r.port.addEventListener("message",r),this.#r.port.start()})}#te(e){return new Promise(t=>{let s=crypto.randomUUID(),r=n=>{n.data.type==="memoryGrown"&&n.data.growId===s&&(this.#r.port.removeEventListener("message",r),t(n.data.success))};this.#r.port.addEventListener("message",r),this.#r.port.postMessage({type:"growMemory",growId:s,pages:e})})}#se(){this.#r.port.addEventListener("message",e=>{let{data:t}=e;switch(t.type){case"error":console.error("[Worklet] Error:",t.error),this.#u.emit("error",new Error(t.error));break;case"version":this.#T=t.version;break;case"snapshot":t.buffer&&(this.#h.updateSnapshot(t.buffer),this.#I=t.snapshotsSent);break;case"debugRawBatch":this.#D?this.#D(t):this.#O.push(t);break}})}#K(){return{preschedulerMetrics:this.#o?.getPreschedulerMetrics(),transportMetrics:this.#o?.getMetrics(),driftOffsetMs:this.#y?.getDriftOffset()??0,ntpStartTime:this.#y?.getNTPStartTime()??0,clockOffsetMs:this.#y?.getClockOffset()??0,audioContextState:this.#e?.state||"unknown",bufferPoolStats:this.#i?.getStats(),bufferPoolGrowthStats:this.#i?.getGrowthStats(),loadedSynthDefsCount:this.loadedSynthDefs?.size||0,preschedulerCapacity:this.#t.preschedulerCapacity,audioHealthPct:this.#A?.update()??100,playbackStats:this.#_.playbackStats?this.#e?.playbackStats:null}}#W(){return this.#h.gatherMetrics(this.#K())}#re(){this.#h.updateMergedArray(this.#K())}#j(){if(this.#t.mode==="sab"){let t=this.#h.getMetricsView();return t?t[0]:null}let e=this.#h.getSnapshotBuffer();return e?new Uint32Array(e,0,1)[0]:null}#C(e="perform this operation"){if(!this.#d)throw new Error(`SuperSonic not initialized. Call init() before attempting to ${e}.`)}#ie(e){return e.includes("/")||e.includes("://")}#ne(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new Error("oscData must be ArrayBuffer or Uint8Array")}#Q(e,t={}){let s=this.#M.classify(e);if(Z(s))this.#t.mode==="sab"?this.#M.send(e):this.#o.sendImmediate(e,s);else{let r=this.#h.bufferConstants,n=r?Math.min(r.IN_BUFFER_SIZE||1/0,r.scheduler_data_pool_size||1/0):1/0;if(e.length>n)throw new Error(`OSC bundle too large to schedule (${e.length} > ${n} bytes).`);this.#o.sendWithOptions(e,t)}}#oe(e,t){let s=(o,a)=>{let c=t[o];if(!Number.isFinite(c))throw new Error(a)},r=(o,a)=>{if(typeof t[o]!="string")throw new Error(a)},n=(o,a)=>{let c=t[o];if(!(c instanceof Uint8Array||c instanceof ArrayBuffer))throw new Error(a)};switch(e){case"/b_alloc":s(0,"/b_alloc requires a buffer number"),s(1,"/b_alloc requires a frame count");break;case"/b_allocRead":s(0,"/b_allocRead requires a buffer number"),r(1,"/b_allocRead requires a file path");break;case"/b_allocReadChannel":s(0,"/b_allocReadChannel requires a buffer number"),r(1,"/b_allocReadChannel requires a file path");break;case"/b_allocFile":s(0,"/b_allocFile requires a buffer number"),n(1,"/b_allocFile requires audio file data as blob");break}}#ae(e,t){this.#P=this.#P.then(async()=>{let s=[e,...t],{packet:r}=await this.#n.rewritePacket(s),n=i.osc.encodeMessage(r[0],r.slice(1));this.#Q(n)}).catch(s=>{console.error(`[SuperSonic] Buffer command ${e} failed:`,s),this.#u.emit("error",s)})}#ce(){return this.#P}},Zi=Xe.osc;export{O as OscChannel,Xe as SuperSonic,Zi as osc};