@mica-js/simulator 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/sandbox.js CHANGED
@@ -1,9 +1,9 @@
1
- import { a as copyBytePayload, r as simulationRuntimeService, t as simulationRuntimeCallTransfer } from "./rpc-D-9O3TZf.js";
1
+ import { a as copyBytePayload, r as simulationRuntimeService, t as simulationRuntimeCallTransfer } from "./rpc-BB5wM0QN.js";
2
2
  import { toDisposable } from "@mica-js/core/lifecycle";
3
3
  import { createRpc } from "@mica-js/core/rpc";
4
4
  import { SandboxWorker } from "@mica-js/sandbox";
5
5
  //#region \0mica-sandbox-worker-code:/home/runner/work/mica-js/mica-js/packages/simulator/src/guest/simulation-runtime.ts
6
- var simulation_runtime_default = "(function(){function e(e){let t=!1;return{dispose(){t||(t=!0,e())}}}var t=class{#e=/* @__PURE__ */ new Set;#t=!1;event=(t,n,r)=>{if(this.#t)return e(()=>{});let i={listener:t,thisArgs:n};this.#e.add(i);let a=e(()=>{this.#e.delete(i)});return r?.push(a),a};get hasListeners(){return this.#e.size>0}fire(e){if(!this.#t)for(let t of[...this.#e])t.listener.call(t.thisArgs,e)}dispose(){this.#t||(this.#t=!0,this.#e.clear())}};function n(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(t.kind===`close`)return!0;if(!Number.isSafeInteger(t.id)||t.id<=0)return!1;switch(t.kind){case`call`:case`listen`:return typeof t.service==`string`&&t.service.length>0&&typeof t.member==`string`&&t.member.length>0&&Array.isArray(t.args)&&(t.kind!==`listen`||t.args.length===0);case`unlisten`:return!0;case`result`:return Object.hasOwn(t,`value`);case`error`:case`subscription-error`:return typeof t.name==`string`&&typeof t.message==`string`;case`event`:return Array.isArray(t.args);default:return!1}}function r(e,t){return Object.assign(Error(t),{name:e})}function i(e,t){if([`constructor`,`__proto__`,`prototype`,`then`].includes(t))throw r(`MethodNotFound`,`Method is not exposed: ${t}`);for(let n=e;n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(e){if(typeof e.value==`function`)return e.value;break}}throw r(`MethodNotFound`,`Method is not callable: ${t}`)}function a(a,l={}){let u=l,d=c(u.timeoutMs??0),f=/* @__PURE__ */ new Map,p=/* @__PURE__ */ new Map,m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Map,g=new t,_=new t,v=0,ee=0,y=!1;function b(e){let t=o(e);try{u.onError?.(t)}catch{}g.fire(t)}function te(){if(y)throw r(`RpcDisconnectedError`,`RPC endpoint is closed`)}function x(){if(v===2**53-1)throw RangeError(`RPC request IDs exhausted`);return++v}function S(e,t){te(),a.postMessage(e,t?[...t]:void 0)}function C(e){let t=p.get(e);return p.delete(e),t?.timer!==void 0&&clearTimeout(t.timer),t}function w(e,t,n){return new Promise((i,a)=>{let s=t>0?setTimeout(()=>{C(e.id)?.reject(r(`RpcTimeoutError`,`RPC ${e.service}.${e.member} timed out`))},t):void 0;p.set(e.id,{resolve:i,reject:a,timer:s});try{S(e,n)}catch(t){C(e.id)?.reject(o(t))}})}function T(e){let t=h.get(e);h.delete(e);try{t?.stop?.()}catch(e){b(e)}}function E(e,t,n){if(y)return;let r=o(n);try{S({kind:e,id:t,name:r.name,message:r.message})}catch(e){b(e),D()}}function ne(){if(!y){y=!0,a.removeEventListener(`message`,ie),a.removeEventListener(`close`,ne),a.removeEventListener(`messageerror`,D);for(let e of p.keys())C(e)?.reject(r(`RpcDisconnectedError`,`RPC endpoint is closed`));m.clear();for(let e of h.keys())T(e);f.clear(),_.fire(void 0),_.dispose(),g.dispose()}}function D(){if(!y){try{S({kind:`close`})}catch(e){b(e)}ne()}}async function re(e){try{let t=f.get(e.service);if(!t)throw r(`ServiceNotFound`,`Unknown service: ${e.service}`);let n=t.implementation,a=i(n,e.member);if(e.kind===`listen`){if(!/^onDid[A-Z]/.test(e.member))throw r(`InvalidSubscription`,`Event members must start with onDid`);let i={registration:t,stop:void 0};h.set(e.id,i);let o=a.call(n,(...n)=>{if(!(y||h.get(e.id)!==i))try{S({kind:`event`,id:e.id,args:n},t.options.transfer?.(e.member,n))}catch(t){T(e.id),E(`subscription-error`,e.id,t)}});if(typeof o!=`function`)throw r(`InvalidSubscription`,`Event registration must return an unsubscribe function`);i.stop=o,h.get(e.id)!==i&&i.stop(),y||S({kind:`result`,id:e.id,value:void 0})}else{if(/^onDid[A-Z]/.test(e.member))throw r(`InvalidCall`,`Event members require a subscription`);let i=await a.apply(n,e.args);y||S({kind:`result`,id:e.id,value:i},t.options.transfer?.(e.member,i))}}catch(t){e.kind===`listen`&&T(e.id),E(`error`,e.id,t)}}function ie(e){let t=e.data;if(!n(t))b(r(`RpcProtocolError`,`Malformed RPC message`));else switch(t.kind){case`call`:case`listen`:if(t.id<=ee){b(r(`RpcProtocolError`,`Request IDs must increase`));return}ee=t.id,re(t);break;case`unlisten`:T(t.id);break;case`result`:C(t.id)?.resolve(t.value);break;case`error`:C(t.id)?.reject(r(t.name,t.message));break;case`subscription-error`:{let e=r(t.name,t.message),n=m.delete(t.id),i=C(t.id);i?i.reject(e):n&&b(e);break}case`event`:try{m.get(t.id)?.(...t.args)}catch(e){b(e)}break;case`close`:ne()}}return a.addEventListener(`message`,ie),a.addEventListener(`close`,ne),a.addEventListener(`messageerror`,D),a.start?.(),{register(t,n,i={}){te();let a=s(t);if(typeof n!=`object`||!n)throw TypeError(`RPC services must be objects`);if(f.has(a))throw Error(`Service already registered: ${a}`);let o={implementation:n,options:i};return f.set(a,o),e(()=>{if(f.get(a)===o){f.delete(a);for(let[e,t]of h)t.registration===o&&(T(e),E(`subscription-error`,e,r(`ServiceUnregistered`,`Service unregistered: ${a}`)))}})},getProxy(t,n={}){let r=s(t),i=c(n.timeoutMs??d),a=/* @__PURE__ */ new Map;return new Proxy(Object.create(null),{get(t,o){if(typeof o==`string`&&o!==`then`)return a.has(o)||a.set(o,/^onDid[A-Z]/.test(o)?t=>{if(te(),typeof t!=`function`)throw TypeError(`Expected an event listener`);let n=x();m.set(n,t),w({kind:`listen`,id:n,service:r,member:o,args:[]},i).catch(e=>{if(m.delete(n),!y)try{S({kind:`unlisten`,id:n})}catch(e){b(e)}b(e)});let a=e(()=>{if(m.delete(n)&&(C(n)?.resolve(void 0),!y))try{S({kind:`unlisten`,id:n})}catch(e){b(e)}});return()=>a.dispose()}:async(...e)=>(te(),w({kind:`call`,id:x(),service:r,member:o,args:e},i,n.transfer?.(o,e)))),a.get(o)}})},onDidError:(e,t,n)=>g.event(n=>{try{e.call(t,n)}catch{}},void 0,n),onDidClose:(t,n,r)=>y?(t.call(n,void 0),e(()=>{})):_.event(e=>{try{t.call(n,e)}catch(e){b(e)}},void 0,r),dispose:D}}function o(e){return e instanceof Error?e:Error(String(e))}function s(e){if(typeof e!=`string`||e.length===0)throw TypeError(`RPC service name must be nonempty`);return e}function c(e){if(!Number.isSafeInteger(e)||e<0||e>2147483647)throw RangeError(`RPC timeout must be an integer between 0 and 2147483647`);return e}function l(e){if(typeof e!=`string`||e.length===0)throw TypeError(`RPC service name must be nonempty`);return e}function u(e,t){return`${e}\\u0000${t}`}function d(e,t){if(Object.is(e,t))return!0;if(e instanceof Uint8Array&&t instanceof Uint8Array){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;let n=e,r=t;return n.x===r.x&&n.y===r.y&&n.z===r.z}function f(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.x==`number`&&typeof t.y==`number`}function p(e,t){switch(e){case`boolean`:return typeof t==`boolean`;case`number`:return typeof t==`number`;case`string`:return typeof t==`string`;case`bytes`:case`bytes<rgb565>`:case`bytes<segments>`:return t instanceof Uint8Array;case`vec2d`:return f(t);case`vec3d`:return f(t)&&typeof t.z==`number`}}function m(e){return e instanceof Uint8Array?new Uint8Array(e):e}function h(e){return e instanceof Uint8Array?new Uint8Array(e):typeof e==`object`&&e?{...e}:e}let g=l(`simulation-runtime`),_=l(`simulation-runtime`);function v(e,t){if(e!==`onDidPublish`||!Array.isArray(t))return[];let n=t[0];return ee(n?.payload)}function ee(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer?[e.buffer]:[]}function y(e,t){if(typeof e!=`number`||!Number.isFinite(e)||!Number.isInteger(e))throw TypeError(`${t}=${String(e)} must be a finite integer number of picoseconds`);if(e<0||e>72e14)throw RangeError(`${t}=${e} must be in [0, 7200000000000000] ps`);return e===0?0:e}function b(e){return y(e,`time`)}function te(e,t){return y(e,`left`),y(t,`right`),y(e+t,`addition ${e} + ${t}`)}function x(e,t=/* @__PURE__ */ new Set,n=[]){if(typeof e!=`object`||!e)return(typeof e==`function`||typeof e==`symbol`||typeof e==`bigint`)&&C(`IR_SCHEMA`,`Expected ordinary IR data.`,n),e;t.has(e)&&C(`IR_SCHEMA`,`Cyclic IR data is not supported.`,n),t.add(e);let r;if(e instanceof Uint8Array)r=Object.freeze(Array.from(Uint8Array.prototype.values.call(e)));else if(Array.isArray(e)){Object.getPrototypeOf(e)!==Array.prototype&&C(`IR_SCHEMA`,`Expected an ordinary IR array.`);let i=[];for(let t of Reflect.ownKeys(e))t!==`length`&&((typeof t!=`string`||!/^(0|[1-9][0-9]*)$/.test(t)||Number(t)>=e.length)&&C(`IR_SCHEMA`,`IR arrays cannot contain extra properties.`),`value`in Object.getOwnPropertyDescriptor(e,t)||C(`IR_SCHEMA`,`IR arrays cannot contain accessors.`));for(let r=0;r<e.length;r++)Object.hasOwn(e,r)||C(`IR_SCHEMA`,`IR arrays cannot be sparse.`),i.push(x(Object.getOwnPropertyDescriptor(e,r).value,t,[...n,r]));r=Object.freeze(i)}else{let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&C(`IR_SCHEMA`,`Expected an ordinary data object.`);let a={};for(let r of Reflect.ownKeys(e)){let i=Object.getOwnPropertyDescriptor(e,r);(typeof r!=`string`||!(`value`in i))&&C(`IR_SCHEMA`,`IR data cannot contain symbols or accessors.`),Object.defineProperty(a,r,{value:x(i.value,t,[...n,r]),enumerable:!0})}r=Object.freeze(a)}return t.delete(e),r}var S=class extends Error{diagnostics;constructor(e){if(!e.length)throw TypeError(`BuildError requires at least one diagnostic.`);super(e.map(e=>e.message).join(`\n`)),this.name=`BuildError`,this.diagnostics=x(e)}};function C(e,t,n=[],r=`finalize`,i){throw new S([{code:e,message:t,path:n,phase:r,related:[],...i===void 0?{}:{source:i}}])}let w=Object.freeze({Logic:[`low`,`high`,`unknown`],SampleStatus:[`valid`,`floating`],Overflow:[`drop_new`,`drop_oldest`,`error`]}),T=[`positive`,`negate`,`not`,`bitNot`],E=[`add`,`subtract`,`multiply`,`divide`,`remainder`,`power`,`lessThan`,`lessThanOrEqual`,`greaterThan`,`greaterThanOrEqual`,`equal`,`notEqual`,`concat`,`bitAnd`,`bitOr`,`bitXor`,`shiftLeft`,`shiftRight`,`shiftRightUnsigned`],ne=[`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`],D=[`load8`,`load16le`,`load16be`,`load32le`,`load32be`],re=[`store8`,`store16le`,`store16be`,`store32le`,`store32be`],ie=[`number`,`bool`,`string`,`bytes`,`sample`,`intent`,`enum`,`record`];function O(e,t){(typeof e!=`object`||!e||Array.isArray(e))&&C(`IR_SCHEMA`,`Expected a data object.`,t)}function k(e,t,n,r,i=!0){for(let n of t)Object.hasOwn(e,n)||C(`IR_SCHEMA`,`Missing field ${n}.`,[...r,n]);for(let a of Object.keys(e))[...t,...n,...i?[`source`]:[]].includes(a)||C(`IR_SCHEMA`,`Unexpected field ${a}.`,[...r,a]);Object.hasOwn(e,`source`)&&se(e.source,[...r,`source`])}function A(e,t){typeof e!=`string`&&C(`IR_SCHEMA`,`Expected a string.`,t)}function ae(e,t){typeof e!=`boolean`&&C(`IR_SCHEMA`,`Expected a boolean.`,t)}function oe(e,t){typeof e!=`number`&&C(`IR_SCHEMA`,`Expected a number.`,t)}function j(e,t){(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)&&C(`IR_SCHEMA`,`Expected a nonnegative safe integer.`,t)}function M(e,t,n){t.includes(e)||C(`IR_SCHEMA`,`Expected one of ${t.join(`, `)}.`,n)}function N(e,t,n){Array.isArray(e)||C(`IR_SCHEMA`,`Expected an array.`,t);for(let r=0;r<e.length;r++)n(e[r],[...t,r])}function se(e,t){O(e,t);let n=Object.hasOwn(e,`uri`);for(let n of Object.keys(e))[`uri`,`range`,`label`].includes(n)||C(`IR_SCHEMA`,`Invalid source field.`,[...t,n]);if(Object.hasOwn(e,`label`)&&A(e.label,[...t,`label`]),!n){(!Object.hasOwn(e,`label`)||Object.hasOwn(e,`range`))&&C(`IR_SCHEMA`,`Source requires a label or URI and range.`,t);return}A(e.uri,[...t,`uri`]),O(e.range,[...t,`range`]);let r=e.range;for(let e of Object.keys(r))[`start`,`end`].includes(e)||C(`IR_SCHEMA`,`Invalid range field.`,[...t,`range`,e]);for(let e of[`start`,`end`]){let n=r[e];O(n,[...t,`range`,e]);for(let r of Object.keys(n))[`line`,`column`].includes(r)||C(`IR_SCHEMA`,`Invalid position field.`,[...t,`range`,e,r]);for(let r of[`line`,`column`])(!Number.isSafeInteger(n[r])||n[r]<1)&&C(`IR_SCHEMA`,`Positions start at one.`,[...t,`range`,e,r])}let{start:i,end:a}=r;(a.line<i.line||a.line===i.line&&a.column<i.column)&&C(`IR_SCHEMA`,`Source range is reversed.`,t)}function P(e,t,n=!0){O(e,t),e.kind===`optional`&&n?(k(e,[`kind`,`inner`],[],t),P(e.inner,[...t,`inner`],!1)):(M(e.kind,ie,[...t,`kind`]),k(e,[`kind`,...[`enum`,`record`].includes(e.kind)?[`name`]:[]],[],t),[`enum`,`record`].includes(e.kind)&&A(e.name,[...t,`name`])),Object.hasOwn(e,`source`)&&C(`IR_SCHEMA`,`Type descriptors cannot carry source information.`,t)}function F(e,t,n){O(e,t),Object.hasOwn(e,`source`)&&C(`IR_SCHEMA`,`Resource references cannot carry source information.`,t),M(e.kind,[`pin`,`memory`,`parameter`],[...t,`kind`]),e.kind===`parameter`?(k(e,[`kind`,`resource`,`index`],[],t),M(e.resource,[`pin`,`memory`],[...t,`resource`]),j(e.index,[...t,`index`]),n&&e.resource!==n&&C(`IR_REFERENCE`,`Resource category does not match.`,t)):(k(e,[`kind`,`name`],[],t),A(e.name,[...t,`name`]),n&&e.kind!==n&&C(`IR_REFERENCE`,`Resource category does not match.`,t))}function ce(e,t,n=!1){O(e,t),Object.hasOwn(e,`source`)&&C(`IR_SCHEMA`,`Constants and patterns cannot carry source information.`,t);let r=n?[`number`,`bool`,`string`,`enum`,`none`]:[`number`,`bool`,`string`,`bytes`,`enum`,`record`,`none`];switch(M(e.kind,r,[...t,`kind`]),e.kind){case`none`:k(e,[`kind`],[],t);break;case`enum`:k(e,[`kind`,`name`,`member`],[],t),A(e.name,[...t,`name`]),A(e.member,[...t,`member`]);break;case`record`:k(e,[`kind`,`name`,`fields`],[],t),A(e.name,[...t,`name`]),N(e.fields,[...t,`fields`],(e,t)=>{O(e,t),k(e,[`name`,`value`],[],t),A(e.name,[...t,`name`]),[`number`,`boolean`].includes(typeof e.value)||C(`IR_SCHEMA`,`Expected a number or boolean field.`,[...t,`value`])});break;case`bytes`:k(e,[`kind`,`value`],[],t),N(e.value,[...t,`value`],(e,t)=>{(!Number.isInteger(e)||e<0||e>255)&&C(`IR_SCHEMA`,`Expected a byte.`,t)});break;default:k(e,[`kind`,`value`],[],t),e.kind===`number`?(oe(e.value,[...t,`value`]),n&&!Number.isFinite(e.value)&&C(`IR_CONTROL_FLOW`,`Numeric match patterns must be finite.`,t)):e.kind===`bool`?ae(e.value,[...t,`value`]):A(e.value,[...t,`value`])}}function I(e,t){O(e,t),k(e,[`operations`],[],t),N(e.operations,[...t,`operations`],le)}function L(e,t){O(e,t),k(e,[`type`,`body`],[],t),P(e.type,[...t,`type`]),I(e.body,[...t,`body`])}function le(e,t){O(e,t),A(e.kind,[...t,`kind`]);let n=[],r=[],i=!1,a=e=>{n=e,i=!0};switch(e.kind){case`constant`:a([`constant`]),ce(e.constant,[...t,`constant`]);break;case`read`:a([`resource`,`name`]),M(e.resource,[`property`,`const`,`state`,`derived`],[...t,`resource`]),A(e.name,[...t,`name`]);break;case`parameter`:case`reactionCapture`:a([`index`]),j(e.index,[...t,`index`]);break;case`reactionValue`:a([`binding`]),M(e.binding,[`previous`,`current`],[...t,`binding`]);break;case`unary`:a([`operator`,`value`]),M(e.operator,T,[...t,`operator`]);break;case`binary`:a([`operator`,`left`,`right`]),M(e.operator,E,[...t,`operator`]);break;case`numeric`:a([`builtin`,`args`]),M(e.builtin,ne,[...t,`builtin`]),N(e.args,[...t,`args`],j);break;case`record`:a([`fields`]),N(e.fields,[...t,`fields`],(e,t)=>{O(e,t),k(e,[`name`,`value`],[],t),A(e.name,[...t,`name`]),j(e.value,[...t,`value`])});break;case`field`:a([`value`,`field`]),A(e.field,[...t,`field`]);break;case`bytes`:a([`elements`]),N(e.elements,[...t,`elements`],j);break;case`length`:case`optional`:case`isNone`:case`nonNull`:a([`value`]);break;case`index`:a([`value`,`index`]),j(e.index,[...t,`index`]);break;case`localRead`:a([`local`]),j(e.local,[...t,`local`]);break;case`local`:n=[`local`,`type`,`initial`],j(e.local,[...t,`local`]),P(e.type,[...t,`type`]);break;case`localWrite`:n=[`local`,`value`],j(e.local,[...t,`local`]);break;case`write`:n=[`resource`,`name`,`value`],M(e.resource,[`state`],[...t,`resource`]),A(e.name,[...t,`name`]);break;case`memoryLength`:a([`memory`]),F(e.memory,[...t,`memory`],`memory`);break;case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:a([`memory`,`offset`]),F(e.memory,[...t,`memory`],`memory`);break;case`store8`:case`store16le`:case`store16be`:case`store32le`:case`store32be`:n=[`memory`,`offset`,`value`],F(e.memory,[...t,`memory`],`memory`);break;case`copyBytes`:a([`memory`,`offset`,`length`]),F(e.memory,[...t,`memory`],`memory`);break;case`readSample`:a([`pin`]),F(e.pin,[...t,`pin`],`pin`);break;case`resistor`:a([`to`,`resistance`]),F(e.to,[...t,`to`],`pin`);break;case`combineIntents`:a([`values`]),N(e.values,[...t,`values`],j);break;case`refEqual`:a([`left`,`right`]),F(e.left,[...t,`left`]),F(e.right,[...t,`right`]);break;case`writeIntent`:n=[`pin`,`value`],F(e.pin,[...t,`pin`],`pin`);break;case`call`:case`callValue`:n=[`name`,`pure`,`args`],i=e.kind===`callValue`,A(e.name,[...t,`name`]),ae(e.pure,[...t,`pure`]),N(e.args,[...t,`args`],(e,t)=>{O(e,t),e.kind===`value`?(k(e,[`kind`,`value`],[],t),j(e.value,[...t,`value`])):F(e,t)});break;case`send`:n=[`channel`,`value`],A(e.channel,[...t,`channel`]);break;case`notify`:n=[`notification`],A(e.notification,[...t,`notification`]);break;case`receive`:a([`channel`]),A(e.channel,[...t,`channel`]);break;case`now`:case`random`:a([]);break;case`if`:n=[`condition`,`yes`],r=[`no`],I(e.yes,[...t,`yes`]),Object.hasOwn(e,`no`)&&I(e.no,[...t,`no`]);break;case`match`:n=[`value`,`arms`],r=[`otherwise`],N(e.arms,[...t,`arms`],(e,t)=>{O(e,t),k(e,[`pattern`,`body`],[],t),ce(e.pattern,[...t,`pattern`],!0),I(e.body,[...t,`body`])}),Object.hasOwn(e,`otherwise`)&&I(e.otherwise,[...t,`otherwise`]);break;case`while`:n=[`test`,`body`],L(e.test,[...t,`test`]),I(e.body,[...t,`body`]);break;case`loop`:n=[`body`],I(e.body,[...t,`body`]);break;case`and`:case`or`:a([`left`,`right`]),L(e.right,[...t,`right`]);break;case`select`:a([`condition`,`yes`,`no`]),L(e.yes,[...t,`yes`]),L(e.no,[...t,`no`]);break;case`assert`:n=[`condition`],r=[`message`],Object.hasOwn(e,`message`)&&L(e.message,[...t,`message`]);break;case`wait`:case`elapse`:n=[`duration`];break;case`waitUntil`:n=[`predicate`],A(e.predicate,[...t,`predicate`]);break;case`redirect`:n=[`target`,`delay`];break;case`return`:case`break`:case`continue`:case`stop`:break;case`returnValue`:case`yield`:n=[`value`];break;default:C(`IR_SCHEMA`,`Unknown operation ${e.kind}.`,[...t,`kind`])}k(e,[`kind`,...n,...i?[`result`,`type`]:[]],r,t),i&&(j(e.result,[...t,`result`]),P(e.type,[...t,`type`]));for(let n of[`value`,`left`,`right`,`condition`,`initial`,`offset`,`length`,`resistance`,`duration`,`target`,`delay`])Object.hasOwn(e,n)&&typeof e[n]!=`object`&&!(n===`value`&&[`constant`,`read`].includes(e.kind))?j(e[n],[...t,n]):Object.hasOwn(e,n)&&typeof e[n]==`object`&&![`refEqual`,`and`,`or`].includes(e.kind)&&C(`IR_SCHEMA`,`Expected a result identifier.`,[...t,n])}function ue(e){O(e,[]),k(e,[`kind`,`name`,`declarations`],[],[]),M(e.kind,[`device`],[`kind`]),A(e.name,[`name`]),N(e.declarations,[`declarations`],(e,t)=>{O(e,t),A(e.kind,[...t,`kind`]);let n=[`kind`],r=[];switch([`start`,`assert`].includes(e.kind)||(n.push(`name`),A(e.name,[...t,`name`])),e.kind){case`enum`:n.push(`members`),N(e.members,[...t,`members`],A);break;case`record`:n.push(`fields`),N(e.fields,[...t,`fields`],(e,t)=>{O(e,t),k(e,[`name`,`type`],[],t),A(e.name,[...t,`name`]),M(e.type,[`number`,`bool`],[...t,`type`])});break;case`property`:n.push(`type`),r=[`default`],Object.hasOwn(e,`default`)&&L(e.default,[...t,`default`]);break;case`const`:case`derived`:n.push(`type`,`value`),L(e.value,[...t,`value`]);break;case`state`:n.push(`type`,`initial`),L(e.initial,[...t,`initial`]);break;case`pin`:r=[`initial`,`low`,`high`];for(let n of r)Object.hasOwn(e,n)&&L(e[n],[...t,n]);Object.hasOwn(e,`low`)!==Object.hasOwn(e,`high`)&&C(`IR_SCHEMA`,`Pin thresholds must be provided together.`,t);break;case`memory`:n.push(`public`,`length`),ae(e.public,[...t,`public`]),L(e.length,[...t,`length`]);break;case`channel`:n.push(`direction`,`type`,`capacity`),r=[`maxLength`,`overflow`],L(e.capacity,[...t,`capacity`]);for(let n of r)Object.hasOwn(e,n)&&L(e[n],[...t,n]);break;case`notification`:n.push(`direction`);break;case`function`:n.push(`pure`,`params`,`body`),r=[`returns`],ae(e.pure,[...t,`pure`]),N(e.params,[...t,`params`],(e,t)=>{O(e,t),k(e,[`name`,`type`],[],t),A(e.name,[...t,`name`]),O(e.type,[...t,`type`]),[`pin`,`memory`].includes(e.type.kind)?k(e.type,[`kind`],[],[...t,`type`]):P(e.type,[...t,`type`])}),Object.hasOwn(e,`returns`)&&P(e.returns,[...t,`returns`]),I(e.body,[...t,`body`]);break;case`start`:case`assert`:n.push(`body`),I(e.body,[...t,`body`]);break;case`on`:n.push(`sourcePath`,`body`),N(e.sourcePath,[...t,`sourcePath`],A),I(e.body,[...t,`body`]);break;case`reaction`:n.push(`sourcePath`,`sourceType`,`previous`,`current`,`captures`,`body`),N(e.sourcePath,[...t,`sourcePath`],A),P(e.sourceType,[...t,`sourceType`]),A(e.previous,[...t,`previous`]),A(e.current,[...t,`current`]),N(e.captures,[...t,`captures`],(e,t)=>{O(e,t),k(e,[`name`,`value`],[],t),A(e.name,[...t,`name`]),L(e.value,[...t,`value`])}),I(e.body,[...t,`body`]);break;default:C(`IR_SCHEMA`,`Unknown declaration ${e.kind}.`,[...t,`kind`])}k(e,n,r,t),Object.hasOwn(e,`type`)&&P(e.type,[...t,`type`]),[`channel`,`notification`].includes(e.kind)&&M(e.direction,[`input`,`output`],[...t,`direction`])})}function de(e){O(e,[]),k(e,[`kind`,`instructions`],[],[]),M(e.kind,[`block`],[`kind`]),N(e.instructions,[`instructions`],(e,t)=>{O(e,t),k(e,[`pc`,`nextPc`,`body`],[],t);for(let n of[`pc`,`nextPc`])(typeof e[n]!=`number`||!Number.isFinite(e[n]))&&C(`IR_SCHEMA`,`Instruction positions must be finite numbers.`,[...t,n]);I(e.body,[...t,`body`])});let t=e.instructions;t.length||C(`IR_JIT_BOUNDARY`,`A block requires at least one instruction.`,[`instructions`]);for(let e=1;e<t.length;e++)t[e-1].nextPc!==t[e].pc&&C(`IR_JIT_BOUNDARY`,`Adjacent instruction boundaries do not match.`,[`instructions`,e,`pc`])}let R={kind:`number`},z={kind:`bool`},fe={kind:`string`},pe={kind:`bytes`},me={kind:`intent`},he={kind:`sample`},ge=/* @__PURE__ */ new Set([`device`,`default`,`const`,`let`,`enum`,`record`,`state`,`derived`,`pin`,`memory`,`fn`,`pure`,`process`,`on`,`reaction`,`as`,`capture`,`if`,`else`,`match`,`while`,`loop`,`break`,`continue`,`return`,`await`,`assert`,`redirect`,`true`,`false`,`none`,`start`,`number`,`bool`,`string`,`bytes`,`sample`,`intent`,`NaN`,`Infinity`,...Object.keys(w),...ne,...D,...re,`resistor`,`copyBytes`,`now`,`random`,`ticks`]);function _e(e,t){let n=e,r=t;return n?.kind===r?.kind&&(n?.kind===`optional`?_e(n.inner,r?.inner):n?.kind===`enum`||n?.kind===`record`?n.name===r?.name:!0)}function ve(e){return e.kind===`optional`?e.inner:e}function ye(e){return ve(e).kind!==`intent`}function be(e){return{facts:new Map(e.facts),locals:new Map(e.locals)}}function xe(e){let t=new Map(e[0]);for(let[n,r]of t)e.some(e=>e.get(n)!==r)&&t.delete(n);return t}function Se(e,t){for(let n of[e.normal,...e.breaks,...e.continues,...e.yieldStates])if(n)for(let e of n.locals.keys())t.has(e)||n.locals.delete(e);return e}function B(e){if(!e.length)return;let t=be(e[0]);t.facts=xe(e.map(e=>e.facts));for(let[n,r]of t.locals){let i=e.map(e=>e.locals.get(n));if(i.some(e=>!e))t.locals.delete(n);else if(i.some(e=>e.value.key!==r.value.key)){let a={type:r.type,key:`join:${n}:${i.map(e=>e.value.key).join(`|`)}`},o=i.map((t,n)=>e[n].facts.get(t.value.key));o.every(e=>e===!0)&&t.facts.set(a.key,!0),o.every(e=>e===!1)&&t.facts.set(a.key,!1),t.locals.set(n,{type:r.type,value:a})}}return t}function Ce(e,t,n=[]){e.operations.forEach((e,r)=>{let i=[...n,`operations`,r];t(e,i);for(let n of[`yes`,`no`,`otherwise`,`body`]){let r=n in e?e[n]:void 0;if(r){let e=`body`in r;Ce(e?r.body:r,t,[...i,n,...e?[`body`]:[]])}}e.kind===`while`&&Ce(e.test.body,t,[...i,`test`,`body`]),e.kind===`assert`&&e.message&&Ce(e.message.body,t,[...i,`message`,`body`]),(e.kind===`and`||e.kind===`or`)&&Ce(e.right.body,t,[...i,`right`,`body`]),e.kind===`match`&&e.arms.forEach((e,n)=>Ce(e.body,t,[...i,`arms`,n,`body`]))})}var we=class{device;declarations=/* @__PURE__ */ new Map;paths=/* @__PURE__ */ new Map;enums=new Map(Object.entries(w));records=/* @__PURE__ */ new Map;functions=/* @__PURE__ */ new Map;effectChecked=/* @__PURE__ */ new Set;receiveOwners=/* @__PURE__ */ new Map;constructor(e){if(this.device=e,!e)return;this.name(e.name,[`name`]);let t=0;e.declarations.forEach((e,n)=>{let r=[`declarations`,n];e.kind===`start`?++t>1&&this.error(`IR_REFERENCE`,`Only one start process is allowed.`,r):e.kind!==`assert`&&(this.name(e.name,[...r,`name`]),this.declarations.has(e.name)&&this.error(`IR_REFERENCE`,`Duplicate declaration ${e.name}.`,r),this.declarations.set(e.name,e),this.paths.set(e.name,r),e.kind===`enum`&&(this.uniqueNames(e.members,[...r,`members`]),e.members.length||this.error(`IR_TYPE`,`An enum must have at least one member.`,r),this.enums.set(e.name,e.members)),e.kind===`record`&&(this.uniqueNames(e.fields.map(e=>e.name),[...r,`fields`]),this.records.set(e.name,e.fields)),e.kind===`function`&&this.functions.set(e.name,e))})}error(e,t,n,r){return C(e,t,n,`finalize`,r?.source)}name(e,t){(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)||ge.has(e))&&this.error(`IR_REFERENCE`,`Invalid or reserved identifier ${e}.`,t)}uniqueNames(e,t,n=!1){let r=/* @__PURE__ */ new Set;e.forEach((e,i)=>{n?/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)||this.error(`IR_REFERENCE`,`Invalid member name.`,[...t,i]):this.name(e,[...t,i]),r.has(e)&&this.error(`IR_REFERENCE`,`Duplicate name ${e}.`,[...t,i]),r.add(e)})}type(e,t){let n=ve(e);n.kind===`enum`&&!this.enums.has(n.name)&&this.device&&this.error(`IR_REFERENCE`,`Unknown enum ${n.name}.`,t),n.kind===`record`&&!this.records.has(n.name)&&this.device&&this.error(`IR_REFERENCE`,`Unknown record ${n.name}.`,t)}expect(e,t,n,r){_e(e,t)||this.error(`IR_TYPE`,`Expected ${this.describe(t)}, received ${this.describe(e)}.`,n,r)}describe(e){let t=e;return t?t.kind===`optional`?`${this.describe(t.inner)}?`:String(t.name??t.kind):`no value`}declaration(e,t,n){if(!this.device)return;let r=this.declarations.get(e);return(!r||r.kind!==t)&&this.error(`IR_REFERENCE`,`Expected ${t} declaration ${e}.`,n),r}ref(e,t,n,r){let i=e.kind===`parameter`?e.resource:e.kind;if(t&&i!==t&&this.error(`IR_REFERENCE`,`Resource category does not match.`,r),e.kind===`parameter`){let t=n.params[e.index];t||this.error(`IR_SCOPE`,`Resource parameter is outside the current function.`,r),t.type.kind!==i&&this.error(`IR_REFERENCE`,`Resource parameter category does not match.`,r)}else this.declaration(e.name,i,r);return i}field(e,t,n){if(e.kind===`sample`){let e={voltage:{kind:`optional`,inner:R},level:{kind:`enum`,name:`Logic`},status:{kind:`enum`,name:`SampleStatus`}};return e[t]||this.error(`IR_REFERENCE`,`Unknown sample field ${t}.`,n),e[t]}e.kind!==`record`&&this.error(`IR_TYPE`,`Field access requires a record or sample.`,n);let r=this.records.get(e.name);if(!r&&!this.device)return R;let i=r?.find(e=>e.name===t);return i||this.error(`IR_REFERENCE`,`Unknown record field ${t}.`,n),{kind:i.type}}constant(e,t,n){if(e.kind===`none`)t.kind!==`optional`&&this.error(`IR_TYPE`,`none requires an optional result type.`,n);else{if(t.kind===`optional`&&this.error(`IR_TYPE`,`Non-null constants require a nonoptional type and explicit optional lift.`,n),(e.kind!==t.kind||(e.kind===`enum`||e.kind===`record`)&&e.name!==(`name`in t?t.name:void 0))&&this.error(`IR_TYPE`,`Constant and result types do not match.`,n),e.kind===`enum`){let t=this.enums.get(e.name);t&&!t.includes(e.member)&&this.error(`IR_REFERENCE`,`Unknown enum member ${e.member}.`,n)}e.kind===`record`&&this.recordFields(e.fields,t,n,e=>({kind:typeof e.value==`boolean`?`bool`:`number`}))}}recordFields(e,t,n,r){t.kind!==`record`&&this.error(`IR_TYPE`,`Record construction requires a named record type.`,n);let i=this.records.get(t.name),a=/* @__PURE__ */ new Set;for(let t=0;t<e.length;t++){let o=e[t];if(a.has(o.name)&&this.error(`IR_REFERENCE`,`Duplicate record field.`,[...n,`fields`,t]),a.add(o.name),i){let e=i.find(e=>e.name===o.name);e||this.error(`IR_REFERENCE`,`Unknown record field ${o.name}.`,[...n,`fields`,t]),this.expect(r(o),{kind:e.type},[...n,`fields`,t])}else r(o)}i&&i.length!==e.length&&this.error(`IR_TYPE`,`Record fields are incomplete.`,n)}context(e,t){return{mode:e,params:[],...t?{returns:t}:{},loop:0,results:/* @__PURE__ */ new Map,resultIds:/* @__PURE__ */ new Set,localIds:/* @__PURE__ */ new Set,tail:!0,finalInstruction:!0,computation:!1}}body(e,t,n){let r=this.region(e,t,{facts:/* @__PURE__ */ new Map,locals:/* @__PURE__ */ new Map},n);t.returns&&r.normal&&this.error(`IR_CONTROL_FLOW`,`A value-returning body has a normal path without returnValue.`,n,e),this.effects(e,t.mode,n)}computation(e,t,n,r){this.type(e.type,[...r,`type`]),this.expect(e.type,t,[...r,`type`]);let i=this.context(n,t);i.computation=!0,this.body(e.body,i,[...r,`body`])}conditioned(e,t,n){let r=be(e),i=n?t.yes:t.no;if(i)for(let[e,t]of i)r.facts.set(e,t);return r}region(e,t,n,r){let i=be(n),a={breaks:[],continues:[],yielded:[],yieldStates:[]},o=new Map(t.results);t={...t,results:o};for(let n=0;n<e.operations.length;n++){let s=e.operations[n],c=[...r,`operations`,n];i||this.error(`IR_CONTROL_FLOW`,`Operation follows an unconditional path terminator.`,c,s);let l=i,u=(e,t)=>{let n=o.get(e);return n||this.error(`IR_SCOPE`,`Result ${e} is not visible or is used before its definition.`,c,s),t&&this.expect(n.type,t,c,s),n},d=(e,t={})=>{let n=s;this.expect(n.type,e,[...c,`type`],s);let r={type:n.type,key:`v:${n.result}`,...t};return o.set(n.result,r),r};`result`in s&&(this.type(s.type,[...c,`type`]),t.resultIds.has(s.result)&&this.error(`IR_SCOPE`,`Duplicate result ${s.result}.`,[...c,`result`],s),t.resultIds.add(s.result));let f=e=>{let t=l.locals.get(e);return t||this.error(`IR_SCOPE`,`Local is not visible or not initialized.`,[...c,`local`],s),t},p=(r,i,a,o={})=>Se(this.region(r,{...t,tail:t.tail&&n===e.operations.length-1,...o},i,[...c,a]),i.locals),m=e=>{a.breaks.push(...e.breaks),a.continues.push(...e.continues),a.yielded.push(...e.yielded),a.yieldStates.push(...e.yieldStates)},h=(e,n,r,i)=>{this.type(e.type,[...c,i,`type`]),this.expect(e.type,n,[...c,i,`type`]);let a=Se(this.region(e.body,{...t,valueRegion:n,loop:0,tail:!1},r,[...c,i,`body`]),r.locals);return a.normal&&this.error(`IR_CONTROL_FLOW`,`A value region has a normal path without yield.`,[...c,i],e),{flow:a,...a.yielded.length?{value:{type:n,key:`region:${`result`in s?s.result:void 0}:${i}`,yes:xe(a.yielded.map(e=>e.yes??/* @__PURE__ */ new Map)),no:xe(a.yielded.map(e=>e.no??/* @__PURE__ */ new Map))}}:{}}};switch(s.kind){case`constant`:{this.constant(s.constant,s.type,[...c,`constant`]);let e=d(s.type,{none:s.constant.kind===`none`});s.constant.kind===`none`&&l.facts.set(e.key,!1);break}case`read`:d(this.declaration(s.name,s.resource,c)?.type??s.type);break;case`parameter`:{let e=t.params[s.index];e||this.error(`IR_SCOPE`,`Parameter index is outside the current function.`,c,s),(e.type.kind===`pin`||e.type.kind===`memory`)&&this.error(`IR_TYPE`,`Resource parameters cannot be read as values.`,c,s),d(e.type,{key:`parameter:${s.index}`});break}case`reactionValue`:t.reaction||this.error(`IR_SCOPE`,`Reaction bindings are only visible inside their response body.`,c,s),d(t.reaction.sourceType,{key:`reaction:${s.binding}`});break;case`reactionCapture`:t.reaction||this.error(`IR_SCOPE`,`Reaction captures are only visible inside their response body.`,c,s),t.reaction.captures[s.index]||this.error(`IR_SCOPE`,`Reaction capture index is out of range.`,c,s),d(t.reaction.captures[s.index].value.type,{key:`capture:${s.index}`});break;case`unary`:{let e=u(s.value,s.operator===`not`?z:R);d(s.operator===`not`?z:R,s.operator===`not`?{yes:e.no??/* @__PURE__ */ new Map,no:e.yes??/* @__PURE__ */ new Map}:{});break}case`binary`:{let e=u(s.left),t=u(s.right);if([`equal`,`notEqual`].includes(s.operator)){this.expect(e.type,t.type,c,s),!ye(e.type)&&(e.type.kind!==`optional`||!e.none&&!t.none)&&this.error(`IR_TYPE`,`Intent values do not support content equality.`,c,s);let n=e.none?t:t.none?e:void 0,r=s.operator===`equal`;d(z,n?{yes:/* @__PURE__ */ new Map([[n.key,!r]]),no:/* @__PURE__ */ new Map([[n.key,r]])}:{})}else s.operator===`concat`?(u(s.left,fe),u(s.right,fe),d(fe)):(u(s.left,R),u(s.right,R),d([`lessThan`,`lessThanOrEqual`,`greaterThan`,`greaterThanOrEqual`].includes(s.operator)?z:R));break}case`numeric`:s.args.length!==([`min`,`max`,`pow`].includes(s.builtin)?2:1)&&this.error(`IR_TYPE`,`Numeric builtin argument count does not match.`,c,s),s.args.forEach(e=>u(e,R)),d(s.builtin.startsWith(`is`)?z:R);break;case`record`:this.recordFields(s.fields,s.type,c,e=>u(e.value).type),d(s.type);break;case`field`:{let e=u(s.value),t=e.type;d(t.kind===`record`&&!this.device?s.type:this.field(t,s.field,c),{key:`field:${e.key}:${s.field}`});break}case`bytes`:s.elements.forEach(e=>u(e,R)),d(pe);break;case`length`:{let e=u(s.value).type;[`string`,`bytes`].includes(e.kind)||this.error(`IR_TYPE`,`length requires string or bytes.`,c,s),d(R);break}case`index`:{let e=u(s.value).type;[`string`,`bytes`].includes(e.kind)||this.error(`IR_TYPE`,`index requires string or bytes.`,c,s),u(s.index,R),d(e.kind===`string`?fe:R);break}case`optional`:{let e=u(s.value).type;e.kind===`optional`&&this.error(`IR_TYPE`,`Optional types cannot be nested.`,c,s);let t=d({kind:`optional`,inner:e});l.facts.set(t.key,!0);break}case`isNone`:{let e=u(s.value);e.type.kind!==`optional`&&this.error(`IR_TYPE`,`isNone requires an optional value.`,c,s),d(z,{yes:/* @__PURE__ */ new Map([[e.key,!1]]),no:/* @__PURE__ */ new Map([[e.key,!0]])});break}case`nonNull`:{let e=u(s.value);(e.type.kind!==`optional`||l.facts.get(e.key)!==!0)&&this.error(`IR_TYPE`,`nonNull requires a dominating non-null proof.`,c,s),d(e.type.inner);break}case`local`:{t.localIds.has(s.local)&&this.error(`IR_SCOPE`,`Duplicate local identifier.`,c,s),t.localIds.add(s.local),this.type(s.type,[...c,`type`]);let e=u(s.initial,s.type);l.locals.set(s.local,{type:s.type,value:e});break}case`localRead`:{let e=f(s.local);d(e.type,{...e.value});break}case`localWrite`:{let e=f(s.local),t=u(s.value,e.type);l.locals.set(s.local,{type:e.type,value:t});break}case`write`:{let e=this.declaration(s.name,`state`,c);u(s.value,e?.type);break}case`memoryLength`:this.ref(s.memory,`memory`,t,c),d(R);break;case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:this.ref(s.memory,`memory`,t,c),u(s.offset,R),d(R);break;case`store8`:case`store16le`:case`store16be`:case`store32le`:case`store32be`:this.ref(s.memory,`memory`,t,c),u(s.offset,R),u(s.value,R);break;case`copyBytes`:this.ref(s.memory,`memory`,t,c),u(s.offset,R),u(s.length,R),d(pe);break;case`readSample`:this.ref(s.pin,`pin`,t,c),d(he);break;case`resistor`:this.ref(s.to,`pin`,t,c),u(s.resistance,R),d(me);break;case`combineIntents`:s.values.forEach(e=>u(e,me)),d(me);break;case`refEqual`:this.expect({kind:this.ref(s.left,void 0,t,c)},{kind:this.ref(s.right,void 0,t,c)},c),d(z);break;case`writeIntent`:this.ref(s.pin,`pin`,t,c),u(s.value,me);break;case`call`:case`callValue`:{let e=this.declaration(s.name,`function`,c);e&&s.pure&&!e.pure&&this.error(`IR_EFFECT`,`A pure call must target an explicitly pure function.`,c,s),e&&s.args.length!==e.params.length&&this.error(`IR_TYPE`,`Call argument count does not match.`,c,s),s.args.forEach((n,r)=>{let i=e?.params[r];n.kind===`value`?(i&&(i.type.kind===`pin`||i.type.kind===`memory`)&&this.error(`IR_TYPE`,`Resource argument required.`,c,s),u(n.value,i?.type)):(i&&i.type.kind!==`pin`&&i.type.kind!==`memory`&&this.error(`IR_TYPE`,`Value argument required.`,c,s),this.ref(n,i?.type.kind,t,c))}),s.kind===`callValue`?(e&&!e.returns&&this.error(`IR_TYPE`,`callValue requires a value-returning function.`,c,s),d(e?.returns??s.type)):e?.returns&&this.error(`IR_TYPE`,`call cannot discard the return type of a value-returning function.`,c,s);break}case`send`:{let e=this.declaration(s.channel,`channel`,c);e?.direction===`input`&&this.error(`IR_REFERENCE`,`send requires an output channel.`,c,s),u(s.value,e?.type);break}case`notify`:this.declaration(s.notification,`notification`,c)?.direction===`input`&&this.error(`IR_REFERENCE`,`notify requires an output notification.`,c,s);break;case`receive`:{let e=this.declaration(s.channel,`channel`,c);e?.direction===`output`&&this.error(`IR_REFERENCE`,`receive requires an input channel.`,c,s),d(e?.type??s.type);break}case`now`:case`random`:d(R);break;case`if`:{let e=u(s.condition,z),t=p(s.yes,this.conditioned(l,e,!0),`yes`),n=s.no?p(s.no,this.conditioned(l,e,!1),`no`):{normal:this.conditioned(l,e,!1),breaks:[],continues:[],yielded:[],yieldStates:[]};m(t),m(n),i=B([t.normal,n.normal].filter(e=>!!e));break}case`match`:{let r=u(s.value),a=ve(r.type),o=/* @__PURE__ */ new Set,d=[];for(let i=0;i<s.arms.length;i++){let u=s.arms[i],f=u.pattern;this.constant(f,f.kind===`none`?r.type:a,[...c,`arms`,i,`pattern`]);let p=f.kind===`enum`?`${f.name}.${f.member}`:`${f.kind}:${String(`value`in f?f.value:void 0)}`;o.has(p)&&this.error(`IR_CONTROL_FLOW`,`Duplicate match pattern.`,[...c,`arms`,i]),o.add(p);let h=be(l);r.type.kind===`optional`&&h.facts.set(r.key,f.kind!==`none`);let g=Se(this.region(u.body,{...t,tail:t.tail&&n===e.operations.length-1},h,[...c,`arms`,i,`body`]),h.locals);m(g),g.normal&&d.push(g.normal)}let f=(a.kind===`bool`?o.has(`bool:true`)&&o.has(`bool:false`):a.kind===`enum`&&this.enums.get(a.name)?.every(e=>o.has(`${a.name}.${e}`)))&&(r.type.kind!==`optional`||o.has(`none:undefined`));if(s.otherwise){let e=be(l);r.type.kind===`optional`&&o.has(`none:undefined`)&&e.facts.set(r.key,!0);let t=p(s.otherwise,e,`otherwise`);m(t),t.normal&&d.push(t.normal)}else f||this.error(`IR_CONTROL_FLOW`,`Match requires exhaustive patterns or a default region.`,c,s);i=B(d);break}case`while`:case`loop`:{let e=/* @__PURE__ */ new Set;Ce(s.body,t=>{t.kind===`localWrite`&&l.locals.has(t.local)&&e.add(t.local)}),s.kind===`while`&&Ce(s.test.body,t=>{t.kind===`localWrite`&&l.locals.has(t.local)&&e.add(t.local)});let n=t=>{let n=be(l),r=[l,...t];for(let t of e){let e=l.locals.get(t),i={type:e.type,key:`loop:${c.join(`.`)}:${t}`};n.locals.set(t,{type:e.type,value:i});let a=r.map(e=>{let n=e.locals.get(t)?.value;return n?e.facts.get(n.key):void 0});a.every(e=>e===!0)?n.facts.set(i.key,!0):a.every(e=>e===!1)&&n.facts.set(i.key,!1)}return n},r=n([]),o=new Set(t.resultIds),u=new Set(t.localIds),d,f;for(;;){t.resultIds.clear();for(let e of o)t.resultIds.add(e);t.localIds.clear();for(let e of u)t.localIds.add(e);d=s.kind===`while`?h(s.test,z,r,`test`):void 0;let i=d?B(d.flow.yieldStates)??r:r,a=d?.value?this.conditioned(i,d.value,!0):i;f=p(s.body,a,`body`,{loop:t.loop+1,tail:!1});let c=n([f.normal,...f.continues].filter(e=>!!e));if([...e].every(e=>{let t=c.locals.get(e).value.key;return c.facts.get(t)===r.facts.get(t)}))break;r=c}a.yielded.push(...f.yielded),a.yieldStates.push(...f.yieldStates);let m=[...f.breaks];if(s.kind===`while`&&d?.value){let e=B(d.flow.yieldStates)??r;m.push(this.conditioned(e,d.value,!1))}i=B(m);break}case`and`:case`or`:{let e=u(s.left,z),t=s.kind===`and`,n=h(s.right,z,this.conditioned(l,e,t),`right`),r=n.value,a=(e,t)=>new Map([...e??[],...t??[]]),o=t?a(e.yes,r?.yes):xe([e.yes??/* @__PURE__ */ new Map,a(e.no,r?.yes)]),c=t?xe([e.no??/* @__PURE__ */ new Map,a(e.yes,r?.no)]):a(e.no,r?.no);d(z,{yes:o,no:c}),i=B([this.conditioned(l,e,!t),...n.flow.yieldStates]);break}case`select`:{let e=u(s.condition,z),t=h(s.yes,s.type,this.conditioned(l,e,!0),`yes`),n=h(s.no,s.type,this.conditioned(l,e,!1),`no`);d(s.type),i=B([...t.flow.yieldStates,...n.flow.yieldStates]);break}case`assert`:{let e=u(s.condition,z);s.message&&h(s.message,fe,this.conditioned(l,e,!1),`message`),i=this.conditioned(l,e,!0);break}case`wait`:(t.valueRegion||t.mode!==`process`)&&this.error(`IR_EFFECT`,`wait is only allowed in a process statement region.`,c,s),u(s.duration,R);break;case`elapse`:(t.valueRegion||t.mode!==`jit`)&&this.error(`IR_EFFECT`,`elapse is only allowed in a JIT statement region.`,c,s),u(s.duration,R);break;case`waitUntil`:t.mode!==`jit`&&this.error(`IR_EFFECT`,`waitUntil requires a JIT instruction.`,c,s),(t.valueRegion||t.loop||!t.tail||n!==e.operations.length-1||!t.finalInstruction)&&this.error(`IR_JIT_BOUNDARY`,`waitUntil must be on the final instruction tail path.`,c,s);{let e=this.declaration(s.predicate,`function`,c);e&&(!e.pure||e.params.length||!_e(e.returns,z))&&this.error(`IR_TYPE`,`waitUntil requires a zero-parameter pure bool function.`,c,s)}i=void 0;break;case`redirect`:[`jit`,`sync`].includes(t.mode)||this.error(`IR_EFFECT`,`redirect is not permitted in this context.`,c,s),u(s.target,R),u(s.delay,R),i=void 0;break;case`stop`:(t.mode!==`jit`||t.valueRegion)&&this.error(`IR_EFFECT`,`stop requires a JIT statement region.`,c,s),i=void 0;break;case`return`:(t.valueRegion||t.returns||t.mode===`jit`||t.computation||t.mode===`creation`||t.mode===`initial`)&&this.error(`IR_CONTROL_FLOW`,`Void return is not valid in this body.`,c,s),i=void 0;break;case`returnValue`:(t.valueRegion||!t.returns)&&this.error(`IR_CONTROL_FLOW`,`returnValue is not valid in this body.`,c,s),u(s.value,t.returns),i=void 0;break;case`yield`:t.valueRegion||this.error(`IR_CONTROL_FLOW`,`yield requires a value region.`,c,s);{let e=u(s.value,t.valueRegion);a.yielded.push(e),a.yieldStates.push(l)}i=void 0;break;case`break`:case`continue`:t.loop||this.error(`IR_CONTROL_FLOW`,`${s.kind} requires an enclosing loop in this region.`,c,s),(s.kind===`break`?a.breaks:a.continues).push(l),i=void 0}}return i&&(a.normal=i),a}effects(e,t,n){Ce(e,(e,n)=>{let r=[`creation`,`initial`,`pure`].includes(t),i=[`creation`,`initial`].includes(t),a=[`write`,`writeIntent`,`send`,`notify`,`now`,`random`,`wait`,`receive`,`elapse`,`waitUntil`,`stop`,`redirect`,...re].includes(e.kind);if(r&&a&&this.error(`IR_EFFECT`,`${e.kind} is not allowed in ${t} code.`,n,e),i&&(e.kind===`read`&&![`property`,`const`].includes(e.resource)||[`readSample`,`memoryLength`,`copyBytes`,...D].includes(e.kind))&&this.error(`IR_EFFECT`,`Creation computations cannot read runtime resources.`,n,e),t===`creation`&&([`resistor`,`combineIntents`,`refEqual`].includes(e.kind)||(e.kind===`call`||e.kind===`callValue`)&&e.args.some(e=>e.kind!==`value`))&&this.error(`IR_EFFECT`,`Ordinary creation computations cannot use resource references or intents.`,n,e),[`reaction`,`process`].includes(t)&&e.kind===`redirect`&&this.error(`IR_EFFECT`,`Control redirection requires a bound JIT entry.`,n,e),[`sync`,`reaction`,`pure`].includes(t)&&[`wait`,`receive`,`elapse`,`waitUntil`,`stop`].includes(e.kind)&&this.error(`IR_EFFECT`,`Synchronous code cannot suspend or use JIT control.`,n,e),t===`process`&&[`elapse`,`waitUntil`,`stop`].includes(e.kind)&&this.error(`IR_EFFECT`,`Process code cannot use JIT control.`,n,e),t===`jit`&&[`wait`,`receive`].includes(e.kind)&&this.error(`IR_EFFECT`,`JIT code cannot use process suspension.`,n,e),e.kind===`call`||e.kind===`callValue`||e.kind===`waitUntil`){let i=e.kind===`waitUntil`?e.predicate:e.name,a=this.functions.get(i);if(a&&r&&!a.pure&&this.error(`IR_EFFECT`,`Pure contexts can only call explicitly pure functions.`,n,e),a){let e=`${t}:${i}`;this.effectChecked.has(e)||(this.effectChecked.add(e),this.effects(a.body,t,[...this.paths.get(i)??[],`body`]))}}},n)}source(e,t,n){e.length||this.error(`IR_SCHEMA`,`An observation source path cannot be empty.`,t);let r=this.declarations.get(e[0]);r||this.error(`IR_REFERENCE`,`Observation source does not exist.`,t);let i,a=1;if(r.kind===`notification`&&n)(r.direction!==`input`||e.length!==1)&&this.error(`IR_REFERENCE`,`Only input notifications can trigger a process.`,t);else{r.kind===`pin`?(e[1]!==`sample`&&this.error(`IR_REFERENCE`,`Pin observation must select sample.`,t),i=he,a=2):r.kind===`state`||r.kind===`derived`?i=r.type:this.error(`IR_REFERENCE`,`An observation source must be state, derived, pin.sample or an input notification.`,t);for(let n=a;n<e.length;n++)i=this.field(i,e[n],[...t,n]);return ye(i)||this.error(`IR_TYPE`,`Observation sources must be comparable.`,t),i}}cycle(e,t){let n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=a=>{if(n.has(a)&&this.error(`IR_DEPENDENCY`,`${t} dependency cycle includes ${a}.`,this.paths.get(a)??[]),!r.has(a)){n.add(a);for(let t of e.get(a)??[])e.has(t)&&i(t);n.delete(a),r.add(a)}};for(let t of e.keys())i(t)}dependencies(e,t,n=/* @__PURE__ */ new Set){let r=/* @__PURE__ */ new Set;return Ce(e,e=>{if(e.kind===`read`&&t.includes(e.resource)&&r.add(e.name),(e.kind===`call`||e.kind===`callValue`)&&!n.has(e.name)){n.add(e.name);let i=this.functions.get(e.name);if(i)for(let e of this.dependencies(i.body,t,n))r.add(e)}}),r}validateDevice(){let e=/* @__PURE__ */ new Map;for(let[t,n]of this.functions){let r=/* @__PURE__ */ new Set;Ce(n.body,e=>{(e.kind===`call`||e.kind===`callValue`)&&r.add(e.name)}),e.set(t,r)}this.cycle(e,`Synchronous call`);let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;this.device.declarations.forEach((e,r)=>{let i=[`declarations`,r];if(`type`in e&&e.type&&this.type(e.type,[...i,`type`]),e.kind===`property`||e.kind===`const`||e.kind===`state`){let n=ve(e.type);([`sample`,`intent`].includes(n.kind)||e.kind===`property`&&n.kind===`record`)&&this.error(`IR_TYPE`,`Type is not valid at this declaration position.`,[...i,`type`],e);let r=e.kind===`property`?`default`:e.kind===`const`?`value`:`initial`,a=e.kind===`property`?e.default:e.kind===`const`?e.value:e.initial;a&&(this.computation(a,e.type,`creation`,[...i,r]),t.set(e.name,this.dependencies(a.body,[`property`,`const`])))}else if(e.kind===`derived`)this.computation(e.value,e.type,`pure`,[...i,`value`]),n.set(e.name,this.dependencies(e.value.body,[`derived`]));else if(e.kind===`pin`){for(let t of[`low`,`high`])e[t]&&this.computation(e[t],R,`creation`,[...i,t]);e.initial&&this.computation(e.initial,me,`initial`,[...i,`initial`])}else if(e.kind===`memory`)this.computation(e.length,R,`creation`,[...i,`length`]);else if(e.kind===`channel`)[`number`,`bool`,`record`,`bytes`].includes(e.type.kind)||this.error(`IR_TYPE`,`Invalid channel payload type.`,[...i,`type`],e),e.type.kind===`bytes`!=!!e.maxLength&&this.error(`IR_TYPE`,`Only bytes channels require maxLength.`,i,e),this.computation(e.capacity,R,`creation`,[...i,`capacity`]),e.maxLength&&this.computation(e.maxLength,R,`creation`,[...i,`maxLength`]),e.overflow&&this.computation(e.overflow,{kind:`enum`,name:`Overflow`},`creation`,[...i,`overflow`]);else if(e.kind===`function`){this.uniqueNames(e.params.map(e=>e.name),[...i,`params`]),e.params.forEach((e,t)=>{this.declarations.has(e.name)&&this.error(`IR_REFERENCE`,`A parameter cannot shadow a device member.`,[...i,`params`,t]),e.type.kind!==`pin`&&e.type.kind!==`memory`&&this.type(e.type,[...i,`params`,t,`type`])}),e.returns&&this.type(e.returns,[...i,`returns`]);let t=this.context(e.pure?`pure`:`sync`,e.returns);t.params=e.params,this.body(e.body,t,[...i,`body`])}else if(e.kind===`start`||e.kind===`on`)e.kind===`on`&&this.source(e.sourcePath,[...i,`sourcePath`],!0),this.body(e.body,this.context(`process`),[...i,`body`]),Ce(e.body,e=>{if(e.kind===`receive`){let t=`${r}`,n=this.receiveOwners.get(e.channel);if(n&&n!==t){let e=new S([{code:`IR_REFERENCE`,message:`An input channel cannot have multiple consumer processes.`,phase:`finalize`,path:i,related:[]}]);throw Object.defineProperty(e,\"code\",{value:`CHANNEL_CONSUMER_CONFLICT`}),e}this.receiveOwners.set(e.channel,t)}});else if(e.kind===`reaction`){let t=this.source(e.sourcePath,[...i,`sourcePath`],!1);this.expect(e.sourceType,t,[...i,`sourceType`]),this.type(e.sourceType,[...i,`sourceType`]);let n=[e.previous,e.current,...e.captures.map(e=>e.name)];e.captures.forEach((e,t)=>{ye(e.value.type)||this.error(`IR_TYPE`,`Capture results must be comparable.`,[...i,`captures`,t]),this.computation(e.value,e.value.type,`pure`,[...i,`captures`,t,`value`])});let r=this.context(`reaction`);r.reaction=e,this.body(e.body,r,[...i,`body`]),this.uniqueNames(n,i);for(let e of n)this.declarations.has(e)&&this.error(`IR_REFERENCE`,`Reaction bindings cannot shadow device members.`,i)}else e.kind===`assert`&&this.body(e.body,this.context(`creation`),[...i,`body`])}),this.cycle(t,`Creation`),this.cycle(n,`Derived`)}validateBlock(e){e.instructions.forEach((t,n)=>{let r=this.context(`jit`);r.finalInstruction=n===e.instructions.length-1,this.body(t.body,r,[`instructions`,n,`body`])})}};function Te(e,t){if(!(e instanceof S))throw e;let n=new S(e.diagnostics.map(e=>{if(e.source)return e;let n=t,r,i=()=>{let e=n?.source;e&&typeof e==`object`&&(typeof e.label==`string`&&e.uri===void 0&&e.range===void 0||typeof e.uri==`string`&&e.range?.start?.line>=1&&e.range?.start?.column>=1&&e.range?.end?.line>=1&&e.range?.end?.column>=1)&&(r=e)};i();for(let t of e.path)n=n?.[t],i();return r?{...e,source:r}:e})),r=Object.getOwnPropertyDescriptor(e,`code`);throw r?.value===`CHANNEL_CONSUMER_CONFLICT`&&Object.defineProperty(n,\"code\",r),n}let Ee=/* @__PURE__ */ new WeakSet,De=/* @__PURE__ */ new WeakSet,Oe=/* @__PURE__ */ new WeakMap;function ke(e){if(typeof e==`object`&&e&&Ee.has(e))return e;let t=x(e);try{ue(t),new we(t).validateDevice();let e=t;return Ee.add(e),e}catch(e){return Te(e,t)}}function Ae(e){if(typeof e==`object`&&e&&De.has(e))return e;let t=x(e);try{de(t),new we().validateBlock(t);let e=t;return De.add(e),e}catch(e){return Te(e,t)}}function je(e,t){try{let n=Ae(e),r=ke(t);if(Oe.get(n)?.has(r))return n;new we(r).validateBlock(n);let i=Oe.get(n);return i||(i=/* @__PURE__ */ new WeakSet,Oe.set(n,i)),i.add(r),n}catch(e){if(e instanceof S){let t=new S(e.diagnostics.map(e=>({...e,phase:`bind`}))),n=Object.getOwnPropertyDescriptor(e,`code`);throw n?.value===`CHANNEL_CONSUMER_CONFLICT`&&Object.defineProperty(t,\"code\",n),t}throw e}}let Me=/* @__PURE__ */ new WeakMap,Ne=/* @__PURE__ */ new WeakMap,Pe=/* @__PURE__ */ new WeakMap,Fe=/* @__PURE__ */ new WeakMap,Ie=/* @__PURE__ */ new WeakMap,Le=e=>{let t=Object.freeze({});return Me.set(t,{type:{kind:e}}),t};function Re(e,t,n){let r={};for(let i of t){let t=Object.freeze({});Ie.set(t,{name:e,member:i,...n?{owner:n}:{}}),Object.defineProperty(r,i,{value:t,enumerable:!0})}let i=Object.freeze({name:e,members:Object.freeze(r)});return Me.set(i,{type:{kind:`enum`,name:e},members:Object.freeze([...t]),...n?{owner:n}:{}}),i}function ze(e,t,n){let r=Object.freeze({name:e,fields:Object.freeze({...t})});return Me.set(r,{type:{kind:`record`,name:e},fields:r.fields,...n?{owner:n}:{}}),r}let Be={number:Le(`number`),bool:Le(`bool`),string:Le(`string`),bytes:Le(`bytes`),intent:Le(`intent`),sample:Le(`sample`),pin:Object.freeze({kind:`pin`}),memory:Object.freeze({kind:`memory`}),logic:Re(`Logic`,w.Logic),sampleStatus:Re(`SampleStatus`,w.SampleStatus),overflow:Re(`Overflow`,w.Overflow),optional(e){let t=Me.get(e);(!t||t.type.kind===`optional`)&&C(`IR_TYPE`,`optional requires a nonoptional value type.`,[],`construct`);let n=Object.freeze({});return Me.set(n,{...t,type:{kind:`optional`,inner:t.type}}),n},namedEnum(e,t){return(typeof e!=`string`||!Array.isArray(t)||!t.length||t.some(e=>typeof e!=`string`)||new Set(t).size!==t.length)&&C(`IR_TYPE`,`Invalid named enum description.`,[],`construct`),Re(e,t)},namedRecord(e,t){(typeof e!=`string`||!t||typeof t!=`object`||Array.isArray(t))&&C(`IR_TYPE`,`Invalid named record description.`,[],`construct`);for(let e of Object.values(t))[`number`,`bool`].includes(Me.get(e)?.type.kind??``)||C(`IR_TYPE`,`Record fields must be number or bool types.`,[],`construct`);return ze(e,t)}};Object.freeze(Be);let V={kind:`number`},H={kind:`bool`},Ve={kind:`string`},He={kind:`bytes`},Ue={kind:`intent`},We={kind:`sample`};function Ge(e,t){for(let n=e;n;n=n.parent)if(n===t)return!0;return!1}function Ke(e){return typeof e==`object`&&e?Ne.get(e):void 0}function qe(e){return typeof e==`object`&&e?Ie.get(e):void 0}function Je(e){return typeof e==`object`&&e?Fe.get(e):void 0}function Ye(e,t){let n=Object.freeze({});return e.set(n,t),n}function U(e){return e.alias?U(e.alias):e}function Xe(e){let t=new Map(e[0]);for(let[n,r]of t)e.some(e=>e.get(n)!==r)&&t.delete(n);return t}let Ze=/* @__PURE__ */ new WeakMap;var Qe=class{options;device;jit;closed=!1;active;source;declarations=[];names=/* @__PURE__ */ new Map;expectedTypes=/* @__PURE__ */ new Set;pending=[];instructions=[];constructor(e,t,n=!1){this.options=e,this.device=t,this.jit=n,e.source!==void 0&&(this.source=x(e.source))}error(e,t,n=[]){return this.closed=!0,C(e,t,n,`construct`,this.active?.source??this.source)}check(){this.closed&&this.error(`IR_LIFECYCLE`,`This Builder is closed.`)}guard(e){this.check();try{return e()}catch(e){throw this.closed=!0,e instanceof S&&e.diagnostics.some(e=>e.phase!==`construct`)?new S(e.diagnostics.map(e=>({...e,phase:`construct`}))):e}}type(e){let t=Me.get(e);if(t||this.error(`IR_TYPE`,`Expected a Builder type descriptor.`),t.owner&&t.owner!==this&&(!this.device||Ze.get(this.device)!==t.owner)&&this.error(`IR_SCOPE`,`Named type belongs to another device definition.`),this.expectedTypes.add(t),t.fields)for(let e of Object.values(t.fields))this.type(e);return t.type}sourceFor(e){let t=e?.source??this.source;return t===void 0?{}:{source:x(t)}}body(e,t,n,r,i){let a=new $e(this,e,{result:0,local:0},{},void 0,n);a.source=r===void 0?this.source:x(r);let o=this.active;this.active=a;try{i?.(a),t(a.view())}finally{a.closed=!0,this.active=o}return this.check(),{operations:a.operations,...a.source?{source:x(a.source)}:{}}}creation(e,t,n=`creation`,r){return{type:e,body:this.body(n,e=>{typeof t==`function`?t(e):e.returnValue(t)},e,r)}}declarationType(e){let t=this.names.get(e);return t&&`type`in t?t.type:void 0}add(e){e.name!==void 0&&(this.names.has(e.name)&&this.error(`IR_REFERENCE`,`Duplicate declaration ${e.name}.`),this.names.set(e.name,e)),e.kind===`start`&&this.declarations.some(e=>e.kind===`start`)&&this.error(`IR_REFERENCE`,`Only one start process is allowed.`),this.declarations.push(e)}resolve(){for(let e of this.pending){let t=this.names.get(e.call);if(!t||t.kind!==`function`){this.jit&&e.requiresSignature&&C(`IR_TYPE`,`A null or record call argument requires a bound function signature or an explicitly typed Value.`);continue}let n=t.params[e.index];if((!n||n.type.kind===`pin`||n.type.kind===`memory`)&&this.error(`IR_TYPE`,`A value argument requires a value parameter.`),n.type.kind===`optional`&&e.value!==null){let t=e.body.constantData(n.type.inner,e.value),r=e.body.space.result++,i={kind:`constant`,result:r,type:n.type.inner,constant:t,...e.node.source?{source:e.node.source}:{}},a=t=>{if(Array.isArray(t)){let n=t.indexOf(e.node);return n>=0?(t.splice(n,0,i),!0):t.some(a)}return typeof t==`object`&&!!t&&Object.values(t).some(a)};a(this.jit?this.instructions:this.declarations)||C(`IR_SCHEMA`,`Pending call argument is not part of this definition.`),delete e.node.constant,Object.assign(e.node,{kind:`optional`,type:n.type,value:r})}else{let t=e.body.constantData(n.type,e.value);Object.assign(e.node,{type:n.type,constant:t})}}for(let e of this.expectedTypes){let t=e.type.kind===`optional`?e.type.inner:e.type;if(![`enum`,`record`].includes(t.kind))continue;let n=t.name,r=this.names.get(n);if(w[n]&&t.kind===`enum`)e.members&&(e.members.length!==w[n].length||e.members.some((e,t)=>e!==w[n][t]))&&C(`IR_TYPE`,`Builtin enum description does not match its members.`);else if(r&&(r.kind!==t.kind&&C(`IR_REFERENCE`,`Named type category does not match its declaration.`),e.members&&(e.members.length!==r.members.length||e.members.some((e,t)=>e!==r.members[t]))&&C(`IR_TYPE`,`Forward enum description does not match its declaration.`),e.fields)){let t=Object.entries(e.fields);(t.length!==r.fields.length||t.some(([e,t])=>!r.fields.some(n=>n.name===e&&n.type===Me.get(t)?.type.kind)))&&C(`IR_TYPE`,`Forward record description does not match its declaration.`)}}}},$e=class e{root;mode;space;scope;parent;returns;closed=!1;ended=!1;endedByWaitUntil=!1;source;operations=[];facts=/* @__PURE__ */ new Map;localValues=/* @__PURE__ */ new Map;loop=0;calculate=!1;yielded=!1;constructor(e,t,n,r,i,a){this.root=e,this.mode=t,this.space=n,this.scope=r,this.parent=i,this.returns=a}view(){return new Proxy(Object.create(null),{get:(e,t)=>typeof t==`string`?(...e)=>this.root.guard(()=>(this.closed&&this.root.error(`IR_LIFECYCLE`,`This body Builder is closed.`),this.root.active!==this&&this.root.error(`IR_SCOPE`,`A captured outer Builder cannot emit into a nested callback.`),this.ended&&this.root.error(this.endedByWaitUntil?`IR_JIT_BOUNDARY`:`IR_CONTROL_FLOW`,`Cannot append an operation after a path terminator.`),this.invoke(t,e))):void 0})}node(e){let t={...e,...e.source===void 0&&this.source!==void 0?{source:x(this.source)}:{}};le(t,[]),this.operations.push(t)}result(e,t,n={}){let r=this.space.result++;return this.node({...t,result:r,type:e}),Ye(Ne,{root:this.root,scope:this.scope,space:this.space,type:e,id:r,...n})}handle(e,t){let n=Ke(e);return(!n||n.root!==this.root||n.space!==this.space||!Ge(this.scope,n.scope))&&this.root.error(`IR_SCOPE`,`Value is not visible in the current execution body or scope.`),t&&!_e(n.type,t)&&this.root.error(`IR_TYPE`,`Operand type does not match the expected type.`),n}localHandle(e){let t=Pe.get(e);return(!t||t.root!==this.root||t.space!==this.space||!Ge(this.scope,t.scope))&&this.root.error(`IR_SCOPE`,`Local is not visible in this execution body or scope.`),t}infer(e){if(Ke(e))return this.handle(e).type;let t=qe(e);if(t)return t.owner&&t.owner!==this.root&&(!this.root.device||Ze.get(this.root.device)!==t.owner)&&this.root.error(`IR_SCOPE`,`Enum member belongs to another device definition.`),{kind:`enum`,name:t.name};if(typeof e==`number`)return V;if(typeof e==`boolean`)return H;if(typeof e==`string`)return Ve;if(Array.isArray(e)||e instanceof Uint8Array)return He;this.root.error(`IR_TYPE`,`A null or record literal requires an explicit target type.`)}constantData(e,t){if(e.kind===`optional`)return t!==null&&this.root.error(`IR_TYPE`,`Optional constants must be lifted from a non-null value.`),{kind:`none`};if(e.kind===`number`||e.kind===`bool`||e.kind===`string`)return typeof t!==(e.kind===`bool`?`boolean`:e.kind)&&this.root.error(`IR_TYPE`,`Constant value does not match its target type.`),{kind:e.kind,value:t};if(e.kind===`enum`){let n=qe(t);return(!n||n.name!==e.name)&&this.root.error(`IR_TYPE`,`Enum constants require a matching enum member token.`),n.owner&&n.owner!==this.root&&(!this.root.device||Ze.get(this.root.device)!==n.owner)&&this.root.error(`IR_SCOPE`,`Enum member belongs to another definition.`),{kind:`enum`,name:n.name,member:n.member}}if(e.kind===`record`){(typeof t!=`object`||!t||Array.isArray(t))&&this.root.error(`IR_TYPE`,`A record constant requires a field object.`);let n=[...this.root.expectedTypes].find(t=>{let n=t.type.kind===`optional`?t.type.inner:t.type;return n.kind===`record`&&n.name===e.name&&t.fields}),r=this.root.names.get(e.name),i=n?.fields?Object.entries(n.fields).map(([e,t])=>({name:e,type:Me.get(t).type.kind})):r?.kind===`record`?r.fields:void 0;i||this.root.error(`IR_TYPE`,`Record constants require a complete named type descriptor.`);let a=t;return(Object.keys(a).length!==i.length||i.some(e=>!Object.hasOwn(a,e.name)||typeof a[e.name]!=(e.type===`bool`?`boolean`:`number`)))&&this.root.error(`IR_TYPE`,`Record constant fields do not match the target type.`),{kind:`record`,name:e.name,fields:Object.keys(a).map(e=>({name:e,value:a[e]}))}}if(e.kind===`bytes`){!(t instanceof Uint8Array)&&!Array.isArray(t)&&this.root.error(`IR_TYPE`,`bytes constants require a Uint8Array or number array.`);let e=Array.from(t);return e.some(e=>!Number.isInteger(e)||e<0||e>255)&&this.root.error(`IR_TYPE`,`Every bytes element must be an integer from zero to 255.`),{kind:`bytes`,value:Object.freeze(e)}}this.root.error(`IR_TYPE`,`sample and intent cannot be constructed from host constants.`)}operand(e,t){if(Ke(e)){let n=this.handle(e);if(t&&t.kind===`optional`&&_e(n.type,t.inner)){let e=this.handle(this.result(t,{kind:`optional`,value:n.id}));return this.facts.set(U(e),!0),e}return t&&!_e(n.type,t)&&this.root.error(`IR_TYPE`,`Operand type does not match the expected type.`),n}let n=t??this.infer(e);if(n.kind===`optional`&&e!==null){let t=this.operand(e,n.inner),r=this.handle(this.result(n,{kind:`optional`,value:t.id}));return this.facts.set(U(r),!0),r}return this.handle(this.result(n,{kind:`constant`,constant:this.constantData(n,e)},{none:e===null}))}ref(e,t){if(typeof e==`string`)return{kind:t,name:e};let n=Je(e);return(!n||n.root!==this.root||n.space!==this.space||!Ge(this.scope,n.scope))&&this.root.error(`IR_SCOPE`,`Resource reference is not visible in this body.`),(n.ref.kind===`parameter`?n.ref.resource:n.ref.kind)!==t&&this.root.error(`IR_REFERENCE`,`Resource reference category does not match.`),n.ref}refHandle(e,t){return Ye(Fe,{root:this.root,scope:this.scope,space:this.space,ref:{kind:t,name:e}})}requireRead(){[`creation`,`initial`].includes(this.mode)&&this.root.error(`IR_EFFECT`,`Runtime resource reads are not available in creation code.`)}requireEffect(){[`creation`,`initial`,`pure`].includes(this.mode)&&this.root.error(`IR_EFFECT`,`Runtime effects are not available in pure or creation code.`)}branch(t,n,r,i=!1){typeof t!=`function`&&this.root.error(`IR_SCHEMA`,`A body callback is required.`);let a=new e(this.root,this.mode,this.space,{parent:this.scope},this,this.returns);if(a.source=this.source,a.loop=r?0:this.loop+ +!!i,a.calculate=!!r||this.calculate,a.facts=new Map(this.facts),a.localValues=new Map(this.localValues),n)for(let[e,t]of(n.truth?n.info.yes:n.info.no)??[])a.facts.set(U(e),t);let o=this.root.active;this.root.active=a;let s;try{if(s=t(a.view()),r){if(s===void 0)a.ended||this.root.error(`IR_CONTROL_FLOW`,`A compute callback must produce a value on every normal path.`);else if(!a.ended){let e=a.operand(s,r);a.node({kind:`yield`,value:e.id}),a.yielded=!0,a.ended=!0}}}finally{a.closed=!0,this.root.active=o}return this.root.check(),{body:{operations:a.operations,...a.source?{source:x(a.source)}:{}},builder:a,returned:s}}merge(e){let t=e.filter(e=>!e.ended);if(!t.length)this.ended=!0,this.endedByWaitUntil=e.some(e=>e.endedByWaitUntil);else{this.facts=Xe(t.map(e=>e.facts));for(let[e,n]of this.localValues){let r=t.map(t=>t.localValues.get(e)??n);if(r.every(e=>e===r[0]))this.localValues.set(e,r[0]);else{let i={...n,alias:void 0};this.localValues.set(e,i),r.every((e,n)=>t[n].facts.get(U(e))===!0)&&this.facts.set(i,!0)}}}}mergeComputations(e,t=!1){let n=e.filter(e=>e.yielded);if(t&&n.push(this),!n.length)this.ended=!0;else{this.facts=Xe(n.map(e=>e.facts));for(let[e,t]of this.localValues){let r=n.map(n=>n.localValues.get(e)??t);if(r.every(e=>e===r[0]))this.localValues.set(e,r[0]);else{let i={...t,alias:void 0};this.localValues.set(e,i),r.every((e,t)=>n[t].facts.get(U(e))===!0)&&this.facts.set(i,!0)}}}}invoke(t,n){if(T.includes(t)){let e=this.operand(n[0],t===`not`?H:V);return this.result(t===`not`?H:V,{kind:`unary`,operator:t,value:e.id},t===`not`?{yes:e.no??/* @__PURE__ */ new Map,no:e.yes??/* @__PURE__ */ new Map}:{})}if(E.includes(t)){let e=[`equal`,`notEqual`].includes(t),r=e?this.root.type(n.shift()):t===`concat`?Ve:V,i=this.operand(n[0],r),a=this.operand(n[1],r);e&&(r.kind===`intent`||r.kind===`optional`&&r.inner.kind===`intent`&&!i.none&&!a.none)&&this.root.error(`IR_TYPE`,`Intent values do not support content equality.`);let o=i.none?a:a.none?i:void 0,s=e||[`lessThan`,`lessThanOrEqual`,`greaterThan`,`greaterThanOrEqual`].includes(t);return this.result(s?H:r,{kind:`binary`,operator:t,left:i.id,right:a.id},o?{yes:/* @__PURE__ */ new Map([[U(o),t!==`equal`]]),no:/* @__PURE__ */ new Map([[U(o),t===`equal`]])}:{})}if(ne.includes(t)){let e=[`min`,`max`,`pow`].includes(t)?2:1;return n.length!==e&&this.root.error(`IR_TYPE`,`Numeric builtin argument count does not match.`),this.result(t.startsWith(`is`)?H:V,{kind:`numeric`,builtin:t,args:n.map(e=>this.operand(e,V).id)})}if(D.includes(t)||re.includes(t)){this.requireRead();let e=this.ref(n[0],`memory`),r=this.operand(n[1],V);if(re.includes(t)){this.requireEffect(),this.node({kind:t,memory:e,offset:r.id,value:this.operand(n[2],V).id});return}return this.result(V,{kind:t,memory:e,offset:r.id})}switch(t){case`withSource`:{let[t,r]=n,i=new e(this.root,this.mode,this.space,this.scope,this.parent,this.returns);i.source=x(t),i.loop=this.loop,i.calculate=this.calculate,i.facts=this.facts,i.localValues=this.localValues;let a=this.root.active;this.root.active=i;try{r(i.view())}finally{i.closed=!0,this.root.active=a}this.operations.push(...i.operations),this.ended=i.ended,this.endedByWaitUntil=i.endedByWaitUntil,this.facts=i.facts,this.localValues=i.localValues;return}case`constant`:return Ke(n[1])&&this.root.error(`IR_TYPE`,`constant requires a host constant, not a Value handle.`),this.objectOperand(n[1],this.root.type(n[0]));case`readProperty`:case`readConst`:case`readState`:case`readDerived`:{[`readState`,`readDerived`].includes(t)&&this.requireRead();let e=t.slice(4).toLowerCase();return this.result(this.root.type(n[1]),{kind:`read`,resource:e,name:n[0]})}case`local`:{let e=this.root.type(n[0]),t=this.operand(n[1],e),r=this.space.local++;this.node({kind:`local`,local:r,type:e,initial:t.id});let i={root:this.root,space:this.space,scope:this.scope,type:e,id:r};return this.localValues.set(i,t),Ye(Pe,i)}case`getLocal`:{let e=this.localHandle(n[0]),t=this.localValues.get(e);return this.result(e.type,{kind:`localRead`,local:e.id},{alias:U(t),yes:t.yes??/* @__PURE__ */ new Map,no:t.no??/* @__PURE__ */ new Map,none:t.none??!1})}case`setLocal`:{let e=this.localHandle(n[0]),t=this.operand(n[1],e.type);this.node({kind:`localWrite`,local:e.id,value:t.id}),this.localValues.set(e,t);return}case`record`:{let e=this.root.type(n[0]),t=Me.get(n[0]),r=n[1];return(e.kind!==`record`||!t.fields||!r||typeof r!=`object`||Object.keys(r).length!==Object.keys(t.fields).length||Object.keys(t.fields).some(e=>!Object.hasOwn(r,e)))&&this.root.error(`IR_TYPE`,`Record fields must exactly match the descriptor.`),this.result(e,{kind:`record`,fields:Object.keys(r).map(e=>({name:e,value:this.operand(r[e],this.root.type(t.fields[e])).id}))})}case`field`:{let e=this.handle(n[0]),t=n[1],r;if(e.type.kind===`sample`)r={voltage:{kind:`optional`,inner:V},level:{kind:`enum`,name:`Logic`},status:{kind:`enum`,name:`SampleStatus`}}[t];else if(e.type.kind===`record`){let n=e.type.name,i=[...this.root.expectedTypes].find(e=>{let t=e.type.kind===`optional`?e.type.inner:e.type;return t.kind===`record`&&t.name===n&&e.fields})?.fields?.[t];if(i)r=this.root.type(i);else{let e=this.root.names.get(n),i=e?.kind===`record`?e.fields.find(e=>e.name===t):void 0;i&&(r={kind:i.type})}}r||this.root.error(`IR_REFERENCE`,`Unknown record or sample field.`);let i=U(e);i.fields??=/* @__PURE__ */ new Map;let a=i.fields.get(t),o=this.result(r,{kind:`field`,value:e.id,field:t},a?{alias:a}:{});return a||i.fields.set(t,this.handle(o)),o}case`bytes`:return this.result(He,{kind:`bytes`,elements:n.map(e=>this.operand(e,V).id)});case`length`:{let e=this.handle(n[0]);return[`string`,`bytes`].includes(e.type.kind)||this.root.error(`IR_TYPE`,`length requires string or bytes.`),this.result(V,{kind:`length`,value:e.id})}case`index`:{let e=this.handle(n[0]);return[`string`,`bytes`].includes(e.type.kind)||this.root.error(`IR_TYPE`,`index requires string or bytes.`),this.result(e.type.kind===`string`?Ve:V,{kind:`index`,value:e.id,index:this.operand(n[1],V).id})}case`optional`:{let e=this.handle(n[0]);e.type.kind===`optional`&&this.root.error(`IR_TYPE`,`Optional types cannot be nested.`);let t=this.result({kind:`optional`,inner:e.type},{kind:`optional`,value:e.id});return this.facts.set(U(this.handle(t)),!0),t}case`isNone`:{let e=this.handle(n[0]);return e.type.kind!==`optional`&&this.root.error(`IR_TYPE`,`isNone requires an optional value.`),this.result(H,{kind:`isNone`,value:e.id},{yes:/* @__PURE__ */ new Map([[U(e),!1]]),no:/* @__PURE__ */ new Map([[U(e),!0]])})}case`nonNull`:{let e=this.handle(n[0]);return(e.type.kind!==`optional`||this.facts.get(U(e))!==!0)&&this.root.error(`IR_TYPE`,`nonNull requires a dominating non-null proof.`),this.result(e.type.inner,{kind:`nonNull`,value:e.id})}case`pin`:return this.mode===`creation`&&this.root.error(`IR_EFFECT`,`Pin references are not available in ordinary creation computations.`),this.refHandle(n[0],`pin`);case`memory`:return this.requireRead(),this.refHandle(n[0],`memory`);case`memoryLength`:return this.requireRead(),this.result(V,{kind:`memoryLength`,memory:this.ref(n[0],`memory`)});case`copyBytes`:return this.requireRead(),this.result(He,{kind:`copyBytes`,memory:this.ref(n[0],`memory`),offset:this.operand(n[1],V).id,length:this.operand(n[2],V).id});case`readSample`:return this.requireRead(),this.result(We,{kind:`readSample`,pin:this.ref(n[0],`pin`)});case`resistor`:return this.mode===`creation`&&this.root.error(`IR_EFFECT`,`Intent construction requires initial-intent or runtime code.`),this.result(Ue,{kind:`resistor`,to:this.ref(n[0],`pin`),resistance:this.operand(n[1],V).id});case`combineIntents`:return this.mode===`creation`&&this.root.error(`IR_EFFECT`,`Intent construction is not available here.`),this.result(Ue,{kind:`combineIntents`,values:n.map(e=>this.operand(e,Ue).id)});case`refEqual`:{this.requireRead();let e=Je(n[0]),t=Je(n[1]);(!e||!t)&&this.root.error(`IR_TYPE`,`refEqual requires resource reference handles.`);let r=e.ref.kind===`parameter`?e.ref.resource:e.ref.kind;return this.result(H,{kind:`refEqual`,left:this.ref(n[0],r),right:this.ref(n[1],r)})}case`writeState`:this.requireEffect(),this.node({kind:`write`,resource:`state`,name:n[0],value:this.operand(n[1],this.root.declarationType(n[0])).id});return;case`writeIntent`:this.requireEffect(),this.node({kind:`writeIntent`,pin:this.ref(n[0],`pin`),value:this.operand(n[1],Ue).id});return;case`send`:this.requireEffect(),this.node({kind:`send`,channel:n[0],value:this.operand(n[1],this.root.declarationType(n[0])).id});return;case`notify`:this.requireEffect(),this.node({kind:`notify`,notification:n[0]});return;case`now`:case`random`:return this.requireEffect(),this.result(V,{kind:t});case`call`:case`callValue`:case`callPure`:case`callPureValue`:{let e=t.startsWith(`callPure`),r=t.endsWith(`Value`);e||this.requireEffect();let i=n.shift(),a=r?this.root.type(n.shift()):void 0,o=this.root.names.get(i),s=o?.kind===`function`?o.params:void 0,c=n.map((e,t)=>{let n=Je(e);if(n)return this.mode===`creation`&&this.root.error(`IR_EFFECT`,`Resource arguments are not available in ordinary creation code.`),this.ref(e,n.ref.kind===`parameter`?n.ref.resource:n.ref.kind);let r=s?.[t]?.type;if(r&&[`pin`,`memory`].includes(r.kind)&&this.root.error(`IR_TYPE`,`A resource reference argument is required.`),!r&&!Ke(e)){let n=e===null||typeof e==`object`&&!qe(e)&&!Array.isArray(e)&&!(e instanceof Uint8Array),r=n?V:this.infer(e),a={kind:`constant`,result:this.space.result++,type:r,constant:n?{kind:`number`,value:0}:this.constantData(r,e),...this.source?{source:x(this.source)}:{}};return this.operations.push(a),this.root.pending.push({node:a,call:i,index:t,value:qe(e)?e:x(e),body:this,requiresSignature:n}),{kind:`value`,value:a.result}}return{kind:`value`,value:this.operand(e,r).id}}),l={kind:r?`callValue`:`call`,name:i,pure:e,args:c};if(r)return this.result(a,l);this.node(l);return}case`receive`:return(this.calculate||this.mode!==`process`)&&this.root.error(`IR_EFFECT`,`receive requires a process statement region.`),this.result(this.root.type(n[1]),{kind:`receive`,channel:n[0]});case`if`:{let e=this.operand(n[0],H),t=this.branch(n[1],{info:e,truth:!0}),r=this.branch(n[2]??(()=>{}),{info:e,truth:!1});this.node({kind:`if`,condition:e.id,yes:t.body,...n[2]?{no:r.body}:{}}),this.merge([t.builder,r.builder]);return}case`match`:{let e=this.handle(n[0]),t=n[1];Array.isArray(t)||this.root.error(`IR_SCHEMA`,`match arms must be an array.`);let r=[],i=t.map(t=>{let n=t.pattern===null?{kind:`none`}:this.constantData(e.type.kind===`optional`?e.type.inner:e.type,t.pattern);[`none`,`number`,`bool`,`string`,`enum`].includes(n.kind)||this.root.error(`IR_TYPE`,`Invalid match pattern.`);let i={...e,yes:/* @__PURE__ */ new Map([[U(e),n.kind!==`none`]])},a=this.branch(t.emit,{info:i,truth:!0});return r.push(a.builder),{pattern:n,body:a.body}}),a=i.some(e=>e.pattern.kind===`none`)?{info:{...e,yes:/* @__PURE__ */ new Map([[U(e),!0]])},truth:!0}:void 0,o=n[2]?this.branch(n[2],a):void 0;o&&r.push(o.builder),this.node({kind:`match`,value:e.id,arms:i,...o?{otherwise:o.body}:{}}),this.merge(r.length?r:[this]);return}case`while`:case`loop`:{let e=new Map(this.localValues),r=t===`while`?this.branch(n[0],void 0,H):void 0,i=this.branch(n[+(t===`while`)],void 0,void 0,!0);this.node({kind:t,...r?{test:{type:H,body:r.body}}:{},body:i.body});for(let[t,n]of e)(i.builder.localValues.get(t)!==n||r&&r.builder.localValues.get(t)!==n)&&this.localValues.set(t,{...n,alias:void 0});r&&!r.builder.yielded&&(this.ended=!0);return}case`and`:case`or`:{let e=this.operand(n[0],H),r=t===`and`,i=this.branch(n[1],{info:e,truth:r},H),a=Ke(i.returned),o=(e,t)=>new Map([...e??[],...t??[]]),s=r?o(e.yes,a?.yes):Xe([e.yes??/* @__PURE__ */ new Map,o(e.no,a?.yes)]),c=r?Xe([e.no??/* @__PURE__ */ new Map,o(e.yes,a?.no)]):o(e.no,a?.no),l=this.result(H,{kind:t,left:e.id,right:{type:H,body:i.body}},{yes:s,no:c});return this.mergeComputations([i.builder],!0),l}case`select`:{let e=this.root.type(n[0]),t=this.operand(n[1],H),r=this.branch(n[2],{info:t,truth:!0},e),i=this.branch(n[3],{info:t,truth:!1},e),a=this.result(e,{kind:`select`,condition:t.id,yes:{type:e,body:r.body},no:{type:e,body:i.body}});return this.mergeComputations([r.builder,i.builder]),a}case`assert`:{let e=this.operand(n[0],H),t=n[1]?this.branch(n[1],{info:e,truth:!1},Ve):void 0;this.node({kind:`assert`,condition:e.id,...t?{message:{type:Ve,body:t.body}}:{}});for(let[t,n]of e.yes??[])this.facts.set(U(t),n);return}case`wait`:case`elapse`:(this.calculate||(t===`wait`?this.mode!==`process`:this.mode!==`jit`))&&this.root.error(`IR_EFFECT`,`${t} is not permitted in this context.`),this.node({kind:t,duration:this.operand(n[0],V).id});return;case`waitUntil`:(this.mode!==`jit`||this.calculate||this.loop)&&this.root.error(`IR_JIT_BOUNDARY`,`waitUntil requires a JIT tail path outside loops and computations.`),this.node({kind:`waitUntil`,predicate:n[0]}),this.ended=!0,this.endedByWaitUntil=!0;return;case`redirect`:[`jit`,`sync`].includes(this.mode)||this.root.error(`IR_EFFECT`,`redirect requires a JIT-capable context.`),this.node({kind:`redirect`,target:this.operand(n[0],V).id,delay:this.operand(n[1]??0,V).id}),this.ended=!0;return;case`stop`:(this.mode!==`jit`||this.calculate)&&this.root.error(`IR_EFFECT`,`stop requires a JIT statement region.`),this.node({kind:`stop`}),this.ended=!0;return;case`break`:case`continue`:this.loop||this.root.error(`IR_CONTROL_FLOW`,`${t} requires an enclosing loop.`),this.node({kind:t}),this.ended=!0;return;case`return`:(this.calculate||this.returns||[`jit`,`creation`,`initial`].includes(this.mode))&&this.root.error(`IR_CONTROL_FLOW`,`Void return is not permitted in this body.`),this.node({kind:`return`}),this.ended=!0;return;case`returnValue`:(this.calculate||!this.returns)&&this.root.error(`IR_CONTROL_FLOW`,`returnValue is not permitted in this body.`),this.node({kind:`returnValue`,value:this.operand(n[0],this.returns).id}),this.ended=!0;return;default:this.root.error(`IR_SCHEMA`,`Unknown Builder operation ${t}.`)}}objectOperand(e,t){let n=this.operand(e,t);return Ye(Ne,n)}};function et(e={}){let t=new Qe({name:`JitBlock`,...e.source?{source:e.source}:{}},e.device,!0);if(e.device)for(let n of e.device.declarations)`name`in n&&t.names.set(n.name,n);let n=(r={closed:!1})=>new Proxy(Object.create(null),{get:(i,a)=>typeof a==`string`?(...i)=>{if(a===`finish`){t.check(),r.closed&&t.error(`IR_LIFECYCLE`,`This source view is closed.`),t.active&&t.error(`IR_SCOPE`,`Cannot finish a block inside an instruction callback.`),t.closed=!0,t.resolve();let n={kind:`block`,instructions:t.instructions,...t.sourceFor()};return e.device?je(n,e.device):Ae(n)}return t.guard(()=>{if(r.closed&&t.error(`IR_LIFECYCLE`,`This source view is closed.`),t.active&&t.error(`IR_SCOPE`,`Cannot add instructions inside an instruction callback.`),a===`withSource`){let e=t.source,r={closed:!1};t.source=x(i[0]);try{i[1](n(r))}finally{r.closed=!0,t.source=e}return}a!==`instruction`&&t.error(`IR_SCHEMA`,`Unknown block Builder method ${a}.`);let e=i[0];(!e||!Number.isFinite(e.pc)||!Number.isFinite(e.nextPc))&&t.error(`IR_SCHEMA`,`Instruction boundaries require finite pc and nextPc.`);let o=t.instructions.at(-1);o&&o.nextPc!==e.pc&&t.error(`IR_JIT_BOUNDARY`,`Adjacent instruction boundaries must match.`);let s=t.body(`jit`,i[1],void 0,e.source??t.source);t.instructions.push({pc:e.pc,nextPc:e.nextPc,body:s,...t.sourceFor(e)})})}:void 0});return n()}function tt(e,t){return t}function nt(e){return Object.freeze(Object.fromEntries(e))}function rt(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isInteger(r))throw TypeError(`Byte value must be an integer number`);if(r<0||r>255)throw RangeError(`Byte value must be in [0, 255]`);t[n]=r}return t}function it(e){let t=[];for(let n of e)if(Array.isArray(n))for(let e of n)t.push(e);else t.push(n);return Object.freeze(t)}function at(e,t){if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return e===t;if(ot(e)||ot(t)){if(!ot(e)||!ot(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}let n=e,r=t,i=Object.keys(n);if(i.length!==Object.keys(r).length)return!1;for(let e of i)if(!Object.hasOwn(r,e)||!at(n[e],r[e]))return!1;return!0}function ot(e){return Array.isArray(e)||ArrayBuffer.isView(e)||`length`in e&&Symbol.iterator in e}function st(e,t){if(typeof t!=`number`||!Number.isSafeInteger(t))throw TypeError(`Index must be a safe integer number`);if(t<0||t>=e.length)throw RangeError(`Index is outside the value`);return e[t]}function ct(e){if(e===null)throw TypeError(`Expected a non-null value`);return e}function lt(e){if(typeof e!=`boolean`)throw TypeError(`Condition must be a boolean`);return e}function ut(e){if(typeof e!=`number`||!Number.isFinite(e)||!Number.isInteger(e))throw TypeError(`Duration must be a finite integer number`);if(e<0||e>72e14)throw RangeError(`Duration must be in [0, 7200000000000000] picoseconds`);return e}function dt(e){if(typeof e!=`number`||!Number.isFinite(e))throw TypeError(`Redirect target must be a finite number`);return e}function ft(e,t){if(!e)throw TypeError(`Reaction value requires a reaction frame`);return e[t]}function pt(e,t){if(!e||t>=e.captures.length)throw RangeError(`Reaction capture is not available`);return e.captures[t]}let mt=Symbol(`terminated call`);function*ht(e){let t=!1;try{let n=e.next();for(;!n.done;){let t=n.value,r=yield t;if(t.kind===`stop`||t.kind===`redirect`)return mt;n=e.next(r)}return t=!0,n.value}finally{t||e.return(void 0)}}let gt=Object.freeze({createEnum:tt,createRecord:nt,createBytes:rt,combineIntents:it,equalValues:at,readIndex:st,nonNull:ct,checkBoolean:lt,checkDuration:ut,checkPc:dt,reactionValue:ft,reactionCapture:pt,delegate:ht,terminated:mt});function _t(e){return e.uri===void 0?Object.freeze({...e}):Object.freeze({...e,range:Object.freeze({start:Object.freeze({...e.range.start}),end:Object.freeze({...e.range.end})})})}function vt(e){return e.kind===`optional`?Object.freeze({...e,inner:Object.freeze({...e.inner})}):Object.freeze({...e})}function yt(e){switch(e.kind){case`unary`:case`field`:case`length`:case`optional`:case`isNone`:case`nonNull`:case`localWrite`:case`write`:case`writeIntent`:case`send`:case`match`:case`returnValue`:case`yield`:return[e.value];case`binary`:return[e.left,e.right];case`numeric`:return[...e.args];case`record`:return e.fields.map(e=>e.value);case`bytes`:return[...e.elements];case`index`:return[e.value,e.index];case`local`:return[e.initial];case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:return[e.offset];case`store8`:case`store16le`:case`store16be`:case`store32le`:case`store32be`:return[e.offset,e.value];case`copyBytes`:return[e.offset,e.length];case`resistor`:return[e.resistance];case`combineIntents`:return[...e.values];case`call`:case`callValue`:return e.args.flatMap(e=>e.kind===`value`?[e.value]:[]);case`if`:case`select`:case`assert`:return[e.condition];case`and`:case`or`:return[e.left];case`wait`:case`elapse`:return[e.duration];case`redirect`:return[e.target,e.delay];default:return[]}}function bt(e){let t=[],n=e=>{e.kind===`parameter`&&t.push(`argument:${e.index}`)};return`memory`in e&&n(e.memory),`pin`in e&&n(e.pin),e.kind===`resistor`&&n(e.to),e.kind===`refEqual`&&(n(e.left),n(e.right)),(e.kind===`call`||e.kind===`callValue`)&&e.args.forEach(e=>{e.kind!==`value`&&n(e)}),e.kind===`parameter`&&t.push(`argument:${e.index}`),(e.kind===`reactionValue`||e.kind===`reactionCapture`)&&t.push(`reaction`),t}function xt(e){return e.kind===`parameter`?`$${e.index}`:e.name}function St(e){let t=[],n=[],r=[],i=e.kind===`call`||e.kind===`callValue`,a=i||[`wait`,`elapse`,`receive`,`waitUntil`,`redirect`].includes(e.kind),o=i||(/* @__PURE__ */ `read.write.readSample.writeIntent.resistor.bytes.index.nonNull.field.length.memoryLength.copyBytes.send.receive.notify.now.random.reactionValue.reactionCapture.if.select.and.or.assert.wait.elapse.redirect`.split(`.`)).includes(e.kind)||e.kind.startsWith(`load`)||e.kind.startsWith(`store`);return e.kind===`read`&&t.push(`${e.resource}:${e.name}`),e.kind===`write`&&n.push(`state:${e.name}`),`memory`in e&&(e.kind.startsWith(`store`)?n:t).push(`memory:${xt(e.memory)}`),e.kind===`readSample`&&t.push(`pin:${xt(e.pin)}`),e.kind===`writeIntent`&&n.push(`pin:${xt(e.pin)}`),e.kind===`send`&&n.push(`channel:${e.channel}`),e.kind===`receive`&&(t.push(`channel:${e.channel}`),n.push(`channel:${e.channel}`)),e.kind===`notify`&&n.push(`notification:${e.notification}`),e.kind===`waitUntil`&&(t.push(`*`),r.push(e.predicate)),i&&(r.push(e.name),t.push(`*`),n.push(`*`)),Object.freeze({reads:Object.freeze(t),writes:Object.freeze(n),calls:Object.freeze(r),operations:Object.freeze([e.kind]),maySuspend:a,mayThrow:o,mayRedirect:i||e.kind===`redirect`,mayStop:i||e.kind===`stop`,timeDependent:i||e.kind===`now`,random:i||e.kind===`random`})}function Ct(e,t){let n=yt(e);if(n.some(e=>!t.has(e)))return;let r=t.get(n[0]),i=t.get(n[1]);switch(e.kind){case`constant`:{let t=e.constant;return t.kind===`none`?{value:null}:t.kind===`enum`?{value:t.member}:t.kind===`number`||t.kind===`bool`||t.kind===`string`?{value:t.value}:void 0}case`optional`:return{value:r};case`isNone`:return{value:r===null};case`nonNull`:return r===null?void 0:{value:r};case`unary`:switch(e.operator){case`positive`:return{value:+r};case`negate`:return{value:-r};case`not`:return{value:!r};case`bitNot`:return{value:~r}}break;case`binary`:{let t=r,n=i;switch(e.operator){case`add`:return{value:t+n};case`subtract`:return{value:t-n};case`multiply`:return{value:t*n};case`divide`:return{value:t/n};case`remainder`:return{value:t%n};case`power`:return{value:t**n};case`lessThan`:return{value:t<n};case`lessThanOrEqual`:return{value:t<=n};case`greaterThan`:return{value:t>n};case`greaterThanOrEqual`:return{value:t>=n};case`equal`:return{value:r===i};case`notEqual`:return{value:r!==i};case`concat`:return{value:r+i};case`bitAnd`:return{value:t&n};case`bitOr`:return{value:t|n};case`bitXor`:return{value:t^n};case`shiftLeft`:return{value:t<<n};case`shiftRight`:return{value:t>>n};case`shiftRightUnsigned`:return{value:t>>>n}}break}case`numeric`:{let n=e.args.map(e=>t.get(e));if(e.builtin===`isNaN`)return{value:Number.isNaN(n[0])};if(e.builtin===`isFinite`)return{value:Number.isFinite(n[0])};if(e.builtin===`isInteger`)return{value:Number.isInteger(n[0])};if(e.builtin===`isSafeInteger`)return{value:Number.isSafeInteger(n[0])};let r=Math[e.builtin];return{value:r(...n)}}}}function wt(e,t,n){switch(e.kind){case`constant`:return e.constant.kind!==`bytes`&&e.constant.kind!==`record`;case`parameter`:case`localRead`:case`optional`:case`isNone`:case`unary`:case`numeric`:return!0;case`nonNull`:return n.has(e.result);case`binary`:{if(e.operator!==`equal`&&e.operator!==`notEqual`)return!0;let n=t.get(e.left);return n?.kind===`optional`&&(n=n.inner),!!n&&[`number`,`string`,`bool`,`enum`].includes(n.kind)}default:return!1}}function Tt(e){let t=e=>typeof e!=`object`||!e?e:Object.freeze(Array.isArray(e)?e.map(t):Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).map(([e,n])=>[e,t(n)])));return Object.freeze(Object.fromEntries(Object.entries(e).flatMap(([n,r])=>[`kind`,`type`,`source`,`body`,`test`,`message`,`yes`,`no`].includes(n)||r===void 0||n===`right`&&typeof r==`object`?[]:[[n,t(n===`arms`?e.arms.map(e=>e.pattern):r)]])))}function Et(e,t,n=!0){return new Dt(e,t.optimize!==!1,n).analyze()}var Dt=class{optimize;metadata;nodes=[];regions=[];blocks=[];blockSpecs=[];buildingGraph=!1;edges=[];byOperation=/* @__PURE__ */ new Map;folded=/* @__PURE__ */ new Map;eliminated=/* @__PURE__ */ new Set;root;throwExit;stopExit;redirectExit;constructor(e,t,n){this.optimize=t,this.metadata=n,this.root=this.index(e,[],null,e.source),this.throwExit=this.block(0,`throw`),this.stopExit=this.block(0,`stop`),this.redirectExit=this.block(0,`redirect`)}block(e,t,n=null){let r=this.blockSpecs.length,i={id:r,region:e,role:t,position:n};return this.blockSpecs.push(i),this.buildingGraph&&this.blocks.push(this.allocateBlock(i)),r}allocateBlock(e){return{...e,uses:/* @__PURE__ */ new Set,definitions:/* @__PURE__ */ new Set,liveIn:/* @__PURE__ */ new Set,liveOut:/* @__PURE__ */ new Set}}edge(e,t,n,r={}){this.edges.push(Object.freeze({from:e,to:t,kind:n,...r}))}index(e,t,n,r){let i=this.regions.length,a={id:i,parent:n,path:Object.freeze([...t]),entry:this.block(i,`entry`),exit:this.block(i,`exit`),nodes:[]};return this.regions.push(a),e.operations.forEach((n,o)=>{let s=this.nodes.length,c=this.block(i,`operation`,s),l=this.metadata?n.source??e.source??r:void 0,u,d={operation:n,position:s,block:c,definitionBlock:c,region:i,path:Object.freeze([...t,`operations`,o]),inputs:Object.freeze(yt(n)),get effects(){return u??=St(n)},children:/* @__PURE__ */ new Map,...l?{source:_t(l)}:{}};a.nodes.push(d),this.nodes.push(d),this.byOperation.set(n,d);let f=(e,t,n=[e],r=l)=>{d.children.set(e,this.index(t,[...d.path,...n],i,r))};switch(n.kind){case`if`:f(`yes`,n.yes),n.no&&f(`no`,n.no);break;case`match`:n.arms.forEach((e,t)=>f(`arm${t}`,e.body,[`arms`,t,`body`],e.source??l)),n.otherwise&&f(`otherwise`,n.otherwise);break;case`while`:f(`test`,n.test.body,[`test`,`body`]),f(`body`,n.body);break;case`loop`:f(`body`,n.body);break;case`select`:f(`yes`,n.yes.body,[`yes`,`body`]),f(`no`,n.no.body,[`no`,`body`]);break;case`and`:case`or`:f(`right`,n.right.body,[`right`,`body`]);break;case`assert`:n.message&&f(`message`,n.message.body,[`message`,`body`])}}),a}link(e,t,n,r=`next`){this.edge(e.entry,e.nodes[0]?.block??e.exit,`next`),t!==null&&this.edge(e.exit,t,r),e.nodes.forEach((t,r)=>{let i=t.operation,a=t.block,o=e.nodes[r+1]?.block??e.exit,s=(e,r=o,i=n,a=`next`)=>{let s=t.children.get(e);return this.link(s,r,i,a),s},c=(e,n)=>{let r=t.children.get(e);return this.link(r,n,{yieldTo:r.exit}),r};switch(t.effects.mayThrow&&i.kind!==`assert`&&this.edge(a,this.throwExit,`throw`),i.kind){case`if`:this.edge(a,s(`yes`).entry,`true`),this.edge(a,t.children.has(`no`)?s(`no`).entry:o,`false`);break;case`match`:i.arms.forEach((e,t)=>this.edge(a,s(`arm${t}`).entry,`arm`,{arm:t})),i.otherwise&&this.edge(a,s(`otherwise`).entry,`default`);break;case`while`:{let e=c(`test`,null),t={...n,breakTo:o,continueTo:e.entry},r=s(`body`,e.entry,t,`backedge`);this.edge(a,e.entry,`next`),this.edge(e.exit,r.entry,`true`),this.edge(e.exit,o,`false`);break}case`loop`:{let e=t.children.get(`body`);s(`body`,e.entry,{...n,breakTo:o,continueTo:e.entry},`backedge`),this.edge(a,e.entry,`next`);break}case`select`:case`and`:case`or`:{let n=this.block(e.id,`join`,t.position);if(t.definitionBlock=n,this.edge(n,o,`next`),i.kind===`select`)this.edge(a,c(`yes`,n).entry,`true`),this.edge(a,c(`no`,n).entry,`false`);else{let e=c(`right`,n);this.edge(a,e.entry,i.kind===`and`?`true`:`false`),this.edge(a,n,i.kind===`and`?`false`:`true`,{value:i.left})}break}case`assert`:{let n=this.block(e.id,`throw`,t.position);t.failureBlock=n,this.edge(a,o,`true`),this.edge(n,this.throwExit,`throw`),this.edge(a,i.message?c(`message`,n).entry:n,`false`);break}case`break`:if(n.breakTo===void 0)throw TypeError(`Break has no loop target`);this.edge(a,n.breakTo,`break`);break;case`continue`:if(n.continueTo===void 0)throw TypeError(`Continue has no loop target`);this.edge(a,n.continueTo,`continue`);break;case`yield`:if(n.yieldTo===void 0)throw TypeError(`Yield has no value-region target`);this.edge(a,n.yieldTo,`yield`,{value:i.value});break;case`return`:case`returnValue`:this.edge(a,this.root.exit,`return`);break;case`redirect`:this.edge(a,this.redirectExit,`redirect`);break;case`stop`:this.edge(a,this.stopExit,`stop`);break;case`wait`:case`elapse`:case`receive`:case`waitUntil`:case`call`:case`callValue`:{let n=this.block(e.id,`resume`,t.position);t.resumeBlock=n;let r=i.kind===`call`||i.kind===`callValue`;if(this.edge(a,n,`suspend`),r){let r=this.block(e.id,`join`,t.position);t.completionBlock=r,t.definitionBlock=r,this.edge(a,r,`next`),this.edge(n,n,`suspend`),this.edge(n,r,`resume`),this.edge(r,o,`next`);for(let e of[a,n])this.edge(e,this.redirectExit,`redirect`),this.edge(e,this.stopExit,`stop`);this.edge(n,this.throwExit,`throw`)}else i.kind===`receive`&&(t.definitionBlock=n),this.edge(n,i.kind===`waitUntil`?this.root.exit:o,`resume`),i.kind===`elapse`&&this.edge(a,o,`next`);break}default:this.edge(a,o,`next`)}})}analyze(){let e=/* @__PURE__ */ new Map;for(let t of this.nodes)`result`in t.operation&&e.set(t.operation.result,t.operation.type);let t=/* @__PURE__ */ new Map;if(this.optimize){for(let e of this.nodes){if(!(`result`in e.operation))continue;let n=Ct(e.operation,t);n&&(t.set(e.operation.result,n.value),e.operation.kind!==`constant`&&this.folded.set(e.position,n.value))}let n=/* @__PURE__ */ new Map;for(let e of this.nodes)`result`in e.operation&&this.folded.has(e.position)&&n.set(e.operation.result,this.folded.get(e.position));let r=new Map(this.nodes.flatMap(e=>`result`in e.operation?[[e.operation.result,e]]:[])),i=/* @__PURE__ */ new Set,a=[],o=e=>{i.has(e)||(i.add(e),a.push(e))};for(let e of this.nodes)this.folded.has(e.position)||e.inputs.forEach(o);for(let e=0;e<a.length;e++){let t=r.get(a[e]);t&&!this.folded.has(t.position)&&t.inputs.forEach(o)}for(let t of this.nodes)`result`in t.operation&&!i.has(t.operation.result)&&wt(t.operation,e,n)&&this.eliminated.add(t.position)}let n,r=()=>n??=this.complete(t);return{nodes:this.nodes,byOperation:this.byOperation,folded:this.folded,constants:t,eliminated:this.eliminated,optimizations:Object.freeze({enabled:this.optimize,foldedPositions:Object.freeze([...this.folded.keys()].filter(e=>!this.eliminated.has(e))),eliminatedPositions:Object.freeze([...this.eliminated])}),get graph(){return r().graph},get effects(){return r().effects},get resources(){return r().resources}}}complete(e){this.buildingGraph=!0,this.blocks=this.blockSpecs.map(e=>this.allocateBlock(e)),this.link(this.root,null,{});for(let e of this.nodes){if(this.eliminated.has(e.position))continue;let t=this.blocks[e.block],n=e.operation;this.folded.has(e.position)||(e.inputs.forEach(e=>t.uses.add(`value:${e}`)),bt(n).forEach(e=>t.uses.add(e)),n.kind===`localRead`&&t.uses.add(`local:${n.local}`)),`result`in n&&this.blocks[e.definitionBlock].definitions.add(`value:${n.result}`),(n.kind===`local`||n.kind===`localWrite`)&&t.definitions.add(`local:${n.local}`)}let t=/* @__PURE__ */ new Map;for(let e of this.nodes){let n=e.operation.kind===`while`?e.children.get(`test`):e.operation.kind===`assert`?e.children.get(`message`):void 0;if(!n)continue;let r=`region:${n.id}`;t.set(n.exit,r),this.blocks[e.failureBlock??n.exit].uses.add(r)}for(let e of this.edges)e.kind===`yield`&&t.has(e.to)&&this.blocks[e.from].definitions.add(t.get(e.to));let n=this.blocks.map(()=>[]),r=this.blocks.map(()=>[]);this.edges.forEach(e=>{n[e.from].push(e.to),r[e.to].push(e.from)});let i=this.blocks.map(e=>new Set([...e.uses].filter(e=>e.startsWith(`region:`)))),a=this.blocks.map(e=>new Set([...e.definitions].filter(e=>e.startsWith(`region:`))));for(let e of this.nodes){let t=e.operation;e.inputs.forEach(t=>i[e.block].add(`value:${t}`)),bt(t).forEach(t=>i[e.block].add(t)),t.kind===`localRead`&&i[e.block].add(`local:${t.local}`),`result`in t&&a[e.definitionBlock].add(`value:${t.result}`),(t.kind===`local`||t.kind===`localWrite`)&&a[e.block].add(`local:${t.local}`)}let o=(e,t)=>{let r=this.blocks.map(()=>/* @__PURE__ */ new Set),i=this.blocks.map(()=>/* @__PURE__ */ new Set),a=!0;for(;a;){a=!1;for(let o=this.blocks.length-1;o>=0;o--){let s=new Set(n[o].flatMap(e=>[...r[e]])),c=/* @__PURE__ */ new Set([...e[o],...[...s].filter(e=>!t[o].has(e))]);(s.size!==i[o].size||[...s].some(e=>!i[o].has(e))||c.size!==r[o].size||[...c].some(e=>!r[o].has(e)))&&(a=!0,i[o]=s,r[o]=c)}}return{input:r,output:i}},s=o(this.blocks.map(e=>e.uses),this.blocks.map(e=>e.definitions)),c=o(i,a);this.blocks.forEach((e,t)=>{e.liveIn=s.input[t],e.liveOut=s.output[t]});let l=/* @__PURE__ */ new Map;for(let e of this.edges)if(e.kind===`yield`&&e.value!==void 0){let t=l.get(e.to)??[];t.push(e.value),l.set(e.to,t)}let u=/* @__PURE__ */ new Map;for(let e of this.nodes)for(let t of e.inputs){let n=u.get(t)??[];n.push(e.position),u.set(t,n)}let d=this.nodes.flatMap(e=>{let t=e.operation;if(!(`result`in t))return[];let n=t.kind===`select`||t.kind===`and`||t.kind===`or`,r=n?[...e.children.values()].flatMap(e=>l.get(e.exit)??[]):[];return(t.kind===`and`||t.kind===`or`)&&r.unshift(t.left),[Object.freeze({result:t.result,type:vt(t.type),position:e.position,region:e.region,block:e.definitionBlock,form:n?`phi`:`operation`,inputs:Object.freeze(n?r:[...e.inputs]),users:Object.freeze(u.get(t.result)??[]),eliminated:this.eliminated.has(e.position),folded:this.folded.has(e.position)})]}),f=Object.freeze({entry:this.root.entry,normalExit:this.root.exit,regions:Object.freeze(this.regions.map(({id:e,parent:t,path:n,entry:r,exit:i})=>Object.freeze({id:e,parent:t,path:n,entry:r,exit:i}))),blocks:Object.freeze(this.blocks.map(e=>Object.freeze({...e,predecessors:Object.freeze([...new Set(r[e.id])]),successors:Object.freeze([...new Set(n[e.id])]),uses:Object.freeze([...e.uses]),definitions:Object.freeze([...e.definitions]),liveIn:Object.freeze([...e.liveIn]),liveOut:Object.freeze([...e.liveOut]),baselineLiveIn:Object.freeze([...c.input[e.id]]),baselineLiveOut:Object.freeze([...c.output[e.id]])}))),edges:Object.freeze([...this.edges]),values:Object.freeze(d),operations:Object.freeze(this.nodes.map(e=>Object.freeze({position:e.position,block:e.block,region:e.region,kind:e.operation.kind,path:e.path,...e.source?{source:e.source}:{},inputs:e.inputs,attributes:Tt(e.operation),regions:Object.freeze([...e.children].map(([e,t])=>Object.freeze({role:e,region:t.id}))),effects:e.effects,eliminated:this.eliminated.has(e.position),folded:this.folded.has(e.position)})))}),p=this.nodes.map(e=>e.effects),m=e=>Object.freeze([...new Set(p.flatMap(t=>t[e]))]),h=Object.freeze({reads:m(`reads`),writes:m(`writes`),calls:m(`calls`),operations:m(`operations`),maySuspend:p.some(e=>e.maySuspend),mayRedirect:p.some(e=>e.mayRedirect),mayStop:p.some(e=>e.mayStop),timeDependent:p.some(e=>e.timeDependent),random:p.some(e=>e.random)}),g=new Set([...h.reads,...h.writes].filter(e=>e!==`*`));for(let e of this.nodes){let t=e.operation;if(t.kind===`resistor`&&g.add(`pin:${xt(t.to)}`),t.kind===`refEqual`)for(let e of[t.left,t.right])g.add(`${e.kind===`parameter`?e.resource:e.kind}:${xt(e)}`);if(t.kind===`call`||t.kind===`callValue`)for(let e of t.args)e.kind!==`value`&&g.add(`${e.kind===`parameter`?e.resource:e.kind}:${xt(e)}`)}return{nodes:this.nodes,byOperation:this.byOperation,graph:f,folded:this.folded,constants:e,eliminated:this.eliminated,effects:h,resources:Object.freeze([...g]),optimizations:Object.freeze({enabled:this.optimize,foldedPositions:Object.freeze([...this.folded.keys()].filter(e=>!this.eliminated.has(e))),eliminatedPositions:Object.freeze([...this.eliminated])})}}};function Ot(e,t,n,r,i,a){let o=[],s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map;for(let t of e.nodes){let e=t.operation;`result`in e&&c.set(`value:${e.result}`,vt(e.type)),e.kind===`local`&&c.set(`local:${e.local}`,vt(e.type)),e.kind===`parameter`&&c.set(`argument:${e.index}`,vt(e.type));let n=e=>{e.kind===`parameter`&&e.resource&&c.set(`argument:${e.index}`,Object.freeze({kind:e.resource}))};`memory`in e&&n(e.memory),`pin`in e&&n(e.pin),e.kind===`resistor`&&n(e.to),e.kind===`refEqual`&&(n(e.left),n(e.right)),(e.kind===`call`||e.kind===`callValue`)&&e.args.forEach(e=>{e.kind!==`value`&&n(e)})}let l=(e,t,n,r,i,a=!0)=>{s.has(e)||(s.set(e,o.length),o.push(Object.freeze({id:o.length,key:e,kind:t,name:n,region:r,definition:i,materialized:a,...c.has(e)?{type:c.get(e)}:{}})))};for(let t of e.nodes){let n=t.operation;`result`in n&&l(`value:${n.result}`,`value`,`v${n.result}`,t.region,t.position,!e.eliminated.has(t.position)),n.kind===`local`&&l(`local:${n.local}`,`local`,`l${n.local}`,t.region,t.position)}for(let e of a)c.set(e.key,vt(e.type)),l(e.key,`temporary`,e.name,e.region,e.definition);for(let t of e.graph.blocks)for(let e of[...t.uses,...t.liveIn,...t.baselineLiveIn])e.startsWith(`argument:`)&&l(e,`argument`,`args[${e.slice(9)}]`,0,null),e===`reaction`&&l(e,`reaction`,`reaction`,0,null);let u=Object.freeze([...e.constants].flatMap(([e,t])=>{let n=s.get(`value:${e}`);return n===void 0?[]:[Object.freeze({slot:n,kind:`constant`,value:t})]})),d=new Set(u.map(e=>e.slot)),f=e=>Object.freeze(e.flatMap(e=>{let t=s.get(e);return t===void 0?[]:[t]}).sort((e,t)=>e-t)),p=e=>Object.freeze(f(e).filter(e=>o[e].materialized&&!d.has(e))),m=e=>Object.freeze(e.flatMap(e=>{let t=s.get(e);return t===void 0||!o[t].materialized?[]:[t]}).sort((e,t)=>e-t)),h=(e,t,n=e.block)=>Object.freeze({position:e.position,block:n,phase:t}),g=new Map(e.nodes.map(e=>[JSON.stringify(e.path),e])),_=r.split(`\n`),v=e=>Object.freeze({start:Object.freeze({line:e,column:(_[e-1]?.search(/\\S/)??0)+1}),end:Object.freeze({line:e,column:(_[e-1]?.length??0)+1})}),ee=Object.freeze({entries:Object.freeze(n.map(t=>{let n=g.get(JSON.stringify(t.path)),r=n.operation.kind===`redirect`||n.operation.kind===`stop`||n.operation.kind===`waitUntil`,i=r?[]:e.graph.blocks[n.resumeBlock].liveIn;return Object.freeze({id:t.id,kind:t.kind,suspended:h(n,`before`),baseline:h(n,t.delegated?`delegate`:`after`,n.resumeBlock??n.block),generated:v(t.line),continuation:Object.freeze({line:t.delegated?t.line:Math.min(t.line+1,_.length),column:t.delegated?t.column:(_[t.line]?.search(/\\S/)??0)+1}),liveSlots:m(i),delegated:t.delegated,terminal:r})}))}),y=[],b=(t,n,r,i=t.block)=>{y.push(Object.freeze({baseline:h(t,`before`,i),reason:n,generated:r,requiredSlots:f(e.graph.blocks[i].baselineLiveIn),captureSlots:p(e.graph.blocks[i].baselineLiveIn)}))};for(let n of e.nodes){let r=t.get(n.position);if(r){if(b(n,`deopt`,v(r.start.line)),n.effects.mayThrow&&!e.folded.has(n.position)){if(n.operation.kind===`assert`){let e=r.start.line;for(let t=r.start.line;t<=r.end.line;t++)_[t-1]?.includes(`host.assert(`)&&(e=t);b(n,`throw`,v(e),n.failureBlock)}else b(n,`throw`,v(r.start.line))}(n.operation.kind===`return`||n.operation.kind===`returnValue`)&&b(n,`return`,v(r.start.line))}}for(let t of ee.entries){let n=t.terminal?[]:e.graph.blocks[t.baseline.block].baselineLiveIn;y.push(Object.freeze({baseline:t.baseline,reason:t.kind===`redirect`?`redirect`:t.kind===`stop`?`stop`:`suspend`,generated:t.generated,requiredSlots:f(n),captureSlots:p(n)}))}for(let e of y)for(let t of e.requiredSlots)if(!o[t].materialized&&!d.has(t))throw Error(`Missing baseline value for frame slot ${t} at position ${e.baseline.position}`);let te=i.binding?Object.freeze({...i.binding,...i.binding.instruction?{instruction:Object.freeze({...i.binding.instruction})}:{}}):null;return{dependencies:Object.freeze({binding:te,reads:e.effects.reads,writes:e.effects.writes,calls:e.effects.calls,resources:e.resources,unresolvedCalls:e.effects.calls.length!==0}),sourceMap:Object.freeze({entries:Object.freeze(e.nodes.map(n=>Object.freeze({position:n.position,block:n.block,path:n.path,kind:n.operation.kind,...n.source?{source:n.source}:{},generated:t.get(n.position)??null,eliminated:e.eliminated.has(n.position),folded:e.folded.has(n.position)})))}),frameLayout:Object.freeze({storage:`native-generator`,serializable:!1,slots:Object.freeze(o),materializations:u}),resumeMap:ee,exitMap:Object.freeze(y)}}let kt={add:`+`,subtract:`-`,multiply:`*`,divide:`/`,remainder:`%`,power:`**`,lessThan:`<`,lessThanOrEqual:`<=`,greaterThan:`>`,greaterThanOrEqual:`>=`,concat:`+`,bitAnd:`&`,bitOr:`|`,bitXor:`^`,shiftLeft:`<<`,shiftRight:`>>`,shiftRightUnsigned:`>>>`},At=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`]),jt=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`]);function Mt(e,t={}){return new zt(Et(e,t,!1),t,!1).compileExecutable(e)}function Nt(e,t={}){return Pt(Mt(e.body,t))}function Pt(e){return t=>{let n=e(t),r=n.next();if(!r.done)throw n.return(void 0),TypeError(`Computation unexpectedly suspended with ${r.value.kind}`);return r.value}}function Ft(e,t){if(!Number.isSafeInteger(t)||t<0)throw TypeError(`IR identifiers must be nonnegative safe integers`);return`${e}${t}`}let W=e=>Ft(`v`,e),It=e=>Ft(`l`,e),Lt=e=>JSON.stringify(e);function Rt(e){return e.uri===void 0?Object.freeze({...e}):Object.freeze({...e,range:Object.freeze({start:Object.freeze({...e.range.start}),end:Object.freeze({...e.range.end})})})}var zt=class{analysis;options;captureMetadata;constructor(e,t,n=!0){this.analysis=e,this.options=t,this.captureMetadata=n}ranges=/* @__PURE__ */ new Map;temporaries=[];lines=[];constants=[];primitiveConstants=/* @__PURE__ */ new Map;negativeZero=Symbol(`negative zero`);positions=[];resume=[];types=/* @__PURE__ */ new Map;indent=0;serial=0;bindingFor;compileExecutable(e){return this.generate(e).execute}compile(e){let t=this.generate(e),n=this.analysis,r,i=()=>r??=Ot(n,this.ranges,this.resume,t.source,this.options,this.temporaries);return Object.freeze({...t,positions:Object.freeze(this.positions.slice()),resume:Object.freeze(this.resume.slice()),optimizations:n.optimizations,get effects(){return n.effects},get mir(){return n.graph},get dependencies(){return i().dependencies},get sourceMap(){return i().sourceMap},get frameLayout(){return i().frameLayout},get resumeMap(){return i().resumeMap},get exitMap(){return i().exitMap}})}generate(e){this.line(`function* compiledBody(host, args = [], reaction) {`),this.indent++,this.region(e,[]),this.indent--,this.line(`}`);let t=this.lines.join(`\n`),n=Object.freeze(this.constants.slice());return{execute:Function(`C`,`H`,`\"use strict\"; return (${t});`)(n,gt),source:t,constants:n}}line(e){this.lines.push(`${` `.repeat(this.indent)}${e}`)}block(e,t){this.line(`${e} {`),this.indent++,t(),this.indent--,this.line(`}`)}capture(e){let t=typeof e!=`object`||!e,n=Object.is(e,-0)?this.negativeZero:e,r=t?this.primitiveConstants.get(n):void 0;if(r!==void 0)return`C[${r}]`;let i=this.constants.push(e)-1;return t&&this.primitiveConstants.set(n,i),`C[${i}]`}ref(e){return e.kind===`parameter`?`args[${e.index}]`:this.capture(e.name)}boundRef(e,t){if(this.bindingFor&&t.kind!==`parameter`)return this.bindingFor(e,t.name)}boundName(e){return this.bindingFor?.(`state`,e)}argument(e){return e.kind===`value`?W(e.value):this.ref(e)}constant(e){switch(e.kind){case`number`:case`bool`:case`string`:return e.value;case`none`:return null;case`enum`:return tt(e.name,e.member);case`bytes`:return Object.freeze(Array.from(rt(e.value)));case`record`:return nt(e.fields.map(e=>[e.name,e.value]));default:return Bt(e)}}position(e,t){let n=Object.freeze({path:Object.freeze([...t]),kind:e.kind,line:this.lines.length+1,column:this.indent*2+1,...this.analysis.byOperation.get(e)?.source?{source:Rt(this.analysis.byOperation.get(e).source)}:{}});return this.positions.push(n),n}suspension(e,t=!1){e&&this.resume.push(Object.freeze({...e,line:this.lines.length+1,column:this.indent*2+1,id:this.resume.length,delegated:t}))}region(e,t,n){e.operations.forEach((e,r)=>{this.operation(e,[...t,`operations`,r],n)})}valueRegion(e,t,n){if(this.captureMetadata&&!t.startsWith(`v`)){let r=JSON.stringify([...n,`body`]),i=this.analysis.nodes.find(e=>[...e.children.values()].some(e=>JSON.stringify(e.path)===r)),a=[...i.children.values()].find(e=>JSON.stringify(e.path)===r);this.temporaries.push({key:`region:${a.id}`,name:t,region:i.region,definition:i.position,type:e.type})}let r=`valueRegion${this.serial++}`;this.block(`${r}:`,()=>this.region(e.body,[...n,`body`],{slot:t,label:r}))}equality(e,t){let n=this.types.get(e);return n?.kind===`optional`&&(n=n.inner),n&&(n.kind===`number`||n.kind===`string`||n.kind===`bool`)?`(${W(e)} === ${W(t)})`:`H.equalValues(${W(e)}, ${W(t)})`}operation(e,t,n){`result`in e&&this.types.set(e.result,e.type);let r=this.analysis.byOperation.get(e);if(this.analysis.eliminated.has(r.position))return;let i=this.captureMetadata?this.position(e,t):void 0;try{`result`in e&&this.analysis.folded.has(r.position)?this.line(`const ${W(e.result)} = ${this.capture(this.analysis.folded.get(r.position))};`):this.emitOperation(e,t,i,n)}finally{i&&this.ranges.set(r.position,Object.freeze({start:Object.freeze({line:i.line,column:i.column}),end:Object.freeze({line:this.lines.length,column:this.lines[this.lines.length-1].length+1})}))}}emitOperation(e,t,n,r){let i=t=>{if(!(`result`in e))throw TypeError(`Expected a result-producing operation`);this.line(`const ${W(e.result)} = ${t};`)},a=(e,n)=>this.region(e,[...t,n],r);switch(e.kind){case`constant`:{let t=this.capture(this.constant(e.constant));i(e.constant.kind===`bytes`?`H.createBytes(${t})`:t);break}case`read`:{let t=e.resource===`state`?this.boundName(e.name):void 0;i(t?`${t}.read()`:`host.read(${this.capture(e.resource)}, ${this.capture(e.name)})`);break}case`parameter`:i(`args[${e.index}]`);break;case`reactionValue`:i(`H.reactionValue(reaction, ${Lt(e.binding)})`);break;case`reactionCapture`:i(`H.reactionCapture(reaction, ${e.index})`);break;case`unary`:{let t={positive:`+`,negate:`-`,not:`!`,bitNot:`~`}[e.operator];if(!t)throw TypeError(`Unknown unary operator`);i(`(${t}${W(e.value)})`);break}case`binary`:if(e.operator===`equal`||e.operator===`notEqual`)i(`${e.operator===`notEqual`?`!`:``}${this.equality(e.left,e.right)}`);else{let t=kt[e.operator];if(!t)throw TypeError(`Unknown binary operator`);i(`(${W(e.left)} ${t} ${W(e.right)})`)}break;case`numeric`:if(!At.has(e.builtin))throw TypeError(`Unknown numeric builtin`);i(`${jt.has(e.builtin)?`Number`:`Math`}.${e.builtin}(${e.args.map(W).join(`, `)})`);break;case`record`:i(`H.createRecord([${e.fields.map(e=>`[${this.capture(e.name)}, ${W(e.value)}]`).join(`, `)}])`);break;case`field`:i(`${W(e.value)}[${this.capture(e.field)}]`);break;case`bytes`:i(`H.createBytes([${e.elements.map(W).join(`, `)}])`);break;case`length`:i(`${W(e.value)}.length`);break;case`index`:i(`H.readIndex(${W(e.value)}, ${W(e.index)})`);break;case`optional`:i(W(e.value));break;case`isNone`:i(`(${W(e.value)} === null)`);break;case`nonNull`:i(`H.nonNull(${W(e.value)})`);break;case`localRead`:i(It(e.local));break;case`local`:this.line(`let ${It(e.local)} = ${W(e.initial)};`);break;case`localWrite`:this.line(`${It(e.local)} = ${W(e.value)};`);break;case`write`:{let t=this.boundName(e.name);t?this.line(`${t}.write(${W(e.value)});`):this.line(`host.write(${this.capture(e.name)}, ${W(e.value)});`);break}case`memoryLength`:{let t=this.boundRef(`memory`,e.memory);i(t?`${t}.length()`:`host.memoryLength(${this.ref(e.memory)})`);break}case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:{let t=this.boundRef(`memory`,e.memory);i(t?`${t}.${e.kind}(${W(e.offset)})`:`host.load(${Lt(e.kind)}, ${this.ref(e.memory)}, ${W(e.offset)})`);break}case`store8`:case`store16le`:case`store16be`:case`store32le`:case`store32be`:{let t=this.boundRef(`memory`,e.memory);t?this.line(`${t}.${e.kind}(${W(e.offset)}, ${W(e.value)});`):this.line(`host.store(${Lt(e.kind)}, ${this.ref(e.memory)}, ${W(e.offset)}, ${W(e.value)});`);break}case`copyBytes`:{let t=this.boundRef(`memory`,e.memory);i(t?`${t}.copy(${W(e.offset)}, ${W(e.length)})`:`host.copyBytes(${this.ref(e.memory)}, ${W(e.offset)}, ${W(e.length)})`);break}case`readSample`:{let t=this.boundRef(`pin`,e.pin);i(t?`${t}.sample()`:`host.sample(${this.ref(e.pin)})`);break}case`resistor`:{let t=this.boundRef(`pin`,e.to);i(t?`${t}.resistor(${W(e.resistance)})`:`host.resistor(${this.ref(e.to)}, ${W(e.resistance)})`);break}case`combineIntents`:i(`H.combineIntents([${e.values.map(W).join(`, `)}])`);break;case`refEqual`:i(`(${this.ref(e.left)} === ${this.ref(e.right)})`);break;case`writeIntent`:{let t=this.boundRef(`pin`,e.pin);t?this.line(`${t}.intent(${W(e.value)});`):this.line(`host.intent(${this.ref(e.pin)}, ${W(e.value)});`);break}case`call`:case`callValue`:{this.suspension(n,!0);let t=`call${this.serial++}`;this.line(`const ${t} = yield* H.delegate(host.call(${this.capture(e.name)}, [${e.args.map(e=>this.argument(e)).join(`, `)}]));`),this.line(`if (${t} === H.terminated) return;`),e.kind===`callValue`&&i(t);break}case`send`:this.line(`host.send(${this.capture(e.channel)}, ${W(e.value)});`);break;case`notify`:this.line(`host.notify(${this.capture(e.notification)});`);break;case`receive`:this.suspension(n),i(`yield { kind: \"receive\", channel: ${this.capture(e.channel)} }`);break;case`now`:i(`host.now()`);break;case`random`:i(`host.random()`);break;case`if`:this.block(`if (H.checkBoolean(${W(e.condition)}))`,()=>a(e.yes,`yes`)),e.no&&this.block(`else`,()=>a(e.no,`no`));break;case`match`:e.arms.forEach((n,i)=>{let a=n.pattern,o=a.kind===`none`?null:a.kind===`enum`?tt(a.name,a.member):a.value;this.block(`${i?`else if`:`if`} (H.equalValues(${W(e.value)}, ${this.capture(o)}))`,()=>{this.region(n.body,[...t,`arms`,i,`body`],r)})}),e.otherwise&&this.block(e.arms.length?`else`:``,()=>a(e.otherwise,`otherwise`));break;case`while`:this.block(`while (true)`,()=>{let n=`condition${this.serial++}`;this.line(`let ${n};`),this.valueRegion(e.test,n,[...t,`test`]),this.line(`if (!H.checkBoolean(${n})) break;`),this.block(``,()=>a(e.body,`body`))});break;case`loop`:this.block(`while (true)`,()=>a(e.body,`body`));break;case`and`:case`or`:{let n=W(e.result);this.line(`let ${n} = H.checkBoolean(${W(e.left)});`),this.block(`if (${e.kind===`or`?`!`:``}${n})`,()=>{this.valueRegion(e.right,n,[...t,`right`]),this.line(`${n} = H.checkBoolean(${n});`)});break}case`select`:{let n=W(e.result);this.line(`let ${n};`),this.block(`if (H.checkBoolean(${W(e.condition)}))`,()=>this.valueRegion(e.yes,n,[...t,`yes`])),this.block(`else`,()=>this.valueRegion(e.no,n,[...t,`no`]));break}case`assert`:this.block(`if (!H.checkBoolean(${W(e.condition)}))`,()=>{if(e.message){let n=`message${this.serial++}`;this.line(`let ${n};`),this.valueRegion(e.message,n,[...t,`message`]),this.line(`host.assert(false, ${n});`)}else this.line(`host.assert(false, undefined);`)});break;case`wait`:case`elapse`:{let t=`duration${this.serial++}`;this.line(`const ${t} = H.checkDuration(${W(e.duration)});`),this.suspension(n);let r=`yield { kind: ${Lt(e.kind===`wait`?`ticks`:`elapse`)}, duration: ${t} };`;e.kind===`elapse`?this.line(`if (${t} !== 0) ${r}`):this.line(r);break}case`waitUntil`:this.suspension(n),this.line(`yield { kind: \"waitUntil\", predicate: ${this.capture(e.predicate)} };`),this.line(`return;`);break;case`redirect`:this.suspension(n),this.line(`yield { kind: \"redirect\", pc: H.checkPc(${W(e.target)}), delay: H.checkDuration(${W(e.delay)}) };`),this.line(`return;`);break;case`stop`:this.suspension(n),this.line(`yield { kind: \"stop\" };`),this.line(`return;`);break;case`return`:this.line(`return;`);break;case`returnValue`:this.line(`return ${W(e.value)};`);break;case`break`:this.line(`break;`);break;case`continue`:this.line(`continue;`);break;case`yield`:if(!r)throw TypeError(`Value-region yield is outside a value region`);this.line(`${r.slot} = ${W(e.value)};`),this.line(`break ${r.label};`);break;default:Bt(e)}}};function Bt(e){throw TypeError(`Unsupported IR operation: ${String(e.kind)}`)}let Vt={add:`+`,subtract:`-`,multiply:`*`,divide:`/`,remainder:`%`,power:`**`,lessThan:`<`,lessThanOrEqual:`<=`,greaterThan:`>`,greaterThanOrEqual:`>=`,equal:`===`,notEqual:`!==`,bitAnd:`&`,bitOr:`|`,bitXor:`^`,shiftLeft:`<<`,shiftRight:`>>`,shiftRightUnsigned:`>>>`},Ht={positive:`+`,negate:`-`,not:`!`,bitNot:`~`},Ut=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`]),Wt=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`]),Gt=/* @__PURE__ */ new Set([`field`,`optional`,`nonNull`,`readSample`,`resistor`,`combineIntents`]),Kt=/* @__PURE__ */ new Set([`send`,`notify`,`readSample`,`writeIntent`,`resistor`,`random`,`assert`]);function qt(e,t){if(typeof t!=`number`||!Number.isSafeInteger(t))throw TypeError(`offset must be a safe integer`);if(t<0)throw RangeError(`offset must be nonnegative`);if(t>=e.length)throw RangeError(`Memory range is out of bounds`);return t}function Jt(e){if(typeof e!=`number`||!Number.isSafeInteger(e))throw TypeError(`stored value must be a safe integer`);return e}let Yt=/* @__PURE__ */ new WeakMap;function Xt(e){let t=Yt.get(e);return t===void 0&&(t=new DataView(e.buffer,e.byteOffset,e.byteLength),Yt.set(e,t)),t}function Zt(e,t,n){if(typeof t!=`number`||!Number.isSafeInteger(t))throw TypeError(`offset must be a safe integer`);if(t<0)throw RangeError(`offset must be nonnegative`);if(t>e.length||n>e.length-t)throw RangeError(`Memory range is out of bounds`);return t}function Qt(e,t,n){return Xt(e).getUint16(Zt(e,t,2),n)}function $t(e,t,n){return Xt(e).getUint32(Zt(e,t,4),n)}function en(e,t,n,r){let i=Zt(e,t,2);Xt(e).setUint16(i,Jt(n),r)}function tn(e,t,n,r){let i=Zt(e,t,4);Xt(e).setUint32(i,Jt(n),r)}let nn=Object.freeze({checkBoolean:lt,checkPc:dt,combineIntents:it,equalValues:at,nonNull:ct,offset:qt,byte:Jt,load16:Qt,load32:$t,store16:en,store32:tn}),G=Symbol(`unsupported direct instruction`);function rn(e,t){if(!fn(t.pc.index)||t.states.get(t.pc.name)!==t.pc.index)return;let n=[],r=e=>`C[${n.push(e)-1}]`,i=[],a=/* @__PURE__ */ new Set;for(let n of e)if(Number.isFinite(n.pc)&&!a.has(n.pc)&&(a.add(n.pc),Number.isFinite(n.nextPc)))try{i.push(new pn(t,r).compile(n))}catch(e){if(e!==G)throw e}if(!i.length)return;let o=Math.max(...i.map(e=>e.slots.length)),s=Array.from({length:o},(e,t)=>`v${t}`),c=t,l=fn(c.shardSlotLimit)?c.shardSlotLimit:2048,u=c.split===!0&&i.reduce((e,t)=>e+t.slots.length,0)>l,d=fn(c.shardSize)&&c.shardSize>0?c.shardSize:48,f=u?sn(i,t,d):on(i,t,s),p=Function(`C`,`H`,u?`\"use strict\";\\n${f.join(`\n`)}\\nreturn run;`:`\"use strict\"; return (${f.join(`\n`)});`),m=e=>Object.freeze([...new Set(i.flatMap(t=>[...t[e]]))]);return Object.freeze({run:p(Object.freeze(n),nn),localCount:o,readStates:m(`readStates`),writeStates:m(`writeStates`),readMemories:m(`readMemories`),writeMemories:m(`writeMemories`)})}let an=e=>[`const S = F.states, M = F.memories, L = F.locals, SD = F.stateDirty, MD = F.memoryDirty;`,...e.length?[`let ${e.join(`,`)};`]:[]];function on(e,t,n){let r=[`function run(F, deadline) {`,`const S = F.states, M = F.memories, L = F.locals, SD = F.stateDirty, MD = F.memoryDirty;`,...n.length?[`let ${n.join(`,`)};`]:[],`while (true) {`,`if (F.time >= deadline) return \"deadline\";`,`if (F.resume !== 0) {`,`if (F.due >= deadline) { F.time = deadline; return \"deadline\"; }`,`F.time = Math.max(F.time, F.due);`,`switch (F.resume) {`];return e.forEach((e,t)=>{r.push(`case ${t+1}: {`),e.slots.forEach((e,t)=>r.push(`${e} = L[${t}];`)),r.push(`F.resume = 0;`,...e.suffix,ln(e.stop),`}`)}),r.push(`default: throw new TypeError(\"Unknown direct JIT continuation\");`,`}`,`}`,`if (F.stopAfterInstruction) return \"invalidated\";`,`switch (H.checkPc(S[${t.pc.index}])) {`),e.forEach((e,n)=>{r.push(`case ${e.pc}: {`,`S[${t.pc.index}] = ${e.nextPc};`,dn(`SD`,t.pc.index),...e.prefix),e.duration!==void 0&&r.push(...cn(e,n)),r.push(...e.suffix,ln(e.stop),`}`)}),r.push(`default: return \"fallback\";`,`}`,`}`,`}`),r}function sn(e,t,n){let r=[...e].sort((e,t)=>e.pcValue-t.pcValue),i=[],a=[],o=0;for(let e of r){let t=e.slots.length;a.length&&(a.length>=n||o+t>1536)&&(i.push(a),a=[],o=0),a.push(e),o+=t}a.length&&i.push(a);let s=0,c=i.map(e=>{let t={start:s,entries:e,maxSlots:Math.max(...e.map(e=>e.slots.length)),lastPc:e[e.length-1].pc,lastResume:s+e.length,resumable:e.some(e=>e.duration!==void 0)};return s+=e.length,t}),l=e=>Array.from({length:e},(e,t)=>`v${t}`),u=[];c.forEach((e,n)=>{u.push(`function stepShard${n}(F, deadline, pc) {`,...an(l(e.maxSlots)),`switch (pc) {`),e.entries.forEach((n,r)=>{u.push(`case ${n.pc}: {`,`S[${t.pc.index}] = ${n.nextPc};`,dn(`SD`,t.pc.index),...n.prefix,...cn(n,e.start+r),...n.suffix,un(n.stop),`}`)}),u.push(`default: return \"fallback\";`,`}`,`}`)}),c.forEach((e,t)=>{e.resumable&&(u.push(`function resumeShard${t}(F, resume) {`,...an(l(e.maxSlots)),`switch (resume) {`),e.entries.forEach((t,n)=>{t.duration!==void 0&&(u.push(`case ${e.start+n+1}: {`),t.slots.forEach((e,t)=>u.push(`${e} = L[${t}];`)),u.push(`F.resume = 0;`,...t.suffix,un(t.stop),`}`))}),u.push(`default: throw new TypeError(\"Unknown direct JIT continuation\");`,`}`,`}`))}),u.push(`function run(F, deadline) {`,`const S = F.states;`,`while (true) {`,`if (F.time >= deadline) return \"deadline\";`,`let status;`,`if (F.resume !== 0) {`,`if (F.due >= deadline) { F.time = deadline; return \"deadline\"; }`,`F.time = Math.max(F.time, F.due);`,`const resume = F.resume;`);let d=c.map((e,t)=>({shard:e,shardIndex:t})).filter(({shard:e})=>e.resumable);return d.length?(d.forEach(({shard:e,shardIndex:t},n)=>{let r=n?`else if`:`if`;u.push(`${r} (resume <= ${e.lastResume}) status = resumeShard${t}(F, resume);`)}),u.push(`else throw new TypeError(\"Unknown direct JIT continuation\");`)):u.push(`throw new TypeError(\"Unknown direct JIT continuation\");`),u.push(`} else {`,`if (F.stopAfterInstruction) return \"invalidated\";`,`const pc = H.checkPc(S[${t.pc.index}]);`),c.forEach((e,t)=>{let n=t?`else if`:`if`;u.push(`${n} (pc <= ${e.lastPc}) status = stepShard${t}(F, deadline, pc);`)}),u.push(`else return \"fallback\";`,`}`,`if (status !== \"next\") return status;`,`}`,`}`),u}function cn(e,t){return e.duration===void 0?[]:[`F.due = F.time + ${e.duration};`,`if (F.due > 7200000000000000) throw new RangeError(\"Time out of range\");`,`if (F.due >= deadline) {`,...e.slots.map((e,t)=>`L[${t}] = ${e};`),`F.resume = ${t+1};`,`F.time = deadline;`,`return \"deadline\";`,`}`,`F.time = F.due;`]}function ln(e){return e?`return \"stopped\";`:`if (F.stopAfterInstruction) return \"invalidated\"; continue;`}function un(e){return e?`return \"stopped\";`:`if (F.stopAfterInstruction) return \"invalidated\"; return \"next\";`}function dn(e,t){return`${e}[${t>>>5}] |= ${1<<(t&31)};`}function fn(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}var pn=class{binding;capture;readStates=/* @__PURE__ */ new Set;writeStates=/* @__PURE__ */ new Set;readMemories=/* @__PURE__ */ new Set;writeMemories=/* @__PURE__ */ new Set;slots=[];prefix=[];suffix=[];pcValue=0;pc=``;nextPc=``;duration;immediate=!1;stop=!1;values=/* @__PURE__ */ new Map;locals=/* @__PURE__ */ new Map;literals=/* @__PURE__ */ new Map;labels=0;constructor(e,t){this.binding=e,this.capture=t}compile(e){this.pcValue=e.pc,this.pc=this.literal(e.pc),this.nextPc=this.literal(e.nextPc),this.readStates.add(this.binding.pc.name),this.state(this.binding.pc.name,!0);let t=this.prefix,n=!1;for(let r of e.body.operations){if(n)throw G;if(r.kind===`elapse`){if(this.terminated)throw G;this.terminate(this.delay(r.duration)),t=this.suffix}else if(r.kind===`redirect`){if(this.terminated)throw G;let e=this.delay(r.delay);t.push(`S[${this.binding.pc.index}] = H.checkPc(${this.value(r.target)});`,dn(`SD`,this.binding.pc.index)),this.terminate(e),t=this.suffix,n=!0}else r.kind===`stop`?(this.stop=!0,n=!0):this.operation(r,t)}if(!this.terminated&&!this.stop)throw G;return this}get terminated(){return this.duration!==void 0||this.immediate}terminate(e){e.zero?this.immediate=!0:this.duration=e.value}delay(e){let t=this.literals.get(e);if(typeof t!=`number`)throw G;try{ut(t)}catch{throw G}return{value:this.literal(t),zero:t===0}}literal(e){return typeof e==`boolean`?e?`true`:`false`:typeof e==`number`&&Number.isSafeInteger(e)?Object.is(e,-0)?`-0`:String(e):typeof e==`string`?JSON.stringify(e).replace(/\\u2028/g,`\\\\u2028`).replace(/\\u2029/g,`\\\\u2029`):this.capture(e)}value(e){let t=this.values.get(e);if(!t)throw G;return t}slot(){let e=`v${this.slots.length}`;return this.slots.push(e),e}state(e,t){let n=this.binding.states.get(e);if(!fn(n)||t&&this.binding.blockedStates?.has(e))throw G;return(t?this.writeStates:this.readStates).add(e),n}memory(e){if(e.memory.kind!==`memory`)throw G;let t=e.memory.name,n=this.binding.memories.get(t),r=e.kind.startsWith(`store`);if(!fn(n)||r&&this.binding.blockedMemories?.has(t))throw G;return(r?this.writeMemories:this.readMemories).add(t),n}expression(e){if(e.type.kind!==`number`&&e.type.kind!==`bool`)return;let{operations:t}=e.body,n=t[t.length-1];if(n?.kind!==`yield`)return;let r=/* @__PURE__ */ new Map;for(let e=0;e<t.length-1;e++)if(!this.fold(t[e],r))return;return r.get(n.value)??this.values.get(n.value)}fold(e,t){if(!(`result`in e)||!(`type`in e)||e.type.kind!==`number`&&e.type.kind!==`bool`)return!1;let n=e=>t.get(e)??this.values.get(e);switch(e.kind){case`constant`:return e.constant.kind!==`number`&&e.constant.kind!==`bool`?!1:(this.literals.set(e.result,e.constant.value),t.set(e.result,this.literal(e.constant.value)),!0);case`read`:return e.resource===`state`&&(t.set(e.result,`S[${this.state(e.name,!1)}]`),!0);case`localRead`:{let n=this.locals.get(e.local);return n?(t.set(e.result,n),!0):!1}case`unary`:{let r=Ht[e.operator],i=n(e.value);return!r||i===void 0?!1:(t.set(e.result,`(${r}${i})`),!0)}case`binary`:{let r=Vt[e.operator],i=n(e.left),a=n(e.right);return!r||i===void 0||a===void 0?!1:(t.set(e.result,`(${i} ${r} ${a})`),!0)}case`numeric`:{if(!Ut.has(e.builtin))return!1;let r=[];for(let t of e.args){let e=n(t);if(e===void 0)return!1;r.push(e)}let i=Wt.has(e.builtin)?`Number`:`Math`;return t.set(e.result,`${i}.${e.builtin}(${r.join(`,`)})`),!0}default:return!1}}requireHost(){if(this.binding.host!==!0)throw G}message(e){let t=e.body.operations,n=t[0],r=t[1];if(t.length!==2||n?.kind!==`constant`||n.constant.kind!==`string`||r?.kind!==`yield`||r.value!==n.result)throw G;return this.literal(n.constant.value)}pattern(e){switch(e.kind){case`none`:return`null`;case`number`:case`bool`:return this.literal(e.value);case`string`:return this.literal(e.value);case`enum`:return this.literal(e.member)}}region(e,t,n){for(let r of e.operations)if(r.kind===`yield`){if(!n)throw G;t.push(`${n.slot} = ${this.value(r.value)}; break ${n.label};`)}else this.operation(r,t,n)}operation(e,t,n){let r;if(Kt.has(e.kind)&&this.requireHost(),`result`in e){let t=e.type.kind;if(t!==`number`&&t!==`bool`&&!(Gt.has(e.kind)||e.kind===`constant`&&(t===`string`||t===`enum`)))throw G;r=this.slot(),this.values.set(e.result,r)}let i=e=>{t.push(`${r} = ${e};`)};switch(e.kind){case`constant`:{let{constant:t}=e;if(t.kind===`number`||t.kind===`bool`)this.literals.set(e.result,t.value),i(this.literal(t.value));else if(t.kind===`string`)i(this.literal(t.value));else if(t.kind===`enum`)i(this.literal(t.member));else throw G;break}case`read`:if(e.resource!==`state`)throw G;i(`S[${this.state(e.name,!1)}]`);break;case`write`:{let n=this.state(e.name,!0);t.push(`S[${n}] = ${this.value(e.value)};`,dn(`SD`,n));break}case`unary`:{let t=Ht[e.operator];if(!t)throw G;i(`(${t}${this.value(e.value)})`);break}case`binary`:{let t=Vt[e.operator];if(!t)throw G;i(`(${this.value(e.left)} ${t} ${this.value(e.right)})`);break}case`numeric`:if(!Ut.has(e.builtin))throw G;i(`${Wt.has(e.builtin)?`Number`:`Math`}.${e.builtin}(${e.args.map(e=>this.value(e)).join(`,`)})`);break;case`send`:t.push(`F.host.send(${this.capture(e.channel)}, ${this.value(e.value)});`);break;case`notify`:t.push(`F.host.notify(${this.capture(e.notification)});`);break;case`readSample`:if(e.pin.kind!==`pin`)throw G;i(`F.host.sample(${this.capture(e.pin.name)})`);break;case`writeIntent`:if(e.pin.kind!==`pin`)throw G;t.push(`F.host.intent(${this.capture(e.pin.name)}, ${this.value(e.value)});`);break;case`resistor`:if(e.to.kind!==`pin`)throw G;i(`F.host.resistor(${this.capture(e.to.name)}, ${this.value(e.resistance)})`);break;case`combineIntents`:i(`H.combineIntents([${e.values.map(e=>this.value(e)).join(`,`)}])`);break;case`field`:i(`${this.value(e.value)}[${this.capture(e.field)}]`);break;case`refEqual`:if(e.left.kind===`parameter`||e.right.kind===`parameter`)throw G;i(e.left.name===e.right.name?`true`:`false`);break;case`length`:i(`${this.value(e.value)}.length`);break;case`optional`:i(this.value(e.value));break;case`isNone`:i(`(${this.value(e.value)} === null)`);break;case`nonNull`:i(`H.nonNull(${this.value(e.value)})`);break;case`now`:i(`F.time`);break;case`random`:i(`F.host.random()`);break;case`assert`:{let n=e.message===void 0?`undefined`:this.message(e.message);t.push(`if (!H.checkBoolean(${this.value(e.condition)})) F.host.assert(false, ${n});`);break}case`local`:{if(e.type.kind!==`number`&&e.type.kind!==`bool`)throw G;let n=this.slot();this.locals.set(e.local,n),t.push(`${n} = ${this.value(e.initial)};`);break}case`localRead`:{let t=this.locals.get(e.local);if(!t)throw G;i(t);break}case`localWrite`:{let n=this.locals.get(e.local);if(!n)throw G;t.push(`${n} = ${this.value(e.value)};`);break}case`load8`:{let t=`M[${this.memory(e)}]`;i(`${t}[H.offset(${t},${this.value(e.offset)})]`);break}case`store8`:{let n=this.memory(e),r=`M[${n}]`;t.push(`${r}[H.offset(${r},${this.value(e.offset)})] = H.byte(${this.value(e.value)});`,dn(`MD`,n));break}case`load16le`:case`load16be`:{let t=`M[${this.memory(e)}]`,n=e.kind.endsWith(`le`)?`true`:`false`;i(`H.load16(${t},${this.value(e.offset)},${n})`);break}case`load32le`:case`load32be`:{let t=`M[${this.memory(e)}]`,n=e.kind.endsWith(`le`)?`true`:`false`;i(`H.load32(${t},${this.value(e.offset)},${n})`);break}case`store16le`:case`store16be`:case`store32le`:case`store32be`:{let n=this.memory(e),r=`M[${n}]`,i=e.kind.startsWith(`store16`)?`store16`:`store32`,a=e.kind.endsWith(`le`)?`true`:`false`;t.push(`H.${i}(${r},${this.value(e.offset)},${this.value(e.value)},${a});`,dn(`MD`,n));break}case`and`:case`or`:{if(e.right.body.operations.at(-1)?.kind!==`yield`)throw G;let n=`${e.kind}${this.labels++}`;t.push(`${r} = H.checkBoolean(${this.value(e.left)});`,`${e.kind===`or`?`if (!`:`if (`}${r}) {`,`${n}: {`),this.region(e.right.body,t,{slot:r,label:n}),t.push(`}`,`${r} = H.checkBoolean(${r});`,`}`);break}case`match`:{let r=this.value(e.value);if(!e.arms.length&&!e.otherwise||!e.otherwise&&n)throw G;e.arms.forEach((e,i)=>{let a=this.pattern(e.pattern);t.push(`${i?`} else if`:`if`} (H.equalValues(${r}, ${a})) {`),this.region(e.body,t,n)}),e.otherwise&&(t.push(e.arms.length?`} else {`:`{`),this.region(e.otherwise,t,n)),t.push(`}`);break}case`if`:t.push(`if (H.checkBoolean(${this.value(e.condition)})) {`),this.region(e.yes,t,n),e.no&&(t.push(`} else {`),this.region(e.no,t,n)),t.push(`}`);break;case`select`:{let n=this.value(e.condition),i=this.expression(e.yes),a=i===void 0?void 0:this.expression(e.no);if(i!==void 0&&a!==void 0){t.push(`${r} = H.checkBoolean(${n}) ? ${i} : ${a};`);break}let o=`select${this.labels++}`;t.push(`${o}: {`,`if (H.checkBoolean(${n})) {`),this.region(e.yes.body,t,{slot:r,label:o}),t.push(`} else {`),this.region(e.no.body,t,{slot:r,label:o}),t.push(`}`,`}`);break}default:throw G}}};let mn=Symbol(`unsupported resumable body`),hn=/^(\\s*)(?:const|let) (v\\d+|l\\d+)( = |;)/;function gn(e,t={}){if(Cn(e))try{return new _n(Et(e,t,!1),t,!1).compileMachine(e)}catch{return}}var _n=class extends zt{blocks=[];slots=/* @__PURE__ */ new Map;resources=[];resourceIndex=/* @__PURE__ */ new Map;current;graph;constructor(e,t,n){super(e,t,n),t.bindResources&&(this.bindingFor=(e,t)=>this.bindResource(e,t))}bindResource(e,t){let n=`${e}\\0${t}`,r=this.resourceIndex.get(n);return r===void 0&&(r=this.resources.push([e,t])-1,this.resourceIndex.set(n,r)),`F.resources[${r}]`}compileMachine(e){this.graph=this.analysis.graph;for(let e of this.analysis.nodes)`result`in e.operation&&this.types.set(e.operation.result,e.operation.type);let t=this.reserve(),n=this.reserve();this.blocks[n].term={kind:`done`};let r=this.buildRegion(e,n,{},[]);this.blocks[t].term={kind:`jump`,to:r};let i=[...this.locals()].sort(),a=[`function resumableBody(host, args = [], reaction, F) {`,...i.length?[`let ${i.join(`, `)};`]:[],...this.resources.length?[`if (F.resources === void 0) F.resources = host.bind(${this.capture(Object.freeze(this.resources.slice()))});`]:[],`for (;;) {`,`switch (F.pc) {`];for(let e of this.blocks){a.push(`case ${e.id}: {`);for(let t of e.code)a.push(t);a.push(...yn(e)),a.push(`}`)}a.push(`default: throw new TypeError(\"Unknown resumable continuation\");`,`}`,`}`,`}`);let o=a.join(`\n`),s=Object.freeze(this.constants.slice()),c=Function(`C`,`H`,`\"use strict\"; return (${o});`);return Object.freeze({run:c(s,gt),slotCount:this.slots.size,start:0})}locals(){let e=/* @__PURE__ */ new Set;for(let t of this.analysis.nodes){let n=t.operation;`result`in n&&e.add(W(n.result)),(n.kind===`local`||n.kind===`localRead`||n.kind===`localWrite`)&&e.add(`l${n.local}`)}return e}buildRegion(e,t,n,r,i){this.current=void 0;let a=t,o=[];for(let t=e.operations.length-1;t>=0;t--){let i=e.operations[t],s=[...r,`operations`,t];Sn(i)?o.unshift(this.emitStraight(i,s)):(a=this.flush(o,a),o=[],a=this.buildControl(i,a,n,s))}if(i!==void 0){if(o.length){let e=this.blocks[i];for(let t of o)e.code.push(...t);e.term={kind:`jump`,to:a}}else i!==a&&(this.blocks[i].term={kind:`jump`,to:a});return i}return this.flush(o,a)}emitStraight(e,t){let n=this.lines,r=this.indent;this.lines=[],this.indent=0;let i;try{super.operation(e,t),i=this.lines}finally{this.lines=n,this.indent=r}return vn(i)}flush(e,t){if(!e.length)return t;let n=this.open();for(let t of e)n.code.push(...t);return this.current=void 0,n.term={kind:`jump`,to:t},n.id}buildControl(e,t,n,r){switch(e.kind){case`if`:{let i=this.reserve(),a=e.no?this.reserve():t,o=this.open();return o.term={kind:`branch`,test:`H.checkBoolean(${W(e.condition)})`,yes:i,no:a},this.current=void 0,this.buildRegion(e.yes,t,n,[...r,`yes`],i),e.no&&this.buildRegion(e.no,t,n,[...r,`no`],a),o.id}case`match`:{let i=e.otherwise?this.reserve():t,a=i;for(let i=e.arms.length-1;i>=0;i--){let o=e.arms[i],s=this.reserve();this.buildRegion(o.body,t,n,[...r,`arms`,i,`body`],s);let c=o.pattern,l=c.kind===`none`?null:c.kind===`enum`?tt(c.name,c.member):c.value,u=this.open();u.term={kind:`branch`,test:`H.equalValues(${W(e.value)}, ${this.capture(l)})`,yes:s,no:a},this.current=void 0,a=u.id}return e.otherwise&&this.buildRegion(e.otherwise,t,n,[...r,`otherwise`],i),a}case`while`:{let n=this.reserve(),i=this.buildRegion(e.body,n,{breakTo:t,continueTo:n},[...r,`body`]);return this.fillTest(n,e.test,[...r,`test`],e=>({kind:`branch`,test:`H.checkBoolean(${e})`,yes:i,no:t})),n}case`loop`:{let n=this.reserve(),i=this.buildRegion(e.body,n,{breakTo:t,continueTo:n},[...r,`body`]);return this.blocks[n].term={kind:`jump`,to:i},n}case`break`:case`continue`:{let t=e.kind===`break`?n.breakTo:n.continueTo;if(t===void 0)throw mn;let r=this.open();return r.term={kind:`jump`,to:t},this.current=void 0,r.id}case`return`:case`returnValue`:{let e=this.open();return e.term={kind:`done`},this.current=void 0,e.id}case`wait`:{let n=`duration${this.serial++}`,r=this.open();r.code.push(`const ${n} = H.checkDuration(${W(e.duration)});`);let i=this.resumeBlock(e);return r.code.push(...this.save(e),`F.pc = ${i};`,`F.kind = 1;`,`F.duration = ${n};`),r.term={kind:`suspend`},this.current=void 0,this.link(i,t),r.id}case`receive`:{let n=this.open(),r=this.resumeBlock(e);return n.code.push(...this.save(e),`F.pc = ${r};`,`F.kind = 2;`,`F.channel = ${this.capture(e.channel)};`),n.term={kind:`suspend`},this.current=void 0,this.link(r,t),n.id}default:throw mn}}fillTest(e,t,n,r){let i=this.blocks[e],a=`condition${this.serial++}`,o=this.lines,s=this.indent;this.lines=i.code,this.indent=0;try{this.line(`let ${a};`),this.valueRegion(t,a,n)}finally{this.lines=o,this.indent=s}this.current=void 0,i.term=r(a)}resumeBlock(e){let t=this.reserve(),n=this.blocks[t],r=this.analysis.byOperation.get(e),i=`result`in e?W(e.result):void 0;for(let e of this.liveIn(r))e!==i&&n.code.push(`${this.slotName(e)} = F.slots[${this.slot(e)}];`);return i&&n.code.push(`${i} = F.value;`),t}link(e,t){let n=this.blocks[e];n.code.push(`F.pc = ${t};`),n.term={kind:`jump`,to:t}}save(e){let t=this.analysis.byOperation.get(e),n=`result`in e?W(e.result):void 0,r=[];for(let e of this.liveIn(t))e!==n&&r.push(`F.slots[${this.slot(e)}] = ${this.slotName(e)};`);return r}liveIn(e){if(e.resumeBlock===void 0)throw mn;return(this.graph??=this.analysis.graph).blocks[e.resumeBlock].liveIn.filter(e=>e.startsWith(`value:`)||e.startsWith(`local:`))}slotName(e){let t=e.indexOf(`:`),n=Number(e.slice(t+1));if(!Number.isSafeInteger(n)||n<0)throw mn;return e.startsWith(`value:`)?W(n):It(n)}slot(e){let t=this.slots.get(e);if(t!==void 0)return t;let n=this.slots.size;return this.slots.set(e,n),n}reserve(){let e={id:this.blocks.length,code:[]};return this.blocks.push(e),e.id}open(){if(this.current)return this.current;let e={id:this.blocks.length,code:[]};return this.blocks.push(e),this.current=e,e}};function vn(e){let t=[];for(let n of e){let e=hn.exec(n);e?e[3]!==`;`&&t.push(`${e[1]}${e[2]}${e[3]}${n.slice(e[0].length)}`):t.push(n)}return t}function yn(e){let t=e.term;if(!t)throw mn;switch(t.kind){case`jump`:return[`F.pc = ${t.to};`,`break;`];case`branch`:return[`if (${t.test}) F.pc = ${t.yes};`,`else F.pc = ${t.no};`,`break;`];case`suspend`:return[`return true;`];case`done`:return[`F.pc = 0;`,`return false;`];default:throw mn}}let bn=/* @__PURE__ */ new Set([`if`,`match`,`while`,`loop`,`break`,`continue`,`return`,`returnValue`,`wait`,`receive`]),xn=/* @__PURE__ */ new Set([`elapse`,`call`,`callValue`,`waitUntil`,`redirect`,`stop`,`yield`]);function Sn(e){return!bn.has(e.kind)&&!xn.has(e.kind)}function Cn(e){for(let t of e.operations)switch(t.kind){case`if`:if(!Cn(t.yes)||t.no&&!Cn(t.no))return!1;break;case`match`:for(let e of t.arms)if(!Cn(e.body))return!1;if(t.otherwise&&!Cn(t.otherwise))return!1;break;case`while`:if(!wn(t.test.body)||!Cn(t.body))return!1;break;case`loop`:if(!Cn(t.body))return!1;break;case`and`:case`or`:if(!wn(t.right.body))return!1;break;case`select`:if(!wn(t.yes.body)||!wn(t.no.body))return!1;break;case`assert`:if(t.message&&!wn(t.message.body))return!1}return!0}function wn(e){for(let t of e.operations)if(t.kind!==`yield`&&(bn.has(t.kind)||xn.has(t.kind)||!Cn({operations:[t]})))return!1;return!0}var Tn=class extends Error{code;instanceId;resource;network;networks;component;reason;constructor(e,t,n={}){super(t),this.name=`ElectricalError`,this.code=e,this.reason=t,this.instanceId=n.instanceId,this.resource=n.resource,this.network=n.network,this.networks=n.networks,this.component=n.component}};function En(e,t={}){if(!Number.isFinite(e)||e<.001||e>1e9)throw new Tn(`INVALID_ELECTRICAL_PARAMETER`,`Resistance must be finite and in [0.001, 1000000000] ohms.`,t)}let Dn=65536;function On(e){let t=0,n=/* @__PURE__ */ new Set;for(let r of e.blocks){t+=r.component.nodes.length+2*r.component.edges.length;let e=r.component.physical;if(e!==void 0&&!n.has(e)&&(n.add(e),t+=e.nodes.length+e.edges.length),t>Dn)break}return t}function kn(e,t,n){let r;for(let i=0;i<e.component.edges.length;i++){let a=e.component.edges[i],o=(n.get(a.pin)?.edges??t[a.pin])[a.index];(a.from!==o.from||a.to!==o.to||a.resistance!==o.resistance)&&(r??=e.component.edges.slice(),r[i]=o)}return r===void 0?e:{...e,component:{...e.component,edges:r}}}function An(e,t,n){let r;for(let i=0;i<e.blocks.length;i++){let a=e.blocks[i],o=kn(a,t,n);o!==a&&(r??=e.blocks.slice(),r[i]=o)}return r===void 0?e:{...e,blocks:r}}function jn(e){return{component:e,key:e.nodes.join(`,`)}}function Mn(e){return e.map(e=>e.to).join(`,`)}function Nn(e,t){let n=new In(e.length);for(let e of t)for(let t of e)n.join(t.from,t.to);let r=/* @__PURE__ */ new Map;for(let t=0;t<e.length;t++){let e=n.find(t),i=r.get(e);i===void 0&&(i={nodes:[],edges:[]},r.set(e,i)),i.nodes.push(t)}for(let e of t)for(let t of e)r.get(n.find(t.from)).edges.push(t);let i=0,a=[],o=[],s=Array(e.length),c=Array(e.length),l=0;for(let t of r.values()){let n,r=!0,u=1;for(let i of t.nodes){let t=e[i].reference;t!==void 0&&(r=!1,n===void 0?n=t:t!==n&&(u=0))}r&&i++;for(let e of t.nodes)s[e]=l,c[e]=u;l++;for(let n of Ln(t,e)){let e=a.length;a.push(jn(n));for(let t of n.edges)(o[t.pin]??=[])[t.index]=e}}return{blocks:a,edgeBlocks:o,components:r.size,floatingComponents:i,nodeComponents:s,nodeUniform:c}}let Pn=e=>e===0?0:e;function Fn(e){return{instanceId:e.instance,resource:e.name}}var In=class{parents;constructor(e){this.parents=Array(e);for(let t=0;t<e;t++)this.parents[t]=t}find(e){let t=e;for(;this.parents[t]!==t;)t=this.parents[t];for(;e!==t;){let n=this.parents[e];this.parents[e]=t,e=n}return t}join(e,t){let n=this.find(e),r=this.find(t);n!==r&&(this.parents[Math.max(n,r)]=Math.min(n,r))}};function Ln(e,t){let n=0,r,i=!1;for(let a of e.nodes){let e=t[a].reference;e===void 0?n++:r===void 0?r=e:e!==r&&(i=!0)}if(n<2||!i)return[e];let a=/* @__PURE__ */ new Map;for(let n of e.nodes)t[n].reference===void 0&&a.set(n,a.size);let o=new In(n),s=!1;for(let t of e.edges){let e=a.get(t.from),n=a.get(t.to);e!==void 0&&n!==void 0&&(o.join(e,n),s=!0)}if(!s&&n<=32)return[e];let c=Array(n),l=[];for(let t=0;t<n;t++){let n=c[o.find(t)];n===void 0&&(n={nodes:[],edges:[],physical:e},l.push(n)),c[t]=n}if(l.length===1)return[e];let u=/* @__PURE__ */ new Map;for(let t of e.edges){let e=a.get(t.from),n=a.get(t.to),r=e??n;if(r===void 0)continue;let i=c[r];i.edges.push(t);let o=e===void 0?t.from:n===void 0?t.to:void 0;if(o===void 0)continue;let s=u.get(o);s===void 0&&(s=[],u.set(o,s)),s.push(i)}for(let t of e.nodes){let e=a.get(t);if(e!==void 0)c[e].nodes.push(t);else{let e=u.get(t);if(e===void 0)continue;for(let n of e)n.nodes[n.nodes.length-1]!==t&&n.nodes.push(t)}}return l}function Rn(e){let t=0,n=0;for(let r of e){let e=t+r;n+=Math.abs(t)>=Math.abs(r)?t-e+r:r-e+t,t=e}return t+n}function zn(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Bn(e,t){if(e.edges.length!==t.edges.length)return!1;for(let n=0;n<e.edges.length;n++){let r=e.edges[n],i=t.edges[n];if(r.from!==i.from||r.to!==i.to||r.resistance!==i.resistance)return!1}return!0}function Vn(e,t,n){let r=t.length;if(e.length===0){for(let e of t)(!(e>0)||!Number.isFinite(e))&&n(`Invalid LDL pivot.`);return{matrix:e,anchors:t,pivots:t,weights:/* @__PURE__ */ new Float64Array}}let i=e.slice(),a=t.slice(),o=new Float64Array(r),s=new Float64Array(r*r);for(let e=0;e<r;e++){let t=e*r,c=[a[e]];for(let n=e+1;n<r;n++)c.push(i[t+n]);let l=Rn(c);(!(l>0)||!Number.isFinite(l))&&n(`Invalid LDL pivot.`),o[e]=l;for(let a=e+1;a<r;a++){let e=i[t+a];if(e===0)continue;let r=e/l;(!(r>0)||!Number.isFinite(r))&&n(`Unrepresentable LDL coefficient.`),s[t+a]=r}for(let o=e+1;o<r;o++){let c=i[t+o];if(c===0)continue;let u=c*(a[e]/l);a[e]>0&&!(u>0)&&n(`Reference coefficient underflow.`),a[o]=a[o]+u;for(let e=o+1;e<r;e++){let a=s[t+e];if(a===0)continue;let l=c*a;l>0||n(`Schur coefficient underflow.`);let u=o*r+e;i[u]=i[u]+l}}}return{matrix:e,anchors:t,pivots:o,weights:s}}function Hn(e,t,n){let{weights:r,pivots:i}=e,a=t.length,o=new Float64Array(a);if(r.length===0)for(let e=0;e<a;e++)o[e]=t[e]/i[e],Number.isFinite(o[e])||n(`Non-finite backward substitution.`);else{let e=new Float64Array(a);for(let i=0;i<a;i++){let o=[t[i]];for(let t=0;t<i;t++)o.push(r[t*a+i]*e[t]);e[i]=Rn(o),Number.isFinite(e[i])||n(`Non-finite forward substitution.`)}for(let t=a-1;t>=0;t--){let s=[e[t]/i[t]];for(let e=t+1;e<a;e++)s.push(r[t*a+e]*o[e]);o[t]=Rn(s),Number.isFinite(o[t])||n(`Non-finite backward substitution.`)}}return o}function Un(e,t){return e-t}function Wn(e,t){e=0+e;let n=e+t;return n+(Math.abs(e)>=Math.abs(t)?e-n+t:t-n+e)}function Gn(e,t,n,r){if(e.length>32||t.length>128)return;let i=Array.from({length:e.length},()=>[]),a=[`unknown.length === ${e.length}`,`edges.length === ${t.length}`],o=[];for(let e=0;e<t.length;e++){let r=t[e],s=n.get(r.from),c=n.get(r.to);if(s!==void 0&&c!==void 0)return;if(s===void 0&&c===void 0){a.push(`nodes[edges[${e}].from].reference !== undefined`,`nodes[edges[${e}].to].reference !== undefined`);continue}let l=s??c;if(i[l].length===2)return;i[l].push(e);let u=s===void 0?`from`:`to`,d=s===void 0?`to`:`from`;o[e]=`nodes[edges[${e}].${u}].reference`,a.push(`edges[${e}].${d} === unknown[${l}]`,`${o[e]} !== undefined`)}if(i.some(e=>e.length===0))return;let s=[];for(let e=0;e<i.length;e++){let t=i[e],n=e=>e.length===1?`(0 + ${e[0]})`:`pair(${e.join(`,`)})`;for(let e of t)s.push(`const g${e} = edges[${e}].conductance / gScale;`);s.push(`anchors[${e}] = ${n(t.map(e=>`g${e}`))};`,`right[${e}] = ${n(t.map(e=>`g${e} * (${o[e]} / vScale)`))};`)}return Function(`pair`,`nodes`,`\"use strict\"; return {\n matches(edges, unknown) { return ${a.join(` && `)}; },\n assemble(edges, gScale, vScale) {\n const anchors = new Float64Array(${e.length});\n const right = new Float64Array(${e.length});\n ${s.join(`\n`)}\n return { anchors, right };\n }\n };`)(Wn,r)}function Kn(e,t){let n=[...e],r=new Map(n.map((e,t)=>[e,t])),i=new In(n.length),a=t.map(e=>({id:e.id,pins:[...e.pins],voltage:e.voltage}));for(let e of n)if(e.low===void 0!=(e.high===void 0)||e.low!==void 0&&(!Number.isFinite(e.low)||!Number.isFinite(e.high)||!(e.low<e.high)))throw new Tn(`INVALID_ELECTRICAL_PARAMETER`,`Pin thresholds must both be omitted or finite with low < high.`,Fn(e));let o=(e,t)=>{let n=r.get(e);if(n===void 0)throw new Tn(`INVALID_ELECTRICAL_PARAMETER`,`Electrical endpoint is not part of this board.`,t===void 0?Fn(e):{network:t});return n},s=(e,t)=>{let n=r.get(e);if(n===void 0)throw new Tn(`INVALID_ELECTRICAL_PARAMETER`,`Electrical endpoint is not part of this board.`,Fn(t));return n},c=e=>Number.isFinite(e)&&e>=.001&&e<=1e9;for(let e of a){if(e.voltage!==void 0&&!Number.isFinite(e.voltage))throw new Tn(`INVALID_ELECTRICAL_PARAMETER`,`Reference must be finite.`,{network:e.id});let t;for(let n of e.pins){let r=o(n,e.id);t===void 0?t=r:i.join(t,r)}}let l=[],u=[],d=/* @__PURE__ */ new Map,f=n.map((e,t)=>{let n=i.find(t),r=d.get(n);return r===void 0&&(r=l.length,d.set(n,r),l.push({pins:[],networks:[],reference:void 0}),u.push([])),l[r].pins.push(e),u[r].push(t),r});for(let e of a){if(e.pins.length===0)continue;let t=l[f[o(e.pins[0],e.id)]];if(t.networks.push(e.id),e.voltage===void 0)continue;let n=Pn(e.voltage);if(t.reference!==void 0&&t.reference!==n)throw new Tn(`CONFLICTING_REFERENCE`,`Conflicting fixed potentials on a net.`,{network:e.id,networks:Object.freeze([...t.networks])});t.reference=n}let p=/* @__PURE__ */ new Map,m=[],h,g,_=0,v=/* @__PURE__ */ new Map,ee=0,y=/* @__PURE__ */ new Map,b=Array(n.length).fill(``),te=(e,t)=>{if(t.cost>Dn)return;let n=y.has(e);if(v.set(e,++ee),n?y.get(e)!==t&&y.set(e,t):y.set(e,void 0),y.size>8){let e,t=1/0;for(let n of v.keys()){let r=v.get(n);r<t&&(e=n,t=r)}y.delete(e),v.delete(e)}},x=Array(l.length),S=Array(n.length),C=Array.from({length:n.length},()=>[]),w=Object.freeze([]),T=new Int32Array(l.length),E=[],ne=[],D=[],re=[],ie=[],O=[],k=new Int32Array(n.length),A=0,ae=!1,oe=!1,j=!1,M=(e,t)=>{for(let n of e)t.indexOf(n)===-1&&(T[n.from]=T[n.from]-1,T[n.to]=T[n.to]-1);for(let n of t)e.indexOf(n)===-1&&(T[n.from]=T[n.from]+1,T[n.to]=T[n.to]+1)},N={solves:0,components:0,floatingComponents:0,factorizations:0,factorizationReuses:0,cacheHits:0,leafPlans:0,leafPropagations:0},se=Object.freeze([]),P=[],F=[],ce=Array(n.length),I=[],L=[],le=[],ue=[],de=[],R=[],z=/* @__PURE__ */ new Map,fe=()=>(++A===2147483647&&(k.fill(0),A=1),A),pe=(e,t)=>{let n=z.get(e);n===void 0&&(z.size>=256&&z.clear(),n={},z.set(e,n));let r=n[t];return r===void 0&&(r=Object.freeze({voltage:Pn(e),level:t,status:`valid`}),n[t]=r),r},me=(e,t)=>e.low===void 0?`unknown`:t<=e.low?`low`:t>=e.high?`high`:`unknown`,he=(e,t,r,i)=>{let a=f[e],o=u[a],s=l[r].reference,c=[],d=[],p=[];for(let e=0;e<o.length;e++){let t=o[e],r=n[t];c.push(t),d.push(r),p.push(pe(s,me(r,s)))}return Object.freeze({targetPin:t.to,resistance:t.resistance,target:r,edges:i,node:a,voltage:s,slots:Object.freeze(c),pins:Object.freeze(d),samples:Object.freeze(p)})},ge=(e,t,n,r)=>{let i=he(e,t,n,r),a=ce[e];if(a===void 0)ce[e]=[i],N.leafPlans++;else{for(let e of a)if(e.targetPin===t.to&&e.resistance===t.resistance)return;a.length<2?a.push(i):a[a.length-1]=i,N.leafPlans++}},_e=()=>{for(let e=0;e<R.length;e++){let t=R[e];ge(t.slot,t.branch,t.target,t.edges)}R.length=0},ve=(e,t)=>{let n=h;if(n===void 0||t.length!==1)return;let r=ce[e];if(r===void 0)return;let i=C[e];if(i.length!==1||l[i[0].to].reference===void 0)return;let a=f[e];if(T[a]!==1||l[a].reference!==void 0)return;let o=t[0];for(let e=0;e<r.length;e++){let t=r[e];if(t.targetPin===o.to&&t.resistance===o.resistance)return n.nodeUniform[t.target]===1?t:void 0}},ye=(e,t)=>{let n=e.length;for(;n>0&&e[n-1]>t;)e[n]=e[n-1],n--;e[n]=t},be=e=>{j||=(h={...h,nodeComponents:h.nodeComponents.slice(),nodeUniform:h.nodeUniform.slice()},!0);let t=h.nodeComponents,r=h.nodeUniform;F.length=0,ie.length=0,O.length=0;for(let i=0;i<e;i++){let e=f[I[i]],a=ue[i];t[e]=t[a],r[e]=r[a];let o=de[i];if(o!==void 0){if(x[e]===o.voltage)continue;let t=o.slots;for(let e=0;e<t.length;e++){let n=o.pins[e],r=o.samples[e];n.sample!==r&&(ye(F,t[e]),ie.push(n),O.push(r))}continue}let s=l[a].reference;if(x[e]===s)continue;let c=u[e];for(let e=0;e<c.length;e++){let t=c[e],r=n[t],i=r.low===void 0?`unknown`:s<=r.low?`low`:s>=r.high?`high`:`unknown`,a=r.sample;(a.voltage!==s||a.level!==i||a.status!==`valid`)&&(ye(F,t),ie.push(r),O.push(pe(s,i)))}}for(let e=0;e<ie.length;e++)ie[e].sample=O[e];for(let t=0;t<e;t++){let e=I[t],n=ue[t],r=C[e][0].to;x[f[e]]=l[n].reference,r!==n&&(T[r]=T[r]-1,T[n]=T[n]+1),S[e]=L[t],C[e]=le[t]}ae=!0,N.solves++,N.leafPropagations++};return{get stats(){return Object.freeze({...N})},solve(e){let t=B(xe(e));if(t.length===0)return w;let r=[];for(let e=0;e<t.length;e++)r.push(n[t[e]]);return Object.freeze(r)},solveSlots(e){if(e===void 0)return B(void 0);let t=e instanceof Set||Array.isArray(e)||ArrayBuffer.isView(e)&&Symbol.iterator in e;if(!t){P.length=0;for(let t of e)P.push(t)}let r=t?e:P,i=()=>t?Se(e):P;if(h!==void 0){let e=fe(),t=0,a=!0;for(let i of r){if(k[i]===e)continue;k[i]=e;let r=n[i].intent;if(r===S[i])continue;let o=ve(i,r);if(o===void 0){a=!1;break}I[t]=i,L[t]=r,le[t]=o.edges,ue[t]=o.target,de[t]=o,t++}if(a)return t===0?B(i()):(be(t),F.length===0?se:F)}return B(i())}};function xe(e){if(e!==void 0){P.length=0;for(let t of e)P.push(o(t));return P}}function Se(e){if(e!==void 0){P.length=0;for(let t of e)P.push(t);return P}}function B(e){let t=h===void 0;if(R.length=0,h!==void 0&&!ae&&e!==void 0&&e.length===0)return N.solves++,N.cacheHits+=h.blocks.length,se;E.length=0,ne.length=0,D.length=0,re.length=0;let r=fe(),i=t,a=h!==void 0&&e!==void 0;if(a){let t=0;for(let i=0;i<e.length;i++){let a=e[i];if(k[a]===r)continue;k[a]=r;let o=n[a].intent;if(o===S[a])continue;let s=ve(a,o);if(s===void 0){t=-1;break}I[t]=a,L[t]=o,le[t]=s.edges,ue[t]=s.target,de[t]=s,t++}if(t>0)return be(t),F.length===0?se:F;r=fe()}let o=t||e===void 0;for(let t=0;t<(o?n.length:e.length);t++){let u=o?t:e[t];if(!o){if(k[u]===r)continue;k[u]=r}let d=n[u],p=d.intent;if(p===S[u])continue;let m=f[u],h=C[u],g=[];for(let e of p){c(e.resistance)||En(e.resistance,Fn(d));let t=f[s(e.to,d)];if(m===t)continue;let n=h[g.length];if(n?.to===t&&n.resistance===e.resistance)g.push(n);else{let r={pin:u,index:g.length,from:m,to:t,resistance:e.resistance,conductance:1/e.resistance};g.push(r),n?.to===t?re.push(n):i=!0}}g.length!==h.length&&(i=!0);let _=h.length===1&&g.length===1&&T[m]===1&&l[m].reference===void 0&&l[h[0].to].reference!==void 0&&l[g[0].to].reference!==void 0;a&&!_&&(a=!1),_&&p.length===1&&g[0]!==h[0]&&R.push({slot:u,branch:p[0],target:g[0].to,edges:g}),E.push(u),ne.push(p),D.push(g)}if(a&&i){let e=h.nodeUniform;for(let t=0;t<E.length;t++)if(e[D[t][0].to]!==1){a=!1;break}}if(a&&i){for(let e=0;e<E.length;e++)I[e]=E[e],L[e]=ne[e],le[e]=D[e],ue[e]=D[e][0].to,de[e]=void 0;return _e(),be(E.length),F.length===0?se:F}ae&&(h=void 0,ae=!1,oe=!0,g=void 0,p=/* @__PURE__ */ new Map,y.clear(),v.clear(),ee=0,i=!0);let d=/* @__PURE__ */ new Map;for(let e=0;e<E.length;e++)d.set(E[e],{intent:ne[e],edges:D[e]});if(h!==void 0&&!i&&re.length===0){for(let[e,t]of d)S[e]=t.intent,C[e]=t.edges;return N.solves++,N.cacheHits+=h.blocks.length,_e(),se}let w=h,ie,O,A,P=/* @__PURE__ */ new Map;if(i){if(oe)oe=!1,O=C.map((e,t)=>Mn(d.get(t)?.edges??e));else{O=b.slice();for(let[e,t]of d)O[e]=Mn(t.edges)}if(ie=O.join(`;`),A=y.get(ie),A!==void 0)w=An(A.topology,C,d);else{let e=C.slice();for(let[t,n]of d)e[t]=n.edges;w=Nn(l,e)}}else{let e=/* @__PURE__ */ new Set;for(let t of re){let n=w.edgeBlocks[t.pin]?.[t.index];n!==void 0&&e.add(n)}for(let t of e)P.set(t,kn(w.blocks[t],C,d))}let ce=/* @__PURE__ */ new Map,z=/* @__PURE__ */ new Map,pe=0,me=0,he=i?0:w.blocks.length-P.size;for(let e of i?w.blocks:P.values()){let{component:t,key:n}=e,r=p.get(n);if(r!==void 0&&Bn(r,t)){he++,ce.set(n,r);continue}let i=new Map(t.nodes.map(e=>[e,l[e].reference??null])),a=t.nodes.filter(e=>l[e].reference!==void 0),o=t.physical??t,s=e=>{let t=o.nodes.flatMap(e=>[...l[e].networks]),n=o.nodes.flatMap(e=>l[e].pins.map(e=>e.id)),r=l[o.nodes[0]].pins[0];throw new Tn(`ELECTRICAL_SOLVE_FAILED`,e,{...Fn(r),...t[0]===void 0?{}:{network:t[0]},networks:Object.freeze(t),component:Object.freeze(n)})},c,u;if(a.length!==0){let e=t.nodes.filter(e=>l[e].reference===void 0);for(let e of a)i.set(e,l[e].reference);let n=l[a[0]].reference;if(a.every(e=>l[e].reference===n))for(let t of e)i.set(t,n);else if(e.length!==0){let n=e.length,o=new Map(e.map((e,t)=>[e,t])),d=0,f=0,p=!1;for(let e of a)f=Math.max(f,Math.abs(l[e].reference));for(let e of t.edges){let t=o.has(e.from),n=o.has(e.to);(t||n)&&(d=Math.max(d,e.conductance)),t&&n&&(p=!0)}(!(d>0)||!(f>0))&&s(`Invalid equation scaling.`),p||(u=m.find(n=>n.matches(t.edges,e)),u===void 0&&(u=Gn(e,t.edges,o,l),u!==void 0&&(m.push(u),m.length>8&&m.shift())));let h=new Float64Array(p?n*n:0),g,_;if(u!==void 0)({anchors:g,right:_}=u.assemble(t.edges,d,f));else{let e=Array.from({length:n},()=>[]),r=Array.from({length:n},()=>[]);for(let i of t.edges){let t=o.get(i.from),a=o.get(i.to),s=i.conductance/d;if(t!==void 0&&a!==void 0){let e=Math.min(t,a)*n+Math.max(t,a);h[e]=h[e]+s}else if(t!==void 0||a!==void 0){let n=t??a,o=l[t===void 0?i.from:i.to].reference;e[n].push(s),r[n].push(o/f*s)}}g=Float64Array.from(e,e=>Rn(e)),_=Float64Array.from(r,e=>Rn(e))}r?.factorization!==void 0&&zn(r.factorization.matrix,h)&&zn(r.factorization.anchors,g)?(c=r.factorization,me++):(c=Vn(h,g,s),pe++);let v=Hn(c,_,s);e.forEach((e,t)=>{let n=Pn(v[t]*f);Number.isFinite(n)||s(`Non-finite node voltage.`),i.set(e,n)})}}ce.set(n,{edges:t.edges,voltages:t.nodes.map(e=>i.get(e)),factorization:c});for(let[e,t]of i)x[e]!==t&&z.set(e,t)}let ge=/* @__PURE__ */ new Map;F.length=0;for(let[e,t]of z){let r=u[e];for(let e=0;e<r.length;e++){let i=r[e],a=n[i],o=t===null||a.low===void 0?`unknown`:t<=a.low?`low`:t>=a.high?`high`:`unknown`,s=t===null?`floating`:`valid`,c=a.sample,l=c.voltage!==t||c.level!==o||c.status!==s;l&&F.push(i),(l||N.solves===0)&&ge.set(a,Object.freeze({voltage:t===null?null:Pn(t),level:o,status:s}))}}F.length>1&&F.sort(Un);for(let[e,t]of ge)e.sample=t;for(let[e,t]of z)x[e]=t;for(let[e,t]of d)M(C[e],t.edges),S[e]=t.intent,C[e]=t.edges;if(i)p=ce;else{for(let[e,t]of ce)p.set(e,t);for(let[e,t]of P)w.blocks[e]=t}return h=w,j=!1,i&&(b=O,g=A!==void 0&&w===A.topology?A:{id:A?.id??_++,cost:A?.cost??On(w),topology:w},te(ie,g)),N.solves++,N.components=w.components,N.floatingComponents=w.floatingComponents,N.factorizations+=pe,N.factorizationReuses+=me,N.cacheHits+=he,_e(),F.length===0?se:F}}var qn=class{heap=[];sequence=0;get time(){return this.heap[0]?.time??1/0}push(e,t){let n={time:e,order:this.sequence++,value:t},r=this.heap.length;for(this.heap.push(n);r>0;){let e=r-1>>>1;if(!this.before(n,this.heap[e]))break;this.heap[r]=this.heap[e],r=e}this.heap[r]=n}pop(){let e=this.heap[0],t=this.heap.pop();if(this.heap.length){let e=0;for(;e*2+1<this.heap.length;){let n=e*2+1;if(n+1<this.heap.length&&this.before(this.heap[n+1],this.heap[n])&&n++,!this.before(this.heap[n],t))break;this.heap[e]=this.heap[n],e=n}this.heap[e]=t}return e.value}clear(){this.heap.length=0}before(e,t){return e.time<t.time||e.time===t.time&&e.order<t.order}},Jn=class{entries=[];words=[];activeWords=[];batch=[];get size(){return this.activeWords.length}register(e){return this.entries.push(e)-1}add(e){let t=e>>>5,n=this.words[t]??0;n===0&&this.activeWords.push(t),this.words[t]=n|1<<(e&31)}take(){let e=this.batch;e.length=0,this.activeWords.length>1&&this.activeWords.sort((e,t)=>e-t);for(let t of this.activeWords){let n=this.words[t];for(this.words[t]=0;n!==0;){let r=31-Math.clz32(n&-n);e.push(this.entries[t*32+r]),n&=n-1}}return this.activeWords.length=0,e}clear(){this.entries.length=0,this.words.length=0,this.activeWords.length=0,this.batch.length=0}},Yn=class{values=[];head=0;get length(){return this.values.length-this.head}push(e){this.values.push(e)}shift(){let e=this.values[this.head];return this.values[this.head++]=void 0,this.head===this.values.length&&this.clear(),e}clear(){this.values.length=0,this.head=0}drain(){let e=this.values.slice(this.head);return this.clear(),e}};function Xn(e,t){if(typeof e!=`object`||!e||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Expected a plain data object`);for(let n of Reflect.ownKeys(e)){if(!(`value`in Object.getOwnPropertyDescriptor(e,n)))throw TypeError(`Accessor properties are not allowed`);if(typeof n!=`string`||t&&!t.includes(n))throw TypeError(`Unknown field ${String(n)}`)}}function Zn(e,t=`value`){if(typeof e!=`number`||!Number.isFinite(e))throw TypeError(`${t} must be finite`);return e}function Qn(e,t=`value`){if(typeof e!=`number`||!Number.isSafeInteger(e))throw TypeError(`${t} must be a safe integer`);return e}function $n(e,t=`value`){let n=Qn(e,t);if(n<0)throw RangeError(`${t} must be nonnegative`);return n}function er(e){if(typeof e!=`string`||e.length===0)throw TypeError(`Expected a nonempty identifier`);return e}function tr(e,t,n){let r=$n(t,`offset`),i=$n(n,`length`);if(r>e.length||i>e.length-r)throw RangeError(`Memory range is out of bounds`);return r}function nr(e,t){if(e===t||typeof e==`number`&&typeof t==`number`&&Number.isNaN(e)&&Number.isNaN(t))return!0;if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&nr(e[n],t[n]))}function K(e){return typeof e!=`object`||!e?e:e instanceof Uint8Array?e.slice():Object.freeze(Array.isArray(e)?e.map(K):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,K(t)])))}function rr(e,t=()=>{}){let n=Object.freeze({get length(){return t(),e.length},get byteLength(){return t(),e.length},slice(n,r){return t(),e.slice(n,r)},*[Symbol.iterator](){for(let n=0;n<e.length;n++)t(),yield e[n];t()}});return new Proxy(n,{get(n,r,i){return t(),typeof r==`string`&&/^(0|[1-9]\\d*)$/.test(r)?e[Number(r)]:Reflect.get(n,r,i)},set(){throw TypeError(`Bytes are read-only`)},defineProperty(){throw TypeError(`Bytes are read-only`)}})}function ir(e,t,n,r=!1){if(e.kind===`optional`)return t===null?null:ir(e.inner,t,n,r);switch(e.kind){case`number`:if(typeof t!=`number`)throw TypeError(`Expected number`);if(r&&!Number.isFinite(t))throw TypeError(`Property must be finite`);return t;case`bool`:if(typeof t!=`boolean`)throw TypeError(`Expected boolean`);return t;case`string`:if(typeof t!=`string`)throw TypeError(`Expected string`);return t;case`bytes`:if(!(t instanceof Uint8Array))throw TypeError(`Expected Uint8Array`);return t.slice();case`enum`:{let r=e.name===`Logic`?[`low`,`high`,`unknown`]:e.name===`SampleStatus`?[`valid`,`floating`]:e.name===`Overflow`?[`drop_new`,`drop_oldest`,`error`]:n.get(e.name)?.members;if(typeof t!=`string`||!r?.includes(t))throw TypeError(`Invalid ${e.name} member`);return t}case`record`:{Xn(t);let r=n.get(e.name);return Object.freeze(Object.fromEntries(r.fields.map(e=>[e.name,ir({kind:e.type},t[e.name],n)])))}case`sample`:case`intent`:return t}}function ar(e){return e instanceof Uint8Array?rr(e.slice()):K(e)}function or(e,t,n){if(n!==void 0){if(!Array.isArray(n)||n.length!==4)throw TypeError(`randomState must contain four words`);for(let e of n)if(Qn(e),e<0||e>4294967295)throw RangeError(`randomState word out of range`);if(!n.some(Boolean))throw RangeError(`randomState cannot be zero`);return Uint32Array.from(n)}let r=2166136261,i=new TextEncoder().encode(t),a=new Uint8Array(4+i.length);new DataView(a.buffer).setUint32(0,e,!0),a.set(i,4);for(let e of a)r=Math.imul(r^e,16777619)>>>0;let o=/* @__PURE__ */ new Uint32Array(4);for(let e=0;e<4;e++){r=r+2654435769>>>0;let t=Math.imul(r^r>>>16,2246822507)>>>0;t=Math.imul(t^t>>>13,3266489909)>>>0,o[e]=(t^t>>>16)>>>0}return o.some(Boolean)||(o[0]=1),o}function sr(e){let t=(e,t)=>(e<<t|e>>>32-t)>>>0,n=Math.imul(t(Math.imul(e[1],5),7),9)>>>0,r=e[1]<<9;return e[2]^=e[0],e[3]^=e[1],e[1]^=e[2],e[0]^=e[3],e[2]^=r,e[3]=t(e[3],11),n/4294967296}let cr={positive:`+`,negate:`-`,not:`!`,bitNot:`~`},lr={add:`+`,subtract:`-`,multiply:`*`,divide:`/`,remainder:`%`,power:`**`,lessThan:`<`,lessThanOrEqual:`<=`,greaterThan:`>`,greaterThanOrEqual:`>=`,concat:`+`,bitAnd:`&`,bitOr:`|`,bitXor:`^`,shiftLeft:`<<`,shiftRight:`>>`,shiftRightUnsigned:`>>>`},ur=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`]),dr=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`]);function fr(e,t,n){let r=e.startsWith(`load8`)?1:e.startsWith(`load16`)?2:4,i=tr(t.bytes,n,r);return r===1?t.bytes[i]:r===2?t.view.getUint16(i,e.endsWith(`le`)):t.view.getUint32(i,e.endsWith(`le`))}function pr(e,t,n){let r=tr(e.bytes,t,n);return e.bytes.slice(r,r+Number(n))}function mr(e){throw Error(e===void 0?`Assertion failed`:String(e))}function hr(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}let gr=Object.freeze({checkBoolean:lt,createBytes:rt,createEnum:tt,createRecord:nt,equalValues:at,nonNull:ct,readIndex:st,load:fr,copyBytes:pr,assertFalse:mr,sameBytes:hr});var _r=class extends Error{};function q(e){throw new _r(e)}var vr=class{target;bindings=[];bindingIds=/* @__PURE__ */ new Map;slots=[];nested=[];named=/* @__PURE__ */ new Map;visiting=/* @__PURE__ */ new Set;results=/* @__PURE__ */ new Set;buffers=[[]];depth=0;serial=0;constructor(e){this.target=e,this.bindings.push(e),this.bindingIds.set(e,0)}build(e,t){let n=this.nestedDerived(e);if(t.length===1)this.line(`return ${n}();`);else{this.line(`let projected = ${n}();`);for(let e=1;e<t.length;e++)this.line(`projected = projected[${this.ref(t[e])}];`);this.line(`return projected;`)}return[`function () {`,...this.nested.map(e=>e),...this.buffers[0].map(e=>` ${e}`),`}`].join(`\n`)}slotsUsed(){return this.slots}bindingTable(){return this.bindings}get lines(){return this.buffers[this.buffers.length-1]}line(e){this.lines.push(`${` `.repeat(this.depth)}${e}`)}block(e,t){this.line(`${e} {`),this.depth++,t(),this.depth--,this.line(`}`)}bind(e){if(!(typeof e==`object`&&e)&&Object.is(e,-0))return this.bindings.push(e)-1;let t=this.bindingIds.get(e);if(t!==void 0)return t;let n=this.bindings.push(e)-1;return this.bindingIds.set(e,n),n}ref(e){return`B[${this.bind(e)}]`}slot(e){this.slots.includes(e)||this.slots.push(e)}nestedSource(e,t,n){this.buffers.push([]);let r=this.depth;this.depth=0;try{n()}finally{this.depth=r}let i=this.buffers.pop(),a=[`function ${e}(${t.join(`, `)}) {`,...i,`}`].join(`\n`);return this.nested.push(a),e}nestedDerived(e){let t=`derived:${e.name}`,n=this.named.get(t);if(n)return n;this.visiting.has(t)&&q(`recursive derived ${e.name}`);let r=`d${this.serial++}`;this.named.set(t,r),this.visiting.add(t);try{this.nestedSource(r,[],()=>this.region(e.value.body,void 0))}finally{this.visiting.delete(t)}return r}nestedFunction(e,t){let n=`function:${e}`,r=this.named.get(n);if(r)return r;this.visiting.has(n)&&q(`recursive pure call ${e}`);let i=`f${this.serial++}`;this.named.set(n,i),this.visiting.add(n);try{let e=t.params.map((e,t)=>`p${t}`);this.nestedSource(i,e,()=>{let n=this.params;this.params=e;try{this.region(t.body,void 0)}finally{this.params=n}})}finally{this.visiting.delete(n)}return i}params;value(e){return this.results.has(e)||q(`result ${e} is used before it is defined`),`v${e}`}defineResult(e){return this.results.add(e),`v${e}`}region(e,t){for(let n of e.operations)this.operation(n,t)}valueRegion(e,t){let n=`s${this.serial++}`;this.line(`${n}: {`),this.depth++,this.region(e.body,{slot:t,label:n}),this.depth--,this.line(`}`)}argument(e){return e.kind!==`value`&&q(`resource argument`),this.value(e.value)}memoryRef(e,t){e.kind===`parameter`&&q(`parameterised memory ${t}`);let n=this.target.memoryPlan(e.name);return this.slot(n.slot),n}pinRef(e,t){e.kind===`parameter`&&q(`parameterised pin ${t}`);let n=this.target.pins.get(e.name),r=this.target.sampleResources.get(e.name);return(!n||!r)&&q(`unknown pin ${e.name}`),this.slot(r),n}operation(e,t){let n=t=>{`result`in e||q(`resultless operation`),this.line(`const ${this.defineResult(e.result)} = ${t};`)},r=e=>this.region(e,t);switch(e.kind){case`constant`:{let t=e.constant;t.kind===`bytes`?n(`H.createBytes(${this.ref(Object.freeze(Array.from(rt(t.value))))})`):t.kind===`enum`?n(this.ref(tt(t.name,t.member))):t.kind===`record`?n(this.ref(nt(t.fields.map(e=>[e.name,e.value])))):t.kind===`none`?n(`null`):n(this.ref(t.value));break}case`read`:if(e.resource===`state`){let t=this.target.stateResources.get(e.name);(!t||!this.target.states.has(e.name))&&q(`unknown state ${e.name}`),this.slot(t),n(`${this.ref(this.target.states)}.get(${this.ref(e.name)})`)}else if(e.resource===`derived`){let t=this.target.declarations.get(e.name);t?.kind!==`derived`&&q(`unknown derived ${e.name}`),n(`${this.nestedDerived(t)}()`)}else n(`${this.ref(this.target)}.read(${this.ref(e.resource)}, ${this.ref(e.name)})`);break;case`parameter`:{let t=this.params;(!t||e.index>=t.length)&&q(`value parameter outside a call`),n(t[e.index]);break}case`unary`:{let t=cr[e.operator];t||q(`unsupported unary ${e.operator}`),n(`(${t}${this.value(e.value)})`);break}case`binary`:if(e.operator===`equal`||e.operator===`notEqual`)n(`${e.operator===`notEqual`?`!`:``}H.equalValues(${this.value(e.left)}, ${this.value(e.right)})`);else{let t=lr[e.operator];t||q(`unsupported binary ${e.operator}`),n(`(${this.value(e.left)} ${t} ${this.value(e.right)})`)}break;case`numeric`:ur.has(e.builtin)||q(`unsupported builtin ${e.builtin}`),n(`${dr.has(e.builtin)?`Number`:`Math`}.${e.builtin}(${e.args.map(e=>this.value(e)).join(`, `)})`);break;case`record`:n(`H.createRecord([${e.fields.map(e=>`[${this.ref(e.name)}, ${this.value(e.value)}]`).join(`, `)}])`);break;case`field`:n(`${this.value(e.value)}[${this.ref(e.field)}]`);break;case`bytes`:n(`H.createBytes([${e.elements.map(e=>this.value(e)).join(`, `)}])`);break;case`length`:n(`${this.value(e.value)}.length`);break;case`index`:n(`H.readIndex(${this.value(e.value)}, ${this.value(e.index)})`);break;case`optional`:n(this.value(e.value));break;case`isNone`:n(`(${this.value(e.value)} === null)`);break;case`nonNull`:n(`H.nonNull(${this.value(e.value)})`);break;case`localRead`:n(`l${e.local}`);break;case`local`:this.line(`let l${e.local} = ${this.value(e.initial)};`);break;case`localWrite`:this.line(`l${e.local} = ${this.value(e.value)};`);break;case`memoryLength`:n(`${this.ref(this.memoryRef(e.memory,e.kind))}.bytes.length`);break;case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:n(`H.load(${this.ref(e.kind)}, ${this.ref(this.memoryRef(e.memory,e.kind))}, ${this.value(e.offset)})`);break;case`copyBytes`:{let t=this.memoryRef(e.memory,e.kind);n(`H.copyBytes(${this.ref(t)}, ${this.value(e.offset)}, ${this.value(e.length)})`);break}case`readSample`:n(`${this.ref(this.pinRef(e.pin,e.kind))}.sample`);break;case`callValue`:{e.pure||q(`impure call`);let t=this.target.declarations.get(e.name);(t?.kind!==`function`||!t.pure)&&q(`unknown pure function ${e.name}`),n(`${this.nestedFunction(e.name,t)}(${e.args.map(e=>this.argument(e)).join(`, `)})`);break}case`if`:this.block(`if (H.checkBoolean(${this.value(e.condition)}))`,()=>r(e.yes)),e.no&&this.block(`else`,()=>r(e.no));break;case`match`:e.arms.forEach((t,n)=>{let i=t.pattern,a=i.kind===`none`?null:i.kind===`enum`?tt(i.name,i.member):i.value;this.block(`${n?`else if`:`if`} (H.equalValues(${this.value(e.value)}, ${this.ref(a)}))`,()=>r(t.body))}),e.otherwise&&this.block(e.arms.length?`else`:``,()=>r(e.otherwise));break;case`while`:this.block(`while (true)`,()=>{let t=`s${this.serial++}`;this.line(`let ${t};`),this.valueRegion(e.test,t),this.line(`if (!H.checkBoolean(${t})) break;`),this.block(``,()=>r(e.body))});break;case`loop`:this.block(`while (true)`,()=>r(e.body));break;case`and`:case`or`:{let t=this.defineResult(e.result);this.line(`let ${t} = H.checkBoolean(${this.value(e.left)});`),this.block(`if (${e.kind===`or`?`!`:``}${t})`,()=>{this.valueRegion(e.right,t),this.line(`${t} = H.checkBoolean(${t});`)});break}case`select`:{let t=this.defineResult(e.result);this.line(`let ${t};`),this.block(`if (H.checkBoolean(${this.value(e.condition)}))`,()=>this.valueRegion(e.yes,t)),this.block(`else`,()=>this.valueRegion(e.no,t));break}case`assert`:this.block(`if (!H.checkBoolean(${this.value(e.condition)}))`,()=>{if(e.message){let t=`s${this.serial++}`;this.line(`let ${t};`),this.valueRegion(e.message,t),this.line(`H.assertFalse(${t});`)}else this.line(`H.assertFalse(undefined);`)});break;case`return`:this.line(`return;`);break;case`returnValue`:this.line(`return ${this.value(e.value)};`);break;case`break`:this.line(`break;`);break;case`continue`:this.line(`continue;`);break;case`yield`:t||q(`yield outside a value region`),this.line(`${t.slot} = ${this.value(e.value)};`),this.line(`break ${t.label};`);break;default:{let t=e.kind;q(`unsupported operation ${String(t)}`)}}}};function yr(e,t,n){if(t&&t.kind!==`optional`){if(t.kind===`record`){let r=e.get(t.name);if(r?.kind!==`record`)return;let i=r.fields.find(e=>e.name===n);return i?{kind:i.type}:void 0}if(t.kind===`sample`){if(n===`voltage`)return{kind:`optional`,inner:{kind:`number`}};if(n===`level`||n===`status`)return{kind:`enum`,name:`Logic`}}}}function br(e,t,n){let r=t;for(let t=1;t<n.length;t++)r=yr(e,r,n[t]);return{type:r}}function xr(e){return e?e.kind===`optional`?xr(e.inner):[`number`,`bool`,`string`,`enum`].includes(e.kind):!1}function Sr(e,t,n,r){if(t)switch(t.kind){case`number`:return`(${n} === ${r} || (${n} !== ${n} && ${r} !== ${r}))`;case`bool`:case`string`:case`enum`:return`(${n} === ${r})`;case`bytes`:return`(${n} === ${r} || (${n} !== null && ${r} !== null && typeof ${n} === \"object\" && typeof ${r} === \"object\" && ${n}.length === ${r}.length && H.sameBytes(${n}, ${r})))`;case`sample`:{let i=[`voltage`,`level`,`status`].map(i=>Sr(e,yr(e,t,i),`${n}[${JSON.stringify(i)}]`,`${r}[${JSON.stringify(i)}]`));return i.some(e=>e===void 0)?void 0:`(${n} === ${r} || (${n} !== null && ${r} !== null && typeof ${n} === \"object\" && typeof ${r} === \"object\" && ${i.join(` && `)}))`}case`record`:{let i=e.get(t.name);if(i?.kind!==`record`||!i.fields.length)return;let a=i.fields.map(t=>Sr(e,{kind:t.type},`${n}[${JSON.stringify(t.name)}]`,`${r}[${JSON.stringify(t.name)}]`));return a.some(e=>e===void 0)?void 0:`(${n} === ${r} || (${n} !== null && ${r} !== null && typeof ${n} === \"object\" && typeof ${r} === \"object\" && ${a.join(` && `)}))`}case`optional`:{let i=Sr(e,t.inner,n,r);return i===void 0?void 0:`(${n} === ${r} || (${n} === null ? ${r} === null : (${r} !== null && ${i})))`}default:return}}function Cr(e,t,n){let r=e.declarations.get(n[0]);if(r?.kind!==`derived`)return{ok:!1,reason:`source root is not a derived declaration`};let{type:i}=br(e.declarations,r.type,n);if(i===void 0)return{ok:!1,reason:`source field type is not resolvable`};if(i.kind===`intent`)return{ok:!1,reason:`intent has no stable content comparison`};try{let a=new vr(e),o=a.build(r,n),s=Function(`B`,`H`,`\"use strict\"; return (${o});`)(a.bindingTable(),gr),c=`function (a, b) { return ${Sr(e.declarations,i,`a`,`b`)??`H.same(a, b)`}; }`,l=Function(`H`,`\"use strict\"; return (${c});`)({...gr,same:nr});return{ok:!0,plan:{key:t,path:[...n],source:o,comparison:c,slots:a.slotsUsed(),evaluate:s,equals:l,needsSnapshot:!xr(i)}}}catch(e){return{ok:!1,reason:e instanceof _r?e.message:`unexpected code generation failure: ${e instanceof Error?e.message:String(e)}`}}}let wr=/* @__PURE__ */ new WeakMap,Tr=/* @__PURE__ */ new WeakMap,Er=/* @__PURE__ */ new WeakMap,Dr=72e14;function Or(e){if(typeof e!=`number`||!Number.isFinite(e)||!Number.isInteger(e))throw TypeError(`Time must be a finite integer`);if(e<0||e>72e14)throw RangeError(`Time out of range`);return e===0?0:e}function kr(e){let t=wr.get(e);return t||(t=Mt(e),wr.set(e,t)),t}function Ar(e){let t=Tr.get(e);return t===void 0&&(t=gn(e,{bindResources:!0})??null,Tr.set(e,t)),t??void 0}function jr(e){return{pc:e.start,slots:Array(e.slotCount),kind:0,duration:0,channel:``,value:void 0}}function J(e,t){let n=Er.get(e);return n||(n=Nt(e),Er.set(e,n)),n(t)}var Mr=class extends Error{code;diagnostic;related;constructor(e){super(e.message),this.name=`SimulationError`,this.code=e.code,this.diagnostic=e,this.related=e.related}};function Nr(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}var Pr=class extends TypeError{code=`ASYNC_HOOK_RESULT`;constructor(){super(`Device hooks must return synchronously`)}},Fr=class extends RangeError{code=`INVALID_ELECTRICAL_PARAMETER`};function Ir(e){if(typeof e!=`number`||!Number.isFinite(e))throw new Fr(`Electrical parameters must be finite numbers`);return e}function Lr(e){if(Nr(e))throw Promise.resolve(e).catch(()=>{}),new Pr}function Rr(e){if(!(e instanceof S))return{};let t=e.diagnostics[0];return t?{...t.path?{path:Object.freeze([...t.path])}:{},...t.source?{source:K(t.source)}:{}}:{}}function zr(e,t,n){return new Mr(Object.freeze({code:e,message:t instanceof Error?t.message:String(t),phase:n,time:null,cause:t,...Rr(t),related:Object.freeze([])}))}let Br=Object.freeze([]);function Vr(e,t){for(let n of t.keys())if(!e.has(n))return!1;return!0}function Hr(e,t){return Object.freeze({get props(){return t.guard(e,!0),Object.freeze(Object.fromEntries([...e.props].map(([e,t])=>[e,ar(t)])))},get inputs(){return e.guard(),e.inputs()},get memory(){return t.guard(e,!0),e.publicMemory()},topics:t.topicBridge(e),reportError:n=>t.report(e,n),attachJit:t=>e.attach(t),loadBytes:(t,n,...r)=>e.loadBytes(t,n,r.length?r[0]:0)})}var Ur=class{board;entry;id;declarations=/* @__PURE__ */ new Map;props=/* @__PURE__ */ new Map;constants=/* @__PURE__ */ new Map;states=/* @__PURE__ */ new Map;memories=/* @__PURE__ */ new Map;memoryViews=/* @__PURE__ */ new Map;memorySizes=/* @__PURE__ */ new Map;pins=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;notificationInputs=/* @__PURE__ */ new Set;notificationOutputs=/* @__PURE__ */ new Map;batchInputs=[];batchOutputs=[];batchNotifications=[];emptyOutputs=Object.create(null);resources=[];jits=[];processes=[];reactions=[];derived=/* @__PURE__ */ new Map;derivedBuffers=/* @__PURE__ */ new Map;stateResources=/* @__PURE__ */ new Map;memoryResources=/* @__PURE__ */ new Map;sampleResources=/* @__PURE__ */ new Map;observerRevision=0;dependencyStack=[];observations=/* @__PURE__ */ new WeakMap;staticObservations=/* @__PURE__ */ new WeakMap;resistorIntents=/* @__PURE__ */ new Map;sampleEntries=/* @__PURE__ */ new Map;stateSlots=/* @__PURE__ */ new Map;resourceHandles=/* @__PURE__ */ new Map;memoryPlans=/* @__PURE__ */ new Map;observationFrames=/* @__PURE__ */ new WeakMap;evaluating=/* @__PURE__ */ new Set;random;host;context;adapter;valid=!0;rawProps;constructor(e,t,n,r,i,a){this.board=e,this.entry=t,this.id=n;for(let e of t.model.declarations)`name`in e&&this.declarations.set(e.name,e),(e.kind===`state`||e.kind===`memory`||e.kind===`pin`)&&(e.kind===`state`?this.stateResources:e.kind===`memory`?this.memoryResources:this.sampleResources).set(e.name,{version:0,subscribers:/* @__PURE__ */ new Set});Xn(r),this.rawProps=r;for(let e of Object.keys(r))if(this.declarations.get(e)?.kind!==`property`)throw TypeError(`Unknown property ${e}`);this.random=or(i,n,a),this.host={read:(e,t)=>this.read(e,t),write:(e,t)=>{let n=this.stateSlot(e);this.states.set(e,K(t)),this.board.invalidate(n)},sample:e=>this.readSample(e),intent:(t,n)=>{let r=this.pin(t);r.intent!==n&&(r.intent=n,e.dirtyElectricalSlots.add(e.electricalSlot(r)),e.electricalDirty=!0)},resistor:(e,t)=>{let n=Ir(t);if(n<.001||n>1e9)throw new Fr(`Resistance outside [0.001, 1e9]`);return this.resistorIntent(e,n)},memoryLength:e=>this.memory(e).length,load:(e,t,n)=>{let r=this.memoryPlan(t),i=e.startsWith(`load8`)?1:e.startsWith(`load16`)?2:4,a=tr(r.bytes,n,i),o=this.dependencyStack.at(-1);return o&&o.set(r.slot,r.slot.version),i===1?r.bytes[a]:i===2?r.view.getUint16(a,e.endsWith(`le`)):r.view.getUint32(a,e.endsWith(`le`))},store:(e,t,n,r)=>{let i=this.memoryPlan(t),a=e.startsWith(`store8`)?1:e.startsWith(`store16`)?2:4,o=tr(i.bytes,n,a),s=Qn(r,`stored value`);a===1?i.bytes[o]=s:a===2?i.view.setUint16(o,s,e.endsWith(`le`)):i.view.setUint32(o,s,e.endsWith(`le`)),this.memoryChangedPlan(i)},copyBytes:(e,t,n)=>{this.track(this.memoryResources,String(e));let r=this.memory(e),i=tr(r,t,n);return r.slice(i,i+Number(n))},send:(e,t)=>this.send(e,t,!1),notify:t=>{if(!this.notificationOutputs.has(t))throw TypeError(`Unknown notification ${t}`);this.notificationOutputs.set(t,e.time)},now:()=>e.time,random:()=>sr(this.random),call:(e,t)=>this.invoke(e,t),assert:(e,t)=>{if(e!==!0)throw Error(t===void 0?`Assertion failed`:String(t))},bind:e=>this.bindResources(e)},this.context=Hr(this,e)}track(e,t){this.trackSlot(e.get(t))}trackSlot(e){let t=this.dependencyStack.at(-1);t&&t.set(e,e.version)}bindingReport(){return Object.freeze({instance:this.id,handles:this.resourceHandles.size,bound:Object.freeze([...this.resourceHandles.keys()].sort()),processes:Object.freeze(this.processes.map(e=>Object.freeze({name:e.declaration.kind===`on`?e.declaration.name:`start`,bound:e.frame?.resources?.length??0})))})}dependenciesCurrent(e){if(!e)return!1;for(let[t,n]of e)if(t.version!==n)return!1;return!0}evaluate(e,t){let n=t??/* @__PURE__ */ new Map;this.dependencyStack.push(n);try{return{value:e(),dependencies:n}}finally{this.dependencyStack.pop();let e=this.dependencyStack.at(-1);if(e)for(let[t,r]of n)e.set(t,r)}}evaluateSource(e,t){this.dependencyStack.push(t);try{return K(this.source(e))}finally{this.dependencyStack.pop();let e=this.dependencyStack.at(-1);if(e)for(let[n,r]of t)e.set(n,r)}}observe(e,t){let n=this.staticObservations.get(e);if(n)return n();let r=this.declarations.get(t[0]);if(r?.kind===`pin`||r?.kind===`state`){let n=r.kind===`pin`?this.sampleResources:this.stateResources,i=r.kind===`pin`?this.pin(r.name):void 0;if(i&&t[1]!==`sample`)throw TypeError(`Invalid source ${t.join(`.`)}`);let a=()=>{let e=i?i.sample:this.states.get(r.name);for(let n=i?2:1;n<t.length;n++)e=e[t[n]];return i?e:K(e)},o=a(),s=n.get(r.name);return s.subscribers.size||this.observerRevision++,s.subscribers.add(e),this.staticObservations.set(e,a),o}let i=this.observationFrames.get(e),a;i===void 0?(a=/* @__PURE__ */ new Map,this.observationFrames.set(e,{first:a,second:/* @__PURE__ */ new Map,alternate:!0})):(a=i.alternate?i.second:i.first,i.alternate=!i.alternate,a.clear());let o=this.evaluateSource(t,a),s=this.observations.get(e);if(s===void 0||s.size!==a.size||!Vr(s,a)){if(s)for(let t of s.keys())!a.has(t)&&t.subscribers.delete(e)&&!t.subscribers.size&&this.observerRevision++;for(let t of a.keys())s?.has(t)||(t.subscribers.size||this.observerRevision++,t.subscribers.add(e))}return this.observations.set(e,a),o}observationReader(e,t){return this.staticObservations.get(e)??(()=>this.observe(e,t))}read(e,t){if(e===`state`)return this.trackSlot(this.stateSlot(t)),this.states.get(t);if(e===`derived`){let e=this.derived.get(t);if(!e||!this.dependenciesCurrent(e.dependencies)){let n=this.declarations.get(t);if(n?.kind!==`derived`)throw TypeError(`Unknown derived ${t}`);let r=this.derivedBuffers.get(t);r===void 0?(r=/* @__PURE__ */ new Map,this.derivedBuffers.set(t,r)):r.clear(),e=this.evaluate(()=>J(n.value,this.host),r),this.derived.set(t,e)}let n=this.dependencyStack.at(-1);if(n)for(let[t,r]of e.dependencies)n.set(t,r);return e.value}let n=e===`property`?this.props:this.constants;if(n.has(t))return n.get(t);if(this.evaluating.has(t))throw TypeError(`Circular creation dependency ${t}`);this.evaluating.add(t);try{let e=this.declarations.get(t);if(e?.kind!==`property`&&e?.kind!==`const`)throw TypeError(`Invalid creation reference ${t}`);let r;if(e.kind===`property`){if(Object.hasOwn(this.rawProps,t))r=ir(e.type,this.rawProps[t],this.declarations,!0);else if(e.default)r=ir(e.type,J(e.default,this.host),this.declarations,!0);else throw TypeError(`Missing property ${t}`)}else r=J(e.value,this.host);return n.set(t,r),r}finally{this.evaluating.delete(t)}}invoke(e,t=[]){let n=this.declarations.get(e);if(n?.kind!==`function`)throw TypeError(`Unknown function ${e}`);return kr(n.body)(this.host,t)}syncCall(e,t=[]){let n=this.invoke(e,t).next();if(!n.done)throw TypeError(`Unexpected suspension in synchronous function`);return n.value}pin(e){let t=this.pins.get(String(e));if(!t)throw TypeError(`Unknown pin ${String(e)}`);return t}resistorIntent(e,t){let n=typeof e==`string`?e:String(e),r=this.resistorIntents.get(n);r===void 0&&(this.resistorIntents.size>=64&&this.resistorIntents.clear(),r=/* @__PURE__ */ new Map,this.resistorIntents.set(n,r));let i=r.get(t);return i===void 0&&(r.size>=8&&r.clear(),i=Object.freeze([Object.freeze({to:this.pin(n),resistance:t})]),r.set(t,i)),i}readSample(e){let t=typeof e==`string`?e:String(e),n=this.sampleEntries.get(t);if(n===void 0){let e=this.pin(t);n={pin:e,slot:this.sampleResources.get(e.name)},this.sampleEntries.size>=512&&this.sampleEntries.clear(),this.sampleEntries.set(t,n)}let r=this.dependencyStack.at(-1);return r&&r.set(n.slot,n.slot.version),n.pin.sample}memory(e){let t=this.memories.get(String(e));if(!t)throw TypeError(`Unknown memory ${String(e)}`);return t}stateSlot(e){let t=this.stateSlots.get(e);if(t===void 0){if(!this.states.has(e))throw TypeError(`Unknown state ${e}`);t=this.stateResources.get(e),this.stateSlots.set(e,t)}return t}memoryPlan(e){let t=typeof e==`string`?e:String(e),n=this.memoryPlans.get(t);if(n===void 0){let e=this.memories.get(t);if(!e)throw TypeError(`Unknown memory ${t}`);n={name:t,bytes:e,view:this.memoryViews.get(t),slot:this.memoryResources.get(t)},this.memoryPlans.set(t,n)}return n}memoryChanged(e){this.memoryChangedSlot(e,this.memoryPlan(e).slot)}memoryChangedPlan(e){this.memoryChangedSlot(e.name,e.slot)}memoryChangedSlot(e,t){this.board.invalidate(t);for(let t of this.jits)t.options.code===e&&(t.cache.clear(),t.revision++,t.directPrograms.clear(),t.directProgramRevision=-1,t.directSkip=void 0,t.direct?.frame.resume?t.direct.frame.stopAfterInstruction=!0:t.direct=void 0)}bindResources(e){let t=Array(e.length);for(let n=0;n<e.length;n++){let r=e[n],i=`${r[0]}\\0${r[1]}`,a=this.resourceHandles.get(i);a===void 0&&(a=this.resourceHandle(r[0],r[1]),this.resourceHandles.set(i,a)),t[n]=a}return t}resourceHandle(e,t){if(e===`pin`){let e,n=-1,r,i=()=>(e===void 0&&(e=this.pin(t),n=this.board.electricalSlot(e),r=this.sampleResources.get(t)),e);return Object.freeze({sample:()=>{let e=i(),t=this.dependencyStack.at(-1);return t&&t.set(r,r.version),e.sample},intent:e=>{let t=i();t.intent!==e&&(t.intent=e,this.board.dirtyElectricalSlots.add(n),this.board.electricalDirty=!0)},resistor:e=>{let n=Ir(e);if(n<.001||n>1e9)throw new Fr(`Resistance outside [0.001, 1e9]`);return this.resistorIntent(t,n)}})}if(e===`state`){let e,n=()=>e??=this.stateSlot(t),r=this.states;return Object.freeze({read:()=>{let e=n(),i=this.dependencyStack.at(-1);return i&&i.set(e,e.version),r.get(t)},write:e=>{let i=n();r.set(t,K(e)),this.board.invalidate(i)}})}let n,r=()=>n??=this.memoryPlan(t),i=(e,t,n)=>{let i=r(),a=tr(i.bytes,n,e),o=this.dependencyStack.at(-1);return o&&o.set(i.slot,i.slot.version),e===1?i.bytes[a]:e===2?i.view.getUint16(a,t):i.view.getUint32(a,t)},a=(e,n,i,a)=>{let o=r(),s=tr(o.bytes,i,e),c=Qn(a,`stored value`);e===1?o.bytes[s]=c:e===2?o.view.setUint16(s,c,n):o.view.setUint32(s,c,n),this.memoryChangedSlot(t,o.slot)};return Object.freeze({load8:e=>i(1,!1,e),load16le:e=>i(2,!0,e),load16be:e=>i(2,!1,e),load32le:e=>i(4,!0,e),load32be:e=>i(4,!1,e),store8:(e,t)=>a(1,!1,e,t),store16le:(e,t)=>a(2,!0,e,t),store16be:(e,t)=>a(2,!1,e,t),store32le:(e,t)=>a(4,!0,e,t),store32be:(e,t)=>a(4,!1,e,t),length:()=>this.memory(t).length,copy:(e,n)=>{this.track(this.memoryResources,t);let r=this.memory(t),i=tr(r,e,n);return r.slice(i,i+Number(n))}})}prepare(){for(let e of this.entry.model.declarations)e.kind===`pin`&&this.pins.set(e.name,{id:`${this.id}\\0${e.name}`,instance:this.id,name:e.name,intent:[],sample:{voltage:null,level:`unknown`,status:`floating`}});for(let e of this.entry.model.declarations)switch(e.kind){case`property`:case`const`:this.read(e.kind,e.name);break;case`state`:this.states.set(e.name,K(J(e.initial,this.host)));break;case`memory`:{let t=$n(J(e.length,this.host),`memory length`);this.memorySizes.set(e.name,t);break}case`pin`:{let t=this.pins.get(e.name);if(e.low&&e.high){let n=Ir(J(e.low,this.host)),r=Ir(J(e.high,this.host));if(n>=r)throw new Fr(`Pin thresholds must satisfy low < high`);Object.assign(t,{low:n,high:r})}e.initial&&(t.intent=J(e.initial,this.host));break}case`channel`:{let t=$n(J(e.capacity,this.host),`capacity`);if(t===0)throw RangeError(`Capacity must be positive`);let n;if(e.maxLength&&(n=$n(J(e.maxLength,this.host),`maxLength`),n===0))throw RangeError(`maxLength must be positive`);this.channels.set(e.name,{declaration:e,capacity:t,...n===void 0?{}:{maxLength:n},overflow:e.overflow?String(J(e.overflow,this.host)):`drop_new`,incoming:new Yn,pending:new Yn,outgoing:new Yn});break}case`notification`:e.direction===`output`&&this.notificationOutputs.set(e.name,null);break;case`start`:case`on`:this.processes.push({instance:this,declaration:e,resumable:Ar(e.body),...e.kind===`on`?{source:e.sourcePath}:{},state:`idle`,pending:!1});break;case`reaction`:this.reactions.push({instance:this,declaration:e,previous:void 0,frame:void 0})}for(let[e,t]of this.channels)t.declaration.direction===`input`?this.batchInputs.push(t):(this.batchOutputs.push([e,t]),this.emptyOutputs[e]=Br);for(let e of this.notificationOutputs.keys())this.batchNotifications.push(e),this.emptyOutputs[e]=null;Object.freeze(this.emptyOutputs)}captureBatch(e,t){for(let e of this.batchInputs)e.incoming.length&&e.incoming.clear();let n=this.emptyOutputs;for(let[e,t]of this.batchOutputs)t.outgoing.length&&(n===this.emptyOutputs&&(n=Object.assign(Object.create(null),this.emptyOutputs)),n[e]=Object.freeze(t.outgoing.drain().map(e=>Object.freeze({time:e.time,value:ar(e.value)}))));for(let e of this.batchNotifications){let t=this.notificationOutputs.get(e);t!==null&&(n===this.emptyOutputs&&(n=Object.assign(Object.create(null),this.emptyOutputs)),n[e]=Object.freeze({time:t}),this.notificationOutputs.set(e,null))}return Object.freeze({from:e,to:t,outputs:n===this.emptyOutputs?n:Object.freeze(n)})}assertCreation(){for(let e of this.entry.model.declarations)if(e.kind===`assert`&&!kr(e.body)(this.host).next().done)throw TypeError(`Creation assertion suspended`)}allocate(){for(let[e,t]of this.memorySizes){let n=new Uint8Array(t);this.memories.set(e,n),this.memoryViews.set(e,new DataView(n.buffer))}this.memorySizes.clear()}guard(){this.board.guard(this)}inputs(){let e=Object.create(null);for(let t of this.entry.model.declarations)t.kind===`channel`&&t.direction===`input`&&(e[t.name]=Object.freeze({send:e=>{this.guard(),this.send(t.name,e,!0)}})),t.kind===`notification`&&t.direction===`input`&&(e[t.name]=Object.freeze({notify:()=>{this.guard(),this.notificationInputs.add(t.name)}}));return Object.freeze(e)}publicMemory(){let e=Object.create(null);for(let t of this.entry.model.declarations)t.kind===`memory`&&t.public&&(e[t.name]=rr(this.memory(t.name),()=>{if(this.board.validity(this),![`idle`,`initialize`,`sync`].includes(this.board.phase))throw this.board.error(`INVALID_CALL_STATE`,`Memory cannot be borrowed in this phase`,this);if(this.board.phase===`initialize`&&this.board.current!==this)throw this.board.error(`INVALID_CALL_STATE`,`Another factory is initializing`,this)}));return Object.freeze(e)}send(e,t,n){let r=this.channels.get(e);if(!r||r.declaration.direction!==(n?`input`:`output`))throw TypeError(`Unknown channel ${e}`);let i=ir(r.declaration.type,t,this.declarations);if(r.maxLength!==void 0&&i.length>r.maxLength)throw RangeError(`Message exceeds maxLength`);let a=n?r.pending:r.outgoing;if(a.length===r.capacity){if(r.overflow===`drop_new`)return;if(r.overflow===`error`){let t=this.board.error(`CHANNEL_OVERFLOW`,`Channel ${e} overflow`,this);throw this.board.fault(t),t}a.shift()}a.push({time:this.board.time,value:i})}attach(e){if(this.guard(),this.board.phase!==`initialize`||this.board.current!==this)throw this.board.error(`INVALID_CALL_STATE`,`attachJit is initialization-only`,this);if(Xn(e,[`entry`,`code`,`pc`,`beforeInstruction`,`polling`,`translate`]),er(e.entry),er(e.code),er(e.pc),this.jits.some(t=>t.active&&t.options.entry===e.entry))throw this.board.error(`INVALID_BINDING`,`Duplicate JIT entry`,this);if(!this.memories.has(e.code)||this.declarations.get(e.pc)?.kind!==`state`||this.declarations.get(e.pc).type.kind!==`number`||typeof e.translate!=`function`)throw this.board.error(`INVALID_BINDING`,`Invalid JIT binding`,this);if(e.beforeInstruction!==void 0){Xn(e.beforeInstruction,[`when`,`call`]);let t=this.declarations.get(e.beforeInstruction.when),n=this.declarations.get(e.beforeInstruction.call);if(!t||![`state`,`derived`].includes(t.kind)||!(`type`in t)||t.type.kind!==`bool`||n?.kind!==`function`||n.params.length||n.returns)throw this.board.error(`INVALID_BINDING`,`Invalid instruction hook`,this)}else if(Object.hasOwn(e,`beforeInstruction`))throw TypeError(`Invalid beforeInstruction`);let t=/* @__PURE__ */ new Map;if(Object.hasOwn(e,`polling`)){if(!Array.isArray(e.polling))throw TypeError(`polling must be an array`);for(let n of e.polling){Xn(n,[`pc`,`predicate`]);let e=Zn(n.pc,`polling pc`),r=er(n.predicate),i=this.declarations.get(r);if(t.has(e)||i?.kind!==`function`||!i.pure||i.params.length||i.returns?.kind!==`bool`)throw this.board.error(`INVALID_BINDING`,`Invalid polling declaration`,this);t.set(e,r)}}let n={instance:this,options:Object.freeze({...e,...e.beforeInstruction?{beforeInstruction:Object.freeze({...e.beforeInstruction})}:{}}),cache:/* @__PURE__ */ new Map,polling:t,revision:0,directRevision:-1,directObserverRevision:-1,directStateGuards:/* @__PURE__ */ new Set,directMemoryGuards:/* @__PURE__ */ new Set,directHookReads:/* @__PURE__ */ new Set,directPrograms:/* @__PURE__ */ new Map,directProgramRevision:-1,direct:void 0,directSkip:void 0,pollReads:void 0,currentPc:void 0,automaticPolling:!1,pollingWait:!1,pollingPeriod:0,pollingOrigin:0,active:!0,stopped:!1,queued:!1,execution:void 0};this.jits.push(n),this.board.jits.push(n);let r={dispose:()=>{n.active&&(n.active=!1,n.execution=void 0,delete n.predicate,this.board.waitingJits.delete(n),n.cache.clear(),n.directPrograms.clear(),n.direct=void 0,n.pollReads=void 0)}};return this.resources.push(r),r}loadBytes(e,t,n){if(this.guard(),this.board.phase!==`idle`&&(this.board.phase!==`initialize`||this.board.current!==this))throw this.board.error(`INVALID_CALL_STATE`,`Code loading is not allowed in this phase`,this);if(typeof e!=`string`||!this.jits.some(t=>t.active&&t.options.code===e))throw this.board.error(`INVALID_BINDING`,`Memory is not bound as code`,this);if(!(t instanceof Uint8Array))throw TypeError(`Code must be Uint8Array`);let r=this.memory(e),i=tr(r,n,t.length);t.length&&(r.set(t.slice(),i),this.memoryChanged(e))}source(e){let t=this.declarations.get(e[0]),n,r=1;if(t?.kind===`pin`){if(this.track(this.sampleResources,t.name),e[1]!==`sample`)throw TypeError(`Invalid source ${e.join(`.`)}`);n=this.pin(t.name).sample,r=2}else if(t?.kind===`state`||t?.kind===`derived`)n=this.read(t.kind,t.name);else throw TypeError(`Invalid source ${e.join(`.`)}`);for(let t=r;t<e.length;t++)n=n[e[t]];return n}};function Wr(e,t,n){let r=/* @__PURE__ */ new Map,i=[],a=e=>{for(let t of e.operations)switch(`result`in t&&r.set(t.result,t),t.kind){case`constant`:case`unary`:case`binary`:case`numeric`:case`field`:case`length`:case`index`:case`isNone`:case`nonNull`:case`optional`:case`local`:case`localRead`:case`localWrite`:case`memoryLength`:case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:case`readSample`:case`yield`:break;case`read`:if(t.resource===`derived`||t.name===n)return!1;break;case`if`:if(!a(t.yes)||t.no&&!a(t.no))return!1;break;case`select`:if(!a(t.yes.body)||!a(t.no.body))return!1;break;case`and`:case`or`:if(!a(t.right.body))return!1;break;case`match`:if(t.arms.some(e=>!a(e.body))||t.otherwise&&!a(t.otherwise))return!1;break;case`redirect`:i.push(t.target);break;default:return!1}return!0};return a(e)?i.some(e=>{let n=r.get(e);return n?.kind!==`constant`||n.constant.kind===`number`&&n.constant.value===t}):!1}function Gr(e,t){let n=!1,r=e.instance,i=e.directHookReads.size;if(t)for(let n of t.keys())e.directHookReads.add(n);if(e.directObserverRevision!==r.observerRevision||i!==e.directHookReads.size){e.directObserverRevision=r.observerRevision;for(let[t,i]of r.stateResources){let r=i.subscribers.size>0||e.directHookReads.has(i);e.directStateGuards.has(t)!==r&&(r?e.directStateGuards.add(t):e.directStateGuards.delete(t),n=!0)}for(let[t,i]of r.memoryResources){let r=i.subscribers.size>0||e.directHookReads.has(i)||t===e.options.code;e.directMemoryGuards.has(t)!==r&&(r?e.directMemoryGuards.add(t):e.directMemoryGuards.delete(t),n=!0)}n&&(e.direct=void 0,e.directRevision=-1,e.directSkip=void 0)}}function Kr(e,t,n){let r=()=>{e.time=n.time};return{send:(e,n)=>{r(),t.host.send(e,n)},sample:e=>(r(),t.host.sample(e)),intent:(e,n)=>{r(),t.host.intent(e,n)},resistor:(e,n)=>(r(),t.host.resistor(e,n)),notify:e=>{r(),t.host.notify(e)},now:()=>(r(),t.host.now()),random:()=>(r(),t.host.random()),assert:(e,n)=>{r(),t.host.assert(e,n)}}}function qr(e,t,n,r,i){let a={states:Array(n.length),memories:r.map(e=>t.memory(e)),locals:Array(i.localCount),stateDirty:Array(Math.ceil(n.length/32)).fill(0),memoryDirty:Array(Math.ceil(r.length/32)).fill(0),time:e.time,due:e.time,resume:0};return a.host=Kr(e,t,a),a}function Jr(e,t,n){let r=t.instance,i=!!t.direct?.frame.resume;if(!i){let i=Zn(r.states.get(t.options.pc),`pc`);if(e.execution!==`throughput`||e.jits.length!==1||t.polling.has(i)||t.cache.get(i)?.polling||(Gr(t,n),t.directSkip===i))return!1;if(t.directRevision!==t.revision){t.directProgramRevision!==t.revision&&(t.directPrograms.clear(),t.directProgramRevision=t.revision);let n=JSON.stringify([[...t.directStateGuards].sort(),[...t.directMemoryGuards].sort()]),i=t.directPrograms.get(n);if(i)t.direct=i,t.directRevision=t.revision;else{let i=[...r.states.keys()].filter(e=>{let t=r.declarations.get(e);return t.type.kind===`number`||t.type.kind===`bool`}),a=[...r.memories.keys()],o=new Map(i.map((e,t)=>[e,t])),s=new Map(a.map((e,t)=>[e,t])),c=rn([...t.cache.values()].filter(e=>!e.polling&&!t.polling.has(e.pc)),{states:o,memories:s,pc:{name:t.options.pc,index:o.get(t.options.pc)},blockedStates:t.directStateGuards,blockedMemories:t.directMemoryGuards,host:!0,split:!0,shardSize:8});t.directRevision=t.revision,t.direct=c?{program:c,stateReads:c.readStates.map(e=>[e,o.get(e)]),stateWrites:c.writeStates.map(e=>[e,o.get(e)]),memoryWrites:c.writeMemories.map(e=>[e,s.get(e)]),revision:t.revision,frame:qr(e,r,i,a,c)}:void 0,t.direct?(t.directPrograms.size>=8&&t.directPrograms.delete(t.directPrograms.keys().next().value),t.directPrograms.set(n,t.direct)):t.directPrograms.delete(n)}}if(!t.direct)return!1}let a=t.direct,o=a.frame;i&&(o.stopAfterInstruction=!0);for(let[e,t]of a.stateReads)o.states[t]=r.states.get(e);o.time=e.time,o.stateDirty.fill(0),o.memoryDirty.fill(0);let s=e.time,c;try{c=a.program.run(o,Math.min(e.executionEnd,e.events.time))}finally{e.time=o.time;for(let[e,t]of a.stateWrites)o.stateDirty[t>>>5]&1<<(t&31)&&r.host.write(e,o.states[t]);for(let[e,t]of a.memoryWrites)o.memoryDirty[t>>>5]&1<<(t&31)&&r.memoryChanged(e)}if(e.boundary(),c===`fallback`){if(t.directSkip=Zn(r.states.get(t.options.pc),`pc`),e.time===s&&e.time<e.executionEnd)return!1}else if(c===`stopped`)return t.stopped=!0,!0;else c===`invalidated`&&(o.stopAfterInstruction=!1,a.revision!==t.revision&&(t.direct=void 0,t.directRevision=-1));return o.resume&&o.due>e.time?e.events.push(o.due,()=>e.queueJit(t)):e.queueJit(t),!0}function Yr(e,t){let n=new Map(t),r=e.instance;for(let t of[r.stateResources.get(e.options.pc),r.memoryResources.get(e.options.code)])n.set(t,t.version);return n}function Xr(e,t,n){if(n.kind===`elapse`){let r=Or(n.duration);if(r===0)return!1;let i=Or(e.time+r);return e.events.push(i,()=>e.queueJit(t)),e.boundary(),!0}if(n.kind===`waitUntil`){let r=t.instance.evaluate(()=>t.instance.syncCall(n.predicate));return r.value!==!0&&(t.predicate=n.predicate,t.pollingWait=!1,t.dependencies=r.dependencies,e.waitingJits.add(t),e.boundary(),!0)}if(n.kind===`stop`)return t.stopped=!0,t.execution=void 0,e.boundary(),!0;if(n.kind===`redirect`){Zn(n.pc,`redirect target`);let r=Or(n.delay);t.instance.host.write(t.options.pc,n.pc),t.execution=void 0;let i=t.automaticPolling&&r>0&&n.pc===t.currentPc&&t.pollReads,a=i?Yr(t,i):void 0;return t.automaticPolling=!1,t.pollReads=void 0,e.boundary(),r===0?e.queueJit(t):e.events.push(Or(e.time+r),()=>{t.active&&!t.stopped&&(a&&t.instance.dependenciesCurrent(a)?(t.dependencies=a,t.pollingWait=!0,t.pollingPeriod=r,t.pollingOrigin=e.time,e.waitingJits.add(t)):e.queueJit(t))}),!0}throw TypeError(`Invalid JIT suspension`)}function Zr(e,t){if(t.queued=!1,t.active&&!t.stopped){if(e.current=t.instance,t.direct?.frame.resume)Jr(e,t);else{if(!t.execution){t.automaticPolling=!1,t.pollReads=void 0;let n,r=!1,i=t.options.beforeInstruction;if(i){let a=t.instance.declarations.get(i.when).kind,o=t.instance.states.get(t.options.pc),s=e.execution===`throughput`&&(e.jits.length===1||t.polling.has(o))?t.instance.evaluate(()=>t.instance.read(a,i.when)):void 0,c=(s?s.value:t.instance.read(a,i.when))===!0;if(c){let n=t.instance.invoke(i.call),r=n.next();if(!r.done){if(t.execution=n,Xr(e,t,r.value))return;throw TypeError(`Invalid hook suspension`)}}n=s?.dependencies,r=c}let a=Zn(t.instance.states.get(t.options.pc),`pc`);if(e.execution===`throughput`){let i=t.polling.get(a);if(i){let r=t.instance.evaluate(()=>t.instance.syncCall(i));if(r.value!==!0){t.dependencies=Yr(t,new Map([...n??[],...r.dependencies])),t.pollingWait=!0,t.pollingPeriod=0,e.waitingJits.add(t),e.boundary();return}}if(!r&&e.jits.length===1&&Jr(e,t,n))return}let o=t.cache.get(a);if(!o){let n=e.phase;e.phase=`translate`;let r=!0;try{let n=rr(t.instance.memory(t.options.code),()=>{if(!r)throw e.error(`OBJECT_DISPOSED`,`Translation view expired`,t.instance)}),i=t.options.translate(Object.freeze({pc:a,code:n}),et({device:t.instance.entry.model}));Lr(i);let s=je(i,t.instance.entry.model);if(s.instructions[0]?.pc!==a)throw TypeError(`Translated first pc does not match`);let c=s.instructions.map(e=>({pc:e.pc,nextPc:e.nextPc,body:e.body,polling:Wr(e.body,e.pc,t.options.pc),execute:kr(e.body)}));for(let e=c.length-1;e>=0;e--){let n=c[e];t.cache.set(n.pc,n)}t.revision++,t.directSkip=void 0,o=c[0]}catch(n){throw e.wrap(n,`JIT_FAILED`,`translate`,t.instance)}finally{r=!1,e.phase=n}}t.currentPc=a,t.automaticPolling=e.execution===`throughput`&&e.jits.length===1&&o.polling&&!r&&(!i||n!==void 0),t.pollReads=n,t.instance.host.write(t.options.pc,o.nextPc),t.execution=o.execute(t.instance.host)}for(;;){let n=t.automaticPolling?(()=>{let e=t.instance.evaluate(()=>t.execution.next());return t.pollReads=new Map([...t.pollReads??[],...e.dependencies]),e.value})():t.execution.next();if(n.done){t.execution=void 0,e.boundary(),e.queueJit(t);return}if(Xr(e,t,n.value))return}}}}let Qr=Symbol.for(`mica-js.simulator/observations`),$r=Symbol.for(`mica-js.simulator/processes`),ei=Object.freeze({}),ti=/* @__PURE__ */ new WeakMap;function ni(e){try{if(!Array.isArray(e))throw TypeError(`Expected device entries`);let t=/* @__PURE__ */ new Set,n=e.map(e=>{Xn(e,[`id`,`model`,`create`]);let n=er(e.id);if(t.has(n))throw TypeError(`Duplicate device type ${n}`);if(t.add(n),typeof e.create!=`function`)throw TypeError(`Expected device factory`);let r;try{r=ke(e.model)}catch(e){throw zr(e instanceof S&&Object.getOwnPropertyDescriptor(e,`code`)?.value===`CHANNEL_CONSUMER_CONFLICT`?`CHANNEL_CONSUMER_CONFLICT`:`MODEL_VALIDATION_FAILED`,e,`library`)}return Object.freeze({id:n,model:r,create:e.create})}),r=Object.freeze({});return ti.set(r,n),r}catch(e){throw e instanceof Mr?e:zr(`INVALID_CONFIGURATION`,e,`library`)}}var ri=class{time=0;status=`ready`;phase=`assembly`;current;electricalDirty=!0;dirtyElectricalSlots=/* @__PURE__ */ new Set;observations=new Jn;reactionBatch=[];changeObservations=[];changePrevious=[];changeCurrent=[];plans=[];skippedPlans=[];sampleSlots=/* @__PURE__ */ new Map;sampleSlotsBySlot=[];electricalSlots=/* @__PURE__ */ new Map;byId=/* @__PURE__ */ new Map;dispatchDepth=0;initialized=!1;errors=new t;diagnostics=new t;listeners=/* @__PURE__ */ new Set;models=new Yn;events=new qn;readyJits=new Yn;waitingJits=/* @__PURE__ */ new Set;jits=[];instances=[];network;primary;execution;executionEnd=0;onDidError=(e,t,n)=>this.errors.event(n=>{try{e.call(t,n)}catch(e){this.diagnostic(`HOST_LISTENER_FAILED`,e)}},void 0,n);onDidDiagnostic=(e,t,n)=>this.diagnostics.event(n=>{try{e.call(t,n)}catch(e){this.fallback(e)}},void 0,n);topics=this.topicBridge();constructor(e,t,n){try{Xn(t,[`instances`,`nets`]),Xn(n,[`seed`,`execution`,`cpuQuantum`]);let r=Object.hasOwn(n,`execution`)?n.execution:`throughput`;if(r!==`throughput`&&r!==`precise`)throw TypeError(`Invalid execution mode`);this.execution=r;let i=Object.hasOwn(n,`cpuQuantum`)?Qn(n.cpuQuantum,`cpuQuantum`):1e7;if(i<1||i>1e7)throw RangeError(`cpuQuantum outside [1, 10000000]`);if(!Array.isArray(t.instances)||!Array.isArray(t.nets))throw TypeError(`instances and nets are required arrays`);let a=Object.hasOwn(n,`seed`)?Qn(n.seed,`seed`):0;if(a<0||a>4294967295)throw RangeError(`seed out of uint32 range`);let o=new Map(e.map(e=>[e.id,e])),s=/* @__PURE__ */ new Set;for(let e of t.instances){Xn(e,[`id`,`type`,`props`,`randomState`]);let t=er(e.id),n=er(e.type);if(s.has(t))throw TypeError(`Duplicate instance ${t}`);s.add(t);let r=o.get(n);if(!r)throw TypeError(`Unknown device type ${n}`);let i=Object.hasOwn(e,`props`)?e.props:{};if(Object.hasOwn(e,`randomState`)&&e.randomState===void 0)throw TypeError(`Invalid randomState`);this.instances.push(new Ur(this,r,t,i,a,e.randomState))}for(let e of this.instances)this.byId.set(e.id,e);let c=this.byId,l=/* @__PURE__ */ new Set,u=/* @__PURE__ */ new Set;for(let e of t.nets){Xn(e,[`id`,`pins`,`voltage`]);let t=er(e.id);if(l.has(t))throw TypeError(`Duplicate network ${t}`);if(l.add(t),!Array.isArray(e.pins))throw TypeError(`Network pins must be an array`);Object.hasOwn(e,`voltage`)&&Zn(e.voltage,`voltage`);for(let t of e.pins){Xn(t,[`instance`,`pin`]);let e=er(t.instance),n=er(t.pin);if(c.get(e)?.declarations.get(n)?.kind!==`pin`)throw TypeError(`Unknown pin endpoint`);let r=`${e}\\0${n}`;if(u.has(r))throw TypeError(`Duplicate connected endpoint`);u.add(r)}}try{for(let e of this.instances)this.current=e,e.prepare();for(let e of this.instances)this.current=e,e.assertCreation();for(let e of this.instances)this.current=e,e.allocate()}catch(e){throw this.wrap(e,`MODEL_EXECUTION_FAILED`,`assembly`,this.current)}let d=t.nets.map(e=>({id:e.id,pins:e.pins.map(e=>c.get(e.instance).pin(e.pin)),...Object.hasOwn(e,`voltage`)?{voltage:e.voltage}:{}})),f=[];for(let e of this.instances)for(let t of e.pins.values()){let n=e.sampleResources.get(t.name);f.push(t),this.sampleSlots.set(t,n),this.electricalSlots.set(t,this.sampleSlotsBySlot.length),this.sampleSlotsBySlot.push(n)}this.network=Kn(f,d),this.phase=`initialize`;for(let e of this.instances){this.current=e;let t;try{if(t=e.entry.create(e.context),Lr(t),typeof t!=`object`||!t||typeof t.sync!=`function`||typeof t.dispose!=`function`)throw TypeError(`Invalid device adapter`)}catch(t){throw this.wrap(t,`DEVICE_CALLBACK_FAILED`,`initialize`,e)}if(e.adapter=t,this.isFaulted)throw this.primary}this.current=void 0,this.phase=`idle`,Object.defineProperty(this,Qr,{value:()=>this.observationReport(),enumerable:!1}),Object.defineProperty(this,$r,{value:()=>this.processReport(),enumerable:!1})}catch(e){let t=e instanceof Mr?e:this.wrap(e,`INVALID_CONFIGURATION`,`assembly`,this.current);this.primary=t;let n=this.cleanup();throw n.length?this.aggregate(t,n):t}}get isFaulted(){return this.status===`faulted`}observationReport(){return Object.freeze({plans:Object.freeze(this.plans.map(e=>Object.freeze({key:e.plan.key,path:Object.freeze([...e.plan.path]),receivers:e.members.length,slots:e.plan.slots.length,source:e.plan.source,comparison:e.plan.comparison}))),skipped:Object.freeze(this.skippedPlans.map(e=>Object.freeze({...e})))})}processReport(){let e=[],t=[];for(let n of this.instances)for(let r of n.processes){let i=`${n.id}/${r.declaration.kind===`on`?r.declaration.name:`start`}`;(r.resumable?e:t).push(i)}return Object.freeze({resumable:Object.freeze(e),generic:Object.freeze(t),bindings:Object.freeze(this.instances.map(e=>e.bindingReport()))})}validity(e){if(this.status===`disposed`||e&&!e.valid)throw this.error(`OBJECT_DISPOSED`,`Object is disposed`,e)}guard(e,t=!1){if(this.validity(e),e&&[`execute`,`translate`,`dispose`,`assembly`].includes(this.phase))throw this.error(`INVALID_CALL_STATE`,`Operation is not allowed in this phase`,e);if(!t&&this.status===`faulted`)throw this.error(`BOARD_FAULTED`,`Board is faulted`,e)}error(e,t,n,r,i){let a=r instanceof Tn?r:void 0;return new Mr(Object.freeze({code:e,message:t,phase:i??(this.phase===`idle`?`host`:this.phase),time:this.time,...a?.instanceId===void 0?n?{instanceId:n.id}:{}:{instanceId:a.instanceId},...a?.resource===void 0?{}:{resource:a.resource},...Rr(r),...r===void 0?{}:{cause:r},related:Object.freeze([])}))}wrap(e,t,n,r){if(e instanceof Mr&&![`DEVICE_CALLBACK_FAILED`,`JIT_FAILED`,`CLEANUP_FAILED`].includes(t))return e;let i=e instanceof Tn||e instanceof Fr||e instanceof Pr?e.code:void 0;return this.error(n!==`dispose`&&i?i:t,e instanceof Error?e.message:String(e),r,e,n)}fault(e){if(this.status===`ready`){this.status=`faulted`,this.primary=e,this.dispatchDepth++;try{this.errors.fire(e.diagnostic)}finally{this.dispatchDepth--}}}diagnostic(e,t,n){let r=this.error(e,t instanceof Error?t.message:String(t),n,t).diagnostic;this.dispatchDepth++;try{this.diagnostics.fire(r)}finally{this.dispatchDepth--}}fallback(e){try{console.error(e)}catch{}}report(e,t){this.status===`disposed`?this.fallback(t):e.valid?this.status===`faulted`?this.diagnostic(`REPORTED_ERROR`,t,e):this.fault(this.error(`REPORTED_ERROR`,t instanceof Error?t.message:String(t),e,t,`report`)):this.diagnostic(`STALE_REPORT`,t,e)}topicBridge(e){return Object.freeze({onDidReceive:((t,n,r)=>{this.guard(e);let i={...e?{owner:e}:{},call:e=>t.call(n,e)};this.listeners.add(i);let a=!0,o={dispose:()=>{a&&(a=!1,this.listeners.delete(i))}};return r?.push(o),e?.resources.push(o),o}),publish:(t,n)=>{if(this.guard(e),typeof t!=`string`)throw TypeError(`Topic must be a string`);this.dispatchDepth++;try{let e=Object.freeze({topic:t,payload:n});for(let t of[...this.listeners])if(!(t.owner&&this.status!==`ready`))try{let n=t.call(e);t.owner&&Lr(n)}catch(e){t.owner?this.fault(this.wrap(e,`DEVICE_CALLBACK_FAILED`,`topic`,t.owner)):this.diagnostic(`HOST_LISTENER_FAILED`,e)}}finally{this.dispatchDepth--}}})}enqueue(e){e.state===`idle`?(e.state=`queued`,this.models.push(e)):e.state!==`queued`&&(e.pending=!0)}queueJit(e){e.active&&!e.stopped&&!e.queued&&(e.queued=!0,this.readyJits.push(e))}invalidate(e){if(e.version++,e.subscribers.size!==0)for(let t of e.subscribers)this.observations.add(t.order)}electricalSlot(e){return this.electricalSlots.get(e)}publish(){if(!this.electricalDirty)return;let e=this.network.solveSlots(this.dirtyElectricalSlots);this.dirtyElectricalSlots.clear(),this.electricalDirty=!1;for(let t=0;t<e.length;t++)this.invalidate(this.sampleSlotsBySlot[e[t]])}bindObservation(e,t){let n=e.instance;e.previous=n.observe(e,t),e.readSource=n.observationReader(e,t),e.order=this.observations.register(e)}baseline(){this.publish();let e=[];for(let t of this.instances){let n=`${t.id}\\0`;for(let r of t.processes)r.source&&t.declarations.get(r.source[0])?.kind!==`notification`&&e.push({observation:r,path:r.source,key:n+r.source.join(`\\0`),instance:t});for(let r of t.reactions){let i=r.declaration.sourcePath;e.push({observation:r,path:i,key:n+i.join(`\\0`),instance:t})}}let t=/* @__PURE__ */ new Map;for(let n of e){if(t.has(n.key))continue;let e=Cr(n.instance,n.key,n.path);if(!e.ok){this.skippedPlans.push({key:n.key,reason:e.reason}),t.set(n.key,void 0);continue}let r={plan:e.plan,instance:n.instance,members:[],dependencies:/* @__PURE__ */ new Map,entry:{dependencies:/* @__PURE__ */ new Map,value:void 0},order:0,previous:void 0,bound:!1};t.set(n.key,r),this.plans.push(r)}for(let n of e){let e=t.get(n.key);e===void 0?this.bindObservation(n.observation,n.path):(e.bound?n.observation.order=this.observations.register(ei):(e.bound=!0,e.order=this.observations.register(e),n.observation.order=e.order,this.bindChain(e)),e.members.push(n.observation),n.observation.previous=e.previous)}}bindChain(e){let t=e.instance;for(let n of e.plan.slots)n.subscribers.size||t.observerRevision++,n.subscribers.add(e);let n=e.plan.evaluate();e.previous=e.plan.needsSnapshot?K(n):n,this.commitChain(e,n)}commitChain(e,t){let n=e.plan.path;if(n.length!==1)return;for(let t of e.plan.slots)e.dependencies.set(t,t.version);let r=e.entry;r.value!==t&&(r.value=t),r.dependencies=e.dependencies,e.instance.derived.get(n[0])!==r&&e.instance.derived.set(n[0],r)}collectChain(e){let t=e.plan.evaluate(),n=e.plan.needsSnapshot?K(t):t;if(this.commitChain(e,t),e.plan.equals(e.previous,n))return;let r=e.previous;e.previous=n;let i=e.members,a=i[0];if(i.length===1&&!this.changeObservations.length)a.previous=n,this.applyChange(a,r,n);else for(let e of i)e.previous=n,this.recordChange(e,r,n)}applyChange(e,t,n){if(e.declaration.kind===`reaction`){let r=e;r.frame={previous:t,current:n,captures:[]},this.reactionBatch.push(r)}else this.enqueue(e)}recordChange(e,t,n){let r=this.changeObservations,i=r.length,a=e.order;for(;i>0&&r[i-1].order>a;)i--;i===r.length?(r.push(e),this.changePrevious.push(t),this.changeCurrent.push(n)):(r.splice(i,0,e),this.changePrevious.splice(i,0,t),this.changeCurrent.splice(i,0,n))}boundary(){for(;;){if(this.publish(),!this.observations.size)return;let e=this.reactionBatch;e.length=0;let t=this.changeObservations;t.length=0,this.changePrevious.length=0,this.changeCurrent.length=0;try{let n=this.observations.take();for(let e=0;e<n.length;e++){let r=n[e];if(`plan`in r){this.collectChain(r);continue}let i=r.readSource();if(nr(r.previous,i))continue;let a=r.previous;r.previous=i,t.length?this.recordChange(r,a,i):this.applyChange(r,a,i)}let r=t.length;if(r){for(let e=0;e<r;e++)this.applyChange(t[e],this.changePrevious[e],this.changeCurrent[e]);t.length=0,this.changePrevious.length=0,this.changeCurrent.length=0}if(!e.length)return;for(let t of e)t.declaration.captures.length&&(t.frame={...t.frame,captures:t.declaration.captures.map(e=>K(J(e.value,t.instance.host)))});for(let t of e)if(this.current=t.instance,t.execute??=kr(t.declaration.body),!t.execute(t.instance.host,[],t.frame).next().done)throw TypeError(`Reaction cannot suspend`)}finally{for(let t of e)t.frame=void 0}}}drive(e,t){let n=e.resumable;if(n)this.driveResumable(e,n,t);else for(this.current=e.instance,e.state=`running`,e.execution??=kr(e.declaration.body)(e.instance.host);;){let n=e.execution.next(t);if(n.done){this.boundary(),e.execution=void 0,e.state=`idle`,e.pending&&(e.pending=!1,this.enqueue(e));return}let r=n.value;if(r.kind===`receive`){let n=e.instance.channels.get(r.channel);if(n.incoming.length){t=n.incoming.shift().value;continue}e.state=`waiting`,n.receiver=e,this.boundary();return}if(r.kind!==`ticks`)throw TypeError(`Invalid process suspension`);let i=Or(r.duration),a=Or(this.time+i);e.state=`waiting`,this.boundary(),i===0?(e.state=`queued`,this.models.push(e)):(e.wake??=()=>{e.state=`queued`,this.models.push(e)},this.events.push(a,e.wake));return}}driveResumable(e,t,n){this.current=e.instance,e.state=`running`;let r=e.frame??=jr(t),i=n;for(;;){if(r.value=i,!t.run(e.instance.host,void 0,void 0,r)){this.boundary(),e.state=`idle`,e.pending&&(e.pending=!1,this.enqueue(e));return}if(r.kind===2){let t=e.instance.channels.get(r.channel);if(t.incoming.length){i=t.incoming.shift().value;continue}e.state=`waiting`,t.receiver=e,this.boundary();return}let n=r.duration,a=Or(this.time+n);e.state=`waiting`,this.boundary(),n===0?(e.state=`queued`,this.models.push(e)):(e.wake??=()=>{e.state=`queued`,this.models.push(e)},this.events.push(a,e.wake));return}}runUntil(e){if(this.validity(),this.phase!==`idle`||this.dispatchDepth)throw this.error(`INVALID_CALL_STATE`,`Board is busy`);if(this.status===`faulted`)throw this.error(`BOARD_FAULTED`,`Board is faulted`);let t=Or(e);if(t<this.time)throw RangeError(`Cannot run backwards`);let n=this.time;this.phase=`execute`,this.executionEnd=t;try{if(!this.initialized){this.baseline(),this.initialized=!0;for(let e of this.instances)for(let t of e.processes)t.declaration.kind===`start`&&this.enqueue(t);for(let e of this.jits)this.queueJit(e)}for(let e of this.instances){for(let t of e.channels.values()){if(t.pending.length)for(let e of t.pending.drain())t.incoming.push(e);if(t.receiver&&t.incoming.length){let e=t.receiver;t.receiver=void 0;let n=t.incoming.shift().value;this.events.push(this.time,()=>{e.state=`queued`,e.resumeValue=n,this.models.push(e)})}}for(let t of e.notificationInputs)for(let n of e.processes)n.source?.[0]===t&&this.enqueue(n);e.notificationInputs.clear()}for(;;){for(;this.events.time===this.time;)this.events.pop()();if(this.models.length){let e=this.models.shift(),t=e.resumeValue;if(e.resumeValue=void 0,this.drive(e,t),this.isFaulted)throw this.primary;continue}let e=1/0;if(this.waitingJits.size)for(let n=0;n<this.jits.length;n++){let r=this.jits[n];if(r.active&&!r.stopped&&this.waitingJits.has(r)){if(r.instance.dependenciesCurrent(r.dependencies)){if(r.pollingWait&&r.pollingPeriod>0){let n=Dr-(Dr-r.pollingOrigin)%r.pollingPeriod;n<72e14&&n<t&&(n===this.time?(r.pollingWait=!1,delete r.dependencies,this.waitingJits.delete(r),this.queueJit(r)):e=Math.min(e,n))}}else if(r.pollingWait){r.pollingWait=!1,delete r.dependencies,this.waitingJits.delete(r);let e=r.pollingPeriod>0?(this.time-r.pollingOrigin)%r.pollingPeriod:0;e?this.events.push(Or(this.time+(r.pollingPeriod-e)),()=>this.queueJit(r)):this.queueJit(r)}else if(r.predicate){let e=r.instance.evaluate(()=>r.instance.syncCall(r.predicate));r.dependencies=e.dependencies,e.value===!0&&(delete r.predicate,delete r.dependencies,this.waitingJits.delete(r),this.queueJit(r))}}}if(this.time<t&&this.readyJits.length){if(Zr(this,this.readyJits.shift()),this.isFaulted)throw this.primary}else if(e<this.events.time&&e<=t)this.time=e;else if(this.events.time<=t)this.time=this.events.time;else{this.time=t;break}}let e=this.instances.map(e=>e.captureBatch(n,t));this.phase=`sync`;for(let t=0;t<this.instances.length;t++){let n=this.instances[t];this.current=n;try{Lr(n.adapter.sync(e[t]))}catch(e){throw this.wrap(e,`DEVICE_CALLBACK_FAILED`,`sync`,n)}if(this.isFaulted)throw this.primary}}catch(e){let t=this.wrap(e,`MODEL_EXECUTION_FAILED`,this.phase===`sync`?`sync`:`execute`,this.current);throw this.fault(t),t}finally{this.current=void 0,this.phase=`idle`}}dispose(){if(this.status===`disposed`)return;if(this.phase!==`idle`||this.dispatchDepth)throw this.error(`INVALID_CALL_STATE`,`Board is busy`);let e=this.cleanup();if(e.length)throw this.primary?this.aggregate(this.primary,e):this.aggregate(e[0],e.slice(1))}aggregate(e,t){return new Mr(Object.freeze({...e.diagnostic,related:Object.freeze([...e.related,...t.map(e=>e.diagnostic)])}))}cleanup(){this.phase=`dispose`;for(let e of this.instances)e.valid=!1;let e=[];for(let t of[...this.instances].reverse()){if(t.adapter)try{Lr(t.adapter.dispose())}catch(n){e.push(this.wrap(n,`CLEANUP_FAILED`,`dispose`,t))}for(let n of[...t.resources].reverse())try{n.dispose()}catch(n){e.push(this.wrap(n,`CLEANUP_FAILED`,`dispose`,t))}t.resources.length=0}return this.events.clear(),this.models.clear(),this.readyJits.clear(),this.observations.clear(),this.reactionBatch.length=0,this.plans.length=0,this.skippedPlans.length=0,this.changeObservations.length=0,this.changePrevious.length=0,this.changeCurrent.length=0,this.sampleSlots.clear(),this.listeners.clear(),this.errors.dispose(),this.diagnostics.dispose(),this.status=`disposed`,this.phase=`idle`,e}};function ii(e,t,n){let r=ti.get(e);if(!r)throw zr(`INVALID_CONFIGURATION`,/* @__PURE__ */ TypeError(`Unknown device library`),`assembly`);if(arguments.length>=3&&n===void 0)throw zr(`INVALID_CONFIGURATION`,/* @__PURE__ */ TypeError(`Explicit undefined options`),`assembly`);return new ri(r,t,n??{})}var Y=class extends Error{name=`SimulationRuntimeError`;code;deviceId;constructor(e,t,n={}){super(t,n.cause===void 0?void 0:{cause:n.cause}),this.code=e,this.deviceId=n.deviceId}};function ai(e){return e instanceof Error&&e.message.length>0?e.message:String(e)}let oi=[`level`,`message`];function si(e){return oi.includes(e)?e:void 0}let ci={boolean:`level`,number:`level`,vec2d:`level`,vec3d:`level`,string:`message`,bytes:`message`,\"bytes<rgb565>\":`message`,\"bytes<segments>\":`message`};function li(e){return ci[e]}function ui(e,t){return si(e)??li(t)}let di=[`file`,`inline`,`store`];function fi(e){return typeof e==`string`&&di.includes(e)}function pi(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return typeof t.src==`string`&&fi(t.mode)}function mi(e){if(e.startsWith(`/`))return`must be relative to the project root, not absolute`;if(/^[A-Za-z]:/.test(e))return`must not carry a drive letter`;if(/^[A-Za-z][A-Za-z0-9+.-]*:/.test(e))return`must not be a URL`;if(e.includes(`\\\\`))return`must use POSIX separators`;let t=e.split(`/`).find(e=>e===`..`||e.startsWith(`~`));if(t!==void 0)return`must stay inside the project root (segment \"${t}\")`}function hi(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)?void 0:`must be base64 text`}function gi(e,t){return e===`inline`?hi(t):e===`file`?mi(t):void 0}var _i=class extends Error{diagnostics;constructor(e){super(vi(e)),this.name=`SchematicError`,this.diagnostics=e}get code(){return this.diagnostics[0]?.code}};function vi(e){let t=e.filter(e=>e.severity===`error`),[n,...r]=t.length>0?t:e;if(n===void 0)return`Schematic validation failed.`;let i=n.pointer===void 0||n.pointer===``?``:` at ${n.pointer}`,a=r.length===0?``:` (and ${r.length} more)`;return`${n.code}${i}: ${n.message}${a}`}function yi(e){if(e.some(e=>e.severity===`error`))throw new _i(e)}function bi(e,t){if(typeof e!=`string`)return{ok:!0,value:e};try{return{ok:!0,value:JSON.parse(e)}}catch(e){let n=e instanceof Error?e.message:String(e);return t.push({severity:`error`,code:`json/invalid`,message:`Invalid JSON: ${n}`}),{ok:!1,value:void 0}}}let xi=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Si(e){return xi.test(e)}let Ci={\"builtin:label\":`label`,\"builtin:power\":`power`,\"builtin:ground\":`ground`},wi=/^@[A-Za-z0-9][A-Za-z0-9._+-]*$/,Ti=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,Ei=/^(?:[A-Za-z0-9][A-Za-z0-9._+-]*|-[A-Za-z0-9-]*)$/;function Di(e){let t=e.indexOf(`:`);if(t<=0||t===e.length-1||e.indexOf(`:`,t+1)!==-1)return;let n=e.slice(0,t),r=e.slice(t+1);if(Oi(n)&&Ei.test(r))return{raw:e,packageId:n,deviceId:r}}function Oi(e){if(e.startsWith(`@`)){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;return n!==void 0&&r!==void 0&&wi.test(n)&&Ti.test(r)}return Ti.test(e)}function ki(e){return e===`builtin:text`}function Ai(e){return Ci[e]}function ji(e){switch(Ai(e)){case`label`:return`net-label`;case`power`:return`power`;case`ground`:return`ground`;default:return ki(e)?`text`:`component`}}function Mi(e){return e===`component`}function Ni(e){return e===`net-label`||e===`power`||e===`ground`}function Pi(e){return Mi(ji(e.device))?e.designator??e.id:void 0}function Fi(e){switch(ji(e.device)){case`power`:return e.net??`VCC`;case`ground`:return e.net??`GND`;case`net-label`:return e.net;default:return}}function Ii(e){return e.length===0?``:`/${e.map(e=>e.replace(/~/g,`~0`).replace(/\\//g,`~1`)).join(`/`)}`}function X(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Li(e){return e.some(e=>e.severity===`error`)}function Z(e,t,n,r,i){let a={severity:`error`,code:t,message:n,pointer:Ii(r)};e.push(i===void 0?a:{...a,entity:i})}function Ri(e,t,n,r){for(let i of Object.keys(e))t.includes(i)||Z(r,`schema/unknown-field`,`Unknown field \"${i}\".`,[...n,i])}function zi(e,t,n,r,i={}){let a=[...n,t];if(!Object.prototype.hasOwnProperty.call(e,t)){Z(r,`schema/missing-field`,`Missing required field \"${t}\".`,a);return}let o=e[t];if(typeof o!=`string`)Z(r,`schema/invalid-type`,`Field \"${t}\" must be a string.`,a);else if(i.nonEmpty===!0&&o.length===0)Z(r,`schema/invalid-value`,`Field \"${t}\" must not be empty.`,a);else return o}function Bi(e,t,n,r){let i=[...n,t];if(!Object.prototype.hasOwnProperty.call(e,t)){Z(r,`schema/missing-field`,`Missing required field \"${t}\".`,i);return}let a=e[t];if(typeof a!=`number`)Z(r,`schema/invalid-type`,`Field \"${t}\" must be a number.`,i);else if(!Number.isFinite(a))Z(r,`schema/invalid-value`,`Field \"${t}\" must be a finite number.`,i);else return a}function Vi(e,t,n,r){let i=Bi(e,t,n,r);if(i!==void 0){if(!Number.isInteger(i))Z(r,`schema/invalid-value`,`Field \"${t}\" must be an integer.`,[...n,t]);else return i}}function Hi(e,t,n,r){let i=[...n,t];if(!Object.prototype.hasOwnProperty.call(e,t)){Z(r,`schema/missing-field`,`Missing required field \"${t}\".`,i);return}let a=e[t];if(!Array.isArray(a))Z(r,`schema/invalid-type`,`Field \"${t}\" must be an array.`,i);else return a}function Ui(e,t,n,r){let i=[...n,t];if(!Object.prototype.hasOwnProperty.call(e,t)){Z(r,`schema/missing-field`,`Missing required field \"${t}\".`,i);return}let a=e[t];if(!X(a))Z(r,`schema/invalid-type`,`Field \"${t}\" must be an object.`,i);else return a}function Wi(e,t,n){if(!X(e)){Z(n,`schema/invalid-type`,`Point must be an object.`,t);return}Ri(e,[`x`,`y`],t,n);let r=Bi(e,`x`,t,n),i=Bi(e,`y`,t,n);if(r!==void 0&&i!==void 0)return{x:r,y:i}}function Gi(e,t,n){if(!X(e)){Z(n,`schema/invalid-type`,`Resource reference must be an object.`,t);return}Ri(e,[`src`,`mode`],t,n);let r=zi(e,`src`,t,n,{nonEmpty:!0}),i;if(Object.prototype.hasOwnProperty.call(e,`mode`)?fi(e.mode)?i=e.mode:Z(n,`schema/invalid-value`,`Field \"mode\" must be \"file\", \"inline\" or \"store\".`,[...t,`mode`]):Z(n,`schema/missing-field`,`Missing required field \"mode\".`,[...t,`mode`]),r===void 0||i===void 0)return;let a=gi(i,r);if(a!==void 0)Z(n,`schema/invalid-value`,`Field \"src\" ${a}.`,[...t,`src`]);else return{src:r,mode:i}}function Ki(e,t,n){if(!X(e)){Z(n,`schema/invalid-type`,`Field \"properties\" must be an object.`,t);return}let r=Object.create(null),i=!1;for(let[a,o]of Object.entries(e)){if(a.length===0){Z(n,`schema/invalid-value`,`Property keys must not be empty.`,t),i=!0;continue}let e=[...t,a];if(typeof o==`string`||typeof o==`boolean`)r[a]=o;else if(o===null)r[a]=null;else if(typeof o==`number`){if(!Number.isFinite(o)){Z(n,`schema/invalid-value`,`Property \"${a}\" must be a finite number.`,e),i=!0;continue}r[a]=o}else if(typeof o==`object`&&!Array.isArray(o)){let t=Gi(o,e,n);if(t===void 0){i=!0;continue}r[a]=t}else Z(n,`schema/invalid-value`,`Property \"${a}\" must be a string, finite number, boolean, resource reference or null.`,e),i=!0}return i?void 0:r}function qi(e,t,n){let r=/* @__PURE__ */ new Set;for(let i of e)r.has(i.id)?Z(n,`id/duplicate`,`Duplicate ${t} id \"${i.id}\".`,i.path,{kind:t,id:i.id}):r.add(i.id)}function Ji(e){let t=[],n=bi(e,t);if(!n.ok)throw new _i(t);let r=Yi(n.value,t);if(r===void 0||Li(t))throw new _i(t);return r}function Yi(e,t){if(!X(e)){Z(t,`json/not-object`,`Schematic must be a JSON object.`,[]);return}Ri(e,[`version`,`sheet`],[],t);let n=Xi(e,t),r=Zi(Ui(e,`sheet`,[],t),t);if(n!==void 0&&r!==void 0)return{version:n,sheet:r}}function Xi(e,t){let n=Vi(e,`version`,[],t);if(n!==void 0){if(n!==1)Z(t,`schema/unsupported-version`,`Unsupported version ${n}; expected 1.`,[`version`]);else return 1}}function Zi(e,t){if(e===void 0)return;Ri(e,[`symbols`,`wires`,`junctions`],[`sheet`],t);let n=Hi(e,`symbols`,[`sheet`],t)??[],r=Hi(e,`wires`,[`sheet`],t)??[],i=Hi(e,`junctions`,[`sheet`],t)??[],a=[],o=[];n.forEach((e,n)=>{let r=[`sheet`,`symbols`,String(n)],i=$i(e,r,t);i!==void 0&&(a.push(i),o.push({id:i.id,path:[...r,`id`]}))});let s=[],c=[];r.forEach((e,n)=>{let r=[`sheet`,`wires`,String(n)],i=ta(e,r,t);i!==void 0&&(s.push(i),c.push({id:i.id,path:[...r,`id`]}))});let l=new Set(s.map(e=>e.id)),u=[],d=[];return i.forEach((e,n)=>{let r=[`sheet`,`junctions`,String(n)],i=na(e,r,t);if(i===void 0)return;let a=/* @__PURE__ */ new Set;i.wires.forEach((e,n)=>{let o=[...r,`wires`,String(n)];a.has(e)?Z(t,`junction/duplicate-wire`,`Junction \"${i.id}\" references wire \"${e}\" more than once.`,o,{kind:`junction`,id:i.id}):a.add(e),l.has(e)||Z(t,`junction/unknown-wire`,`Junction \"${i.id}\" references unknown wire \"${e}\".`,o,{kind:`junction`,id:i.id})}),u.push(i),d.push({id:i.id,path:[...r,`id`]})}),qi(o,`symbol`,t),Qi(a,t),qi(c,`wire`,t),qi(d,`junction`,t),{symbols:a,wires:s,junctions:u}}function Qi(e,t){let n=/* @__PURE__ */ new Set;e.forEach((e,r)=>{let i=Pi(e);i!==void 0&&(n.has(i)?Z(t,`symbol/designator-duplicate`,`Reference designator ${JSON.stringify(i)} is used more than once.`,[`sheet`,`symbols`,String(r),`designator`],{kind:`symbol`,id:e.id}):n.add(i))})}function $i(e,t,n){if(!X(e)){Z(n,`schema/invalid-type`,`Symbol must be an object.`,t);return}Ri(e,[`id`,`device`,`x`,`y`,`rotation`,`properties`,`designator`,`net`,`reference`],t,n);let r=ra(e,t,n),i=zi(e,`device`,t,n,{nonEmpty:!0}),a=Bi(e,`x`,t,n),o=Bi(e,`y`,t,n),s=Bi(e,`rotation`,t,n),c=e.properties===void 0?void 0:Ki(e.properties,[...t,`properties`],n),l=e.reference===void 0?void 0:Wi(e.reference,[...t,`reference`],n),u=ea(e,`designator`,i,t,n,Mi),d=ea(e,`net`,i,t,n,Ni);if(i!==void 0){let r=ji(i);Ni(r)&&d===void 0&&e.net===void 0&&Z(n,`symbol/missing-net`,`Symbols of role \"${r}\" must name the net they attach to.`,[...t,`net`]),!Mi(r)&&e.reference!==void 0&&Z(n,`symbol/unsupported-field`,`Symbols of role \"${r}\" carry no reference designator.`,[...t,`reference`])}if(!(r===void 0||i===void 0||a===void 0||o===void 0||s===void 0||e.reference!==void 0&&l===void 0))return{id:r,device:i,x:a,y:o,rotation:s,...c===void 0?{}:{properties:c},...u===void 0?{}:{designator:u},...d===void 0?{}:{net:d},...l===void 0?{}:{reference:l}}}function ea(e,t,n,r,i,a){if(e[t]===void 0||n===void 0)return;let o=ji(n);if(!a(o))Z(i,`symbol/unsupported-field`,`Symbols of role \"${o}\" must not declare \"${t}\".`,[...r,t]);else return zi(e,t,r,i,{nonEmpty:!0})}function ta(e,t,n){if(!X(e)){Z(n,`schema/invalid-type`,`Wire must be an object.`,t);return}Ri(e,[`id`,`points`],t,n);let r=ra(e,t,n),i=Hi(e,`points`,t,n),a=[];if(i!==void 0&&(i.length<2&&Z(n,`wire/invalid-points`,`Wire must contain at least two points.`,[...t,`points`]),i.forEach((e,r)=>{let i=Wi(e,[...t,`points`,String(r)],n);i!==void 0&&a.push(i)})),r!==void 0&&i!==void 0){for(let e=1;e<a.length;e+=1){let r=a[e-1],i=a[e];if(r!==void 0&&i!==void 0&&r.x!==i.x&&r.y!==i.y){Z(n,`wire/not-orthogonal`,`Wire segments must be horizontal or vertical.`,[...t,`points`,String(e)]);return}}return{id:r,points:a}}}function na(e,t,n){if(!X(e)){Z(n,`schema/invalid-type`,`Junction must be an object.`,t);return}Ri(e,[`id`,`x`,`y`,`wires`],t,n);let r=ra(e,t,n),i=Bi(e,`x`,t,n),a=Bi(e,`y`,t,n),o=Hi(e,`wires`,t,n),s=[];if(o!==void 0&&(o.length<2&&Z(n,`schema/invalid-value`,`Junction must reference at least two wires.`,[...t,`wires`]),o.forEach((e,r)=>{let i=[...t,`wires`,String(r)];typeof e==`string`?e.length===0?Z(n,`schema/invalid-value`,`Junction wire reference must not be empty.`,i):s.push(e):Z(n,`schema/invalid-type`,`Junction wire reference must be a string.`,i)})),r!==void 0&&i!==void 0&&a!==void 0&&o!==void 0)return{id:r,x:i,y:a,wires:s}}function ra(e,t,n){let r=zi(e,`id`,t,n,{nonEmpty:!0});if(r!==void 0){if(!Si(r))Z(n,`schema/invalid-value`,`Field \"id\" must be a UUID v4.`,[...t,`id`]);else return r}}function ia(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}function aa(e,t,n=0){return ia(e,t)<=n}function oa(e,t,n,r=0){let i=n.x-t.x,a=n.y-t.y,o=Math.hypot(i,a);if(o===0)return aa(e,t,r);let s=(e.x-t.x)*a-(e.y-t.y)*i;if(Math.abs(s)/o>r)return!1;let c=((e.x-t.x)*i+(e.y-t.y)*a)/(o*o),l=r/o;return c<-l||c>1+l?!1:sa(e,t,n)<=r}function sa(e,t,n){let r=n.x-t.x,i=n.y-t.y,a=r*r+i*i;if(a===0)return ia(e,t);let o=((e.x-t.x)*r+(e.y-t.y)*i)/a,s=o<0?0:o>1?1:o;return ia(e,{x:t.x+s*r,y:t.y+s*i})}function ca(e,t,n=0){if(e.length===1){let[r]=e;return r!==void 0&&aa(r,t,n)}for(let r=1;r<e.length;r+=1){let i=e[r-1],a=e[r];if(i!==void 0&&a!==void 0&&oa(t,i,a,n))return!0}return!1}function la(e){let[t,...n]=e;if(t===void 0)return;let r=t.x,i=t.y,a=t.x,o=t.y;for(let e of n)r=Math.min(r,e.x),i=Math.min(i,e.y),a=Math.max(a,e.x),o=Math.max(o,e.y);return{x:r,y:i,width:a-r,height:o-i}}function ua(e,t){if(e===void 0)return t;if(t===void 0)return e;let n=Math.min(e.x,t.x),r=Math.min(e.y,t.y),i=Math.max(e.x+e.width,t.x+t.width),a=Math.max(e.y+e.height,t.y+t.height);return{x:n,y:r,width:i-n,height:a-r}}function da(e,t){let n=t*Math.PI/180,r=Math.cos(n),i=Math.sin(n);return{x:e.x*r-e.y*i,y:e.x*i+e.y*r}}function fa(e,t){let n=da(t,e.rotation);return{x:e.x+n.x,y:e.y+n.y}}function pa(e,t,n){if(t!==void 0)return la([{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x,y:t.y+t.height},{x:t.x+t.width,y:t.y+t.height}].map(t=>fa(e,t)));let r=Object.values(n).map(t=>fa(e,t));return r.length>0?la(r):{x:e.x,y:e.y,width:0,height:0}}function ma(e,t={}){let n=[],r=t.tolerance??0,{devices:i}=t,{symbols:a,wires:o,junctions:s}=e.sheet,c=[],l;for(let e of a){l=ua(l,{x:e.x,y:e.y,width:0,height:0});let t=Ai(e.device);if(t!==void 0){let n=Fi(e);n!==void 0&&c.push({kind:t,symbolId:e.id,point:{x:e.x,y:e.y},name:n});continue}let r=Di(e.device);if(r===void 0){i!==void 0&&n.push({severity:`error`,code:`device/invalid-reference`,message:`Symbol \"${e.id}\" has an invalid device reference ${JSON.stringify(e.device)}.`,entity:{kind:`symbol`,id:e.id}});continue}if(i===void 0)continue;let a=i.getDeviceSymbol(r);if(i.getDeviceName(r)===void 0)n.push({severity:`error`,code:`device/unresolved`,message:`Symbol \"${e.id}\" references unresolved device ${JSON.stringify(e.device)}.`,entity:{kind:`symbol`,id:e.id}});else if(a!==void 0){l=ua(l,pa(e,a.bounds,a.pins));for(let[t,n]of Object.entries(a.pins)){let r=fa(e,n);c.push({kind:`pin`,symbolId:e.id,pinId:t,point:r}),l=ua(l,{x:r.x,y:r.y,width:0,height:0})}}}for(let e of o)l=ua(l,la(e.points));let u=/* @__PURE__ */ new Map;o.forEach((e,t)=>u.set(e.id,t));let d=o.length,f=Array(d+c.length);for(let e=0;e<f.length;e+=1)f[e]=e;let p=e=>{let t=e;for(;f[t]!==t;){let e=f[t];f[t]=f[e],t=e}return t},m=(e,t)=>{let n=p(e),r=p(t);n!==r&&(f[r]=n)};for(let e of s){let[t,...n]=e.wires.map(e=>u.get(e)).filter(e=>e!==void 0);if(t!==void 0)for(let e of n)m(t,e)}let h=/* @__PURE__ */ new Map;c.forEach((e,t)=>{o.forEach((n,i)=>{if(!ca(n.points,e.point,r))return;m(i,d+t);let a=h.get(i);a===void 0?h.set(i,[t]):a.push(t)})});let g=/* @__PURE__ */ new Map,_=e=>{let t=g.get(e);if(t!==void 0)return t;let n={wires:[],connections:[]};return g.set(e,n),n};o.forEach((e,t)=>{_(p(t)).wires.push(t)}),c.forEach((e,t)=>{_(p(d+t)).connections.push(t)});let v=/* @__PURE__ */ new Map,ee=[];for(let e of ha(g,c,n)){let t=e.wires.length>0||e.connections.length>=2;if(e.connections.length===0||!t)continue;let n=e.name,r=e.connections.map(e=>c[e]).map(e=>{if(e!==void 0)return e.kind===`pin`?{kind:`pin`,symbolId:e.symbolId,pinId:e.pinId}:{kind:e.kind,symbolId:e.symbolId}}).filter(e=>e!==void 0).sort(_a),i={name:n,wireIds:e.wires.map(e=>o[e]?.id).filter(e=>e!==void 0).sort(),members:r};ee.push(i);for(let t of e.connections)v.set(t,i)}let y=[];c.forEach((e,t)=>{if(e.kind!==`pin`)return;let n=v.get(t);y.push({symbolId:e.symbolId,pinId:e.pinId,position:e.point,open:n===void 0,netName:n?.name??null})}),y.sort((e,t)=>e.symbolId.localeCompare(t.symbolId)||e.pinId.localeCompare(t.pinId));let b=[];return o.forEach((e,t)=>{let n=[{end:`start`,point:e.points[0]},{end:`end`,point:e.points[e.points.length-1]}];for(let{end:i,point:a}of n){if(a===void 0)continue;let n=(h.get(t)??[]).some(e=>{let t=c[e];return t!==void 0&&aa(t.point,a,r)}),o=s.some(t=>t.wires.includes(e.id)&&aa({x:t.x,y:t.y},a,r));!n&&!o&&b.push({wireId:e.id,end:i,point:a})}}),b.sort((e,t)=>e.wireId.localeCompare(t.wireId)||e.end.localeCompare(t.end)),yi(n),{nets:ee.sort((e,t)=>va(e.name,t.name)||_a(e.members[0],t.members[0])),pins:y,danglingWireEnds:b,bounds:l}}function ha(e,t,n){let r=/* @__PURE__ */ new Map,i=[];for(let a of e.values()){let e=a.connections.map(e=>t[e]).filter(e=>e!==void 0&&e.kind!==`pin`).map(e=>e.name).sort();e.length>1&&n.push({severity:`error`,code:`net/naming-conflict`,message:`Net has conflicting names: ${e.map(e=>JSON.stringify(e)).join(`, `)}.`});let o=e.length===1?e[0]:null;if(o===null||a.wires.length===0&&a.connections.length<2){i.push({wires:a.wires,connections:a.connections,name:o});continue}let s=r.get(o);if(s===void 0){let e={wires:[...a.wires],connections:[...a.connections]};r.set(o,e),i.push({...e,name:o})}else s.wires.push(...a.wires),s.connections.push(...a.connections)}return i}let ga=[`label`,`power`,`ground`,`pin`];function _a(e,t){if(e===void 0||t===void 0)return e===void 0?t===void 0?0:1:-1;if(e.kind!==t.kind)return ga.indexOf(e.kind)-ga.indexOf(t.kind);let n=e.symbolId.localeCompare(t.symbolId);if(n!==0)return n;let r=e.kind===`pin`?e.pinId:``,i=t.kind===`pin`?t.pinId:``;return r.localeCompare(i)}function va(e,t){return e===null||t===null?e===null?t===null?0:1:-1:e.localeCompare(t)}function ya(e,t={}){let n=t.pinPitch??10,r=t.stubLength??10,i=t.minWidth??60,a=t.minHeight??40,o=t.horizontalPadding??10,s=t.verticalPadding??10,c=t.characterWidth??5.5,l=t.labelCharacterWidth??4.5,u=t.nameGap??12,d=t.labelInset??10,f={left:[],right:[],top:[],bottom:[]};for(let[t,n]of Object.entries(e.pins))f[n.side??`left`].push(t);let p=Math.max(f.left.length,f.right.length),m=Math.max(f.top.length,f.bottom.length),h=Math.max(a,s*2+Math.max(p-1,0)*n+n,2*(1*c+n/2+d+xa(f,l))),g=Math.max(i,o*2+Math.max(m-1,0)*n+n),_=(ba(f.left)+ba(f.right))*l+e.name.length*c+o*2+u*2,v=Math.ceil(Math.max(g,_)/n)*n,ee=Math.ceil(h/n)*n,y={x:-v/2,y:-ee/2,width:v,height:ee},b=Object.create(null),te=(e,t)=>{let i=-((e.length-1)*n)/2;e.forEach((e,a)=>{let o=i+a*n,s=t===`left`?y.x-r:y.x+y.width+r;b[e]={x:s,y:o,side:t}})};te(f.left,`left`),te(f.right,`right`);let x=(e,t)=>{let i=-((e.length-1)*n)/2;e.forEach((e,a)=>{let o=i+a*n,s=t===`top`?y.y-r:y.y+y.height+r;b[e]={x:o,y:s,side:t}})};return x(f.top,`top`),x(f.bottom,`bottom`),{name:e.name,pins:b,bounds:y}}function ba(e){return e.reduce((e,t)=>Math.max(e,t.length),0)}function xa(e,t){return Math.max(ba(e.top),ba(e.bottom))*t/2}let Q=(e,t,n)=>{t.push({severity:`error`,code:`device/invalid-description`,pointer:e,message:n})},Sa=(e,t,n)=>{typeof e!=`string`&&Q(t,n,`Expected a string.`)},Ca=(e,t,n)=>{(typeof e!=`string`||e.length===0)&&Q(t,n,`Expected a nonempty string.`)},wa=(e,t,n)=>{(typeof e!=`number`||!Number.isFinite(e))&&Q(t,n,`Expected a finite number.`)},Ta=(e,t,n)=>{wa(e,t,n),typeof e==`number`&&e<=0&&Q(t,n,`Expected a positive number.`)},Ea=(e,t,n)=>{typeof e!=`boolean`&&Q(t,n,`Expected a boolean.`)},Da=(...e)=>(t,n,r)=>{e.includes(t)||Q(n,r,`Expected one of ${e.join(`, `)}.`)},Oa=e=>e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`),$=(e,t=[])=>(n,r,i)=>{if(!X(n))Q(r,i,`Expected an object.`);else{for(let e of t)Object.hasOwn(n,e)||Q(`${r}/${Oa(e)}`,i,`Required field is missing.`);for(let[t,a]of Object.entries(n)){let n=Object.hasOwn(e,t)?e[t]:void 0;n===void 0?Q(`${r}/${Oa(t)}`,i,`Unknown field.`):n(a,`${r}/${Oa(t)}`,i)}}},ka=e=>(t,n,r)=>{if(!X(t))Q(n,r,`Expected a map.`);else for(let[i,a]of Object.entries(t))e(a,`${n}/${Oa(i)}`,r)},Aa=(e,t,n)=>{!Array.isArray(e)||e.length!==2?Q(t,n,`Expected two coordinates.`):e.forEach((e,r)=>wa(e,`${t}/${r}`,n))},ja=(e,t,n)=>{Array.isArray(e)?(e.forEach((e,r)=>Ca(e,`${t}/${r}`,n)),new Set(e).size!==e.length&&Q(t,n,`Values must be unique.`)):Q(t,n,`Expected an array.`)},Ma=Da(`left`,`center`,`right`),Na=$({visible:Ea,position:Aa,align:Ma},[`visible`]),Pa=(e,t,n)=>{let r={kind:Da(`number`,`text`,`textarea`,`checkbox`,`file`,`select`)};X(e)&&e.kind===`number`&&Object.assign(r,{min:wa,max:wa,step:Ta}),X(e)&&e.kind===`file`&&(r.extensions=(e,t,n)=>{ja(e,t,n),Array.isArray(e)&&e.forEach((e,r)=>{typeof e==`string`&&!/^\\.[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*$/.test(e)&&Q(`${t}/${r}`,n,`Expected a dotted filename extension.`)})},r.maxSize=(e,t,n)=>{Ta(e,t,n),typeof e==`number`&&!Number.isInteger(e)&&Q(t,n,`Expected an integer byte count.`)}),X(e)&&e.kind===`select`&&(r.labels=ka(Sa)),$(r,[`kind`])(e,t,n)},Fa=(e,t,n)=>{$({type:Da(`number`,`boolean`,`string`,`enum`,`bytes`),required:Ea,nullable:Ea,default:()=>{},enumName:Ca,values:ja,title:Sa,description:Sa,unit:Sa,group:Sa,order:(e,t,n)=>{(typeof e!=`number`||!Number.isInteger(e)||e<0)&&Q(t,n,`Expected a nonnegative integer.`)},editor:Pa},[`type`,`required`])(e,t,n),X(e)&&(e.required===!0&&Object.hasOwn(e,`default`)&&Q(`${t}/default`,n,`Required properties cannot declare defaults.`),e.type===`enum`?((!Object.hasOwn(e,`enumName`)||!Object.hasOwn(e,`values`))&&Q(t,n,`Enum properties require enumName and values.`),Array.isArray(e.values)&&e.values.length===0&&Q(`${t}/values`,n,`Enum values cannot be empty.`)):(Object.hasOwn(e,`enumName`)||Object.hasOwn(e,`values`))&&Q(t,n,`Only enum properties declare enumName and values.`))},Ia=(e,t,n)=>{let r={type:Da(`line`,`polyline`,`rect`,`circle`,`arc`,`text`),fill:Da(`none`,`foreground`,`background`),strokeWidth:Ta},i={line:{fields:{from:Aa,to:Aa},required:[`from`,`to`]},polyline:{fields:{points:(e,t,n)=>{!Array.isArray(e)||e.length<2?Q(t,n,`Expected at least two points.`):e.forEach((e,r)=>Aa(e,`${t}/${r}`,n))},closed:Ea},required:[`points`]},rect:{fields:{x:wa,y:wa,width:Ta,height:Ta},required:[`x`,`y`,`width`,`height`]},circle:{fields:{center:Aa,radius:Ta},required:[`center`,`radius`]},arc:{fields:{center:Aa,radius:Ta,startAngle:wa,sweepAngle:(e,t,n)=>{wa(e,t,n),typeof e==`number`&&(e===0||e<-360||e>360)&&Q(t,n,`Sweep must be nonzero and within [-360, 360].`)}},required:[`center`,`radius`,`startAngle`,`sweepAngle`]},text:{fields:{position:Aa,text:Sa,align:Ma,fontSize:Ta},required:[`position`,`text`]}},a=X(e)&&typeof e.type==`string`&&Object.hasOwn(i,e.type)?i[e.type]:void 0;$({...r,...a?.fields},[`type`,...a?.required??[]])(e,t,n)},La=(e,t,n)=>{Array.isArray(e)?e.forEach((e,r)=>Ia(e,`${t}/${r}`,n)):Q(t,n,`Expected graphics array.`)},Ra=$({designator:$({position:Aa,align:Ma},[`position`])}),za=$({kind:Da(`device`),id:(e,t,n)=>{(typeof e!=`string`||!/^[A-Za-z0-9-]+$/.test(e))&&Q(t,n,`Invalid device id.`)},version:Ca,displayName:Ca,description:Ca,license:Ca,tags:ja,templates:ja,recommends:$({widgets:ja}),designatorPrefix:(e,t,n)=>{(typeof e!=`string`||!/^\\S+$/.test(e))&&Q(t,n,`Expected a nonempty prefix without whitespace.`)},properties:ka(Fa),pins:ka($({label:Sa,description:Sa,group:Sa})),ports:ka($({direction:Da(`input`,`output`),type:Da(`boolean`,`number`,`string`,`vec2d`,`vec3d`,`bytes`,`bytes<rgb565>`,`bytes<segments>`),title:Sa,description:Sa,delivery:Da(`level`,`message`)},[`direction`,`type`])),symbol:$({bounds:$({x:wa,y:wa,width:Ta,height:Ta},[`x`,`y`,`width`,`height`]),graphics:La,pins:ka($({position:Aa,direction:Da(`left`,`right`,`up`,`down`),label:Na},[`position`,`direction`])),annotations:Ra},[`bounds`,`graphics`,`pins`])},[`kind`,`id`,`version`,`displayName`]);function Ba(e){let t=[],n=bi(e,t);if(n.ok&&za(n.value,``,t),t.length>0)throw new _i(t);return n.value}function Va(e){let t=e.symbol,n=t===void 0?ya({name:e.displayName,pins:Object.fromEntries(Object.keys(e.pins??{}).map(e=>[e,{}]))}):void 0,r=Object.create(null);for(let[i,a]of Object.entries(t?.pins??n.pins)){let n=e.pins?.[i]?.label;if(t!==void 0){let e=t.pins[i];r[i]={x:e.position[0],y:e.position[1],side:e.direction===`up`?`top`:e.direction===`down`?`bottom`:e.direction,...e.label===void 0?{}:{label:e.label},...n===void 0?{}:{displayName:n}}}else r[i]={...a,...n===void 0?{}:{displayName:n}}}return t===void 0?{...n,pins:r}:{name:e.displayName,bounds:t.bounds,graphics:t.graphics,pins:r,...t.annotations===void 0?{}:{annotations:t.annotations}}}async function Ha(e,t,n){if(!qa(e)||!Array.isArray(e.devices))throw new Y(`invalid-input`,`Expected schematic and devices`);let r=Ji(e.schematic),i=Ga(e.assets),a=Wa(e.voltageReferences),o=/* @__PURE__ */ new Map;for(let t of e.devices){if(!qa(t)||typeof t.id!=`string`||Di(t.id)===void 0||o.has(t.id)||typeof t.code!=`string`||t.code.trim().length===0)throw new Y(`invalid-input`,`Expected unique device ids and self-contained ESM code`);let e;try{e=structuredClone(Ba(t.definition))}catch(e){throw new Y(`invalid-device`,`Invalid metadata for \"${t.id}\": ${ai(e)}`,{cause:e})}if(e.id!==Di(t.id).deviceId)throw new Y(`invalid-device`,`Metadata id does not match \"${t.id}\"`,{deviceId:t.id});o.set(t.id,{definition:e,code:t.code})}let s=/* @__PURE__ */ new Map,c=r.sheet.symbols.filter(e=>ji(e.device)===`component`);for(let e of c){if(s.has(e.device))continue;let r=o.get(e.device);if(r===void 0)throw new Y(`unresolved-device`,`Missing prepared device \"${e.device}\"`,{deviceId:e.device});n();try{let i=await t(r.code,e.device);if(n(),!qa(i)||!Object.hasOwn(i,`model`)||!Object.hasOwn(i,`create`)||typeof i.create!=`function`)throw TypeError(`SDK device modules must export named model and synchronous create`);let a=ke(i.model),o=a.declarations.filter(e=>e.kind===`pin`).map(e=>e.name),c=r.definition.pins;if(c!==void 0&&!Ka(Object.keys(c),o))throw TypeError(`Metadata pins do not match model pins`);let l={...r.definition,pins:c??Object.fromEntries(o.map(e=>[e,{}]))},u=Va(l);if(!Ka(Object.keys(u.pins),o))throw TypeError(`Symbol pins do not match model pins`);s.set(e.device,{id:e.device,definition:l,model:a,create:i.create,topics:new Map(Object.entries(l.ports??{}).map(([e,t])=>[e,{port:e,...t,delivery:ui(t.delivery,t.type)}]))})}catch(t){throw n(),new Y(`invalid-device`,`Device \"${e.device}\" failed to load: ${ai(t)}`,{deviceId:e.device,cause:t})}}let l=ma(r,{devices:{getDeviceName:e=>s.get(e.raw)?.definition.displayName,getDeviceSymbol:e=>{let t=s.get(e.raw);return t===void 0?void 0:Va(t.definition)}}}),u=r.sheet.symbols.length===0&&r.sheet.wires.length===0&&r.sheet.junctions.length===0;for(let e of a.keys())if(!u&&!l.nets.some(t=>t.name===e))throw new Y(`invalid-input`,`Voltage reference names missing schematic net \"${e}\"`);return{instances:c.map(e=>({symbol:e.id,device:s.get(e.device)})),description:{instances:c.map(e=>({id:e.id,type:e.id,props:Ua(e,s.get(e.device),i.get(e.id))})),nets:l.nets.map((e,t)=>{let n=e.name===null?void 0:a.get(e.name),r=e.members.some(e=>e.kind===`ground`);if(r&&n!==void 0&&n!==0)throw new Y(`invalid-input`,`Conflicting voltage references on ground net \"${e.name}\": 0 and ${n}`);let i=r?0:n;return{id:`net:${t}`,pins:e.members.flatMap(e=>e.kind===`pin`?[{instance:e.symbolId,pin:e.pinId}]:[]),...i===void 0?{}:{voltage:i}}})}}}function Ua(e,t,n){let r=Object.create(null);for(let[e,n]of Object.entries(t.definition.properties??{}))Object.hasOwn(n,`default`)&&(r[e]=n.default);Object.assign(r,e.properties);let i=Object.create(null);for(let[a,o]of Object.entries(r))if(pi(o)){let r=gi(o.mode,o.src);if(r!==void 0)throw new Y(`invalid-input`,r,{deviceId:t.id});let s=n?.get(o.src);if(s===void 0)throw new Y(`unresolved-asset`,`Symbol \"${e.id}\" is missing resource \"${o.src}\"`,{deviceId:t.id});i[a]=new Uint8Array(s)}else if(o instanceof Uint8Array)i[a]=new Uint8Array(o);else if(o===null||typeof o==`number`||typeof o==`boolean`||typeof o==`string`)i[a]=o;else throw new Y(`invalid-input`,`Unsupported property \"${e.id}.${a}\"`,{deviceId:t.id});return i}function Wa(e){if(e===void 0)return/* @__PURE__ */ new Map;if(!qa(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new Y(`invalid-input`,`Expected a plain voltageReferences map`);let t=/* @__PURE__ */ new Map;for(let n of Reflect.ownKeys(e)){let r=typeof n==`string`?e[n]:void 0;if(typeof n!=`string`||n.trim().length===0||typeof r!=`number`||!Number.isFinite(r))throw new Y(`invalid-input`,`Expected voltageReferences with nonempty net names and finite numeric voltages`);t.set(n,r)}return t}function Ga(e){let t=/* @__PURE__ */ new Map;if(e===void 0)return t;if(!qa(e))throw new Y(`invalid-input`,`Expected assets keyed by symbol id`);for(let[n,r]of Object.entries(e)){if(!qa(r))throw new Y(`invalid-input`,`Expected asset entries keyed by src`);let e=/* @__PURE__ */ new Map;for(let[t,n]of Object.entries(r)){if(!t||!(n instanceof Uint8Array))throw new Y(`invalid-input`,`Resource bytes must be Uint8Array`);e.set(t,new Uint8Array(n))}t.set(n,e)}return t}function Ka(e,t){return e.length===t.length&&e.every(e=>t.includes(e))}function qa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ja(e={}){let n=new t,r=new t,i=[],a=/* @__PURE__ */ new Map,o,s=b(0),c=!1,l=0,f=()=>{if(c)throw new Y(`disposed`,`Simulation runtime has been disposed`)},m=e=>{for(let t of e.outputs.splice(0)){let r=e.prepared.instances.find(e=>e.symbol===t.symbol).device.topics.get(t.port),i=u(t.symbol,t.port);if(r.delivery===`level`){if(a.has(i)&&d(a.get(i),t.payload))continue;n.hasListeners&&a.set(i,h(t.payload))}n.fire({target:{symbol:t.symbol,port:t.port},payload:h(t.payload),simTime:s})}for(let t of e.diagnostics.splice(0))r.fire(t.runtimeCode===void 0?{...t,simTime:s}:t)},g=e=>{if(e!==void 0)try{e.board.dispose()}catch(e){r.fire({code:`board/diagnostic`,symbol:``,message:ai(e),simTime:s,phase:`dispose`})}finally{for(let t of e.subscriptions)t.dispose()}},_=e=>{let t=o;o=e,i.length=0,a.clear(),s=b(0),g(t)};return{async load(t){f();let n=++l,r=await Ha(t,e.importer??Qa,f);f(),n===l&&_(Ya(r))},async reset(){f(),++l,o===void 0?(i.length=0,a.clear(),s=b(0)):_(Ya(o.prepared))},async tick(e){if(f(),!Number.isSafeInteger(e)||e<=0)throw TypeError(`tick expects a positive integer dt in picoseconds`);let t=te(s,e),n=o;if(n===void 0)return s=t,{simTime:s,executed:0};try{for(let e of i.splice(0))n.board.topics.publish(Za(e.symbol,e.port),e.payload);n.board.runUntil(t)}finally{s=b(n.board.time),m(n)}return{simTime:s,executed:1}},async deliver(e){if(f(),typeof e!=`object`||!e||e.target===null||typeof e.target!=`object`||typeof e.target.symbol!=`string`||typeof e.target.port!=`string`)throw new Y(`invalid-input`,`Expected a message with string symbol and port`);if(o===void 0)throw new Y(`not-loaded`,`No simulation loaded`);let{symbol:t,port:n}=e.target,r=o.inputs.get(u(t,n));if(r===void 0||!p(r.type,e.payload))throw new Y(`invalid-input`,`Unknown input or invalid payload for ${t}.${n}`);if(r.delivery===`level`){let e=i.findIndex(e=>e.symbol===t&&e.port===n);e!==-1&&i.splice(e,1)}i.push({symbol:t,port:n,payload:h(e.payload)})},onDidPublish:n.event,onDidDiagnostic:r.event,async dispose(){c||(c=!0,++l,i.length=0,a.clear(),g(o),o=void 0,n.dispose(),r.dispose())}}}function Ya(e){let t=[],n=[],r=/* @__PURE__ */ new Map,i=ii(ni(e.instances.map(e=>{for(let t of e.device.topics.values())t.direction===`input`&&r.set(u(e.symbol,t.port),t);return{id:e.symbol,model:e.device.model,create:r=>e.device.create({...r,topics:Xa(r.topics,e,t,n)})}})),{...e.description,instances:e.description.instances.map(e=>({...e,props:Object.fromEntries(Object.entries(e.props??{}).map(([e,t])=>[e,t instanceof Uint8Array?new Uint8Array(t):t]))}))}),a=(e,t)=>{n.push({code:t?e.phase===`topic`?`device/input-failed`:e.phase===`sync`?`device/output-failed`:`board/error`:`board/diagnostic`,symbol:e.instanceId??``,message:e.message,simTime:b(e.time??i.time),runtimeCode:e.code,phase:e.phase})};return{prepared:e,board:i,inputs:r,outputs:t,diagnostics:n,subscriptions:[i.onDidError(e=>a(e,!0)),i.onDidDiagnostic(e=>a(e,!1))]}}function Xa(e,t,n,r){let i=`${encodeURIComponent(t.symbol)}/`;return{onDidReceive:((n,r,a)=>e.onDidReceive(e=>{if(!e.topic.startsWith(i))return;let a=e.topic.slice(i.length);if(t.device.topics.get(a)?.direction===`input`)return n.call(r,{topic:a,payload:h(e.payload)})},void 0,a)),publish(i,a){let o=t.device.topics.get(i);if(o?.direction!==`output`||!p(o.type,a)){r.push({code:`device/output-failed`,symbol:t.symbol,port:i,message:`Unknown output or invalid payload for ${t.symbol}.${i}`,simTime:b(0)});return}let s=h(a);e.publish(Za(t.symbol,i),s),n.push({symbol:t.symbol,port:i,payload:s})}}}function Za(e,t){return`${encodeURIComponent(e)}/${t}`}function Qa(e){if(typeof URL>`u`||typeof URL.createObjectURL!=`function`||typeof Blob>`u`)return Promise.reject(/* @__PURE__ */ Error(`Inject a module importer outside a browser worker`));let t=URL.createObjectURL(new Blob([e],{type:`text/javascript`}));return import(\n/* @vite-ignore */\nt).finally(()=>URL.revokeObjectURL(t))}function $a(e,t,n){let r=no(t),i=e.register(g,r,{transfer:v}),a=n===void 0?void 0:n.register(_,{deliver:r.deliver,onDidPublish:r.onDidPublish},{transfer:v}),o=!1;return{dispose(){if(!o){o=!0;try{a?.dispose()}finally{i.dispose()}}}}}function eo(e,t={}){let n=a(e),r=Ja(to(t)),i=t.ports??[],o=i[0],s=o===void 0?void 0:a(o),c=$a(n,r,s),l=!1;return{rpc:n,ports:i,runtime:r,async dispose(){if(!l){l=!0;try{c.dispose(),await r.dispose()}finally{s?.dispose(),n.dispose(),e.close();for(let e of i)e.close()}}}}}function to(e){return{...e.importer===void 0?{}:{importer:e.importer}}}function no(e){return{load:t=>e.load(t),reset:()=>e.reset(),tick:t=>e.tick(t),deliver:t=>e.deliver(t),onDidPublish:t=>{let n=e.onDidPublish(e=>t(ro(e)));return()=>n.dispose()},onDidDiagnostic(t){let n=e.onDidDiagnostic(t);return()=>n.dispose()},dispose:()=>e.dispose()}}function ro(e){let t=m(e.payload);return t===e.payload?e:{...e,payload:t}}globalThis.addEventListener(`message`,function e(t){let[n,...r]=t.ports;n!==void 0&&(globalThis.removeEventListener(`message`,e),eo(n,{ports:r}))})})();";
6
+ var simulation_runtime_default = "(function(){function e(e){let t=!1;return{dispose(){t||(t=!0,e())}}}var t=class{#e=/* @__PURE__ */ new Set;#t=!1;event=(t,n,r)=>{if(this.#t)return e(()=>{});let i={listener:t,thisArgs:n};this.#e.add(i);let a=e(()=>{this.#e.delete(i)});return r?.push(a),a};get hasListeners(){return this.#e.size>0}fire(e){if(!this.#t)for(let t of[...this.#e])t.listener.call(t.thisArgs,e)}dispose(){this.#t||(this.#t=!0,this.#e.clear())}};function n(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(t.kind===`close`)return!0;if(!Number.isSafeInteger(t.id)||t.id<=0)return!1;switch(t.kind){case`call`:case`listen`:return typeof t.service==`string`&&t.service.length>0&&typeof t.member==`string`&&t.member.length>0&&Array.isArray(t.args)&&(t.kind!==`listen`||t.args.length===0);case`unlisten`:return!0;case`result`:return Object.hasOwn(t,`value`);case`error`:case`subscription-error`:return typeof t.name==`string`&&typeof t.message==`string`;case`event`:return Array.isArray(t.args);default:return!1}}function r(e,t){return Object.assign(Error(t),{name:e})}function i(e,t){if([`constructor`,`__proto__`,`prototype`,`then`].includes(t))throw r(`MethodNotFound`,`Method is not exposed: ${t}`);for(let n=e;n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(e){if(typeof e.value==`function`)return e.value;break}}throw r(`MethodNotFound`,`Method is not callable: ${t}`)}function a(a,l={}){let u=l,d=c(u.timeoutMs??0),f=/* @__PURE__ */ new Map,p=/* @__PURE__ */ new Map,m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Map,g=new t,_=new t,v=0,y=0,b=!1;function x(e){let t=o(e);try{u.onError?.(t)}catch{}g.fire(t)}function ee(){if(b)throw r(`RpcDisconnectedError`,`RPC endpoint is closed`)}function te(){if(v===2**53-1)throw RangeError(`RPC request IDs exhausted`);return++v}function S(e,t){ee(),a.postMessage(e,t?[...t]:void 0)}function C(e){let t=p.get(e);return p.delete(e),t?.timer!==void 0&&clearTimeout(t.timer),t}function w(e,t,n){return new Promise((i,a)=>{let s=t>0?setTimeout(()=>{C(e.id)?.reject(r(`RpcTimeoutError`,`RPC ${e.service}.${e.member} timed out`))},t):void 0;p.set(e.id,{resolve:i,reject:a,timer:s});try{S(e,n)}catch(t){C(e.id)?.reject(o(t))}})}function ne(e){let t=h.get(e);h.delete(e);try{t?.stop?.()}catch(e){x(e)}}function T(e,t,n){if(b)return;let r=o(n);try{S({kind:e,id:t,name:r.name,message:r.message})}catch(e){x(e),re()}}function E(){if(!b){b=!0,a.removeEventListener(`message`,ae),a.removeEventListener(`close`,E),a.removeEventListener(`messageerror`,re);for(let e of p.keys())C(e)?.reject(r(`RpcDisconnectedError`,`RPC endpoint is closed`));m.clear();for(let e of h.keys())ne(e);f.clear(),_.fire(void 0),_.dispose(),g.dispose()}}function re(){if(!b){try{S({kind:`close`})}catch(e){x(e)}E()}}async function ie(e){try{let t=f.get(e.service);if(!t)throw r(`ServiceNotFound`,`Unknown service: ${e.service}`);let n=t.implementation,a=i(n,e.member);if(e.kind===`listen`){if(!/^onDid[A-Z]/.test(e.member))throw r(`InvalidSubscription`,`Event members must start with onDid`);let i={registration:t,stop:void 0};h.set(e.id,i);let o=a.call(n,(...n)=>{if(!(b||h.get(e.id)!==i))try{S({kind:`event`,id:e.id,args:n},t.options.transfer?.(e.member,n))}catch(t){ne(e.id),T(`subscription-error`,e.id,t)}});if(typeof o!=`function`)throw r(`InvalidSubscription`,`Event registration must return an unsubscribe function`);i.stop=o,h.get(e.id)!==i&&i.stop(),b||S({kind:`result`,id:e.id,value:void 0})}else{if(/^onDid[A-Z]/.test(e.member))throw r(`InvalidCall`,`Event members require a subscription`);let i=await a.apply(n,e.args);b||S({kind:`result`,id:e.id,value:i},t.options.transfer?.(e.member,i))}}catch(t){e.kind===`listen`&&ne(e.id),T(`error`,e.id,t)}}function ae(e){let t=e.data;if(!n(t))x(r(`RpcProtocolError`,`Malformed RPC message`));else switch(t.kind){case`call`:case`listen`:if(t.id<=y){x(r(`RpcProtocolError`,`Request IDs must increase`));return}y=t.id,ie(t);break;case`unlisten`:ne(t.id);break;case`result`:C(t.id)?.resolve(t.value);break;case`error`:C(t.id)?.reject(r(t.name,t.message));break;case`subscription-error`:{let e=r(t.name,t.message),n=m.delete(t.id),i=C(t.id);i?i.reject(e):n&&x(e);break}case`event`:try{m.get(t.id)?.(...t.args)}catch(e){x(e)}break;case`close`:E()}}return a.addEventListener(`message`,ae),a.addEventListener(`close`,E),a.addEventListener(`messageerror`,re),a.start?.(),{register(t,n,i={}){ee();let a=s(t);if(typeof n!=`object`||!n)throw TypeError(`RPC services must be objects`);if(f.has(a))throw Error(`Service already registered: ${a}`);let o={implementation:n,options:i};return f.set(a,o),e(()=>{if(f.get(a)===o){f.delete(a);for(let[e,t]of h)t.registration===o&&(ne(e),T(`subscription-error`,e,r(`ServiceUnregistered`,`Service unregistered: ${a}`)))}})},getProxy(t,n={}){let r=s(t),i=c(n.timeoutMs??d),a=/* @__PURE__ */ new Map;return new Proxy(Object.create(null),{get(t,o){if(typeof o==`string`&&o!==`then`)return a.has(o)||a.set(o,/^onDid[A-Z]/.test(o)?t=>{if(ee(),typeof t!=`function`)throw TypeError(`Expected an event listener`);let n=te();m.set(n,t),w({kind:`listen`,id:n,service:r,member:o,args:[]},i).catch(e=>{if(m.delete(n),!b)try{S({kind:`unlisten`,id:n})}catch(e){x(e)}x(e)});let a=e(()=>{if(m.delete(n)&&(C(n)?.resolve(void 0),!b))try{S({kind:`unlisten`,id:n})}catch(e){x(e)}});return()=>a.dispose()}:async(...e)=>(ee(),w({kind:`call`,id:te(),service:r,member:o,args:e},i,n.transfer?.(o,e)))),a.get(o)}})},onDidError:(e,t,n)=>g.event(n=>{try{e.call(t,n)}catch{}},void 0,n),onDidClose:(t,n,r)=>b?(t.call(n,void 0),e(()=>{})):_.event(e=>{try{t.call(n,e)}catch(e){x(e)}},void 0,r),dispose:re}}function o(e){return e instanceof Error?e:Error(String(e))}function s(e){if(typeof e!=`string`||e.length===0)throw TypeError(`RPC service name must be nonempty`);return e}function c(e){if(!Number.isSafeInteger(e)||e<0||e>2147483647)throw RangeError(`RPC timeout must be an integer between 0 and 2147483647`);return e}function l(e){if(typeof e!=`string`||e.length===0)throw TypeError(`RPC service name must be nonempty`);return e}function u(e,t){if(typeof e!=`object`||!e||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Expected a plain data object`);for(let n of Reflect.ownKeys(e)){if(!(`value`in Object.getOwnPropertyDescriptor(e,n)))throw TypeError(`Accessor properties are not allowed`);if(typeof n!=`string`||t&&!t.includes(n))throw TypeError(`Unknown field ${String(n)}`)}}function d(e,t=`value`){if(typeof e!=`number`||!Number.isFinite(e))throw TypeError(`${t} must be finite`);return e}function f(e,t=`value`){if(typeof e!=`number`||!Number.isSafeInteger(e))throw TypeError(`${t} must be a safe integer`);return e}function p(e,t=`value`){let n=f(e,t);if(n<0)throw RangeError(`${t} must be nonnegative`);return n}function m(e){if(typeof e!=`string`||e.length===0)throw TypeError(`Expected a nonempty identifier`);return e}function h(e,t,n){let r=p(t,`offset`),i=p(n,`length`);if(r>e.length||i>e.length-r)throw RangeError(`Memory range is out of bounds`);return r}function g(e,t){if(e===t||typeof e==`number`&&typeof t==`number`&&Number.isNaN(e)&&Number.isNaN(t))return!0;if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&g(e[n],t[n]))}function _(e){return typeof e!=`object`||!e?e:e instanceof Uint8Array?e.slice():Object.freeze(Array.isArray(e)?e.map(_):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,_(t)])))}let v=/* @__PURE__ */ new WeakSet;function y(e){return typeof e==`object`&&!!e&&v.has(e)}function b(e,t=()=>{}){let n=Object.freeze({get length(){return t(),e.length},get byteLength(){return t(),e.length},slice(n,r){return t(),e.slice(n,r)},*[Symbol.iterator](){for(let n=0;n<e.length;n++)t(),yield e[n];t()}}),r=new Proxy(n,{get(n,r,i){return t(),typeof r==`string`&&/^(0|[1-9]\\d*)$/.test(r)?e[Number(r)]:Reflect.get(n,r,i)},set(){throw TypeError(`Bytes are read-only`)},defineProperty(){throw TypeError(`Bytes are read-only`)}});return v.add(r),r}function x(e,t,n,r=!1){if(e.kind===`optional`)return t===null?null:x(e.inner,t,n,r);switch(e.kind){case`number`:if(typeof t!=`number`)throw TypeError(`Expected number`);if(r&&!Number.isFinite(t))throw TypeError(`Property must be finite`);return t;case`bool`:if(typeof t!=`boolean`)throw TypeError(`Expected boolean`);return t;case`string`:if(typeof t!=`string`)throw TypeError(`Expected string`);return t;case`bytes`:if(!(t instanceof Uint8Array))throw TypeError(`Expected Uint8Array`);return t.slice();case`enum`:{let r=e.name===`Logic`?[`low`,`high`,`unknown`]:e.name===`SampleStatus`?[`valid`,`floating`]:e.name===`Overflow`?[`drop_new`,`drop_oldest`,`error`]:n.get(e.name)?.members;if(typeof t!=`string`||!r?.includes(t))throw TypeError(`Invalid ${e.name} member`);return t}case`record`:{u(t);let r=n.get(e.name);return Object.freeze(Object.fromEntries(r.fields.map(e=>[e.name,x({kind:e.type},t[e.name],n)])))}case`sample`:case`intent`:return t}}function ee(e){return e instanceof Uint8Array?b(e.slice()):_(e)}function te(e,t,n){if(n!==void 0){if(!Array.isArray(n)||n.length!==4)throw TypeError(`randomState must contain four words`);for(let e of n)if(f(e),e<0||e>4294967295)throw RangeError(`randomState word out of range`);if(!n.some(Boolean))throw RangeError(`randomState cannot be zero`);return Uint32Array.from(n)}let r=2166136261,i=new TextEncoder().encode(t),a=new Uint8Array(4+i.length);new DataView(a.buffer).setUint32(0,e,!0),a.set(i,4);for(let e of a)r=Math.imul(r^e,16777619)>>>0;let o=/* @__PURE__ */ new Uint32Array(4);for(let e=0;e<4;e++){r=r+2654435769>>>0;let t=Math.imul(r^r>>>16,2246822507)>>>0;t=Math.imul(t^t>>>13,3266489909)>>>0,o[e]=(t^t>>>16)>>>0}return o.some(Boolean)||(o[0]=1),o}function S(e){let t=(e,t)=>(e<<t|e>>>32-t)>>>0,n=Math.imul(t(Math.imul(e[1],5),7),9)>>>0,r=e[1]<<9;return e[2]^=e[0],e[3]^=e[1],e[1]^=e[2],e[0]^=e[3],e[2]^=r,e[3]=t(e[3],11),n/4294967296}function C(e,t){return`${e}\\u0000${t}`}function w(e){return e instanceof Uint8Array||y(e)?e:void 0}function ne(e,t){if(Object.is(e,t))return!0;let n=w(e),r=w(t);if(n!==void 0||r!==void 0){if(n===void 0||r===void 0||n.length!==r.length)return!1;for(let e=0;e<n.length;e+=1)if(n[e]!==r[e])return!1;return!0}if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;let i=e,a=t;return i.x===a.x&&i.y===a.y&&i.z===a.z}function T(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.x==`number`&&typeof t.y==`number`}function E(e,t){switch(e){case`boolean`:return typeof t==`boolean`;case`number`:return typeof t==`number`;case`string`:return typeof t==`string`;case`bytes`:case`bytes<rgb565>`:case`bytes<segments>`:return w(t)!==void 0;case`vec2d`:return T(t);case`vec3d`:return T(t)&&typeof t.z==`number`}}function re(e){return e instanceof Uint8Array?new Uint8Array(e):y(e)?e.slice():e}function ie(e){return e instanceof Uint8Array?new Uint8Array(e):y(e)?e.slice():typeof e==`object`&&e?{...e}:e}let ae=l(`simulation-runtime`),oe=l(`simulation-runtime`);function se(e,t){if(e!==`onDidPublish`||!Array.isArray(t))return[];let n=t[0];return D(n?.payload)}function D(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer?[e.buffer]:[]}function ce(e,t){if(typeof e!=`number`||!Number.isFinite(e)||!Number.isInteger(e))throw TypeError(`${t}=${String(e)} must be a finite integer number of picoseconds`);if(e<0||e>72e14)throw RangeError(`${t}=${e} must be in [0, 7200000000000000] ps`);return e===0?0:e}function O(e){return ce(e,`time`)}function le(e,t){return ce(e,`left`),ce(t,`right`),ce(e+t,`addition ${e} + ${t}`)}function k(e){return ue(e,/* @__PURE__ */ new Set,[])}function ue(e,t,n){if(typeof e!=`object`||!e)return(typeof e==`function`||typeof e==`symbol`||typeof e==`bigint`)&&A(`IR_SCHEMA`,`Expected ordinary IR data.`,n.slice()),e;t.has(e)&&A(`IR_SCHEMA`,`Cyclic IR data is not supported.`,n.slice()),t.add(e);let r;if(e instanceof Uint8Array)r=Object.freeze(Array.from(Uint8Array.prototype.values.call(e)));else if(Array.isArray(e)){Object.getPrototypeOf(e)!==Array.prototype&&A(`IR_SCHEMA`,`Expected an ordinary IR array.`);let i=[];for(let t of Reflect.ownKeys(e))t!==`length`&&((typeof t!=`string`||!/^(0|[1-9][0-9]*)$/.test(t)||Number(t)>=e.length)&&A(`IR_SCHEMA`,`IR arrays cannot contain extra properties.`),`value`in Object.getOwnPropertyDescriptor(e,t)||A(`IR_SCHEMA`,`IR arrays cannot contain accessors.`));for(let r=0;r<e.length;r++)Object.hasOwn(e,r)||A(`IR_SCHEMA`,`IR arrays cannot be sparse.`),n.push(r),i.push(ue(Object.getOwnPropertyDescriptor(e,r).value,t,n)),n.pop();r=Object.freeze(i)}else{let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&A(`IR_SCHEMA`,`Expected an ordinary data object.`);let a={};for(let r of Reflect.ownKeys(e)){let i=Object.getOwnPropertyDescriptor(e,r);(typeof r!=`string`||!(`value`in i))&&A(`IR_SCHEMA`,`IR data cannot contain symbols or accessors.`),n.push(r);let o=ue(i.value,t,n);n.pop(),r===`__proto__`?Object.defineProperty(a,r,{value:o,enumerable:!0}):a[r]=o}r=Object.freeze(a)}return t.delete(e),r}var de=class extends Error{diagnostics;constructor(e){if(!e.length)throw TypeError(`BuildError requires at least one diagnostic.`);super(e.map(e=>e.message).join(`\n`)),this.name=`BuildError`,this.diagnostics=k(e)}};function A(e,t,n=[],r=`finalize`,i){throw new de([{code:e,message:t,path:n,phase:r,related:[],...i===void 0?{}:{source:i}}])}let j=Object.freeze({Logic:[`low`,`high`,`unknown`],SampleStatus:[`valid`,`floating`],Overflow:[`drop_new`,`drop_oldest`,`error`]}),M=[`positive`,`negate`,`not`,`bitNot`],N=[`add`,`subtract`,`multiply`,`divide`,`remainder`,`power`,`lessThan`,`lessThanOrEqual`,`greaterThan`,`greaterThanOrEqual`,`equal`,`notEqual`,`concat`,`bitAnd`,`bitOr`,`bitXor`,`shiftLeft`,`shiftRight`,`shiftRightUnsigned`],fe=[`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`],pe=[`load8`,`load16le`,`load16be`,`load32le`,`load32be`],me=[`store8`,`store16le`,`store16be`,`store32le`,`store32be`],he=[`number`,`bool`,`string`,`bytes`,`sample`,`intent`,`enum`,`record`];function P(e,t){(typeof e!=`object`||!e||Array.isArray(e))&&A(`IR_SCHEMA`,`Expected a data object.`,t)}function F(e,t,n,r,i=!0){for(let n of t)Object.hasOwn(e,n)||A(`IR_SCHEMA`,`Missing field ${n}.`,[...r,n]);for(let a of Object.keys(e))[...t,...n,...i?[`source`]:[]].includes(a)||A(`IR_SCHEMA`,`Unexpected field ${a}.`,[...r,a]);Object.hasOwn(e,`source`)&&ve(e.source,[...r,`source`])}function I(e,t){typeof e!=`string`&&A(`IR_SCHEMA`,`Expected a string.`,t)}function ge(e,t){typeof e!=`boolean`&&A(`IR_SCHEMA`,`Expected a boolean.`,t)}function _e(e,t){typeof e!=`number`&&A(`IR_SCHEMA`,`Expected a number.`,t)}function L(e,t){(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)&&A(`IR_SCHEMA`,`Expected a nonnegative safe integer.`,t)}function R(e,t,n){t.includes(e)||A(`IR_SCHEMA`,`Expected one of ${t.join(`, `)}.`,n)}function z(e,t,n){Array.isArray(e)||A(`IR_SCHEMA`,`Expected an array.`,t);for(let r=0;r<e.length;r++)n(e[r],[...t,r])}function ve(e,t){P(e,t);let n=Object.hasOwn(e,`uri`);for(let n of Object.keys(e))[`uri`,`range`,`label`].includes(n)||A(`IR_SCHEMA`,`Invalid source field.`,[...t,n]);if(Object.hasOwn(e,`label`)&&I(e.label,[...t,`label`]),!n){(!Object.hasOwn(e,`label`)||Object.hasOwn(e,`range`))&&A(`IR_SCHEMA`,`Source requires a label or URI and range.`,t);return}I(e.uri,[...t,`uri`]),P(e.range,[...t,`range`]);let r=e.range;for(let e of Object.keys(r))[`start`,`end`].includes(e)||A(`IR_SCHEMA`,`Invalid range field.`,[...t,`range`,e]);for(let e of[`start`,`end`]){let n=r[e];P(n,[...t,`range`,e]);for(let r of Object.keys(n))[`line`,`column`].includes(r)||A(`IR_SCHEMA`,`Invalid position field.`,[...t,`range`,e,r]);for(let r of[`line`,`column`])(!Number.isSafeInteger(n[r])||n[r]<1)&&A(`IR_SCHEMA`,`Positions start at one.`,[...t,`range`,e,r])}let{start:i,end:a}=r;(a.line<i.line||a.line===i.line&&a.column<i.column)&&A(`IR_SCHEMA`,`Source range is reversed.`,t)}function ye(e,t,n=!0){P(e,t),e.kind===`optional`&&n?(F(e,[`kind`,`inner`],[],t),ye(e.inner,[...t,`inner`],!1)):(R(e.kind,he,[...t,`kind`]),F(e,[`kind`,...[`enum`,`record`].includes(e.kind)?[`name`]:[]],[],t),[`enum`,`record`].includes(e.kind)&&I(e.name,[...t,`name`])),Object.hasOwn(e,`source`)&&A(`IR_SCHEMA`,`Type descriptors cannot carry source information.`,t)}function be(e,t,n){P(e,t),Object.hasOwn(e,`source`)&&A(`IR_SCHEMA`,`Resource references cannot carry source information.`,t),R(e.kind,[`pin`,`memory`,`parameter`],[...t,`kind`]),e.kind===`parameter`?(F(e,[`kind`,`resource`,`index`],[],t),R(e.resource,[`pin`,`memory`],[...t,`resource`]),L(e.index,[...t,`index`]),n&&e.resource!==n&&A(`IR_REFERENCE`,`Resource category does not match.`,t)):(F(e,[`kind`,`name`],[],t),I(e.name,[...t,`name`]),n&&e.kind!==n&&A(`IR_REFERENCE`,`Resource category does not match.`,t))}function xe(e,t,n=!1){P(e,t),Object.hasOwn(e,`source`)&&A(`IR_SCHEMA`,`Constants and patterns cannot carry source information.`,t);let r=n?[`number`,`bool`,`string`,`enum`,`none`]:[`number`,`bool`,`string`,`bytes`,`enum`,`record`,`none`];switch(R(e.kind,r,[...t,`kind`]),e.kind){case`none`:F(e,[`kind`],[],t);break;case`enum`:F(e,[`kind`,`name`,`member`],[],t),I(e.name,[...t,`name`]),I(e.member,[...t,`member`]);break;case`record`:F(e,[`kind`,`name`,`fields`],[],t),I(e.name,[...t,`name`]),z(e.fields,[...t,`fields`],(e,t)=>{P(e,t),F(e,[`name`,`value`],[],t),I(e.name,[...t,`name`]),[`number`,`boolean`].includes(typeof e.value)||A(`IR_SCHEMA`,`Expected a number or boolean field.`,[...t,`value`])});break;case`bytes`:F(e,[`kind`,`value`],[],t),z(e.value,[...t,`value`],(e,t)=>{(!Number.isInteger(e)||e<0||e>255)&&A(`IR_SCHEMA`,`Expected a byte.`,t)});break;default:F(e,[`kind`,`value`],[],t),e.kind===`number`?(_e(e.value,[...t,`value`]),n&&!Number.isFinite(e.value)&&A(`IR_CONTROL_FLOW`,`Numeric match patterns must be finite.`,t)):e.kind===`bool`?ge(e.value,[...t,`value`]):I(e.value,[...t,`value`])}}function B(e,t){P(e,t),F(e,[`operations`],[],t),z(e.operations,[...t,`operations`],Se)}function V(e,t){P(e,t),F(e,[`type`,`body`],[],t),ye(e.type,[...t,`type`]),B(e.body,[...t,`body`])}function Se(e,t){P(e,t),I(e.kind,[...t,`kind`]);let n=[],r=[],i=!1,a=e=>{n=e,i=!0};switch(e.kind){case`constant`:a([`constant`]),xe(e.constant,[...t,`constant`]);break;case`read`:a([`resource`,`name`]),R(e.resource,[`property`,`const`,`state`,`derived`],[...t,`resource`]),I(e.name,[...t,`name`]);break;case`parameter`:case`reactionCapture`:a([`index`]),L(e.index,[...t,`index`]);break;case`reactionValue`:a([`binding`]),R(e.binding,[`previous`,`current`],[...t,`binding`]);break;case`unary`:a([`operator`,`value`]),R(e.operator,M,[...t,`operator`]);break;case`binary`:a([`operator`,`left`,`right`]),R(e.operator,N,[...t,`operator`]);break;case`numeric`:a([`builtin`,`args`]),R(e.builtin,fe,[...t,`builtin`]),z(e.args,[...t,`args`],L);break;case`record`:a([`fields`]),z(e.fields,[...t,`fields`],(e,t)=>{P(e,t),F(e,[`name`,`value`],[],t),I(e.name,[...t,`name`]),L(e.value,[...t,`value`])});break;case`field`:a([`value`,`field`]),I(e.field,[...t,`field`]);break;case`bytes`:a([`elements`]),z(e.elements,[...t,`elements`],L);break;case`length`:case`optional`:case`isNone`:case`nonNull`:a([`value`]);break;case`index`:a([`value`,`index`]),L(e.index,[...t,`index`]);break;case`localRead`:a([`local`]),L(e.local,[...t,`local`]);break;case`local`:n=[`local`,`type`,`initial`],L(e.local,[...t,`local`]),ye(e.type,[...t,`type`]);break;case`localWrite`:n=[`local`,`value`],L(e.local,[...t,`local`]);break;case`write`:n=[`resource`,`name`,`value`],R(e.resource,[`state`],[...t,`resource`]),I(e.name,[...t,`name`]);break;case`memoryLength`:a([`memory`]),be(e.memory,[...t,`memory`],`memory`);break;case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:a([`memory`,`offset`]),be(e.memory,[...t,`memory`],`memory`);break;case`store8`:case`store16le`:case`store16be`:case`store32le`:case`store32be`:n=[`memory`,`offset`,`value`],be(e.memory,[...t,`memory`],`memory`);break;case`copyBytes`:a([`memory`,`offset`,`length`]),be(e.memory,[...t,`memory`],`memory`);break;case`readSample`:a([`pin`]),be(e.pin,[...t,`pin`],`pin`);break;case`resistor`:a([`to`,`resistance`]),be(e.to,[...t,`to`],`pin`);break;case`combineIntents`:a([`values`]),z(e.values,[...t,`values`],L);break;case`refEqual`:a([`left`,`right`]),be(e.left,[...t,`left`]),be(e.right,[...t,`right`]);break;case`writeIntent`:n=[`pin`,`value`],be(e.pin,[...t,`pin`],`pin`);break;case`call`:case`callValue`:n=[`name`,`pure`,`args`],i=e.kind===`callValue`,I(e.name,[...t,`name`]),ge(e.pure,[...t,`pure`]),z(e.args,[...t,`args`],(e,t)=>{P(e,t),e.kind===`value`?(F(e,[`kind`,`value`],[],t),L(e.value,[...t,`value`])):be(e,t)});break;case`send`:n=[`channel`,`value`],I(e.channel,[...t,`channel`]);break;case`notify`:n=[`notification`],I(e.notification,[...t,`notification`]);break;case`receive`:a([`channel`]),I(e.channel,[...t,`channel`]);break;case`now`:case`random`:a([]);break;case`if`:n=[`condition`,`yes`],r=[`no`],B(e.yes,[...t,`yes`]),Object.hasOwn(e,`no`)&&B(e.no,[...t,`no`]);break;case`match`:n=[`value`,`arms`],r=[`otherwise`],z(e.arms,[...t,`arms`],(e,t)=>{P(e,t),F(e,[`pattern`,`body`],[],t),xe(e.pattern,[...t,`pattern`],!0),B(e.body,[...t,`body`])}),Object.hasOwn(e,`otherwise`)&&B(e.otherwise,[...t,`otherwise`]);break;case`while`:n=[`test`,`body`],V(e.test,[...t,`test`]),B(e.body,[...t,`body`]);break;case`loop`:n=[`body`],B(e.body,[...t,`body`]);break;case`and`:case`or`:a([`left`,`right`]),V(e.right,[...t,`right`]);break;case`select`:a([`condition`,`yes`,`no`]),V(e.yes,[...t,`yes`]),V(e.no,[...t,`no`]);break;case`assert`:n=[`condition`],r=[`message`],Object.hasOwn(e,`message`)&&V(e.message,[...t,`message`]);break;case`wait`:case`elapse`:n=[`duration`];break;case`waitUntil`:n=[`predicate`],I(e.predicate,[...t,`predicate`]);break;case`redirect`:n=[`target`,`delay`];break;case`return`:case`break`:case`continue`:case`stop`:break;case`returnValue`:case`yield`:n=[`value`];break;default:A(`IR_SCHEMA`,`Unknown operation ${e.kind}.`,[...t,`kind`])}F(e,[`kind`,...n,...i?[`result`,`type`]:[]],r,t),i&&(L(e.result,[...t,`result`]),ye(e.type,[...t,`type`]));for(let n of[`value`,`left`,`right`,`condition`,`initial`,`offset`,`length`,`resistance`,`duration`,`target`,`delay`])Object.hasOwn(e,n)&&typeof e[n]!=`object`&&!(n===`value`&&[`constant`,`read`].includes(e.kind))?L(e[n],[...t,n]):Object.hasOwn(e,n)&&typeof e[n]==`object`&&![`refEqual`,`and`,`or`].includes(e.kind)&&A(`IR_SCHEMA`,`Expected a result identifier.`,[...t,n])}function Ce(e){P(e,[]),F(e,[`kind`,`name`,`declarations`],[],[]),R(e.kind,[`device`],[`kind`]),I(e.name,[`name`]),z(e.declarations,[`declarations`],(e,t)=>{P(e,t),I(e.kind,[...t,`kind`]);let n=[`kind`],r=[];switch([`start`,`assert`].includes(e.kind)||(n.push(`name`),I(e.name,[...t,`name`])),e.kind){case`enum`:n.push(`members`),z(e.members,[...t,`members`],I);break;case`record`:n.push(`fields`),z(e.fields,[...t,`fields`],(e,t)=>{P(e,t),F(e,[`name`,`type`],[],t),I(e.name,[...t,`name`]),R(e.type,[`number`,`bool`],[...t,`type`])});break;case`property`:n.push(`type`),r=[`default`],Object.hasOwn(e,`default`)&&V(e.default,[...t,`default`]);break;case`const`:case`derived`:n.push(`type`,`value`),V(e.value,[...t,`value`]);break;case`state`:n.push(`type`,`initial`),V(e.initial,[...t,`initial`]);break;case`pin`:r=[`initial`,`low`,`high`];for(let n of r)Object.hasOwn(e,n)&&V(e[n],[...t,n]);Object.hasOwn(e,`low`)!==Object.hasOwn(e,`high`)&&A(`IR_SCHEMA`,`Pin thresholds must be provided together.`,t);break;case`memory`:n.push(`public`,`length`),ge(e.public,[...t,`public`]),V(e.length,[...t,`length`]);break;case`channel`:n.push(`direction`,`type`,`capacity`),r=[`maxLength`,`overflow`],V(e.capacity,[...t,`capacity`]);for(let n of r)Object.hasOwn(e,n)&&V(e[n],[...t,n]);break;case`notification`:n.push(`direction`);break;case`function`:n.push(`pure`,`params`,`body`),r=[`returns`],ge(e.pure,[...t,`pure`]),z(e.params,[...t,`params`],(e,t)=>{P(e,t),F(e,[`name`,`type`],[],t),I(e.name,[...t,`name`]),P(e.type,[...t,`type`]),[`pin`,`memory`].includes(e.type.kind)?F(e.type,[`kind`],[],[...t,`type`]):ye(e.type,[...t,`type`])}),Object.hasOwn(e,`returns`)&&ye(e.returns,[...t,`returns`]),B(e.body,[...t,`body`]);break;case`start`:case`assert`:n.push(`body`),B(e.body,[...t,`body`]);break;case`on`:n.push(`sourcePath`,`body`),z(e.sourcePath,[...t,`sourcePath`],I),B(e.body,[...t,`body`]);break;case`reaction`:n.push(`sourcePath`,`sourceType`,`previous`,`current`,`captures`,`body`),z(e.sourcePath,[...t,`sourcePath`],I),ye(e.sourceType,[...t,`sourceType`]),I(e.previous,[...t,`previous`]),I(e.current,[...t,`current`]),z(e.captures,[...t,`captures`],(e,t)=>{P(e,t),F(e,[`name`,`value`],[],t),I(e.name,[...t,`name`]),V(e.value,[...t,`value`])}),B(e.body,[...t,`body`]);break;default:A(`IR_SCHEMA`,`Unknown declaration ${e.kind}.`,[...t,`kind`])}F(e,n,r,t),Object.hasOwn(e,`type`)&&ye(e.type,[...t,`type`]),[`channel`,`notification`].includes(e.kind)&&R(e.direction,[`input`,`output`],[...t,`direction`])})}function we(e){P(e,[]),F(e,[`kind`,`instructions`],[],[]),R(e.kind,[`block`],[`kind`]),z(e.instructions,[`instructions`],(e,t)=>{P(e,t),F(e,[`pc`,`nextPc`,`body`],[],t);for(let n of[`pc`,`nextPc`])(typeof e[n]!=`number`||!Number.isFinite(e[n]))&&A(`IR_SCHEMA`,`Instruction positions must be finite numbers.`,[...t,n]);B(e.body,[...t,`body`])});let t=e.instructions;t.length||A(`IR_JIT_BOUNDARY`,`A block requires at least one instruction.`,[`instructions`]);for(let e=1;e<t.length;e++)t[e-1].nextPc!==t[e].pc&&A(`IR_JIT_BOUNDARY`,`Adjacent instruction boundaries do not match.`,[`instructions`,e,`pc`])}let H={kind:`number`},U={kind:`bool`},Te={kind:`string`},Ee={kind:`bytes`},De={kind:`intent`},Oe={kind:`sample`},ke=/* @__PURE__ */ new Set([`device`,`default`,`const`,`let`,`enum`,`record`,`state`,`derived`,`pin`,`memory`,`fn`,`pure`,`process`,`on`,`reaction`,`as`,`capture`,`if`,`else`,`match`,`while`,`loop`,`break`,`continue`,`return`,`await`,`assert`,`redirect`,`true`,`false`,`none`,`start`,`number`,`bool`,`string`,`bytes`,`sample`,`intent`,`NaN`,`Infinity`,...Object.keys(j),...fe,...pe,...me,`resistor`,`copyBytes`,`now`,`random`,`ticks`]);function Ae(e,t){let n=e,r=t;return n?.kind===r?.kind&&(n?.kind===`optional`?Ae(n.inner,r?.inner):n?.kind===`enum`||n?.kind===`record`?n.name===r?.name:!0)}function je(e){return e.kind===`optional`?e.inner:e}function Me(e){return je(e).kind!==`intent`}function Ne(e){return{facts:new Map(e.facts),locals:new Map(e.locals)}}function Pe(e){let t=new Map(e[0]);for(let[n,r]of t)e.some(e=>e.get(n)!==r)&&t.delete(n);return t}function Fe(e,t){for(let n of[e.normal,...e.breaks,...e.continues,...e.yieldStates])if(n)for(let e of n.locals.keys())t.has(e)||n.locals.delete(e);return e}function Ie(e){if(!e.length)return;let t=Ne(e[0]);t.facts=Pe(e.map(e=>e.facts));for(let[n,r]of t.locals){let i=e.map(e=>e.locals.get(n));if(i.some(e=>!e))t.locals.delete(n);else if(i.some(e=>e.value.key!==r.value.key)){let a={type:r.type,key:`join:${n}:${i.map(e=>e.value.key).join(`|`)}`},o=i.map((t,n)=>e[n].facts.get(t.value.key));o.every(e=>e===!0)&&t.facts.set(a.key,!0),o.every(e=>e===!1)&&t.facts.set(a.key,!1),t.locals.set(n,{type:r.type,value:a})}}return t}function Le(e,t,n=[]){e.operations.forEach((e,r)=>{let i=[...n,`operations`,r];t(e,i);for(let n of[`yes`,`no`,`otherwise`,`body`]){let r=n in e?e[n]:void 0;if(r){let e=`body`in r;Le(e?r.body:r,t,[...i,n,...e?[`body`]:[]])}}e.kind===`while`&&Le(e.test.body,t,[...i,`test`,`body`]),e.kind===`assert`&&e.message&&Le(e.message.body,t,[...i,`message`,`body`]),(e.kind===`and`||e.kind===`or`)&&Le(e.right.body,t,[...i,`right`,`body`]),e.kind===`match`&&e.arms.forEach((e,n)=>Le(e.body,t,[...i,`arms`,n,`body`]))})}var Re=class{device;declarations=/* @__PURE__ */ new Map;paths=/* @__PURE__ */ new Map;enums=new Map(Object.entries(j));records=/* @__PURE__ */ new Map;functions=/* @__PURE__ */ new Map;effectChecked=/* @__PURE__ */ new Set;receiveOwners=/* @__PURE__ */ new Map;constructor(e){if(this.device=e,!e)return;this.name(e.name,[`name`]);let t=0;e.declarations.forEach((e,n)=>{let r=[`declarations`,n];e.kind===`start`?++t>1&&this.error(`IR_REFERENCE`,`Only one start process is allowed.`,r):e.kind!==`assert`&&(this.name(e.name,[...r,`name`]),this.declarations.has(e.name)&&this.error(`IR_REFERENCE`,`Duplicate declaration ${e.name}.`,r),this.declarations.set(e.name,e),this.paths.set(e.name,r),e.kind===`enum`&&(this.uniqueNames(e.members,[...r,`members`]),e.members.length||this.error(`IR_TYPE`,`An enum must have at least one member.`,r),this.enums.set(e.name,e.members)),e.kind===`record`&&(this.uniqueNames(e.fields.map(e=>e.name),[...r,`fields`]),this.records.set(e.name,e.fields)),e.kind===`function`&&this.functions.set(e.name,e))})}error(e,t,n,r){return A(e,t,n,`finalize`,r?.source)}name(e,t){(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)||ke.has(e))&&this.error(`IR_REFERENCE`,`Invalid or reserved identifier ${e}.`,t)}uniqueNames(e,t,n=!1){let r=/* @__PURE__ */ new Set;e.forEach((e,i)=>{n?/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)||this.error(`IR_REFERENCE`,`Invalid member name.`,[...t,i]):this.name(e,[...t,i]),r.has(e)&&this.error(`IR_REFERENCE`,`Duplicate name ${e}.`,[...t,i]),r.add(e)})}type(e,t){let n=je(e);n.kind===`enum`&&!this.enums.has(n.name)&&this.device&&this.error(`IR_REFERENCE`,`Unknown enum ${n.name}.`,t),n.kind===`record`&&!this.records.has(n.name)&&this.device&&this.error(`IR_REFERENCE`,`Unknown record ${n.name}.`,t)}expect(e,t,n,r){Ae(e,t)||this.error(`IR_TYPE`,`Expected ${this.describe(t)}, received ${this.describe(e)}.`,n,r)}describe(e){let t=e;return t?t.kind===`optional`?`${this.describe(t.inner)}?`:String(t.name??t.kind):`no value`}declaration(e,t,n){if(!this.device)return;let r=this.declarations.get(e);return(!r||r.kind!==t)&&this.error(`IR_REFERENCE`,`Expected ${t} declaration ${e}.`,n),r}ref(e,t,n,r){let i=e.kind===`parameter`?e.resource:e.kind;if(t&&i!==t&&this.error(`IR_REFERENCE`,`Resource category does not match.`,r),e.kind===`parameter`){let t=n.params[e.index];t||this.error(`IR_SCOPE`,`Resource parameter is outside the current function.`,r),t.type.kind!==i&&this.error(`IR_REFERENCE`,`Resource parameter category does not match.`,r)}else this.declaration(e.name,i,r);return i}field(e,t,n){if(e.kind===`sample`){let e={voltage:{kind:`optional`,inner:H},level:{kind:`enum`,name:`Logic`},status:{kind:`enum`,name:`SampleStatus`}};return e[t]||this.error(`IR_REFERENCE`,`Unknown sample field ${t}.`,n),e[t]}e.kind!==`record`&&this.error(`IR_TYPE`,`Field access requires a record or sample.`,n);let r=this.records.get(e.name);if(!r&&!this.device)return H;let i=r?.find(e=>e.name===t);return i||this.error(`IR_REFERENCE`,`Unknown record field ${t}.`,n),{kind:i.type}}constant(e,t,n){if(e.kind===`none`)t.kind!==`optional`&&this.error(`IR_TYPE`,`none requires an optional result type.`,n);else{if(t.kind===`optional`&&this.error(`IR_TYPE`,`Non-null constants require a nonoptional type and explicit optional lift.`,n),(e.kind!==t.kind||(e.kind===`enum`||e.kind===`record`)&&e.name!==(`name`in t?t.name:void 0))&&this.error(`IR_TYPE`,`Constant and result types do not match.`,n),e.kind===`enum`){let t=this.enums.get(e.name);t&&!t.includes(e.member)&&this.error(`IR_REFERENCE`,`Unknown enum member ${e.member}.`,n)}e.kind===`record`&&this.recordFields(e.fields,t,n,e=>({kind:typeof e.value==`boolean`?`bool`:`number`}))}}recordFields(e,t,n,r){t.kind!==`record`&&this.error(`IR_TYPE`,`Record construction requires a named record type.`,n);let i=this.records.get(t.name),a=/* @__PURE__ */ new Set;for(let t=0;t<e.length;t++){let o=e[t];if(a.has(o.name)&&this.error(`IR_REFERENCE`,`Duplicate record field.`,[...n,`fields`,t]),a.add(o.name),i){let e=i.find(e=>e.name===o.name);e||this.error(`IR_REFERENCE`,`Unknown record field ${o.name}.`,[...n,`fields`,t]),this.expect(r(o),{kind:e.type},[...n,`fields`,t])}else r(o)}i&&i.length!==e.length&&this.error(`IR_TYPE`,`Record fields are incomplete.`,n)}context(e,t){return{mode:e,params:[],...t?{returns:t}:{},loop:0,results:/* @__PURE__ */ new Map,resultIds:/* @__PURE__ */ new Set,localIds:/* @__PURE__ */ new Set,tail:!0,finalInstruction:!0,computation:!1}}body(e,t,n){let r=this.region(e,t,{facts:/* @__PURE__ */ new Map,locals:/* @__PURE__ */ new Map},n);t.returns&&r.normal&&this.error(`IR_CONTROL_FLOW`,`A value-returning body has a normal path without returnValue.`,n,e),this.effects(e,t.mode,n)}computation(e,t,n,r){this.type(e.type,[...r,`type`]),this.expect(e.type,t,[...r,`type`]);let i=this.context(n,t);i.computation=!0,this.body(e.body,i,[...r,`body`])}conditioned(e,t,n){let r=Ne(e),i=n?t.yes:t.no;if(i)for(let[e,t]of i)r.facts.set(e,t);return r}region(e,t,n,r){let i=Ne(n),a={breaks:[],continues:[],yielded:[],yieldStates:[]},o=new Map(t.results);t={...t,results:o};for(let n=0;n<e.operations.length;n++){let s=e.operations[n],c=[...r,`operations`,n];i||this.error(`IR_CONTROL_FLOW`,`Operation follows an unconditional path terminator.`,c,s);let l=i,u=(e,t)=>{let n=o.get(e);return n||this.error(`IR_SCOPE`,`Result ${e} is not visible or is used before its definition.`,c,s),t&&this.expect(n.type,t,c,s),n},d=(e,t={})=>{let n=s;this.expect(n.type,e,[...c,`type`],s);let r={type:n.type,key:`v:${n.result}`,...t};return o.set(n.result,r),r};`result`in s&&(this.type(s.type,[...c,`type`]),t.resultIds.has(s.result)&&this.error(`IR_SCOPE`,`Duplicate result ${s.result}.`,[...c,`result`],s),t.resultIds.add(s.result));let f=e=>{let t=l.locals.get(e);return t||this.error(`IR_SCOPE`,`Local is not visible or not initialized.`,[...c,`local`],s),t},p=(r,i,a,o={})=>Fe(this.region(r,{...t,tail:t.tail&&n===e.operations.length-1,...o},i,[...c,a]),i.locals),m=e=>{a.breaks.push(...e.breaks),a.continues.push(...e.continues),a.yielded.push(...e.yielded),a.yieldStates.push(...e.yieldStates)},h=(e,n,r,i)=>{this.type(e.type,[...c,i,`type`]),this.expect(e.type,n,[...c,i,`type`]);let a=Fe(this.region(e.body,{...t,valueRegion:n,loop:0,tail:!1},r,[...c,i,`body`]),r.locals);return a.normal&&this.error(`IR_CONTROL_FLOW`,`A value region has a normal path without yield.`,[...c,i],e),{flow:a,...a.yielded.length?{value:{type:n,key:`region:${`result`in s?s.result:void 0}:${i}`,yes:Pe(a.yielded.map(e=>e.yes??/* @__PURE__ */ new Map)),no:Pe(a.yielded.map(e=>e.no??/* @__PURE__ */ new Map))}}:{}}};switch(s.kind){case`constant`:{this.constant(s.constant,s.type,[...c,`constant`]);let e=d(s.type,{none:s.constant.kind===`none`});s.constant.kind===`none`&&l.facts.set(e.key,!1);break}case`read`:d(this.declaration(s.name,s.resource,c)?.type??s.type);break;case`parameter`:{let e=t.params[s.index];e||this.error(`IR_SCOPE`,`Parameter index is outside the current function.`,c,s),(e.type.kind===`pin`||e.type.kind===`memory`)&&this.error(`IR_TYPE`,`Resource parameters cannot be read as values.`,c,s),d(e.type,{key:`parameter:${s.index}`});break}case`reactionValue`:t.reaction||this.error(`IR_SCOPE`,`Reaction bindings are only visible inside their response body.`,c,s),d(t.reaction.sourceType,{key:`reaction:${s.binding}`});break;case`reactionCapture`:t.reaction||this.error(`IR_SCOPE`,`Reaction captures are only visible inside their response body.`,c,s),t.reaction.captures[s.index]||this.error(`IR_SCOPE`,`Reaction capture index is out of range.`,c,s),d(t.reaction.captures[s.index].value.type,{key:`capture:${s.index}`});break;case`unary`:{let e=u(s.value,s.operator===`not`?U:H);d(s.operator===`not`?U:H,s.operator===`not`?{yes:e.no??/* @__PURE__ */ new Map,no:e.yes??/* @__PURE__ */ new Map}:{});break}case`binary`:{let e=u(s.left),t=u(s.right);if([`equal`,`notEqual`].includes(s.operator)){this.expect(e.type,t.type,c,s),!Me(e.type)&&(e.type.kind!==`optional`||!e.none&&!t.none)&&this.error(`IR_TYPE`,`Intent values do not support content equality.`,c,s);let n=e.none?t:t.none?e:void 0,r=s.operator===`equal`;d(U,n?{yes:/* @__PURE__ */ new Map([[n.key,!r]]),no:/* @__PURE__ */ new Map([[n.key,r]])}:{})}else s.operator===`concat`?(u(s.left,Te),u(s.right,Te),d(Te)):(u(s.left,H),u(s.right,H),d([`lessThan`,`lessThanOrEqual`,`greaterThan`,`greaterThanOrEqual`].includes(s.operator)?U:H));break}case`numeric`:s.args.length!==([`min`,`max`,`pow`].includes(s.builtin)?2:1)&&this.error(`IR_TYPE`,`Numeric builtin argument count does not match.`,c,s),s.args.forEach(e=>u(e,H)),d(s.builtin.startsWith(`is`)?U:H);break;case`record`:this.recordFields(s.fields,s.type,c,e=>u(e.value).type),d(s.type);break;case`field`:{let e=u(s.value),t=e.type;d(t.kind===`record`&&!this.device?s.type:this.field(t,s.field,c),{key:`field:${e.key}:${s.field}`});break}case`bytes`:s.elements.forEach(e=>u(e,H)),d(Ee);break;case`length`:{let e=u(s.value).type;[`string`,`bytes`].includes(e.kind)||this.error(`IR_TYPE`,`length requires string or bytes.`,c,s),d(H);break}case`index`:{let e=u(s.value).type;[`string`,`bytes`].includes(e.kind)||this.error(`IR_TYPE`,`index requires string or bytes.`,c,s),u(s.index,H),d(e.kind===`string`?Te:H);break}case`optional`:{let e=u(s.value).type;e.kind===`optional`&&this.error(`IR_TYPE`,`Optional types cannot be nested.`,c,s);let t=d({kind:`optional`,inner:e});l.facts.set(t.key,!0);break}case`isNone`:{let e=u(s.value);e.type.kind!==`optional`&&this.error(`IR_TYPE`,`isNone requires an optional value.`,c,s),d(U,{yes:/* @__PURE__ */ new Map([[e.key,!1]]),no:/* @__PURE__ */ new Map([[e.key,!0]])});break}case`nonNull`:{let e=u(s.value);(e.type.kind!==`optional`||l.facts.get(e.key)!==!0)&&this.error(`IR_TYPE`,`nonNull requires a dominating non-null proof.`,c,s),d(e.type.inner);break}case`local`:{t.localIds.has(s.local)&&this.error(`IR_SCOPE`,`Duplicate local identifier.`,c,s),t.localIds.add(s.local),this.type(s.type,[...c,`type`]);let e=u(s.initial,s.type);l.locals.set(s.local,{type:s.type,value:e});break}case`localRead`:{let e=f(s.local);d(e.type,{...e.value});break}case`localWrite`:{let e=f(s.local),t=u(s.value,e.type);l.locals.set(s.local,{type:e.type,value:t});break}case`write`:{let e=this.declaration(s.name,`state`,c);u(s.value,e?.type);break}case`memoryLength`:this.ref(s.memory,`memory`,t,c),d(H);break;case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:this.ref(s.memory,`memory`,t,c),u(s.offset,H),d(H);break;case`store8`:case`store16le`:case`store16be`:case`store32le`:case`store32be`:this.ref(s.memory,`memory`,t,c),u(s.offset,H),u(s.value,H);break;case`copyBytes`:this.ref(s.memory,`memory`,t,c),u(s.offset,H),u(s.length,H),d(Ee);break;case`readSample`:this.ref(s.pin,`pin`,t,c),d(Oe);break;case`resistor`:this.ref(s.to,`pin`,t,c),u(s.resistance,H),d(De);break;case`combineIntents`:s.values.forEach(e=>u(e,De)),d(De);break;case`refEqual`:this.expect({kind:this.ref(s.left,void 0,t,c)},{kind:this.ref(s.right,void 0,t,c)},c),d(U);break;case`writeIntent`:this.ref(s.pin,`pin`,t,c),u(s.value,De);break;case`call`:case`callValue`:{let e=this.declaration(s.name,`function`,c);e&&s.pure&&!e.pure&&this.error(`IR_EFFECT`,`A pure call must target an explicitly pure function.`,c,s),e&&s.args.length!==e.params.length&&this.error(`IR_TYPE`,`Call argument count does not match.`,c,s),s.args.forEach((n,r)=>{let i=e?.params[r];n.kind===`value`?(i&&(i.type.kind===`pin`||i.type.kind===`memory`)&&this.error(`IR_TYPE`,`Resource argument required.`,c,s),u(n.value,i?.type)):(i&&i.type.kind!==`pin`&&i.type.kind!==`memory`&&this.error(`IR_TYPE`,`Value argument required.`,c,s),this.ref(n,i?.type.kind,t,c))}),s.kind===`callValue`?(e&&!e.returns&&this.error(`IR_TYPE`,`callValue requires a value-returning function.`,c,s),d(e?.returns??s.type)):e?.returns&&this.error(`IR_TYPE`,`call cannot discard the return type of a value-returning function.`,c,s);break}case`send`:{let e=this.declaration(s.channel,`channel`,c);e?.direction===`input`&&this.error(`IR_REFERENCE`,`send requires an output channel.`,c,s),u(s.value,e?.type);break}case`notify`:this.declaration(s.notification,`notification`,c)?.direction===`input`&&this.error(`IR_REFERENCE`,`notify requires an output notification.`,c,s);break;case`receive`:{let e=this.declaration(s.channel,`channel`,c);e?.direction===`output`&&this.error(`IR_REFERENCE`,`receive requires an input channel.`,c,s),d(e?.type??s.type);break}case`now`:case`random`:d(H);break;case`if`:{let e=u(s.condition,U),t=p(s.yes,this.conditioned(l,e,!0),`yes`),n=s.no?p(s.no,this.conditioned(l,e,!1),`no`):{normal:this.conditioned(l,e,!1),breaks:[],continues:[],yielded:[],yieldStates:[]};m(t),m(n),i=Ie([t.normal,n.normal].filter(e=>!!e));break}case`match`:{let r=u(s.value),a=je(r.type),o=/* @__PURE__ */ new Set,d=[];for(let i=0;i<s.arms.length;i++){let u=s.arms[i],f=u.pattern;this.constant(f,f.kind===`none`?r.type:a,[...c,`arms`,i,`pattern`]);let p=f.kind===`enum`?`${f.name}.${f.member}`:`${f.kind}:${String(`value`in f?f.value:void 0)}`;o.has(p)&&this.error(`IR_CONTROL_FLOW`,`Duplicate match pattern.`,[...c,`arms`,i]),o.add(p);let h=Ne(l);r.type.kind===`optional`&&h.facts.set(r.key,f.kind!==`none`);let g=Fe(this.region(u.body,{...t,tail:t.tail&&n===e.operations.length-1},h,[...c,`arms`,i,`body`]),h.locals);m(g),g.normal&&d.push(g.normal)}let f=(a.kind===`bool`?o.has(`bool:true`)&&o.has(`bool:false`):a.kind===`enum`&&this.enums.get(a.name)?.every(e=>o.has(`${a.name}.${e}`)))&&(r.type.kind!==`optional`||o.has(`none:undefined`));if(s.otherwise){let e=Ne(l);r.type.kind===`optional`&&o.has(`none:undefined`)&&e.facts.set(r.key,!0);let t=p(s.otherwise,e,`otherwise`);m(t),t.normal&&d.push(t.normal)}else f||this.error(`IR_CONTROL_FLOW`,`Match requires exhaustive patterns or a default region.`,c,s);i=Ie(d);break}case`while`:case`loop`:{let e=/* @__PURE__ */ new Set;Le(s.body,t=>{t.kind===`localWrite`&&l.locals.has(t.local)&&e.add(t.local)}),s.kind===`while`&&Le(s.test.body,t=>{t.kind===`localWrite`&&l.locals.has(t.local)&&e.add(t.local)});let n=t=>{let n=Ne(l),r=[l,...t];for(let t of e){let e=l.locals.get(t),i={type:e.type,key:`loop:${c.join(`.`)}:${t}`};n.locals.set(t,{type:e.type,value:i});let a=r.map(e=>{let n=e.locals.get(t)?.value;return n?e.facts.get(n.key):void 0});a.every(e=>e===!0)?n.facts.set(i.key,!0):a.every(e=>e===!1)&&n.facts.set(i.key,!1)}return n},r=n([]),o=new Set(t.resultIds),u=new Set(t.localIds),d,f;for(;;){t.resultIds.clear();for(let e of o)t.resultIds.add(e);t.localIds.clear();for(let e of u)t.localIds.add(e);d=s.kind===`while`?h(s.test,U,r,`test`):void 0;let i=d?Ie(d.flow.yieldStates)??r:r,a=d?.value?this.conditioned(i,d.value,!0):i;f=p(s.body,a,`body`,{loop:t.loop+1,tail:!1});let c=n([f.normal,...f.continues].filter(e=>!!e));if([...e].every(e=>{let t=c.locals.get(e).value.key;return c.facts.get(t)===r.facts.get(t)}))break;r=c}a.yielded.push(...f.yielded),a.yieldStates.push(...f.yieldStates);let m=[...f.breaks];if(s.kind===`while`&&d?.value){let e=Ie(d.flow.yieldStates)??r;m.push(this.conditioned(e,d.value,!1))}i=Ie(m);break}case`and`:case`or`:{let e=u(s.left,U),t=s.kind===`and`,n=h(s.right,U,this.conditioned(l,e,t),`right`),r=n.value,a=(e,t)=>new Map([...e??[],...t??[]]),o=t?a(e.yes,r?.yes):Pe([e.yes??/* @__PURE__ */ new Map,a(e.no,r?.yes)]),c=t?Pe([e.no??/* @__PURE__ */ new Map,a(e.yes,r?.no)]):a(e.no,r?.no);d(U,{yes:o,no:c}),i=Ie([this.conditioned(l,e,!t),...n.flow.yieldStates]);break}case`select`:{let e=u(s.condition,U),t=h(s.yes,s.type,this.conditioned(l,e,!0),`yes`),n=h(s.no,s.type,this.conditioned(l,e,!1),`no`);d(s.type),i=Ie([...t.flow.yieldStates,...n.flow.yieldStates]);break}case`assert`:{let e=u(s.condition,U);s.message&&h(s.message,Te,this.conditioned(l,e,!1),`message`),i=this.conditioned(l,e,!0);break}case`wait`:(t.valueRegion||t.mode!==`process`)&&this.error(`IR_EFFECT`,`wait is only allowed in a process statement region.`,c,s),u(s.duration,H);break;case`elapse`:(t.valueRegion||t.mode!==`jit`)&&this.error(`IR_EFFECT`,`elapse is only allowed in a JIT statement region.`,c,s),u(s.duration,H);break;case`waitUntil`:t.mode!==`jit`&&this.error(`IR_EFFECT`,`waitUntil requires a JIT instruction.`,c,s),(t.valueRegion||t.loop||!t.tail||n!==e.operations.length-1||!t.finalInstruction)&&this.error(`IR_JIT_BOUNDARY`,`waitUntil must be on the final instruction tail path.`,c,s);{let e=this.declaration(s.predicate,`function`,c);e&&(!e.pure||e.params.length||!Ae(e.returns,U))&&this.error(`IR_TYPE`,`waitUntil requires a zero-parameter pure bool function.`,c,s)}i=void 0;break;case`redirect`:[`jit`,`sync`].includes(t.mode)||this.error(`IR_EFFECT`,`redirect is not permitted in this context.`,c,s),u(s.target,H),u(s.delay,H),i=void 0;break;case`stop`:(t.mode!==`jit`||t.valueRegion)&&this.error(`IR_EFFECT`,`stop requires a JIT statement region.`,c,s),i=void 0;break;case`return`:(t.valueRegion||t.returns||t.mode===`jit`||t.computation||t.mode===`creation`||t.mode===`initial`)&&this.error(`IR_CONTROL_FLOW`,`Void return is not valid in this body.`,c,s),i=void 0;break;case`returnValue`:(t.valueRegion||!t.returns)&&this.error(`IR_CONTROL_FLOW`,`returnValue is not valid in this body.`,c,s),u(s.value,t.returns),i=void 0;break;case`yield`:t.valueRegion||this.error(`IR_CONTROL_FLOW`,`yield requires a value region.`,c,s);{let e=u(s.value,t.valueRegion);a.yielded.push(e),a.yieldStates.push(l)}i=void 0;break;case`break`:case`continue`:t.loop||this.error(`IR_CONTROL_FLOW`,`${s.kind} requires an enclosing loop in this region.`,c,s),(s.kind===`break`?a.breaks:a.continues).push(l),i=void 0}}return i&&(a.normal=i),a}effects(e,t,n){Le(e,(e,n)=>{let r=[`creation`,`initial`,`pure`].includes(t),i=[`creation`,`initial`].includes(t),a=[`write`,`writeIntent`,`send`,`notify`,`now`,`random`,`wait`,`receive`,`elapse`,`waitUntil`,`stop`,`redirect`,...me].includes(e.kind);if(r&&a&&this.error(`IR_EFFECT`,`${e.kind} is not allowed in ${t} code.`,n,e),i&&(e.kind===`read`&&![`property`,`const`].includes(e.resource)||[`readSample`,`memoryLength`,`copyBytes`,...pe].includes(e.kind))&&this.error(`IR_EFFECT`,`Creation computations cannot read runtime resources.`,n,e),t===`creation`&&([`resistor`,`combineIntents`,`refEqual`].includes(e.kind)||(e.kind===`call`||e.kind===`callValue`)&&e.args.some(e=>e.kind!==`value`))&&this.error(`IR_EFFECT`,`Ordinary creation computations cannot use resource references or intents.`,n,e),[`reaction`,`process`].includes(t)&&e.kind===`redirect`&&this.error(`IR_EFFECT`,`Control redirection requires a bound JIT entry.`,n,e),[`sync`,`reaction`,`pure`].includes(t)&&[`wait`,`receive`,`elapse`,`waitUntil`,`stop`].includes(e.kind)&&this.error(`IR_EFFECT`,`Synchronous code cannot suspend or use JIT control.`,n,e),t===`process`&&[`elapse`,`waitUntil`,`stop`].includes(e.kind)&&this.error(`IR_EFFECT`,`Process code cannot use JIT control.`,n,e),t===`jit`&&[`wait`,`receive`].includes(e.kind)&&this.error(`IR_EFFECT`,`JIT code cannot use process suspension.`,n,e),e.kind===`call`||e.kind===`callValue`||e.kind===`waitUntil`){let i=e.kind===`waitUntil`?e.predicate:e.name,a=this.functions.get(i);if(a&&r&&!a.pure&&this.error(`IR_EFFECT`,`Pure contexts can only call explicitly pure functions.`,n,e),a){let e=`${t}:${i}`;this.effectChecked.has(e)||(this.effectChecked.add(e),this.effects(a.body,t,[...this.paths.get(i)??[],`body`]))}}},n)}source(e,t,n){e.length||this.error(`IR_SCHEMA`,`An observation source path cannot be empty.`,t);let r=this.declarations.get(e[0]);r||this.error(`IR_REFERENCE`,`Observation source does not exist.`,t);let i,a=1;if(r.kind===`notification`&&n)(r.direction!==`input`||e.length!==1)&&this.error(`IR_REFERENCE`,`Only input notifications can trigger a process.`,t);else{r.kind===`pin`?(e[1]!==`sample`&&this.error(`IR_REFERENCE`,`Pin observation must select sample.`,t),i=Oe,a=2):r.kind===`state`||r.kind===`derived`?i=r.type:this.error(`IR_REFERENCE`,`An observation source must be state, derived, pin.sample or an input notification.`,t);for(let n=a;n<e.length;n++)i=this.field(i,e[n],[...t,n]);return Me(i)||this.error(`IR_TYPE`,`Observation sources must be comparable.`,t),i}}cycle(e,t){let n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=a=>{if(n.has(a)&&this.error(`IR_DEPENDENCY`,`${t} dependency cycle includes ${a}.`,this.paths.get(a)??[]),!r.has(a)){n.add(a);for(let t of e.get(a)??[])e.has(t)&&i(t);n.delete(a),r.add(a)}};for(let t of e.keys())i(t)}dependencies(e,t,n=/* @__PURE__ */ new Set){let r=/* @__PURE__ */ new Set;return Le(e,e=>{if(e.kind===`read`&&t.includes(e.resource)&&r.add(e.name),(e.kind===`call`||e.kind===`callValue`)&&!n.has(e.name)){n.add(e.name);let i=this.functions.get(e.name);if(i)for(let e of this.dependencies(i.body,t,n))r.add(e)}}),r}validateDevice(){let e=/* @__PURE__ */ new Map;for(let[t,n]of this.functions){let r=/* @__PURE__ */ new Set;Le(n.body,e=>{(e.kind===`call`||e.kind===`callValue`)&&r.add(e.name)}),e.set(t,r)}this.cycle(e,`Synchronous call`);let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;this.device.declarations.forEach((e,r)=>{let i=[`declarations`,r];if(`type`in e&&e.type&&this.type(e.type,[...i,`type`]),e.kind===`property`||e.kind===`const`||e.kind===`state`){let n=je(e.type);([`sample`,`intent`].includes(n.kind)||e.kind===`property`&&n.kind===`record`)&&this.error(`IR_TYPE`,`Type is not valid at this declaration position.`,[...i,`type`],e);let r=e.kind===`property`?`default`:e.kind===`const`?`value`:`initial`,a=e.kind===`property`?e.default:e.kind===`const`?e.value:e.initial;a&&(this.computation(a,e.type,`creation`,[...i,r]),t.set(e.name,this.dependencies(a.body,[`property`,`const`])))}else if(e.kind===`derived`)this.computation(e.value,e.type,`pure`,[...i,`value`]),n.set(e.name,this.dependencies(e.value.body,[`derived`]));else if(e.kind===`pin`){for(let t of[`low`,`high`])e[t]&&this.computation(e[t],H,`creation`,[...i,t]);e.initial&&this.computation(e.initial,De,`initial`,[...i,`initial`])}else if(e.kind===`memory`)this.computation(e.length,H,`creation`,[...i,`length`]);else if(e.kind===`channel`)[`number`,`bool`,`record`,`bytes`].includes(e.type.kind)||this.error(`IR_TYPE`,`Invalid channel payload type.`,[...i,`type`],e),e.type.kind===`bytes`!=!!e.maxLength&&this.error(`IR_TYPE`,`Only bytes channels require maxLength.`,i,e),this.computation(e.capacity,H,`creation`,[...i,`capacity`]),e.maxLength&&this.computation(e.maxLength,H,`creation`,[...i,`maxLength`]),e.overflow&&this.computation(e.overflow,{kind:`enum`,name:`Overflow`},`creation`,[...i,`overflow`]);else if(e.kind===`function`){this.uniqueNames(e.params.map(e=>e.name),[...i,`params`]),e.params.forEach((e,t)=>{this.declarations.has(e.name)&&this.error(`IR_REFERENCE`,`A parameter cannot shadow a device member.`,[...i,`params`,t]),e.type.kind!==`pin`&&e.type.kind!==`memory`&&this.type(e.type,[...i,`params`,t,`type`])}),e.returns&&this.type(e.returns,[...i,`returns`]);let t=this.context(e.pure?`pure`:`sync`,e.returns);t.params=e.params,this.body(e.body,t,[...i,`body`])}else if(e.kind===`start`||e.kind===`on`)e.kind===`on`&&this.source(e.sourcePath,[...i,`sourcePath`],!0),this.body(e.body,this.context(`process`),[...i,`body`]),Le(e.body,e=>{if(e.kind===`receive`){let t=`${r}`,n=this.receiveOwners.get(e.channel);if(n&&n!==t){let e=new de([{code:`IR_REFERENCE`,message:`An input channel cannot have multiple consumer processes.`,phase:`finalize`,path:i,related:[]}]);throw Object.defineProperty(e,\"code\",{value:`CHANNEL_CONSUMER_CONFLICT`}),e}this.receiveOwners.set(e.channel,t)}});else if(e.kind===`reaction`){let t=this.source(e.sourcePath,[...i,`sourcePath`],!1);this.expect(e.sourceType,t,[...i,`sourceType`]),this.type(e.sourceType,[...i,`sourceType`]);let n=[e.previous,e.current,...e.captures.map(e=>e.name)];e.captures.forEach((e,t)=>{Me(e.value.type)||this.error(`IR_TYPE`,`Capture results must be comparable.`,[...i,`captures`,t]),this.computation(e.value,e.value.type,`pure`,[...i,`captures`,t,`value`])});let r=this.context(`reaction`);r.reaction=e,this.body(e.body,r,[...i,`body`]),this.uniqueNames(n,i);for(let e of n)this.declarations.has(e)&&this.error(`IR_REFERENCE`,`Reaction bindings cannot shadow device members.`,i)}else e.kind===`assert`&&this.body(e.body,this.context(`creation`),[...i,`body`])}),this.cycle(t,`Creation`),this.cycle(n,`Derived`)}validateBlock(e){e.instructions.forEach((t,n)=>{let r=this.context(`jit`);r.finalInstruction=n===e.instructions.length-1,this.body(t.body,r,[`instructions`,n,`body`])})}};function ze(e,t){if(!(e instanceof de))throw e;let n=new de(e.diagnostics.map(e=>{if(e.source)return e;let n=t,r,i=()=>{let e=n?.source;e&&typeof e==`object`&&(typeof e.label==`string`&&e.uri===void 0&&e.range===void 0||typeof e.uri==`string`&&e.range?.start?.line>=1&&e.range?.start?.column>=1&&e.range?.end?.line>=1&&e.range?.end?.column>=1)&&(r=e)};i();for(let t of e.path)n=n?.[t],i();return r?{...e,source:r}:e})),r=Object.getOwnPropertyDescriptor(e,`code`);throw r?.value===`CHANNEL_CONSUMER_CONFLICT`&&Object.defineProperty(n,\"code\",r),n}let Be=/* @__PURE__ */ new WeakMap,Ve=/* @__PURE__ */ new WeakMap,He=/* @__PURE__ */ new WeakMap;function Ue(e,t){return typeof t==`object`&&t?e.get(t):void 0}function We(e,t,n){typeof t==`object`&&t&&e.set(t,n),e.set(n,n)}function Ge(e){let t=Ue(Be,e);if(t!==void 0)return t;let n=k(e);try{Ce(n),new Re(n).validateDevice();let t=n;return We(Be,e,t),t}catch(e){return ze(e,n)}}function Ke(e){let t=Ue(Ve,e);if(t!==void 0)return t;let n=k(e);try{we(n),new Re().validateBlock(n);let t=n;return We(Ve,e,t),t}catch(e){return ze(e,n)}}function qe(e,t){try{let n=Ke(e),r=Ge(t);if(He.get(n)?.has(r))return n;new Re(r).validateBlock(n);let i=He.get(n);return i||(i=/* @__PURE__ */ new WeakSet,He.set(n,i)),i.add(r),n}catch(e){if(e instanceof de){let t=new de(e.diagnostics.map(e=>({...e,phase:`bind`}))),n=Object.getOwnPropertyDescriptor(e,`code`);throw n?.value===`CHANNEL_CONSUMER_CONFLICT`&&Object.defineProperty(t,\"code\",n),t}throw e}}let Je=/* @__PURE__ */ new WeakMap,Ye=/* @__PURE__ */ new WeakMap,Xe=/* @__PURE__ */ new WeakMap,Ze=/* @__PURE__ */ new WeakMap,Qe=/* @__PURE__ */ new WeakMap,$e=e=>{let t=Object.freeze({});return Je.set(t,{type:{kind:e}}),t};function et(e,t,n){let r={};for(let i of t){let t=Object.freeze({});Qe.set(t,{name:e,member:i,...n?{owner:n}:{}}),Object.defineProperty(r,i,{value:t,enumerable:!0})}let i=Object.freeze({name:e,members:Object.freeze(r)});return Je.set(i,{type:{kind:`enum`,name:e},members:Object.freeze([...t]),...n?{owner:n}:{}}),i}function tt(e,t,n){let r=Object.freeze({name:e,fields:Object.freeze({...t})});return Je.set(r,{type:{kind:`record`,name:e},fields:r.fields,...n?{owner:n}:{}}),r}let nt={number:$e(`number`),bool:$e(`bool`),string:$e(`string`),bytes:$e(`bytes`),intent:$e(`intent`),sample:$e(`sample`),pin:Object.freeze({kind:`pin`}),memory:Object.freeze({kind:`memory`}),logic:et(`Logic`,j.Logic),sampleStatus:et(`SampleStatus`,j.SampleStatus),overflow:et(`Overflow`,j.Overflow),optional(e){let t=Je.get(e);(!t||t.type.kind===`optional`)&&A(`IR_TYPE`,`optional requires a nonoptional value type.`,[],`construct`);let n=Object.freeze({});return Je.set(n,{...t,type:{kind:`optional`,inner:t.type}}),n},namedEnum(e,t){return(typeof e!=`string`||!Array.isArray(t)||!t.length||t.some(e=>typeof e!=`string`)||new Set(t).size!==t.length)&&A(`IR_TYPE`,`Invalid named enum description.`,[],`construct`),et(e,t)},namedRecord(e,t){(typeof e!=`string`||!t||typeof t!=`object`||Array.isArray(t))&&A(`IR_TYPE`,`Invalid named record description.`,[],`construct`);for(let e of Object.values(t))[`number`,`bool`].includes(Je.get(e)?.type.kind??``)||A(`IR_TYPE`,`Record fields must be number or bool types.`,[],`construct`);return tt(e,t)}};Object.freeze(nt);let W={kind:`number`},G={kind:`bool`},rt={kind:`string`},it={kind:`bytes`},at={kind:`intent`},ot={kind:`sample`};function st(e,t){for(let n=e;n;n=n.parent)if(n===t)return!0;return!1}function ct(e){return typeof e==`object`&&e?Ye.get(e):void 0}function lt(e){return typeof e==`object`&&e?Qe.get(e):void 0}function ut(e){return typeof e==`object`&&e?Ze.get(e):void 0}function dt(e,t){let n=Object.freeze({});return e.set(n,t),n}function K(e){return e.alias?K(e.alias):e}function ft(e){let t=new Map(e[0]);for(let[n,r]of t)e.some(e=>e.get(n)!==r)&&t.delete(n);return t}let pt=/* @__PURE__ */ new WeakMap;var mt=class{options;device;jit;closed=!1;active;source;declarations=[];names=/* @__PURE__ */ new Map;expectedTypes=/* @__PURE__ */ new Set;pending=[];instructions=[];constructor(e,t,n=!1){this.options=e,this.device=t,this.jit=n,e.source!==void 0&&(this.source=k(e.source))}error(e,t,n=[]){return this.closed=!0,A(e,t,n,`construct`,this.active?.source??this.source)}check(){this.closed&&this.error(`IR_LIFECYCLE`,`This Builder is closed.`)}guard(e){this.check();try{return e()}catch(e){throw this.closed=!0,e instanceof de&&e.diagnostics.some(e=>e.phase!==`construct`)?new de(e.diagnostics.map(e=>({...e,phase:`construct`}))):e}}type(e){let t=Je.get(e);if(t||this.error(`IR_TYPE`,`Expected a Builder type descriptor.`),t.owner&&t.owner!==this&&(!this.device||pt.get(this.device)!==t.owner)&&this.error(`IR_SCOPE`,`Named type belongs to another device definition.`),this.expectedTypes.add(t),t.fields)for(let e of Object.values(t.fields))this.type(e);return t.type}sourceFor(e){let t=e?.source??this.source;return t===void 0?{}:{source:k(t)}}body(e,t,n,r,i){let a=new ht(this,e,{result:0,local:0},{},void 0,n);a.source=r===void 0?this.source:k(r);let o=this.active;this.active=a;try{i?.(a),t(a.view())}finally{a.closed=!0,this.active=o}return this.check(),{operations:a.operations,...a.source?{source:k(a.source)}:{}}}creation(e,t,n=`creation`,r){return{type:e,body:this.body(n,e=>{typeof t==`function`?t(e):e.returnValue(t)},e,r)}}declarationType(e){let t=this.names.get(e);return t&&`type`in t?t.type:void 0}add(e){e.name!==void 0&&(this.names.has(e.name)&&this.error(`IR_REFERENCE`,`Duplicate declaration ${e.name}.`),this.names.set(e.name,e)),e.kind===`start`&&this.declarations.some(e=>e.kind===`start`)&&this.error(`IR_REFERENCE`,`Only one start process is allowed.`),this.declarations.push(e)}resolve(){for(let e of this.pending){let t=this.names.get(e.call);if(!t||t.kind!==`function`){this.jit&&e.requiresSignature&&A(`IR_TYPE`,`A null or record call argument requires a bound function signature or an explicitly typed Value.`);continue}let n=t.params[e.index];if((!n||n.type.kind===`pin`||n.type.kind===`memory`)&&this.error(`IR_TYPE`,`A value argument requires a value parameter.`),n.type.kind===`optional`&&e.value!==null){let t=e.body.constantData(n.type.inner,e.value),r=e.body.space.result++,i={kind:`constant`,result:r,type:n.type.inner,constant:t,...e.node.source?{source:e.node.source}:{}},a=t=>{if(Array.isArray(t)){let n=t.indexOf(e.node);return n>=0?(t.splice(n,0,i),!0):t.some(a)}return typeof t==`object`&&!!t&&Object.values(t).some(a)};a(this.jit?this.instructions:this.declarations)||A(`IR_SCHEMA`,`Pending call argument is not part of this definition.`),delete e.node.constant,Object.assign(e.node,{kind:`optional`,type:n.type,value:r})}else{let t=e.body.constantData(n.type,e.value);Object.assign(e.node,{type:n.type,constant:t})}}for(let e of this.expectedTypes){let t=e.type.kind===`optional`?e.type.inner:e.type;if(![`enum`,`record`].includes(t.kind))continue;let n=t.name,r=this.names.get(n);if(j[n]&&t.kind===`enum`)e.members&&(e.members.length!==j[n].length||e.members.some((e,t)=>e!==j[n][t]))&&A(`IR_TYPE`,`Builtin enum description does not match its members.`);else if(r&&(r.kind!==t.kind&&A(`IR_REFERENCE`,`Named type category does not match its declaration.`),e.members&&(e.members.length!==r.members.length||e.members.some((e,t)=>e!==r.members[t]))&&A(`IR_TYPE`,`Forward enum description does not match its declaration.`),e.fields)){let t=Object.entries(e.fields);(t.length!==r.fields.length||t.some(([e,t])=>!r.fields.some(n=>n.name===e&&n.type===Je.get(t)?.type.kind)))&&A(`IR_TYPE`,`Forward record description does not match its declaration.`)}}}},ht=class e{root;mode;space;scope;parent;returns;closed=!1;ended=!1;endedByWaitUntil=!1;source;operations=[];facts=/* @__PURE__ */ new Map;localValues=/* @__PURE__ */ new Map;loop=0;calculate=!1;yielded=!1;constructor(e,t,n,r,i,a){this.root=e,this.mode=t,this.space=n,this.scope=r,this.parent=i,this.returns=a}view(){return new Proxy(Object.create(null),{get:(e,t)=>typeof t==`string`?(...e)=>this.root.guard(()=>(this.closed&&this.root.error(`IR_LIFECYCLE`,`This body Builder is closed.`),this.root.active!==this&&this.root.error(`IR_SCOPE`,`A captured outer Builder cannot emit into a nested callback.`),this.ended&&this.root.error(this.endedByWaitUntil?`IR_JIT_BOUNDARY`:`IR_CONTROL_FLOW`,`Cannot append an operation after a path terminator.`),this.invoke(t,e))):void 0})}node(e){let t={...e,...e.source===void 0&&this.source!==void 0?{source:k(this.source)}:{}};Se(t,[]),this.operations.push(t)}result(e,t,n={}){let r=this.space.result++;return this.node({...t,result:r,type:e}),dt(Ye,{root:this.root,scope:this.scope,space:this.space,type:e,id:r,...n})}handle(e,t){let n=ct(e);return(!n||n.root!==this.root||n.space!==this.space||!st(this.scope,n.scope))&&this.root.error(`IR_SCOPE`,`Value is not visible in the current execution body or scope.`),t&&!Ae(n.type,t)&&this.root.error(`IR_TYPE`,`Operand type does not match the expected type.`),n}localHandle(e){let t=Xe.get(e);return(!t||t.root!==this.root||t.space!==this.space||!st(this.scope,t.scope))&&this.root.error(`IR_SCOPE`,`Local is not visible in this execution body or scope.`),t}infer(e){if(ct(e))return this.handle(e).type;let t=lt(e);if(t)return t.owner&&t.owner!==this.root&&(!this.root.device||pt.get(this.root.device)!==t.owner)&&this.root.error(`IR_SCOPE`,`Enum member belongs to another device definition.`),{kind:`enum`,name:t.name};if(typeof e==`number`)return W;if(typeof e==`boolean`)return G;if(typeof e==`string`)return rt;if(Array.isArray(e)||e instanceof Uint8Array)return it;this.root.error(`IR_TYPE`,`A null or record literal requires an explicit target type.`)}constantData(e,t){if(e.kind===`optional`)return t!==null&&this.root.error(`IR_TYPE`,`Optional constants must be lifted from a non-null value.`),{kind:`none`};if(e.kind===`number`||e.kind===`bool`||e.kind===`string`)return typeof t!==(e.kind===`bool`?`boolean`:e.kind)&&this.root.error(`IR_TYPE`,`Constant value does not match its target type.`),{kind:e.kind,value:t};if(e.kind===`enum`){let n=lt(t);return(!n||n.name!==e.name)&&this.root.error(`IR_TYPE`,`Enum constants require a matching enum member token.`),n.owner&&n.owner!==this.root&&(!this.root.device||pt.get(this.root.device)!==n.owner)&&this.root.error(`IR_SCOPE`,`Enum member belongs to another definition.`),{kind:`enum`,name:n.name,member:n.member}}if(e.kind===`record`){(typeof t!=`object`||!t||Array.isArray(t))&&this.root.error(`IR_TYPE`,`A record constant requires a field object.`);let n=[...this.root.expectedTypes].find(t=>{let n=t.type.kind===`optional`?t.type.inner:t.type;return n.kind===`record`&&n.name===e.name&&t.fields}),r=this.root.names.get(e.name),i=n?.fields?Object.entries(n.fields).map(([e,t])=>({name:e,type:Je.get(t).type.kind})):r?.kind===`record`?r.fields:void 0;i||this.root.error(`IR_TYPE`,`Record constants require a complete named type descriptor.`);let a=t;return(Object.keys(a).length!==i.length||i.some(e=>!Object.hasOwn(a,e.name)||typeof a[e.name]!=(e.type===`bool`?`boolean`:`number`)))&&this.root.error(`IR_TYPE`,`Record constant fields do not match the target type.`),{kind:`record`,name:e.name,fields:Object.keys(a).map(e=>({name:e,value:a[e]}))}}if(e.kind===`bytes`){!(t instanceof Uint8Array)&&!Array.isArray(t)&&this.root.error(`IR_TYPE`,`bytes constants require a Uint8Array or number array.`);let e=Array.from(t);return e.some(e=>!Number.isInteger(e)||e<0||e>255)&&this.root.error(`IR_TYPE`,`Every bytes element must be an integer from zero to 255.`),{kind:`bytes`,value:Object.freeze(e)}}this.root.error(`IR_TYPE`,`sample and intent cannot be constructed from host constants.`)}operand(e,t){if(ct(e)){let n=this.handle(e);if(t&&t.kind===`optional`&&Ae(n.type,t.inner)){let e=this.handle(this.result(t,{kind:`optional`,value:n.id}));return this.facts.set(K(e),!0),e}return t&&!Ae(n.type,t)&&this.root.error(`IR_TYPE`,`Operand type does not match the expected type.`),n}let n=t??this.infer(e);if(n.kind===`optional`&&e!==null){let t=this.operand(e,n.inner),r=this.handle(this.result(n,{kind:`optional`,value:t.id}));return this.facts.set(K(r),!0),r}return this.handle(this.result(n,{kind:`constant`,constant:this.constantData(n,e)},{none:e===null}))}ref(e,t){if(typeof e==`string`)return{kind:t,name:e};let n=ut(e);return(!n||n.root!==this.root||n.space!==this.space||!st(this.scope,n.scope))&&this.root.error(`IR_SCOPE`,`Resource reference is not visible in this body.`),(n.ref.kind===`parameter`?n.ref.resource:n.ref.kind)!==t&&this.root.error(`IR_REFERENCE`,`Resource reference category does not match.`),n.ref}refHandle(e,t){return dt(Ze,{root:this.root,scope:this.scope,space:this.space,ref:{kind:t,name:e}})}requireRead(){[`creation`,`initial`].includes(this.mode)&&this.root.error(`IR_EFFECT`,`Runtime resource reads are not available in creation code.`)}requireEffect(){[`creation`,`initial`,`pure`].includes(this.mode)&&this.root.error(`IR_EFFECT`,`Runtime effects are not available in pure or creation code.`)}branch(t,n,r,i=!1){typeof t!=`function`&&this.root.error(`IR_SCHEMA`,`A body callback is required.`);let a=new e(this.root,this.mode,this.space,{parent:this.scope},this,this.returns);if(a.source=this.source,a.loop=r?0:this.loop+ +!!i,a.calculate=!!r||this.calculate,a.facts=new Map(this.facts),a.localValues=new Map(this.localValues),n)for(let[e,t]of(n.truth?n.info.yes:n.info.no)??[])a.facts.set(K(e),t);let o=this.root.active;this.root.active=a;let s;try{if(s=t(a.view()),r){if(s===void 0)a.ended||this.root.error(`IR_CONTROL_FLOW`,`A compute callback must produce a value on every normal path.`);else if(!a.ended){let e=a.operand(s,r);a.node({kind:`yield`,value:e.id}),a.yielded=!0,a.ended=!0}}}finally{a.closed=!0,this.root.active=o}return this.root.check(),{body:{operations:a.operations,...a.source?{source:k(a.source)}:{}},builder:a,returned:s}}merge(e){let t=e.filter(e=>!e.ended);if(!t.length)this.ended=!0,this.endedByWaitUntil=e.some(e=>e.endedByWaitUntil);else{this.facts=ft(t.map(e=>e.facts));for(let[e,n]of this.localValues){let r=t.map(t=>t.localValues.get(e)??n);if(r.every(e=>e===r[0]))this.localValues.set(e,r[0]);else{let i={...n,alias:void 0};this.localValues.set(e,i),r.every((e,n)=>t[n].facts.get(K(e))===!0)&&this.facts.set(i,!0)}}}}mergeComputations(e,t=!1){let n=e.filter(e=>e.yielded);if(t&&n.push(this),!n.length)this.ended=!0;else{this.facts=ft(n.map(e=>e.facts));for(let[e,t]of this.localValues){let r=n.map(n=>n.localValues.get(e)??t);if(r.every(e=>e===r[0]))this.localValues.set(e,r[0]);else{let i={...t,alias:void 0};this.localValues.set(e,i),r.every((e,t)=>n[t].facts.get(K(e))===!0)&&this.facts.set(i,!0)}}}}invoke(t,n){if(M.includes(t)){let e=this.operand(n[0],t===`not`?G:W);return this.result(t===`not`?G:W,{kind:`unary`,operator:t,value:e.id},t===`not`?{yes:e.no??/* @__PURE__ */ new Map,no:e.yes??/* @__PURE__ */ new Map}:{})}if(N.includes(t)){let e=[`equal`,`notEqual`].includes(t),r=e?this.root.type(n.shift()):t===`concat`?rt:W,i=this.operand(n[0],r),a=this.operand(n[1],r);e&&(r.kind===`intent`||r.kind===`optional`&&r.inner.kind===`intent`&&!i.none&&!a.none)&&this.root.error(`IR_TYPE`,`Intent values do not support content equality.`);let o=i.none?a:a.none?i:void 0,s=e||[`lessThan`,`lessThanOrEqual`,`greaterThan`,`greaterThanOrEqual`].includes(t);return this.result(s?G:r,{kind:`binary`,operator:t,left:i.id,right:a.id},o?{yes:/* @__PURE__ */ new Map([[K(o),t!==`equal`]]),no:/* @__PURE__ */ new Map([[K(o),t===`equal`]])}:{})}if(fe.includes(t)){let e=[`min`,`max`,`pow`].includes(t)?2:1;return n.length!==e&&this.root.error(`IR_TYPE`,`Numeric builtin argument count does not match.`),this.result(t.startsWith(`is`)?G:W,{kind:`numeric`,builtin:t,args:n.map(e=>this.operand(e,W).id)})}if(pe.includes(t)||me.includes(t)){this.requireRead();let e=this.ref(n[0],`memory`),r=this.operand(n[1],W);if(me.includes(t)){this.requireEffect(),this.node({kind:t,memory:e,offset:r.id,value:this.operand(n[2],W).id});return}return this.result(W,{kind:t,memory:e,offset:r.id})}switch(t){case`withSource`:{let[t,r]=n,i=new e(this.root,this.mode,this.space,this.scope,this.parent,this.returns);i.source=k(t),i.loop=this.loop,i.calculate=this.calculate,i.facts=this.facts,i.localValues=this.localValues;let a=this.root.active;this.root.active=i;try{r(i.view())}finally{i.closed=!0,this.root.active=a}this.operations.push(...i.operations),this.ended=i.ended,this.endedByWaitUntil=i.endedByWaitUntil,this.facts=i.facts,this.localValues=i.localValues;return}case`constant`:return ct(n[1])&&this.root.error(`IR_TYPE`,`constant requires a host constant, not a Value handle.`),this.objectOperand(n[1],this.root.type(n[0]));case`readProperty`:case`readConst`:case`readState`:case`readDerived`:{[`readState`,`readDerived`].includes(t)&&this.requireRead();let e=t.slice(4).toLowerCase();return this.result(this.root.type(n[1]),{kind:`read`,resource:e,name:n[0]})}case`local`:{let e=this.root.type(n[0]),t=this.operand(n[1],e),r=this.space.local++;this.node({kind:`local`,local:r,type:e,initial:t.id});let i={root:this.root,space:this.space,scope:this.scope,type:e,id:r};return this.localValues.set(i,t),dt(Xe,i)}case`getLocal`:{let e=this.localHandle(n[0]),t=this.localValues.get(e);return this.result(e.type,{kind:`localRead`,local:e.id},{alias:K(t),yes:t.yes??/* @__PURE__ */ new Map,no:t.no??/* @__PURE__ */ new Map,none:t.none??!1})}case`setLocal`:{let e=this.localHandle(n[0]),t=this.operand(n[1],e.type);this.node({kind:`localWrite`,local:e.id,value:t.id}),this.localValues.set(e,t);return}case`record`:{let e=this.root.type(n[0]),t=Je.get(n[0]),r=n[1];return(e.kind!==`record`||!t.fields||!r||typeof r!=`object`||Object.keys(r).length!==Object.keys(t.fields).length||Object.keys(t.fields).some(e=>!Object.hasOwn(r,e)))&&this.root.error(`IR_TYPE`,`Record fields must exactly match the descriptor.`),this.result(e,{kind:`record`,fields:Object.keys(r).map(e=>({name:e,value:this.operand(r[e],this.root.type(t.fields[e])).id}))})}case`field`:{let e=this.handle(n[0]),t=n[1],r;if(e.type.kind===`sample`)r={voltage:{kind:`optional`,inner:W},level:{kind:`enum`,name:`Logic`},status:{kind:`enum`,name:`SampleStatus`}}[t];else if(e.type.kind===`record`){let n=e.type.name,i=[...this.root.expectedTypes].find(e=>{let t=e.type.kind===`optional`?e.type.inner:e.type;return t.kind===`record`&&t.name===n&&e.fields})?.fields?.[t];if(i)r=this.root.type(i);else{let e=this.root.names.get(n),i=e?.kind===`record`?e.fields.find(e=>e.name===t):void 0;i&&(r={kind:i.type})}}r||this.root.error(`IR_REFERENCE`,`Unknown record or sample field.`);let i=K(e);i.fields??=/* @__PURE__ */ new Map;let a=i.fields.get(t),o=this.result(r,{kind:`field`,value:e.id,field:t},a?{alias:a}:{});return a||i.fields.set(t,this.handle(o)),o}case`bytes`:return this.result(it,{kind:`bytes`,elements:n.map(e=>this.operand(e,W).id)});case`length`:{let e=this.handle(n[0]);return[`string`,`bytes`].includes(e.type.kind)||this.root.error(`IR_TYPE`,`length requires string or bytes.`),this.result(W,{kind:`length`,value:e.id})}case`index`:{let e=this.handle(n[0]);return[`string`,`bytes`].includes(e.type.kind)||this.root.error(`IR_TYPE`,`index requires string or bytes.`),this.result(e.type.kind===`string`?rt:W,{kind:`index`,value:e.id,index:this.operand(n[1],W).id})}case`optional`:{let e=this.handle(n[0]);e.type.kind===`optional`&&this.root.error(`IR_TYPE`,`Optional types cannot be nested.`);let t=this.result({kind:`optional`,inner:e.type},{kind:`optional`,value:e.id});return this.facts.set(K(this.handle(t)),!0),t}case`isNone`:{let e=this.handle(n[0]);return e.type.kind!==`optional`&&this.root.error(`IR_TYPE`,`isNone requires an optional value.`),this.result(G,{kind:`isNone`,value:e.id},{yes:/* @__PURE__ */ new Map([[K(e),!1]]),no:/* @__PURE__ */ new Map([[K(e),!0]])})}case`nonNull`:{let e=this.handle(n[0]);return(e.type.kind!==`optional`||this.facts.get(K(e))!==!0)&&this.root.error(`IR_TYPE`,`nonNull requires a dominating non-null proof.`),this.result(e.type.inner,{kind:`nonNull`,value:e.id})}case`pin`:return this.mode===`creation`&&this.root.error(`IR_EFFECT`,`Pin references are not available in ordinary creation computations.`),this.refHandle(n[0],`pin`);case`memory`:return this.requireRead(),this.refHandle(n[0],`memory`);case`memoryLength`:return this.requireRead(),this.result(W,{kind:`memoryLength`,memory:this.ref(n[0],`memory`)});case`copyBytes`:return this.requireRead(),this.result(it,{kind:`copyBytes`,memory:this.ref(n[0],`memory`),offset:this.operand(n[1],W).id,length:this.operand(n[2],W).id});case`readSample`:return this.requireRead(),this.result(ot,{kind:`readSample`,pin:this.ref(n[0],`pin`)});case`resistor`:return this.mode===`creation`&&this.root.error(`IR_EFFECT`,`Intent construction requires initial-intent or runtime code.`),this.result(at,{kind:`resistor`,to:this.ref(n[0],`pin`),resistance:this.operand(n[1],W).id});case`combineIntents`:return this.mode===`creation`&&this.root.error(`IR_EFFECT`,`Intent construction is not available here.`),this.result(at,{kind:`combineIntents`,values:n.map(e=>this.operand(e,at).id)});case`refEqual`:{this.requireRead();let e=ut(n[0]),t=ut(n[1]);(!e||!t)&&this.root.error(`IR_TYPE`,`refEqual requires resource reference handles.`);let r=e.ref.kind===`parameter`?e.ref.resource:e.ref.kind;return this.result(G,{kind:`refEqual`,left:this.ref(n[0],r),right:this.ref(n[1],r)})}case`writeState`:this.requireEffect(),this.node({kind:`write`,resource:`state`,name:n[0],value:this.operand(n[1],this.root.declarationType(n[0])).id});return;case`writeIntent`:this.requireEffect(),this.node({kind:`writeIntent`,pin:this.ref(n[0],`pin`),value:this.operand(n[1],at).id});return;case`send`:this.requireEffect(),this.node({kind:`send`,channel:n[0],value:this.operand(n[1],this.root.declarationType(n[0])).id});return;case`notify`:this.requireEffect(),this.node({kind:`notify`,notification:n[0]});return;case`now`:case`random`:return this.requireEffect(),this.result(W,{kind:t});case`call`:case`callValue`:case`callPure`:case`callPureValue`:{let e=t.startsWith(`callPure`),r=t.endsWith(`Value`);e||this.requireEffect();let i=n.shift(),a=r?this.root.type(n.shift()):void 0,o=this.root.names.get(i),s=o?.kind===`function`?o.params:void 0,c=n.map((e,t)=>{let n=ut(e);if(n)return this.mode===`creation`&&this.root.error(`IR_EFFECT`,`Resource arguments are not available in ordinary creation code.`),this.ref(e,n.ref.kind===`parameter`?n.ref.resource:n.ref.kind);let r=s?.[t]?.type;if(r&&[`pin`,`memory`].includes(r.kind)&&this.root.error(`IR_TYPE`,`A resource reference argument is required.`),!r&&!ct(e)){let n=e===null||typeof e==`object`&&!lt(e)&&!Array.isArray(e)&&!(e instanceof Uint8Array),r=n?W:this.infer(e),a={kind:`constant`,result:this.space.result++,type:r,constant:n?{kind:`number`,value:0}:this.constantData(r,e),...this.source?{source:k(this.source)}:{}};return this.operations.push(a),this.root.pending.push({node:a,call:i,index:t,value:lt(e)?e:k(e),body:this,requiresSignature:n}),{kind:`value`,value:a.result}}return{kind:`value`,value:this.operand(e,r).id}}),l={kind:r?`callValue`:`call`,name:i,pure:e,args:c};if(r)return this.result(a,l);this.node(l);return}case`receive`:return(this.calculate||this.mode!==`process`)&&this.root.error(`IR_EFFECT`,`receive requires a process statement region.`),this.result(this.root.type(n[1]),{kind:`receive`,channel:n[0]});case`if`:{let e=this.operand(n[0],G),t=this.branch(n[1],{info:e,truth:!0}),r=this.branch(n[2]??(()=>{}),{info:e,truth:!1});this.node({kind:`if`,condition:e.id,yes:t.body,...n[2]?{no:r.body}:{}}),this.merge([t.builder,r.builder]);return}case`match`:{let e=this.handle(n[0]),t=n[1];Array.isArray(t)||this.root.error(`IR_SCHEMA`,`match arms must be an array.`);let r=[],i=t.map(t=>{let n=t.pattern===null?{kind:`none`}:this.constantData(e.type.kind===`optional`?e.type.inner:e.type,t.pattern);[`none`,`number`,`bool`,`string`,`enum`].includes(n.kind)||this.root.error(`IR_TYPE`,`Invalid match pattern.`);let i={...e,yes:/* @__PURE__ */ new Map([[K(e),n.kind!==`none`]])},a=this.branch(t.emit,{info:i,truth:!0});return r.push(a.builder),{pattern:n,body:a.body}}),a=i.some(e=>e.pattern.kind===`none`)?{info:{...e,yes:/* @__PURE__ */ new Map([[K(e),!0]])},truth:!0}:void 0,o=n[2]?this.branch(n[2],a):void 0;o&&r.push(o.builder),this.node({kind:`match`,value:e.id,arms:i,...o?{otherwise:o.body}:{}}),this.merge(r.length?r:[this]);return}case`while`:case`loop`:{let e=new Map(this.localValues),r=t===`while`?this.branch(n[0],void 0,G):void 0,i=this.branch(n[+(t===`while`)],void 0,void 0,!0);this.node({kind:t,...r?{test:{type:G,body:r.body}}:{},body:i.body});for(let[t,n]of e)(i.builder.localValues.get(t)!==n||r&&r.builder.localValues.get(t)!==n)&&this.localValues.set(t,{...n,alias:void 0});r&&!r.builder.yielded&&(this.ended=!0);return}case`and`:case`or`:{let e=this.operand(n[0],G),r=t===`and`,i=this.branch(n[1],{info:e,truth:r},G),a=ct(i.returned),o=(e,t)=>new Map([...e??[],...t??[]]),s=r?o(e.yes,a?.yes):ft([e.yes??/* @__PURE__ */ new Map,o(e.no,a?.yes)]),c=r?ft([e.no??/* @__PURE__ */ new Map,o(e.yes,a?.no)]):o(e.no,a?.no),l=this.result(G,{kind:t,left:e.id,right:{type:G,body:i.body}},{yes:s,no:c});return this.mergeComputations([i.builder],!0),l}case`select`:{let e=this.root.type(n[0]),t=this.operand(n[1],G),r=this.branch(n[2],{info:t,truth:!0},e),i=this.branch(n[3],{info:t,truth:!1},e),a=this.result(e,{kind:`select`,condition:t.id,yes:{type:e,body:r.body},no:{type:e,body:i.body}});return this.mergeComputations([r.builder,i.builder]),a}case`assert`:{let e=this.operand(n[0],G),t=n[1]?this.branch(n[1],{info:e,truth:!1},rt):void 0;this.node({kind:`assert`,condition:e.id,...t?{message:{type:rt,body:t.body}}:{}});for(let[t,n]of e.yes??[])this.facts.set(K(t),n);return}case`wait`:case`elapse`:(this.calculate||(t===`wait`?this.mode!==`process`:this.mode!==`jit`))&&this.root.error(`IR_EFFECT`,`${t} is not permitted in this context.`),this.node({kind:t,duration:this.operand(n[0],W).id});return;case`waitUntil`:(this.mode!==`jit`||this.calculate||this.loop)&&this.root.error(`IR_JIT_BOUNDARY`,`waitUntil requires a JIT tail path outside loops and computations.`),this.node({kind:`waitUntil`,predicate:n[0]}),this.ended=!0,this.endedByWaitUntil=!0;return;case`redirect`:[`jit`,`sync`].includes(this.mode)||this.root.error(`IR_EFFECT`,`redirect requires a JIT-capable context.`),this.node({kind:`redirect`,target:this.operand(n[0],W).id,delay:this.operand(n[1]??0,W).id}),this.ended=!0;return;case`stop`:(this.mode!==`jit`||this.calculate)&&this.root.error(`IR_EFFECT`,`stop requires a JIT statement region.`),this.node({kind:`stop`}),this.ended=!0;return;case`break`:case`continue`:this.loop||this.root.error(`IR_CONTROL_FLOW`,`${t} requires an enclosing loop.`),this.node({kind:t}),this.ended=!0;return;case`return`:(this.calculate||this.returns||[`jit`,`creation`,`initial`].includes(this.mode))&&this.root.error(`IR_CONTROL_FLOW`,`Void return is not permitted in this body.`),this.node({kind:`return`}),this.ended=!0;return;case`returnValue`:(this.calculate||!this.returns)&&this.root.error(`IR_CONTROL_FLOW`,`returnValue is not permitted in this body.`),this.node({kind:`returnValue`,value:this.operand(n[0],this.returns).id}),this.ended=!0;return;default:this.root.error(`IR_SCHEMA`,`Unknown Builder operation ${t}.`)}}objectOperand(e,t){let n=this.operand(e,t);return dt(Ye,n)}};function gt(e={}){let t=new mt({name:`JitBlock`,...e.source?{source:e.source}:{}},e.device,!0);if(e.device)for(let n of e.device.declarations)`name`in n&&t.names.set(n.name,n);let n=(r={closed:!1})=>new Proxy(Object.create(null),{get:(i,a)=>typeof a==`string`?(...i)=>{if(a===`finish`){t.check(),r.closed&&t.error(`IR_LIFECYCLE`,`This source view is closed.`),t.active&&t.error(`IR_SCOPE`,`Cannot finish a block inside an instruction callback.`),t.closed=!0,t.resolve();let n={kind:`block`,instructions:t.instructions,...t.sourceFor()};return e.device?qe(n,e.device):Ke(n)}return t.guard(()=>{if(r.closed&&t.error(`IR_LIFECYCLE`,`This source view is closed.`),t.active&&t.error(`IR_SCOPE`,`Cannot add instructions inside an instruction callback.`),a===`withSource`){let e=t.source,r={closed:!1};t.source=k(i[0]);try{i[1](n(r))}finally{r.closed=!0,t.source=e}return}a!==`instruction`&&t.error(`IR_SCHEMA`,`Unknown block Builder method ${a}.`);let e=i[0];(!e||!Number.isFinite(e.pc)||!Number.isFinite(e.nextPc))&&t.error(`IR_SCHEMA`,`Instruction boundaries require finite pc and nextPc.`);let o=t.instructions.at(-1);o&&o.nextPc!==e.pc&&t.error(`IR_JIT_BOUNDARY`,`Adjacent instruction boundaries must match.`);let s=t.body(`jit`,i[1],void 0,e.source??t.source);t.instructions.push({pc:e.pc,nextPc:e.nextPc,body:s,...t.sourceFor(e)})})}:void 0});return n()}function _t(e,t){return t}function vt(e){return Object.freeze(Object.fromEntries(e))}function yt(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isInteger(r))throw TypeError(`Byte value must be an integer number`);if(r<0||r>255)throw RangeError(`Byte value must be in [0, 255]`);t[n]=r}return t}let bt=Object.freeze([]);function xt(e){if(e.length===0)return bt;if(e.length===1&&Array.isArray(e[0]))return e[0];let t=[];for(let n of e)if(Array.isArray(n))for(let e of n)t.push(e);else t.push(n);return Object.freeze(t)}function St(e,t){if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return e===t;if(Ct(e)||Ct(t)){if(!Ct(e)||!Ct(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}let n=e,r=t,i=Object.keys(n);if(i.length!==Object.keys(r).length)return!1;for(let e of i)if(!Object.hasOwn(r,e)||!St(n[e],r[e]))return!1;return!0}function Ct(e){return Array.isArray(e)||ArrayBuffer.isView(e)||`length`in e&&Symbol.iterator in e}function wt(e,t){if(typeof t!=`number`||!Number.isSafeInteger(t))throw TypeError(`Index must be a safe integer number`);if(t<0||t>=e.length)throw RangeError(`Index is outside the value`);return e[t]}function Tt(e){if(e===null)throw TypeError(`Expected a non-null value`);return e}function Et(e){if(typeof e!=`boolean`)throw TypeError(`Condition must be a boolean`);return e}function Dt(e){if(typeof e!=`number`||!Number.isFinite(e)||!Number.isInteger(e))throw TypeError(`Duration must be a finite integer number`);if(e<0||e>72e14)throw RangeError(`Duration must be in [0, 7200000000000000] picoseconds`);return e}function Ot(e){if(typeof e!=`number`||!Number.isFinite(e))throw TypeError(`Redirect target must be a finite number`);return e}function kt(e,t){if(!e)throw TypeError(`Reaction value requires a reaction frame`);return e[t]}function At(e,t){if(!e||t>=e.captures.length)throw RangeError(`Reaction capture is not available`);return e.captures[t]}let jt=Symbol(`terminated call`);function*Mt(e){let t=!1;try{let n=e.next();for(;!n.done;){let t=n.value,r=yield t;if(t.kind===`stop`||t.kind===`redirect`)return jt;n=e.next(r)}return t=!0,n.value}finally{t||e.return(void 0)}}let Nt=Object.freeze({createEnum:_t,createRecord:vt,createBytes:yt,combineIntents:xt,equalValues:St,readIndex:wt,nonNull:Tt,checkBoolean:Et,checkDuration:Dt,checkPc:Ot,reactionValue:kt,reactionCapture:At,delegate:Mt,terminated:jt});function Pt(e){return e.uri===void 0?Object.freeze({...e}):Object.freeze({...e,range:Object.freeze({start:Object.freeze({...e.range.start}),end:Object.freeze({...e.range.end})})})}function Ft(e){return e.kind===`optional`?Object.freeze({...e,inner:Object.freeze({...e.inner})}):Object.freeze({...e})}function It(e){switch(e.kind){case`unary`:case`field`:case`length`:case`optional`:case`isNone`:case`nonNull`:case`localWrite`:case`write`:case`writeIntent`:case`send`:case`match`:case`returnValue`:case`yield`:return[e.value];case`binary`:return[e.left,e.right];case`numeric`:return[...e.args];case`record`:return e.fields.map(e=>e.value);case`bytes`:return[...e.elements];case`index`:return[e.value,e.index];case`local`:return[e.initial];case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:return[e.offset];case`store8`:case`store16le`:case`store16be`:case`store32le`:case`store32be`:return[e.offset,e.value];case`copyBytes`:return[e.offset,e.length];case`resistor`:return[e.resistance];case`combineIntents`:return[...e.values];case`call`:case`callValue`:return e.args.flatMap(e=>e.kind===`value`?[e.value]:[]);case`if`:case`select`:case`assert`:return[e.condition];case`and`:case`or`:return[e.left];case`wait`:case`elapse`:return[e.duration];case`redirect`:return[e.target,e.delay];default:return[]}}function Lt(e){let t=[],n=e=>{e.kind===`parameter`&&t.push(`argument:${e.index}`)};return`memory`in e&&n(e.memory),`pin`in e&&n(e.pin),e.kind===`resistor`&&n(e.to),e.kind===`refEqual`&&(n(e.left),n(e.right)),(e.kind===`call`||e.kind===`callValue`)&&e.args.forEach(e=>{e.kind!==`value`&&n(e)}),e.kind===`parameter`&&t.push(`argument:${e.index}`),(e.kind===`reactionValue`||e.kind===`reactionCapture`)&&t.push(`reaction`),t}function Rt(e){return e.kind===`parameter`?`$${e.index}`:e.name}function zt(e){let t=[],n=[],r=[],i=e.kind===`call`||e.kind===`callValue`,a=i||[`wait`,`elapse`,`receive`,`waitUntil`,`redirect`].includes(e.kind),o=i||(/* @__PURE__ */ `read.write.readSample.writeIntent.resistor.bytes.index.nonNull.field.length.memoryLength.copyBytes.send.receive.notify.now.random.reactionValue.reactionCapture.if.select.and.or.assert.wait.elapse.redirect`.split(`.`)).includes(e.kind)||e.kind.startsWith(`load`)||e.kind.startsWith(`store`);return e.kind===`read`&&t.push(`${e.resource}:${e.name}`),e.kind===`write`&&n.push(`state:${e.name}`),`memory`in e&&(e.kind.startsWith(`store`)?n:t).push(`memory:${Rt(e.memory)}`),e.kind===`readSample`&&t.push(`pin:${Rt(e.pin)}`),e.kind===`writeIntent`&&n.push(`pin:${Rt(e.pin)}`),e.kind===`send`&&n.push(`channel:${e.channel}`),e.kind===`receive`&&(t.push(`channel:${e.channel}`),n.push(`channel:${e.channel}`)),e.kind===`notify`&&n.push(`notification:${e.notification}`),e.kind===`waitUntil`&&(t.push(`*`),r.push(e.predicate)),i&&(r.push(e.name),t.push(`*`),n.push(`*`)),Object.freeze({reads:Object.freeze(t),writes:Object.freeze(n),calls:Object.freeze(r),operations:Object.freeze([e.kind]),maySuspend:a,mayThrow:o,mayRedirect:i||e.kind===`redirect`,mayStop:i||e.kind===`stop`,timeDependent:i||e.kind===`now`,random:i||e.kind===`random`})}function Bt(e,t){let n=It(e);if(n.some(e=>!t.has(e)))return;let r=t.get(n[0]),i=t.get(n[1]);switch(e.kind){case`constant`:{let t=e.constant;return t.kind===`none`?{value:null}:t.kind===`enum`?{value:t.member}:t.kind===`number`||t.kind===`bool`||t.kind===`string`?{value:t.value}:void 0}case`optional`:return{value:r};case`isNone`:return{value:r===null};case`nonNull`:return r===null?void 0:{value:r};case`unary`:switch(e.operator){case`positive`:return{value:+r};case`negate`:return{value:-r};case`not`:return{value:!r};case`bitNot`:return{value:~r}}break;case`binary`:{let t=r,n=i;switch(e.operator){case`add`:return{value:t+n};case`subtract`:return{value:t-n};case`multiply`:return{value:t*n};case`divide`:return{value:t/n};case`remainder`:return{value:t%n};case`power`:return{value:t**n};case`lessThan`:return{value:t<n};case`lessThanOrEqual`:return{value:t<=n};case`greaterThan`:return{value:t>n};case`greaterThanOrEqual`:return{value:t>=n};case`equal`:return{value:r===i};case`notEqual`:return{value:r!==i};case`concat`:return{value:r+i};case`bitAnd`:return{value:t&n};case`bitOr`:return{value:t|n};case`bitXor`:return{value:t^n};case`shiftLeft`:return{value:t<<n};case`shiftRight`:return{value:t>>n};case`shiftRightUnsigned`:return{value:t>>>n}}break}case`numeric`:{let n=e.args.map(e=>t.get(e));if(e.builtin===`isNaN`)return{value:Number.isNaN(n[0])};if(e.builtin===`isFinite`)return{value:Number.isFinite(n[0])};if(e.builtin===`isInteger`)return{value:Number.isInteger(n[0])};if(e.builtin===`isSafeInteger`)return{value:Number.isSafeInteger(n[0])};let r=Math[e.builtin];return{value:r(...n)}}}}function Vt(e,t,n){switch(e.kind){case`constant`:return e.constant.kind!==`bytes`&&e.constant.kind!==`record`;case`parameter`:case`localRead`:case`optional`:case`isNone`:case`unary`:case`numeric`:return!0;case`nonNull`:return n.has(e.result);case`binary`:{if(e.operator!==`equal`&&e.operator!==`notEqual`)return!0;let n=t.get(e.left);return n?.kind===`optional`&&(n=n.inner),!!n&&[`number`,`string`,`bool`,`enum`].includes(n.kind)}default:return!1}}function Ht(e){let t=e=>typeof e!=`object`||!e?e:Object.freeze(Array.isArray(e)?e.map(t):Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).map(([e,n])=>[e,t(n)])));return Object.freeze(Object.fromEntries(Object.entries(e).flatMap(([n,r])=>[`kind`,`type`,`source`,`body`,`test`,`message`,`yes`,`no`].includes(n)||r===void 0||n===`right`&&typeof r==`object`?[]:[[n,t(n===`arms`?e.arms.map(e=>e.pattern):r)]])))}function Ut(e,t,n=!0){return new Wt(e,t.optimize!==!1,n).analyze()}var Wt=class{optimize;metadata;nodes=[];regions=[];blocks=[];blockSpecs=[];buildingGraph=!1;edges=[];byOperation=/* @__PURE__ */ new Map;folded=/* @__PURE__ */ new Map;eliminated=/* @__PURE__ */ new Set;root;throwExit;stopExit;redirectExit;constructor(e,t,n){this.optimize=t,this.metadata=n,this.root=this.index(e,[],null,e.source),this.throwExit=this.block(0,`throw`),this.stopExit=this.block(0,`stop`),this.redirectExit=this.block(0,`redirect`)}block(e,t,n=null){let r=this.blockSpecs.length,i={id:r,region:e,role:t,position:n};return this.blockSpecs.push(i),this.buildingGraph&&this.blocks.push(this.allocateBlock(i)),r}allocateBlock(e){return{...e,uses:/* @__PURE__ */ new Set,definitions:/* @__PURE__ */ new Set,liveIn:/* @__PURE__ */ new Set,liveOut:/* @__PURE__ */ new Set}}edge(e,t,n,r={}){this.edges.push(Object.freeze({from:e,to:t,kind:n,...r}))}index(e,t,n,r){let i=this.regions.length,a={id:i,parent:n,path:Object.freeze([...t]),entry:this.block(i,`entry`),exit:this.block(i,`exit`),nodes:[]};return this.regions.push(a),e.operations.forEach((n,o)=>{let s=this.nodes.length,c=this.block(i,`operation`,s),l=this.metadata?n.source??e.source??r:void 0,u,d={operation:n,position:s,block:c,definitionBlock:c,region:i,path:Object.freeze([...t,`operations`,o]),inputs:Object.freeze(It(n)),get effects(){return u??=zt(n)},children:/* @__PURE__ */ new Map,...l?{source:Pt(l)}:{}};a.nodes.push(d),this.nodes.push(d),this.byOperation.set(n,d);let f=(e,t,n=[e],r=l)=>{d.children.set(e,this.index(t,[...d.path,...n],i,r))};switch(n.kind){case`if`:f(`yes`,n.yes),n.no&&f(`no`,n.no);break;case`match`:n.arms.forEach((e,t)=>f(`arm${t}`,e.body,[`arms`,t,`body`],e.source??l)),n.otherwise&&f(`otherwise`,n.otherwise);break;case`while`:f(`test`,n.test.body,[`test`,`body`]),f(`body`,n.body);break;case`loop`:f(`body`,n.body);break;case`select`:f(`yes`,n.yes.body,[`yes`,`body`]),f(`no`,n.no.body,[`no`,`body`]);break;case`and`:case`or`:f(`right`,n.right.body,[`right`,`body`]);break;case`assert`:n.message&&f(`message`,n.message.body,[`message`,`body`])}}),a}link(e,t,n,r=`next`){this.edge(e.entry,e.nodes[0]?.block??e.exit,`next`),t!==null&&this.edge(e.exit,t,r),e.nodes.forEach((t,r)=>{let i=t.operation,a=t.block,o=e.nodes[r+1]?.block??e.exit,s=(e,r=o,i=n,a=`next`)=>{let s=t.children.get(e);return this.link(s,r,i,a),s},c=(e,n)=>{let r=t.children.get(e);return this.link(r,n,{yieldTo:r.exit}),r};switch(t.effects.mayThrow&&i.kind!==`assert`&&this.edge(a,this.throwExit,`throw`),i.kind){case`if`:this.edge(a,s(`yes`).entry,`true`),this.edge(a,t.children.has(`no`)?s(`no`).entry:o,`false`);break;case`match`:i.arms.forEach((e,t)=>this.edge(a,s(`arm${t}`).entry,`arm`,{arm:t})),i.otherwise&&this.edge(a,s(`otherwise`).entry,`default`);break;case`while`:{let e=c(`test`,null),t={...n,breakTo:o,continueTo:e.entry},r=s(`body`,e.entry,t,`backedge`);this.edge(a,e.entry,`next`),this.edge(e.exit,r.entry,`true`),this.edge(e.exit,o,`false`);break}case`loop`:{let e=t.children.get(`body`);s(`body`,e.entry,{...n,breakTo:o,continueTo:e.entry},`backedge`),this.edge(a,e.entry,`next`);break}case`select`:case`and`:case`or`:{let n=this.block(e.id,`join`,t.position);if(t.definitionBlock=n,this.edge(n,o,`next`),i.kind===`select`)this.edge(a,c(`yes`,n).entry,`true`),this.edge(a,c(`no`,n).entry,`false`);else{let e=c(`right`,n);this.edge(a,e.entry,i.kind===`and`?`true`:`false`),this.edge(a,n,i.kind===`and`?`false`:`true`,{value:i.left})}break}case`assert`:{let n=this.block(e.id,`throw`,t.position);t.failureBlock=n,this.edge(a,o,`true`),this.edge(n,this.throwExit,`throw`),this.edge(a,i.message?c(`message`,n).entry:n,`false`);break}case`break`:if(n.breakTo===void 0)throw TypeError(`Break has no loop target`);this.edge(a,n.breakTo,`break`);break;case`continue`:if(n.continueTo===void 0)throw TypeError(`Continue has no loop target`);this.edge(a,n.continueTo,`continue`);break;case`yield`:if(n.yieldTo===void 0)throw TypeError(`Yield has no value-region target`);this.edge(a,n.yieldTo,`yield`,{value:i.value});break;case`return`:case`returnValue`:this.edge(a,this.root.exit,`return`);break;case`redirect`:this.edge(a,this.redirectExit,`redirect`);break;case`stop`:this.edge(a,this.stopExit,`stop`);break;case`wait`:case`elapse`:case`receive`:case`waitUntil`:case`call`:case`callValue`:{let n=this.block(e.id,`resume`,t.position);t.resumeBlock=n;let r=i.kind===`call`||i.kind===`callValue`;if(this.edge(a,n,`suspend`),r){let r=this.block(e.id,`join`,t.position);t.completionBlock=r,t.definitionBlock=r,this.edge(a,r,`next`),this.edge(n,n,`suspend`),this.edge(n,r,`resume`),this.edge(r,o,`next`);for(let e of[a,n])this.edge(e,this.redirectExit,`redirect`),this.edge(e,this.stopExit,`stop`);this.edge(n,this.throwExit,`throw`)}else i.kind===`receive`&&(t.definitionBlock=n),this.edge(n,i.kind===`waitUntil`?this.root.exit:o,`resume`),i.kind===`elapse`&&this.edge(a,o,`next`);break}default:this.edge(a,o,`next`)}})}analyze(){let e=/* @__PURE__ */ new Map;for(let t of this.nodes)`result`in t.operation&&e.set(t.operation.result,t.operation.type);let t=/* @__PURE__ */ new Map;if(this.optimize){for(let e of this.nodes){if(!(`result`in e.operation))continue;let n=Bt(e.operation,t);n&&(t.set(e.operation.result,n.value),e.operation.kind!==`constant`&&this.folded.set(e.position,n.value))}let n=/* @__PURE__ */ new Map;for(let e of this.nodes)`result`in e.operation&&this.folded.has(e.position)&&n.set(e.operation.result,this.folded.get(e.position));let r=new Map(this.nodes.flatMap(e=>`result`in e.operation?[[e.operation.result,e]]:[])),i=/* @__PURE__ */ new Set,a=[],o=e=>{i.has(e)||(i.add(e),a.push(e))};for(let e of this.nodes)this.folded.has(e.position)||e.inputs.forEach(o);for(let e=0;e<a.length;e++){let t=r.get(a[e]);t&&!this.folded.has(t.position)&&t.inputs.forEach(o)}for(let t of this.nodes)`result`in t.operation&&!i.has(t.operation.result)&&Vt(t.operation,e,n)&&this.eliminated.add(t.position)}let n,r=()=>n??=this.complete(t);return{nodes:this.nodes,byOperation:this.byOperation,folded:this.folded,constants:t,eliminated:this.eliminated,optimizations:Object.freeze({enabled:this.optimize,foldedPositions:Object.freeze([...this.folded.keys()].filter(e=>!this.eliminated.has(e))),eliminatedPositions:Object.freeze([...this.eliminated])}),get graph(){return r().graph},get effects(){return r().effects},get resources(){return r().resources}}}complete(e){this.buildingGraph=!0,this.blocks=this.blockSpecs.map(e=>this.allocateBlock(e)),this.link(this.root,null,{});for(let e of this.nodes){if(this.eliminated.has(e.position))continue;let t=this.blocks[e.block],n=e.operation;this.folded.has(e.position)||(e.inputs.forEach(e=>t.uses.add(`value:${e}`)),Lt(n).forEach(e=>t.uses.add(e)),n.kind===`localRead`&&t.uses.add(`local:${n.local}`)),`result`in n&&this.blocks[e.definitionBlock].definitions.add(`value:${n.result}`),(n.kind===`local`||n.kind===`localWrite`)&&t.definitions.add(`local:${n.local}`)}let t=/* @__PURE__ */ new Map;for(let e of this.nodes){let n=e.operation.kind===`while`?e.children.get(`test`):e.operation.kind===`assert`?e.children.get(`message`):void 0;if(!n)continue;let r=`region:${n.id}`;t.set(n.exit,r),this.blocks[e.failureBlock??n.exit].uses.add(r)}for(let e of this.edges)e.kind===`yield`&&t.has(e.to)&&this.blocks[e.from].definitions.add(t.get(e.to));let n=this.blocks.map(()=>[]),r=this.blocks.map(()=>[]);this.edges.forEach(e=>{n[e.from].push(e.to),r[e.to].push(e.from)});let i=this.blocks.map(e=>new Set([...e.uses].filter(e=>e.startsWith(`region:`)))),a=this.blocks.map(e=>new Set([...e.definitions].filter(e=>e.startsWith(`region:`))));for(let e of this.nodes){let t=e.operation;e.inputs.forEach(t=>i[e.block].add(`value:${t}`)),Lt(t).forEach(t=>i[e.block].add(t)),t.kind===`localRead`&&i[e.block].add(`local:${t.local}`),`result`in t&&a[e.definitionBlock].add(`value:${t.result}`),(t.kind===`local`||t.kind===`localWrite`)&&a[e.block].add(`local:${t.local}`)}let o=(e,t)=>{let r=this.blocks.map(()=>/* @__PURE__ */ new Set),i=this.blocks.map(()=>/* @__PURE__ */ new Set),a=!0;for(;a;){a=!1;for(let o=this.blocks.length-1;o>=0;o--){let s=new Set(n[o].flatMap(e=>[...r[e]])),c=/* @__PURE__ */ new Set([...e[o],...[...s].filter(e=>!t[o].has(e))]);(s.size!==i[o].size||[...s].some(e=>!i[o].has(e))||c.size!==r[o].size||[...c].some(e=>!r[o].has(e)))&&(a=!0,i[o]=s,r[o]=c)}}return{input:r,output:i}},s=o(this.blocks.map(e=>e.uses),this.blocks.map(e=>e.definitions)),c=o(i,a);this.blocks.forEach((e,t)=>{e.liveIn=s.input[t],e.liveOut=s.output[t]});let l=/* @__PURE__ */ new Map;for(let e of this.edges)if(e.kind===`yield`&&e.value!==void 0){let t=l.get(e.to)??[];t.push(e.value),l.set(e.to,t)}let u=/* @__PURE__ */ new Map;for(let e of this.nodes)for(let t of e.inputs){let n=u.get(t)??[];n.push(e.position),u.set(t,n)}let d=this.nodes.flatMap(e=>{let t=e.operation;if(!(`result`in t))return[];let n=t.kind===`select`||t.kind===`and`||t.kind===`or`,r=n?[...e.children.values()].flatMap(e=>l.get(e.exit)??[]):[];return(t.kind===`and`||t.kind===`or`)&&r.unshift(t.left),[Object.freeze({result:t.result,type:Ft(t.type),position:e.position,region:e.region,block:e.definitionBlock,form:n?`phi`:`operation`,inputs:Object.freeze(n?r:[...e.inputs]),users:Object.freeze(u.get(t.result)??[]),eliminated:this.eliminated.has(e.position),folded:this.folded.has(e.position)})]}),f=Object.freeze({entry:this.root.entry,normalExit:this.root.exit,regions:Object.freeze(this.regions.map(({id:e,parent:t,path:n,entry:r,exit:i})=>Object.freeze({id:e,parent:t,path:n,entry:r,exit:i}))),blocks:Object.freeze(this.blocks.map(e=>Object.freeze({...e,predecessors:Object.freeze([...new Set(r[e.id])]),successors:Object.freeze([...new Set(n[e.id])]),uses:Object.freeze([...e.uses]),definitions:Object.freeze([...e.definitions]),liveIn:Object.freeze([...e.liveIn]),liveOut:Object.freeze([...e.liveOut]),baselineLiveIn:Object.freeze([...c.input[e.id]]),baselineLiveOut:Object.freeze([...c.output[e.id]])}))),edges:Object.freeze([...this.edges]),values:Object.freeze(d),operations:Object.freeze(this.nodes.map(e=>Object.freeze({position:e.position,block:e.block,region:e.region,kind:e.operation.kind,path:e.path,...e.source?{source:e.source}:{},inputs:e.inputs,attributes:Ht(e.operation),regions:Object.freeze([...e.children].map(([e,t])=>Object.freeze({role:e,region:t.id}))),effects:e.effects,eliminated:this.eliminated.has(e.position),folded:this.folded.has(e.position)})))}),p=this.nodes.map(e=>e.effects),m=e=>Object.freeze([...new Set(p.flatMap(t=>t[e]))]),h=Object.freeze({reads:m(`reads`),writes:m(`writes`),calls:m(`calls`),operations:m(`operations`),maySuspend:p.some(e=>e.maySuspend),mayRedirect:p.some(e=>e.mayRedirect),mayStop:p.some(e=>e.mayStop),timeDependent:p.some(e=>e.timeDependent),random:p.some(e=>e.random)}),g=new Set([...h.reads,...h.writes].filter(e=>e!==`*`));for(let e of this.nodes){let t=e.operation;if(t.kind===`resistor`&&g.add(`pin:${Rt(t.to)}`),t.kind===`refEqual`)for(let e of[t.left,t.right])g.add(`${e.kind===`parameter`?e.resource:e.kind}:${Rt(e)}`);if(t.kind===`call`||t.kind===`callValue`)for(let e of t.args)e.kind!==`value`&&g.add(`${e.kind===`parameter`?e.resource:e.kind}:${Rt(e)}`)}return{nodes:this.nodes,byOperation:this.byOperation,graph:f,folded:this.folded,constants:e,eliminated:this.eliminated,effects:h,resources:Object.freeze([...g]),optimizations:Object.freeze({enabled:this.optimize,foldedPositions:Object.freeze([...this.folded.keys()].filter(e=>!this.eliminated.has(e))),eliminatedPositions:Object.freeze([...this.eliminated])})}}};function Gt(e,t,n,r,i,a){let o=[],s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map;for(let t of e.nodes){let e=t.operation;`result`in e&&c.set(`value:${e.result}`,Ft(e.type)),e.kind===`local`&&c.set(`local:${e.local}`,Ft(e.type)),e.kind===`parameter`&&c.set(`argument:${e.index}`,Ft(e.type));let n=e=>{e.kind===`parameter`&&e.resource&&c.set(`argument:${e.index}`,Object.freeze({kind:e.resource}))};`memory`in e&&n(e.memory),`pin`in e&&n(e.pin),e.kind===`resistor`&&n(e.to),e.kind===`refEqual`&&(n(e.left),n(e.right)),(e.kind===`call`||e.kind===`callValue`)&&e.args.forEach(e=>{e.kind!==`value`&&n(e)})}let l=(e,t,n,r,i,a=!0)=>{s.has(e)||(s.set(e,o.length),o.push(Object.freeze({id:o.length,key:e,kind:t,name:n,region:r,definition:i,materialized:a,...c.has(e)?{type:c.get(e)}:{}})))};for(let t of e.nodes){let n=t.operation;`result`in n&&l(`value:${n.result}`,`value`,`v${n.result}`,t.region,t.position,!e.eliminated.has(t.position)),n.kind===`local`&&l(`local:${n.local}`,`local`,`l${n.local}`,t.region,t.position)}for(let e of a)c.set(e.key,Ft(e.type)),l(e.key,`temporary`,e.name,e.region,e.definition);for(let t of e.graph.blocks)for(let e of[...t.uses,...t.liveIn,...t.baselineLiveIn])e.startsWith(`argument:`)&&l(e,`argument`,`args[${e.slice(9)}]`,0,null),e===`reaction`&&l(e,`reaction`,`reaction`,0,null);let u=Object.freeze([...e.constants].flatMap(([e,t])=>{let n=s.get(`value:${e}`);return n===void 0?[]:[Object.freeze({slot:n,kind:`constant`,value:t})]})),d=new Set(u.map(e=>e.slot)),f=e=>Object.freeze(e.flatMap(e=>{let t=s.get(e);return t===void 0?[]:[t]}).sort((e,t)=>e-t)),p=e=>Object.freeze(f(e).filter(e=>o[e].materialized&&!d.has(e))),m=e=>Object.freeze(e.flatMap(e=>{let t=s.get(e);return t===void 0||!o[t].materialized?[]:[t]}).sort((e,t)=>e-t)),h=(e,t,n=e.block)=>Object.freeze({position:e.position,block:n,phase:t}),g=new Map(e.nodes.map(e=>[JSON.stringify(e.path),e])),_=r.split(`\n`),v=e=>Object.freeze({start:Object.freeze({line:e,column:(_[e-1]?.search(/\\S/)??0)+1}),end:Object.freeze({line:e,column:(_[e-1]?.length??0)+1})}),y=Object.freeze({entries:Object.freeze(n.map(t=>{let n=g.get(JSON.stringify(t.path)),r=n.operation.kind===`redirect`||n.operation.kind===`stop`||n.operation.kind===`waitUntil`,i=r?[]:e.graph.blocks[n.resumeBlock].liveIn;return Object.freeze({id:t.id,kind:t.kind,suspended:h(n,`before`),baseline:h(n,t.delegated?`delegate`:`after`,n.resumeBlock??n.block),generated:v(t.line),continuation:Object.freeze({line:t.delegated?t.line:Math.min(t.line+1,_.length),column:t.delegated?t.column:(_[t.line]?.search(/\\S/)??0)+1}),liveSlots:m(i),delegated:t.delegated,terminal:r})}))}),b=[],x=(t,n,r,i=t.block)=>{b.push(Object.freeze({baseline:h(t,`before`,i),reason:n,generated:r,requiredSlots:f(e.graph.blocks[i].baselineLiveIn),captureSlots:p(e.graph.blocks[i].baselineLiveIn)}))};for(let n of e.nodes){let r=t.get(n.position);if(r){if(x(n,`deopt`,v(r.start.line)),n.effects.mayThrow&&!e.folded.has(n.position)){if(n.operation.kind===`assert`){let e=r.start.line;for(let t=r.start.line;t<=r.end.line;t++)_[t-1]?.includes(`host.assert(`)&&(e=t);x(n,`throw`,v(e),n.failureBlock)}else x(n,`throw`,v(r.start.line))}(n.operation.kind===`return`||n.operation.kind===`returnValue`)&&x(n,`return`,v(r.start.line))}}for(let t of y.entries){let n=t.terminal?[]:e.graph.blocks[t.baseline.block].baselineLiveIn;b.push(Object.freeze({baseline:t.baseline,reason:t.kind===`redirect`?`redirect`:t.kind===`stop`?`stop`:`suspend`,generated:t.generated,requiredSlots:f(n),captureSlots:p(n)}))}for(let e of b)for(let t of e.requiredSlots)if(!o[t].materialized&&!d.has(t))throw Error(`Missing baseline value for frame slot ${t} at position ${e.baseline.position}`);let ee=i.binding?Object.freeze({...i.binding,...i.binding.instruction?{instruction:Object.freeze({...i.binding.instruction})}:{}}):null;return{dependencies:Object.freeze({binding:ee,reads:e.effects.reads,writes:e.effects.writes,calls:e.effects.calls,resources:e.resources,unresolvedCalls:e.effects.calls.length!==0}),sourceMap:Object.freeze({entries:Object.freeze(e.nodes.map(n=>Object.freeze({position:n.position,block:n.block,path:n.path,kind:n.operation.kind,...n.source?{source:n.source}:{},generated:t.get(n.position)??null,eliminated:e.eliminated.has(n.position),folded:e.folded.has(n.position)})))}),frameLayout:Object.freeze({storage:`native-generator`,serializable:!1,slots:Object.freeze(o),materializations:u}),resumeMap:y,exitMap:Object.freeze(b)}}let Kt={add:`+`,subtract:`-`,multiply:`*`,divide:`/`,remainder:`%`,power:`**`,lessThan:`<`,lessThanOrEqual:`<=`,greaterThan:`>`,greaterThanOrEqual:`>=`,concat:`+`,bitAnd:`&`,bitOr:`|`,bitXor:`^`,shiftLeft:`<<`,shiftRight:`>>`,shiftRightUnsigned:`>>>`},qt=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`]),Jt=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`]);function Yt(e,t={}){return new nn(Ut(e,t,!1),t,!1).compileExecutable(e)}function Xt(e,t={}){return Zt(Yt(e.body,t))}function Zt(e){return t=>{let n=e(t),r=n.next();if(!r.done)throw n.return(void 0),TypeError(`Computation unexpectedly suspended with ${r.value.kind}`);return r.value}}function Qt(e,t){if(!Number.isSafeInteger(t)||t<0)throw TypeError(`IR identifiers must be nonnegative safe integers`);return`${e}${t}`}let q=e=>Qt(`v`,e),$t=e=>Qt(`l`,e),en=e=>JSON.stringify(e);function tn(e){return e.uri===void 0?Object.freeze({...e}):Object.freeze({...e,range:Object.freeze({start:Object.freeze({...e.range.start}),end:Object.freeze({...e.range.end})})})}var nn=class{analysis;options;captureMetadata;constructor(e,t,n=!0){this.analysis=e,this.options=t,this.captureMetadata=n}ranges=/* @__PURE__ */ new Map;temporaries=[];lines=[];constants=[];primitiveConstants=/* @__PURE__ */ new Map;negativeZero=Symbol(`negative zero`);positions=[];resume=[];types=/* @__PURE__ */ new Map;indent=0;serial=0;bindingFor;compileExecutable(e){return this.generate(e).execute}compile(e){let t=this.generate(e),n=this.analysis,r,i=()=>r??=Gt(n,this.ranges,this.resume,t.source,this.options,this.temporaries);return Object.freeze({...t,positions:Object.freeze(this.positions.slice()),resume:Object.freeze(this.resume.slice()),optimizations:n.optimizations,get effects(){return n.effects},get mir(){return n.graph},get dependencies(){return i().dependencies},get sourceMap(){return i().sourceMap},get frameLayout(){return i().frameLayout},get resumeMap(){return i().resumeMap},get exitMap(){return i().exitMap}})}generate(e){this.line(`function* compiledBody(host, args = [], reaction) {`),this.indent++,this.region(e,[]),this.indent--,this.line(`}`);let t=this.lines.join(`\n`),n=Object.freeze(this.constants.slice());return{execute:Function(`C`,`H`,`\"use strict\"; return (${t});`)(n,Nt),source:t,constants:n}}line(e){this.lines.push(`${` `.repeat(this.indent)}${e}`)}block(e,t){this.line(`${e} {`),this.indent++,t(),this.indent--,this.line(`}`)}capture(e){let t=typeof e!=`object`||!e,n=Object.is(e,-0)?this.negativeZero:e,r=t?this.primitiveConstants.get(n):void 0;if(r!==void 0)return`C[${r}]`;let i=this.constants.push(e)-1;return t&&this.primitiveConstants.set(n,i),`C[${i}]`}ref(e){return e.kind===`parameter`?`args[${e.index}]`:this.capture(e.name)}boundRef(e,t){if(this.bindingFor&&t.kind!==`parameter`)return this.bindingFor(e,t.name)}boundName(e){return this.bindingFor?.(`state`,e)}argument(e){return e.kind===`value`?q(e.value):this.ref(e)}constant(e){switch(e.kind){case`number`:case`bool`:case`string`:return e.value;case`none`:return null;case`enum`:return _t(e.name,e.member);case`bytes`:return Object.freeze(Array.from(yt(e.value)));case`record`:return vt(e.fields.map(e=>[e.name,e.value]));default:return rn(e)}}position(e,t){let n=Object.freeze({path:Object.freeze([...t]),kind:e.kind,line:this.lines.length+1,column:this.indent*2+1,...this.analysis.byOperation.get(e)?.source?{source:tn(this.analysis.byOperation.get(e).source)}:{}});return this.positions.push(n),n}suspension(e,t=!1){e&&this.resume.push(Object.freeze({...e,line:this.lines.length+1,column:this.indent*2+1,id:this.resume.length,delegated:t}))}region(e,t,n){e.operations.forEach((e,r)=>{this.operation(e,[...t,`operations`,r],n)})}valueRegion(e,t,n){if(this.captureMetadata&&!t.startsWith(`v`)){let r=JSON.stringify([...n,`body`]),i=this.analysis.nodes.find(e=>[...e.children.values()].some(e=>JSON.stringify(e.path)===r)),a=[...i.children.values()].find(e=>JSON.stringify(e.path)===r);this.temporaries.push({key:`region:${a.id}`,name:t,region:i.region,definition:i.position,type:e.type})}let r=`valueRegion${this.serial++}`;this.block(`${r}:`,()=>this.region(e.body,[...n,`body`],{slot:t,label:r}))}equality(e,t){let n=this.types.get(e);return n?.kind===`optional`&&(n=n.inner),n&&(n.kind===`number`||n.kind===`string`||n.kind===`bool`)?`(${q(e)} === ${q(t)})`:`H.equalValues(${q(e)}, ${q(t)})`}operation(e,t,n){`result`in e&&this.types.set(e.result,e.type);let r=this.analysis.byOperation.get(e);if(this.analysis.eliminated.has(r.position))return;let i=this.captureMetadata?this.position(e,t):void 0;try{`result`in e&&this.analysis.folded.has(r.position)?this.line(`const ${q(e.result)} = ${this.capture(this.analysis.folded.get(r.position))};`):this.emitOperation(e,t,i,n)}finally{i&&this.ranges.set(r.position,Object.freeze({start:Object.freeze({line:i.line,column:i.column}),end:Object.freeze({line:this.lines.length,column:this.lines[this.lines.length-1].length+1})}))}}emitOperation(e,t,n,r){let i=t=>{if(!(`result`in e))throw TypeError(`Expected a result-producing operation`);this.line(`const ${q(e.result)} = ${t};`)},a=(e,n)=>this.region(e,[...t,n],r);switch(e.kind){case`constant`:{let t=this.capture(this.constant(e.constant));i(e.constant.kind===`bytes`?`H.createBytes(${t})`:t);break}case`read`:{let t=e.resource===`state`?this.boundName(e.name):void 0;i(t?`${t}.read()`:`host.read(${this.capture(e.resource)}, ${this.capture(e.name)})`);break}case`parameter`:i(`args[${e.index}]`);break;case`reactionValue`:i(`H.reactionValue(reaction, ${en(e.binding)})`);break;case`reactionCapture`:i(`H.reactionCapture(reaction, ${e.index})`);break;case`unary`:{let t={positive:`+`,negate:`-`,not:`!`,bitNot:`~`}[e.operator];if(!t)throw TypeError(`Unknown unary operator`);i(`(${t}${q(e.value)})`);break}case`binary`:if(e.operator===`equal`||e.operator===`notEqual`)i(`${e.operator===`notEqual`?`!`:``}${this.equality(e.left,e.right)}`);else{let t=Kt[e.operator];if(!t)throw TypeError(`Unknown binary operator`);i(`(${q(e.left)} ${t} ${q(e.right)})`)}break;case`numeric`:if(!qt.has(e.builtin))throw TypeError(`Unknown numeric builtin`);i(`${Jt.has(e.builtin)?`Number`:`Math`}.${e.builtin}(${e.args.map(q).join(`, `)})`);break;case`record`:i(`H.createRecord([${e.fields.map(e=>`[${this.capture(e.name)}, ${q(e.value)}]`).join(`, `)}])`);break;case`field`:i(`${q(e.value)}[${this.capture(e.field)}]`);break;case`bytes`:i(`H.createBytes([${e.elements.map(q).join(`, `)}])`);break;case`length`:i(`${q(e.value)}.length`);break;case`index`:i(`H.readIndex(${q(e.value)}, ${q(e.index)})`);break;case`optional`:i(q(e.value));break;case`isNone`:i(`(${q(e.value)} === null)`);break;case`nonNull`:i(`H.nonNull(${q(e.value)})`);break;case`localRead`:i($t(e.local));break;case`local`:this.line(`let ${$t(e.local)} = ${q(e.initial)};`);break;case`localWrite`:this.line(`${$t(e.local)} = ${q(e.value)};`);break;case`write`:{let t=this.boundName(e.name);t?this.line(`${t}.write(${q(e.value)});`):this.line(`host.write(${this.capture(e.name)}, ${q(e.value)});`);break}case`memoryLength`:{let t=this.boundRef(`memory`,e.memory);i(t?`${t}.length()`:`host.memoryLength(${this.ref(e.memory)})`);break}case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:{let t=this.boundRef(`memory`,e.memory);i(t?`${t}.${e.kind}(${q(e.offset)})`:`host.load(${en(e.kind)}, ${this.ref(e.memory)}, ${q(e.offset)})`);break}case`store8`:case`store16le`:case`store16be`:case`store32le`:case`store32be`:{let t=this.boundRef(`memory`,e.memory);t?this.line(`${t}.${e.kind}(${q(e.offset)}, ${q(e.value)});`):this.line(`host.store(${en(e.kind)}, ${this.ref(e.memory)}, ${q(e.offset)}, ${q(e.value)});`);break}case`copyBytes`:{let t=this.boundRef(`memory`,e.memory);i(t?`${t}.copy(${q(e.offset)}, ${q(e.length)})`:`host.copyBytes(${this.ref(e.memory)}, ${q(e.offset)}, ${q(e.length)})`);break}case`readSample`:{let t=this.boundRef(`pin`,e.pin);i(t?`${t}.sample()`:`host.sample(${this.ref(e.pin)})`);break}case`resistor`:{let t=this.boundRef(`pin`,e.to);i(t?`${t}.resistor(${q(e.resistance)})`:`host.resistor(${this.ref(e.to)}, ${q(e.resistance)})`);break}case`combineIntents`:i(`H.combineIntents([${e.values.map(q).join(`, `)}])`);break;case`refEqual`:i(`(${this.ref(e.left)} === ${this.ref(e.right)})`);break;case`writeIntent`:{let t=this.boundRef(`pin`,e.pin);t?this.line(`${t}.intent(${q(e.value)});`):this.line(`host.intent(${this.ref(e.pin)}, ${q(e.value)});`);break}case`call`:case`callValue`:{this.suspension(n,!0);let t=`call${this.serial++}`;this.line(`const ${t} = yield* H.delegate(host.call(${this.capture(e.name)}, [${e.args.map(e=>this.argument(e)).join(`, `)}]));`),this.line(`if (${t} === H.terminated) return;`),e.kind===`callValue`&&i(t);break}case`send`:this.line(`host.send(${this.capture(e.channel)}, ${q(e.value)});`);break;case`notify`:this.line(`host.notify(${this.capture(e.notification)});`);break;case`receive`:this.suspension(n),i(`yield { kind: \"receive\", channel: ${this.capture(e.channel)} }`);break;case`now`:i(`host.now()`);break;case`random`:i(`host.random()`);break;case`if`:this.block(`if (H.checkBoolean(${q(e.condition)}))`,()=>a(e.yes,`yes`)),e.no&&this.block(`else`,()=>a(e.no,`no`));break;case`match`:e.arms.forEach((n,i)=>{let a=n.pattern,o=a.kind===`none`?null:a.kind===`enum`?_t(a.name,a.member):a.value;this.block(`${i?`else if`:`if`} (H.equalValues(${q(e.value)}, ${this.capture(o)}))`,()=>{this.region(n.body,[...t,`arms`,i,`body`],r)})}),e.otherwise&&this.block(e.arms.length?`else`:``,()=>a(e.otherwise,`otherwise`));break;case`while`:this.block(`while (true)`,()=>{let n=`condition${this.serial++}`;this.line(`let ${n};`),this.valueRegion(e.test,n,[...t,`test`]),this.line(`if (!H.checkBoolean(${n})) break;`),this.block(``,()=>a(e.body,`body`))});break;case`loop`:this.block(`while (true)`,()=>a(e.body,`body`));break;case`and`:case`or`:{let n=q(e.result);this.line(`let ${n} = H.checkBoolean(${q(e.left)});`),this.block(`if (${e.kind===`or`?`!`:``}${n})`,()=>{this.valueRegion(e.right,n,[...t,`right`]),this.line(`${n} = H.checkBoolean(${n});`)});break}case`select`:{let n=q(e.result);this.line(`let ${n};`),this.block(`if (H.checkBoolean(${q(e.condition)}))`,()=>this.valueRegion(e.yes,n,[...t,`yes`])),this.block(`else`,()=>this.valueRegion(e.no,n,[...t,`no`]));break}case`assert`:this.block(`if (!H.checkBoolean(${q(e.condition)}))`,()=>{if(e.message){let n=`message${this.serial++}`;this.line(`let ${n};`),this.valueRegion(e.message,n,[...t,`message`]),this.line(`host.assert(false, ${n});`)}else this.line(`host.assert(false, undefined);`)});break;case`wait`:case`elapse`:{let t=`duration${this.serial++}`;this.line(`const ${t} = H.checkDuration(${q(e.duration)});`),this.suspension(n);let r=`yield { kind: ${en(e.kind===`wait`?`ticks`:`elapse`)}, duration: ${t} };`;e.kind===`elapse`?this.line(`if (${t} !== 0) ${r}`):this.line(r);break}case`waitUntil`:this.suspension(n),this.line(`yield { kind: \"waitUntil\", predicate: ${this.capture(e.predicate)} };`),this.line(`return;`);break;case`redirect`:this.suspension(n),this.line(`yield { kind: \"redirect\", pc: H.checkPc(${q(e.target)}), delay: H.checkDuration(${q(e.delay)}) };`),this.line(`return;`);break;case`stop`:this.suspension(n),this.line(`yield { kind: \"stop\" };`),this.line(`return;`);break;case`return`:this.line(`return;`);break;case`returnValue`:this.line(`return ${q(e.value)};`);break;case`break`:this.line(`break;`);break;case`continue`:this.line(`continue;`);break;case`yield`:if(!r)throw TypeError(`Value-region yield is outside a value region`);this.line(`${r.slot} = ${q(e.value)};`),this.line(`break ${r.label};`);break;default:rn(e)}}};function rn(e){throw TypeError(`Unsupported IR operation: ${String(e.kind)}`)}let an={add:`+`,subtract:`-`,multiply:`*`,divide:`/`,remainder:`%`,power:`**`,lessThan:`<`,lessThanOrEqual:`<=`,greaterThan:`>`,greaterThanOrEqual:`>=`,equal:`===`,notEqual:`!==`,bitAnd:`&`,bitOr:`|`,bitXor:`^`,shiftLeft:`<<`,shiftRight:`>>`,shiftRightUnsigned:`>>>`},on={positive:`+`,negate:`-`,not:`!`,bitNot:`~`},sn=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`]),cn=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`]),ln=/* @__PURE__ */ new Set([`field`,`optional`,`nonNull`,`readSample`,`resistor`,`combineIntents`,`bytes`,`index`,`select`,`match`]),un=/* @__PURE__ */ new Set([`bytes`,`record`,`sample`,`intent`,`optional`]),dn=/* @__PURE__ */ new Set([`send`,`notify`,`readSample`,`writeIntent`,`resistor`,`random`,`assert`]);function fn(e,t){if(typeof t!=`number`||!Number.isSafeInteger(t))throw TypeError(`offset must be a safe integer`);if(t<0)throw RangeError(`offset must be nonnegative`);if(t>=e.length)throw RangeError(`Memory range is out of bounds`);return t}function pn(e){if(typeof e!=`number`||!Number.isSafeInteger(e))throw TypeError(`stored value must be a safe integer`);return e}let mn=/* @__PURE__ */ new WeakMap;function hn(e){let t=mn.get(e);return t===void 0&&(t=new DataView(e.buffer,e.byteOffset,e.byteLength),mn.set(e,t)),t}function gn(e,t,n){if(typeof t!=`number`||!Number.isSafeInteger(t))throw TypeError(`offset must be a safe integer`);if(t<0)throw RangeError(`offset must be nonnegative`);if(t>e.length||n>e.length-t)throw RangeError(`Memory range is out of bounds`);return t}function _n(e,t,n){return hn(e).getUint16(gn(e,t,2),n)}function vn(e,t,n){return hn(e).getUint32(gn(e,t,4),n)}function yn(e,t,n,r){let i=gn(e,t,2);hn(e).setUint16(i,pn(n),r)}function bn(e,t,n,r){let i=gn(e,t,4);hn(e).setUint32(i,pn(n),r)}let xn=Object.freeze({checkBoolean:Et,checkDuration:Dt,checkPc:Ot,combineIntents:xt,createBytes:yt,equalValues:St,nonNull:Tt,readIndex:wt,offset:fn,byte:pn,load16:_n,load32:vn,store16:yn,store32:bn}),J=Symbol(`unsupported direct instruction`),Sn=/* @__PURE__ */ new WeakMap;function Cn(e){let t=Sn.get(e);if(t===void 0){try{t=Ut(e,{},!1).constants}catch{t=/* @__PURE__ */ new Map}Sn.set(e,t)}return t}function wn(e,t){if(!Ln(t.pc.index)||t.states.get(t.pc.name)!==t.pc.index)return;let n=[],r=e=>`C[${n.push(e)-1}]`,i=[],a=/* @__PURE__ */ new Set;for(let n of e)if(Number.isFinite(n.pc)&&!a.has(n.pc)&&(a.add(n.pc),Number.isFinite(n.nextPc)))try{i.push(new Rn(t,r).compile(n))}catch(e){if(e!==J)throw e}if(!i.length)return;let o=Math.max(...i.map(e=>e.slots.length)),s=Array.from({length:o},(e,t)=>`v${t}`),c=t,l=Ln(c.shardSlotLimit)?c.shardSlotLimit:void 0,u=c.split===!0&&(l===void 0?i.reduce((e,t)=>e+t.size,0)>48e3:i.reduce((e,t)=>e+t.slots.length,0)>l),d=Ln(c.shardSize)&&c.shardSize>0?c.shardSize:48,f=u?An(i,t,d):kn(i,t,s),p=Function(`C`,`H`,u?`\"use strict\";\\n${f.join(`\n`)}\\nreturn run;`:`\"use strict\"; return (${f.join(`\n`)});`),m=e=>Object.freeze([...new Set(i.flatMap(t=>[...t[e]]))]),h={run:p(Object.freeze(n),xn),localCount:o,readStates:m(`readStates`),writeStates:m(`writeStates`),readMemories:m(`readMemories`),writeMemories:m(`writeMemories`)};return Object.defineProperty(h,\"emitStats\",{value:Tn(i)}),Object.freeze(h)}function Tn(e){let t=0,n=0,r=0,i=0,a=0,o=null,s=e=>Number(e.toFixed(3));for(let c of e){t+=c.operations,n+=c.nestedOperations,r+=c.statements,i+=c.foldedOperations,a+=c.selects;let e=c.operations?c.statements/c.operations:0;(o===null||e>o.statementsPerOperation)&&(o=Object.freeze({pc:c.pcValue,operations:c.operations,statements:c.statements,statementsPerOperation:s(e),foldedOperations:c.foldedOperations,selectBlocks:c.selects}))}return Object.freeze({blocks:e.length,operations:t,nestedOperations:n,statements:r,statementsPerOperation:s(t?r/t:0),statementsPerNestedOperation:s(n?r/n:0),foldedOperations:i,selectBlocks:a,worst:o})}function En(e){let t=0;for(let n of e.operations)switch(t++,n.kind){case`if`:t+=En(n.yes),n.no&&(t+=En(n.no));break;case`match`:for(let e of n.arms)t+=En(e.body);n.otherwise&&(t+=En(n.otherwise));break;case`select`:t+=En(n.yes.body)+En(n.no.body);break;case`and`:case`or`:t+=En(n.right.body);break;case`assert`:n.message&&(t+=En(n.message.body))}return t}function Dn(e){let t=0,n=!1;for(let r=0;r<e.length;r++){let i=e[r];n?i===`\\\\`?r++:i===`\"`&&(n=!1):i===`\"`?n=!0:i===`;`&&t++}return t}let On=e=>[`const S = F.states, M = F.memories, L = F.locals, SD = F.stateDirty, MD = F.memoryDirty;`,`const BS = F.blockedStates ?? [], BM = F.blockedMemories ?? [];`,...e.length?[`let ${e.join(`,`)};`]:[]];function kn(e,t,n){let r=[`function run(F, deadline) {`,...On(n),`while (true) {`,`if (F.time >= deadline) return \"deadline\";`,`if (F.resume !== 0) {`,`if (F.due >= deadline) { F.time = deadline; return \"deadline\"; }`,`F.time = Math.max(F.time, F.due);`,`switch (F.resume) {`];return e.forEach((e,t)=>{r.push(`case ${t+1}: {`),e.slots.forEach((e,t)=>r.push(`${e} = L[${t}];`)),r.push(`F.resume = 0;`,...e.suffix,Mn(e.stop),`}`)}),r.push(`default: throw new TypeError(\"Unknown direct JIT continuation\");`,`}`,`}`,`if (F.stopAfterInstruction) return \"invalidated\";`,`switch (H.checkPc(S[${t.pc.index}])) {`),e.forEach((e,n)=>{r.push(`case ${e.pc}: {`,...e.barrier,...e.guard,`S[${t.pc.index}] = ${e.nextPc};`,In(`SD`,t.pc.index),...e.prefix),e.duration!==void 0&&r.push(...jn(e,n)),r.push(...e.suffix,Mn(e.stop),`}`)}),r.push(`default: return \"fallback\";`,`}`,`}`,`}`),r}function An(e,t,n){let r=[...e].sort((e,t)=>e.pcValue-t.pcValue),i=[],a=[],o=0;for(let e of r)a.length&&(a.length>=n||o+e.size>36e3)&&(i.push(a),a=[],o=0),a.push(e),o+=e.size;a.length&&i.push(a);let s=0,c=i.map(e=>{let t={start:s,entries:e,maxSlots:Math.max(...e.map(e=>e.slots.length)),lastPc:e[e.length-1].pc,lastResume:s+e.length,resumable:e.some(e=>e.duration!==void 0)};return s+=e.length,t}),l=e=>Array.from({length:e},(e,t)=>`v${t}`),u=[];c.forEach((e,n)=>{let r=n?c[n-1].lastPc:void 0;u.push(`function stepShard${n}(F, deadline, pc) {`,...On(l(e.maxSlots)),`while (true) {`,`switch (pc) {`),e.entries.forEach((n,i)=>{u.push(`case ${n.pc}: {`,...n.barrier,...n.guard,`S[${t.pc.index}] = ${n.nextPc};`,In(`SD`,t.pc.index),...n.prefix,...jn(n,e.start+i),...n.suffix,Fn(n.stop,r,e.lastPc,t.pc.index),`}`)}),u.push(`default: return \"fallback\";`,`}`,`}`,`}`)}),c.forEach((e,t)=>{e.resumable&&(u.push(`function resumeShard${t}(F, resume) {`,...On(l(e.maxSlots)),`switch (resume) {`),e.entries.forEach((t,n)=>{t.duration!==void 0&&(u.push(`case ${e.start+n+1}: {`),t.slots.forEach((e,t)=>u.push(`${e} = L[${t}];`)),u.push(`F.resume = 0;`,...t.suffix,Nn(t.stop),`}`))}),u.push(`default: throw new TypeError(\"Unknown direct JIT continuation\");`,`}`,`}`))}),u.push(`function run(F, deadline) {`,`const S = F.states;`,`while (true) {`,`if (F.time >= deadline) return \"deadline\";`,`let status;`,`if (F.resume !== 0) {`,`if (F.due >= deadline) { F.time = deadline; return \"deadline\"; }`,`F.time = Math.max(F.time, F.due);`,`const resume = F.resume;`);let d=c.map((e,t)=>({shard:e,shardIndex:t})).filter(({shard:e})=>e.resumable);return d.length?(d.forEach(({shard:e,shardIndex:t},n)=>{let r=n?`else if`:`if`;u.push(`${r} (resume <= ${e.lastResume}) status = resumeShard${t}(F, resume);`)}),u.push(`else throw new TypeError(\"Unknown direct JIT continuation\");`)):u.push(`throw new TypeError(\"Unknown direct JIT continuation\");`),u.push(`} else {`,`if (F.stopAfterInstruction) return \"invalidated\";`,`const pc = H.checkPc(S[${t.pc.index}]);`),c.forEach((e,t)=>{let n=t?`else if`:`if`;u.push(`${n} (pc <= ${e.lastPc}) status = stepShard${t}(F, deadline, pc);`)}),u.push(`else return \"fallback\";`,`}`,`if (status !== \"next\") return status;`,`}`,`}`),u}function jn(e,t){return e.duration===void 0?[]:[`F.due = F.time + ${e.dynamicDuration?`H.checkDuration(${e.duration})`:e.duration};`,`if (F.due > 7200000000000000) throw new RangeError(\"Time out of range\");`,`if (F.due >= deadline) {`,...e.slots.map((e,t)=>`L[${t}] = ${e};`),`F.resume = ${t+1};`,`F.time = deadline;`,`return \"deadline\";`,`}`,`F.time = F.due;`]}function Mn(e){return e?`return \"stopped\";`:`if (F.stopAfterInstruction) return \"invalidated\"; continue;`}function Nn(e){return e?`return \"stopped\";`:`if (F.stopAfterInstruction) return \"invalidated\"; return \"next\";`}function Pn(e){return`(typeof ${e} === \"boolean\" ? ${e} : H.checkBoolean(${e}))`}function Fn(e,t,n,r){return e?`return \"stopped\";`:`if (F.stopAfterInstruction) return \"invalidated\"; pc = S[${r}]; if (!(typeof pc === \"number\" && pc < Infinity && pc > -Infinity)) H.checkPc(pc); if (${t===void 0?`pc <= ${n}`:`pc <= ${n} && pc > ${t}`}) continue; return \"next\";`}function In(e,t){return`${e}[${t>>>5}] |= ${1<<(t&31)};`}function Ln(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}var Rn=class{binding;capture;readStates=/* @__PURE__ */ new Set;writeStates=/* @__PURE__ */ new Set;readMemories=/* @__PURE__ */ new Set;writeMemories=/* @__PURE__ */ new Set;slots=[];size=0;statements=0;operations=0;selects=0;foldedOperations=0;nestedOperations=0;guard=[];barrier=[];prefix=[];suffix=[];pcValue=0;pc=``;nextPc=``;duration;dynamicDuration=!1;immediate=!1;stop=!1;values=/* @__PURE__ */ new Map;locals=/* @__PURE__ */ new Map;folded=/* @__PURE__ */ new Map;constants;writtenStates=/* @__PURE__ */ new Set;writtenMemories=/* @__PURE__ */ new Set;references=/* @__PURE__ */ new Set;labels=0;constructor(e,t){this.binding=e,this.capture=t}compile(e){this.pcValue=e.pc,this.constants=Cn(e.body),this.operations=e.body.operations.length,this.nestedOperations=En(e.body),this.pc=this.literal(e.pc),this.nextPc=this.literal(e.nextPc),this.readStates.add(this.binding.pc.name),this.state(this.binding.pc.name,!0);let t=this.binding.delayLoops?.get(e.pc);t!==void 0&&Ln(t.counter)&&Ln(t.cycles)&&this.guard.push(`if (S[${t.counter}] > 1) {`,`const rounds = Math.min(S[${t.counter}] - 1, Math.floor((deadline - F.time) / ${t.cycles}));`,`if (rounds > 0) {`,`F.time += rounds * ${t.cycles};`,`if (F.time > 7200000000000000) throw new RangeError(\"Time out of range\");`,`S[${t.counter}] = S[${t.counter}] - rounds;`,In(`SD`,t.counter),`}`,`if (F.time >= deadline) { F.time = deadline; return \"deadline\"; }`,`}`);let n=this.prefix,r=!1;for(let t of e.body.operations){if(r)throw J;if(t.kind===`elapse`){if(this.terminated)throw J;this.terminate(this.delay(t.duration)),n=this.suffix}else if(t.kind===`redirect`){if(this.terminated)throw J;let e=this.delay(t.delay);n.push(`S[${this.binding.pc.index}] = H.checkPc(${this.value(t.target)});`,In(`SD`,this.binding.pc.index)),this.terminate(e),n=this.suffix,r=!0}else if(t.kind===`stop`)this.stop=!0,r=!0;else if(t.kind===`yield`){if(this.terminated)throw J;this.terminate({value:`0`,zero:!0,dynamic:!1}),r=!0}else this.operation(t,n)}if(!this.terminated&&!this.stop)throw J;this.compact(),this.barrier=this.emitBarrier();let i=[...this.barrier,...this.guard,...this.prefix,...this.suffix];return this.size=i.reduce((e,t)=>e+t.length,0),this.statements=i.reduce((e,t)=>e+Dn(t),0),this.selects=i.filter(e=>/^select\\d+: \\{/.test(e)).length,this}emitBarrier(){let e=[],t=(t,n)=>{if(!n.size)return;let r=/* @__PURE__ */ new Map;for(let e of n)r.set(e>>>5,(r.get(e>>>5)??0)|1<<(e&31));for(let[n,i]of[...r].sort(([e],[t])=>e-t))e.push(`if (${t}[${n}] & ${i>>>0}) return \"fallback\";`)};return t(`BS`,this.writtenStates),t(`BM`,this.writtenMemories),e}get terminated(){return this.duration!==void 0||this.immediate}compact(){let e=this.prefix.length,t=[...this.prefix,...this.suffix],n=e=>(e.match(/\\bv\\d+\\b/g)??[]).map(e=>Number(e.slice(1))),r=t.map(()=>[]),i=[],a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=/* @__PURE__ */ new Map;t.forEach((e,t)=>{let c=n(e),l=/^v(\\d+) = /.exec(e);if(l!==null){let e=Number(l[1]);r[t].push(e),a.set(e,t);let n=c.indexOf(e);n>=0&&c.splice(n,1)}for(let e of c)o.has(e)||o.set(e,t),s.set(e,t);i.push(c)});let c=/* @__PURE__ */ new Map;r.forEach((e,t)=>{for(let n of e)c.has(n)||c.set(n,t)});for(let[e,t]of o)if((c.get(e)??1/0)>t)return;let l=/* @__PURE__ */ new Map;for(let e of a.keys())l.set(e,Math.max(a.get(e),s.get(e)??-1));let u=/* @__PURE__ */ new Map,d=/* @__PURE__ */ new Map,f=[],p=0,m=e=>{let t=d.get(e);t!==void 0&&(d.delete(e),f.push(t))};t.forEach((e,t)=>{for(let e of r[t]){if(u.has(e))continue;let t=f.pop()??`v${p++}`;u.set(e,t),d.set(e,t)}for(let e of[...r[t],...i[t]])l.get(e)===t&&m(e)});let h=e=>e.replace(/\\bv(\\d+)\\b/g,(e,t)=>u.get(Number(t))??e);this.prefix=t.slice(0,e).map(e=>h(e)),this.suffix=t.slice(e).map(e=>h(e)),this.duration!==void 0&&(this.duration=h(this.duration)),this.slots=Array.from({length:p},(e,t)=>`v${t}`)}terminate(e){e.zero?this.immediate=!0:(this.duration=e.value,this.dynamicDuration=e.dynamic)}delay(e){let t=this.folded.get(e);if(t!==void 0&&typeof t.value==`number`){try{Dt(t.value)}catch{throw J}return{value:t.text,zero:t.value===0,dynamic:!1}}let n=this.values.get(e);if(n===void 0)throw J;return{value:n,zero:!1,dynamic:!0}}literal(e){return typeof e==`boolean`?e?`true`:`false`:typeof e==`number`&&Number.isSafeInteger(e)?Object.is(e,-0)?`-0`:String(e):typeof e==`string`?JSON.stringify(e).replace(/\\u2028/g,`\\\\u2028`).replace(/\\u2029/g,`\\\\u2029`):this.capture(e)}value(e){let t=this.expressionOf(e);if(!t)throw J;return t}expressionOf(e){return this.values.get(e)??this.folded.get(e)?.text}condition(e){let t=this.folded.get(e);return t!==void 0&&typeof t.value==`boolean`?t.text:Pn(this.value(e))}foldResult(e){if(!(`result`in e))return!1;switch(e.kind){case`constant`:{let{constant:t}=e;return t.kind===`string`?this.foldConstant(e.result,t.value):t.kind===`enum`?this.foldConstant(e.result,t.member):t.kind===`number`||t.kind===`bool`?this.foldConstant(e.result,t.value):!1}case`unary`:case`binary`:case`numeric`:{let t=this.constants?.get(e.result);return t!==void 0&&this.foldConstant(e.result,t)}default:return!1}}foldConstant(e,t){return this.folded.set(e,{value:t,text:this.literal(t)}),this.foldedOperations++,!0}slot(){let e=`v${this.slots.length}`;return this.slots.push(e),e}state(e,t){let n=this.binding.states.get(e);if(!Ln(n)||t&&this.binding.blockedStates?.has(e))throw J;return(t?this.writeStates:this.readStates).add(e),t&&this.writtenStates.add(n),n}memory(e){if(e.memory.kind!==`memory`)throw J;let t=e.memory.name,n=this.binding.memories.get(t),r=e.kind.startsWith(`store`);if(!Ln(n)||r&&this.binding.blockedMemories?.has(t))throw J;return(r?this.writeMemories:this.readMemories).add(t),r&&this.writtenMemories.add(n),n}expression(e){if(e.type.kind!==`number`&&e.type.kind!==`bool`)return;let{operations:t}=e.body,n=t[t.length-1];if(n?.kind!==`yield`)return;let r=/* @__PURE__ */ new Map;for(let e=0;e<t.length-1;e++)if(!this.fold(t[e],r))return;return r.get(n.value)??this.expressionOf(n.value)}fold(e,t){if(!(`result`in e)||!(`type`in e)||e.type.kind!==`number`&&e.type.kind!==`bool`)return!1;let n=e=>t.get(e)??this.expressionOf(e);switch(e.kind){case`constant`:return e.constant.kind!==`number`&&e.constant.kind!==`bool`?!1:(t.set(e.result,this.literal(e.constant.value)),!0);case`read`:return e.resource===`state`&&(t.set(e.result,`S[${this.state(e.name,!1)}]`),!0);case`localRead`:{let n=this.locals.get(e.local);return n?(t.set(e.result,n),!0):!1}case`unary`:{let r=on[e.operator],i=n(e.value);return!r||i===void 0?!1:(t.set(e.result,`(${r}${i})`),!0)}case`binary`:{let r=an[e.operator],i=n(e.left),a=n(e.right);return!r||i===void 0||a===void 0?!1:(t.set(e.result,`(${i} ${r} ${a})`),!0)}case`numeric`:{if(!sn.has(e.builtin))return!1;let r=[];for(let t of e.args){let e=n(t);if(e===void 0)return!1;r.push(e)}let i=cn.has(e.builtin)?`Number`:`Math`;return t.set(e.result,`${i}.${e.builtin}(${r.join(`,`)})`),!0}default:return!1}}requireHost(){if(this.binding.host!==!0)throw J}message(e){let t=e.body.operations,n=t[0],r=t[1];if(t.length!==2||n?.kind!==`constant`||n.constant.kind!==`string`||r?.kind!==`yield`||r.value!==n.result)throw J;return this.literal(n.constant.value)}pattern(e){switch(e.kind){case`none`:return`null`;case`number`:case`bool`:return this.literal(e.value);case`string`:return this.literal(e.value);case`enum`:return this.literal(e.member)}}region(e,t,n){for(let r of e.operations)if(r.kind===`yield`){if(!n)throw J;t.push(`${n.slot} = ${this.value(r.value)}; break ${n.label};`)}else this.operation(r,t,n)}operation(e,t,n){let r;if(dn.has(e.kind)&&this.requireHost(),`result`in e){let t=e.type.kind;if(t!==`number`&&t!==`bool`&&!(ln.has(e.kind)||e.kind===`constant`&&(t===`string`||t===`enum`||t===`bytes`)))throw J;if(this.foldResult(e))return;r=this.slot(),this.values.set(e.result,r),un.has(t)&&this.references.add(e.result)}let i=e=>{t.push(`${r} = ${e};`)};switch(e.kind){case`constant`:{if(e.constant.kind!==`bytes`)throw J;let t;try{t=Object.freeze(Array.from(yt(e.constant.value)))}catch{throw J}i(`H.createBytes(${this.capture(t)})`);break}case`read`:if(e.resource!==`state`)throw J;i(`S[${this.state(e.name,!1)}]`);break;case`write`:{let n=this.state(e.name,!0);t.push(`S[${n}] = ${this.value(e.value)};`,In(`SD`,n));break}case`unary`:{let t=on[e.operator];if(!t)throw J;i(`(${t}${this.value(e.value)})`);break}case`binary`:{let t=an[e.operator];if(!t)throw J;let n=this.value(e.left),r=this.value(e.right);if((e.operator===`equal`||e.operator===`notEqual`)&&(this.references.has(e.left)||this.references.has(e.right))){i(`${e.operator===`notEqual`?`!`:``}H.equalValues(${n},${r})`);break}i(`(${n} ${t} ${r})`);break}case`numeric`:if(!sn.has(e.builtin))throw J;i(`${cn.has(e.builtin)?`Number`:`Math`}.${e.builtin}(${e.args.map(e=>this.value(e)).join(`,`)})`);break;case`send`:t.push(`F.host.send(${this.capture(e.channel)}, ${this.value(e.value)});`);break;case`notify`:t.push(`F.host.notify(${this.capture(e.notification)});`);break;case`readSample`:if(e.pin.kind!==`pin`)throw J;i(`F.host.sample(${this.capture(e.pin.name)})`);break;case`writeIntent`:if(e.pin.kind!==`pin`)throw J;t.push(`F.host.intent(${this.capture(e.pin.name)}, ${this.value(e.value)});`);break;case`resistor`:if(e.to.kind!==`pin`)throw J;i(`F.host.resistor(${this.capture(e.to.name)}, ${this.value(e.resistance)})`);break;case`combineIntents`:i(`H.combineIntents([${e.values.map(e=>this.value(e)).join(`,`)}])`);break;case`field`:i(`${this.value(e.value)}[${this.capture(e.field)}]`);break;case`bytes`:i(`H.createBytes([${e.elements.map(e=>this.value(e)).join(`,`)}])`);break;case`index`:i(`H.readIndex(${this.value(e.value)},${this.value(e.index)})`);break;case`refEqual`:if(e.left.kind===`parameter`||e.right.kind===`parameter`)throw J;i(e.left.name===e.right.name?`true`:`false`);break;case`length`:i(`${this.value(e.value)}.length`);break;case`optional`:i(this.value(e.value));break;case`isNone`:i(`(${this.value(e.value)} === null)`);break;case`nonNull`:i(`H.nonNull(${this.value(e.value)})`);break;case`now`:i(`F.time`);break;case`random`:i(`F.host.random()`);break;case`assert`:{let n=e.message===void 0?`undefined`:this.message(e.message);t.push(`if (!${this.condition(e.condition)}) F.host.assert(false, ${n});`);break}case`local`:{if(e.type.kind!==`number`&&e.type.kind!==`bool`)throw J;let n=this.slot();this.locals.set(e.local,n),t.push(`${n} = ${this.value(e.initial)};`);break}case`localRead`:{let t=this.locals.get(e.local);if(!t)throw J;i(t);break}case`localWrite`:{let n=this.locals.get(e.local);if(!n)throw J;t.push(`${n} = ${this.value(e.value)};`);break}case`load8`:{let t=`M[${this.memory(e)}]`;i(`${t}[H.offset(${t},${this.value(e.offset)})]`);break}case`store8`:{let n=this.memory(e),r=`M[${n}]`;t.push(`${r}[H.offset(${r},${this.value(e.offset)})] = H.byte(${this.value(e.value)});`,In(`MD`,n));break}case`load16le`:case`load16be`:{let t=`M[${this.memory(e)}]`,n=e.kind.endsWith(`le`)?`true`:`false`;i(`H.load16(${t},${this.value(e.offset)},${n})`);break}case`load32le`:case`load32be`:{let t=`M[${this.memory(e)}]`,n=e.kind.endsWith(`le`)?`true`:`false`;i(`H.load32(${t},${this.value(e.offset)},${n})`);break}case`store16le`:case`store16be`:case`store32le`:case`store32be`:{let n=this.memory(e),r=`M[${n}]`,i=e.kind.startsWith(`store16`)?`store16`:`store32`,a=e.kind.endsWith(`le`)?`true`:`false`;t.push(`H.${i}(${r},${this.value(e.offset)},${this.value(e.value)},${a});`,In(`MD`,n));break}case`and`:case`or`:{if(e.right.body.operations.at(-1)?.kind!==`yield`)throw J;let n=`${e.kind}${this.labels++}`;t.push(`${r} = ${this.condition(e.left)};`,`${e.kind===`or`?`if (!`:`if (`}${r}) {`,`${n}: {`),this.region(e.right.body,t,{slot:r,label:n}),t.push(`}`,`${r} = ${Pn(r)};`,`}`);break}case`match`:{let r=this.value(e.value);if(!e.arms.length&&!e.otherwise||!e.otherwise&&n)throw J;e.arms.forEach((e,i)=>{let a=this.pattern(e.pattern);t.push(`${i?`} else if`:`if`} (H.equalValues(${r}, ${a})) {`),this.region(e.body,t,n)}),e.otherwise&&(t.push(e.arms.length?`} else {`:`{`),this.region(e.otherwise,t,n)),t.push(`}`);break}case`if`:t.push(`if (${this.condition(e.condition)}) {`),this.region(e.yes,t,n),e.no&&(t.push(`} else {`),this.region(e.no,t,n)),t.push(`}`);break;case`select`:{let n=this.condition(e.condition),i=this.expression(e.yes),a=i===void 0?void 0:this.expression(e.no);if(i!==void 0&&a!==void 0){t.push(`${r} = ${n} ? ${i} : ${a};`);break}let o=`select${this.labels++}`;t.push(`${o}: {`,`if (${n}) {`),this.region(e.yes.body,t,{slot:r,label:o}),t.push(`} else {`),this.region(e.no.body,t,{slot:r,label:o}),t.push(`}`,`}`);break}default:throw J}}};let zn=Symbol(`unsupported resumable body`),Bn=/^(\\s*)(?:const|let) (v\\d+|l\\d+)( = |;)/;function Vn(e,t={}){if(Jn(e))try{return new Hn(Ut(e,t,!1),t,!1).compileMachine(e)}catch{return}}var Hn=class extends nn{blocks=[];slots=/* @__PURE__ */ new Map;resources=[];resourceIndex=/* @__PURE__ */ new Map;current;graph;constructor(e,t,n){super(e,t,n),t.bindResources&&(this.bindingFor=(e,t)=>this.bindResource(e,t))}bindResource(e,t){let n=`${e}\\0${t}`,r=this.resourceIndex.get(n);return r===void 0&&(r=this.resources.push([e,t])-1,this.resourceIndex.set(n,r)),`F.resources[${r}]`}compileMachine(e){this.graph=this.analysis.graph;for(let e of this.analysis.nodes)`result`in e.operation&&this.types.set(e.operation.result,e.operation.type);let t=this.reserve(),n=this.reserve();this.blocks[n].term={kind:`done`};let r=this.buildRegion(e,n,{},[]);this.blocks[t].term={kind:`jump`,to:r};let i=[...this.locals()].sort(),a=[`function resumableBody(host, args = [], reaction, F) {`,...i.length?[`let ${i.join(`, `)};`]:[],...this.resources.length?[`if (F.resources === void 0) F.resources = host.bind(${this.capture(Object.freeze(this.resources.slice()))});`]:[],`for (;;) {`,`switch (F.pc) {`];for(let e of this.blocks){a.push(`case ${e.id}: {`);for(let t of e.code)a.push(t);a.push(...Wn(e)),a.push(`}`)}a.push(`default: throw new TypeError(\"Unknown resumable continuation\");`,`}`,`}`,`}`);let o=a.join(`\n`),s=Object.freeze(this.constants.slice()),c=Function(`C`,`H`,`\"use strict\"; return (${o});`);return Object.freeze({run:c(s,Nt),slotCount:this.slots.size,start:0})}locals(){let e=/* @__PURE__ */ new Set;for(let t of this.analysis.nodes){let n=t.operation;`result`in n&&e.add(q(n.result)),(n.kind===`local`||n.kind===`localRead`||n.kind===`localWrite`)&&e.add(`l${n.local}`)}return e}buildRegion(e,t,n,r,i){this.current=void 0;let a=t,o=[];for(let t=e.operations.length-1;t>=0;t--){let i=e.operations[t],s=[...r,`operations`,t];qn(i)?o.unshift(this.emitStraight(i,s)):(a=this.flush(o,a),o=[],a=this.buildControl(i,a,n,s))}if(i!==void 0){if(o.length){let e=this.blocks[i];for(let t of o)e.code.push(...t);e.term={kind:`jump`,to:a}}else i!==a&&(this.blocks[i].term={kind:`jump`,to:a});return i}return this.flush(o,a)}emitStraight(e,t){let n=this.lines,r=this.indent;this.lines=[],this.indent=0;let i;try{super.operation(e,t),i=this.lines}finally{this.lines=n,this.indent=r}return Un(i)}flush(e,t){if(!e.length)return t;let n=this.open();for(let t of e)n.code.push(...t);return this.current=void 0,n.term={kind:`jump`,to:t},n.id}buildControl(e,t,n,r){switch(e.kind){case`if`:{let i=this.reserve(),a=e.no?this.reserve():t,o=this.open();return o.term={kind:`branch`,test:`H.checkBoolean(${q(e.condition)})`,yes:i,no:a},this.current=void 0,this.buildRegion(e.yes,t,n,[...r,`yes`],i),e.no&&this.buildRegion(e.no,t,n,[...r,`no`],a),o.id}case`match`:{let i=e.otherwise?this.reserve():t,a=i;for(let i=e.arms.length-1;i>=0;i--){let o=e.arms[i],s=this.reserve();this.buildRegion(o.body,t,n,[...r,`arms`,i,`body`],s);let c=o.pattern,l=c.kind===`none`?null:c.kind===`enum`?_t(c.name,c.member):c.value,u=this.open();u.term={kind:`branch`,test:`H.equalValues(${q(e.value)}, ${this.capture(l)})`,yes:s,no:a},this.current=void 0,a=u.id}return e.otherwise&&this.buildRegion(e.otherwise,t,n,[...r,`otherwise`],i),a}case`while`:{let n=this.reserve(),i=this.buildRegion(e.body,n,{breakTo:t,continueTo:n},[...r,`body`]);return this.fillTest(n,e.test,[...r,`test`],e=>({kind:`branch`,test:`H.checkBoolean(${e})`,yes:i,no:t})),n}case`loop`:{let n=this.reserve(),i=this.buildRegion(e.body,n,{breakTo:t,continueTo:n},[...r,`body`]);return this.blocks[n].term={kind:`jump`,to:i},n}case`break`:case`continue`:{let t=e.kind===`break`?n.breakTo:n.continueTo;if(t===void 0)throw zn;let r=this.open();return r.term={kind:`jump`,to:t},this.current=void 0,r.id}case`return`:case`returnValue`:{let e=this.open();return e.term={kind:`done`},this.current=void 0,e.id}case`wait`:{let n=`duration${this.serial++}`,r=this.open();r.code.push(`const ${n} = H.checkDuration(${q(e.duration)});`);let i=this.resumeBlock(e);return r.code.push(...this.save(e),`F.pc = ${i};`,`F.kind = 1;`,`F.duration = ${n};`),r.term={kind:`suspend`},this.current=void 0,this.link(i,t),r.id}case`receive`:{let n=this.open(),r=this.resumeBlock(e);return n.code.push(...this.save(e),`F.pc = ${r};`,`F.kind = 2;`,`F.channel = ${this.capture(e.channel)};`),n.term={kind:`suspend`},this.current=void 0,this.link(r,t),n.id}default:throw zn}}fillTest(e,t,n,r){let i=this.blocks[e],a=`condition${this.serial++}`,o=this.lines,s=this.indent;this.lines=i.code,this.indent=0;try{this.line(`let ${a};`),this.valueRegion(t,a,n)}finally{this.lines=o,this.indent=s}this.current=void 0,i.term=r(a)}resumeBlock(e){let t=this.reserve(),n=this.blocks[t],r=this.analysis.byOperation.get(e),i=`result`in e?q(e.result):void 0;for(let e of this.liveIn(r))e!==i&&n.code.push(`${this.slotName(e)} = F.slots[${this.slot(e)}];`);return i&&n.code.push(`${i} = F.value;`),t}link(e,t){let n=this.blocks[e];n.code.push(`F.pc = ${t};`),n.term={kind:`jump`,to:t}}save(e){let t=this.analysis.byOperation.get(e),n=`result`in e?q(e.result):void 0,r=[];for(let e of this.liveIn(t))e!==n&&r.push(`F.slots[${this.slot(e)}] = ${this.slotName(e)};`);return r}liveIn(e){if(e.resumeBlock===void 0)throw zn;return(this.graph??=this.analysis.graph).blocks[e.resumeBlock].liveIn.filter(e=>e.startsWith(`value:`)||e.startsWith(`local:`))}slotName(e){let t=e.indexOf(`:`),n=Number(e.slice(t+1));if(!Number.isSafeInteger(n)||n<0)throw zn;return e.startsWith(`value:`)?q(n):$t(n)}slot(e){let t=this.slots.get(e);if(t!==void 0)return t;let n=this.slots.size;return this.slots.set(e,n),n}reserve(){let e={id:this.blocks.length,code:[]};return this.blocks.push(e),e.id}open(){if(this.current)return this.current;let e={id:this.blocks.length,code:[]};return this.blocks.push(e),this.current=e,e}};function Un(e){let t=[];for(let n of e){let e=Bn.exec(n);e?e[3]!==`;`&&t.push(`${e[1]}${e[2]}${e[3]}${n.slice(e[0].length)}`):t.push(n)}return t}function Wn(e){let t=e.term;if(!t)throw zn;switch(t.kind){case`jump`:return[`F.pc = ${t.to};`,`break;`];case`branch`:return[`if (${t.test}) F.pc = ${t.yes};`,`else F.pc = ${t.no};`,`break;`];case`suspend`:return[`return true;`];case`done`:return[`F.pc = 0;`,`return false;`];default:throw zn}}let Gn=/* @__PURE__ */ new Set([`if`,`match`,`while`,`loop`,`break`,`continue`,`return`,`returnValue`,`wait`,`receive`]),Kn=/* @__PURE__ */ new Set([`elapse`,`call`,`callValue`,`waitUntil`,`redirect`,`stop`,`yield`]);function qn(e){return!Gn.has(e.kind)&&!Kn.has(e.kind)}function Jn(e){for(let t of e.operations)switch(t.kind){case`if`:if(!Jn(t.yes)||t.no&&!Jn(t.no))return!1;break;case`match`:for(let e of t.arms)if(!Jn(e.body))return!1;if(t.otherwise&&!Jn(t.otherwise))return!1;break;case`while`:if(!Yn(t.test.body)||!Jn(t.body))return!1;break;case`loop`:if(!Jn(t.body))return!1;break;case`and`:case`or`:if(!Yn(t.right.body))return!1;break;case`select`:if(!Yn(t.yes.body)||!Yn(t.no.body))return!1;break;case`assert`:if(t.message&&!Yn(t.message.body))return!1}return!0}function Yn(e){for(let t of e.operations)if(t.kind!==`yield`&&(Gn.has(t.kind)||Kn.has(t.kind)||!Jn({operations:[t]})))return!1;return!0}var Xn=class extends Error{code;instanceId;resource;network;networks;component;reason;constructor(e,t,n={}){super(t),this.name=`ElectricalError`,this.code=e,this.reason=t,this.instanceId=n.instanceId,this.resource=n.resource,this.network=n.network,this.networks=n.networks,this.component=n.component}};function Zn(e,t={}){if(!Number.isFinite(e)||e<.001||e>1e9)throw new Xn(`INVALID_ELECTRICAL_PARAMETER`,`Resistance must be finite and in [0.001, 1000000000] ohms.`,t)}let Qn=65536;function $n(e,t){let n=Math.imul(2166136261^e,16777619);for(let e=0;e<t.length;e++)n=Math.imul(n^t[e].to,16777619);return Math.imul(n^t.length,16777619)>>>0}function er(e){let t=0,n=/* @__PURE__ */ new Set;for(let r of e.blocks){t+=r.component.nodes.length+2*r.component.edges.length;let e=r.component.physical;if(e!==void 0&&!n.has(e)&&(n.add(e),t+=e.nodes.length+e.edges.length),t>Qn)break}return t}function tr(e,t,n){let r;for(let i=0;i<e.component.edges.length;i++){let a=e.component.edges[i],o=(n[a.pin]??t[a.pin])[a.index];(a.from!==o.from||a.to!==o.to||a.resistance!==o.resistance)&&(r??=e.component.edges.slice(),r[i]=o)}return r===void 0?e:{...e,component:{...e.component,edges:r}}}function nr(e,t,n){let r;for(let i=0;i<e.blocks.length;i++){let a=e.blocks[i],o=tr(a,t,n);o!==a&&(r??=e.blocks.slice(),r[i]=o)}return r===void 0?e:{...e,blocks:r}}function rr(e){return{component:e,key:e.nodes.join(`,`)}}function ir(e,t){let n=new sr(e.length);for(let e of t)for(let t of e)n.join(t.from,t.to);let r=/* @__PURE__ */ new Map;for(let t=0;t<e.length;t++){let e=n.find(t),i=r.get(e);i===void 0&&(i={nodes:[],edges:[]},r.set(e,i)),i.nodes.push(t)}for(let e of t)for(let t of e)r.get(n.find(t.from)).edges.push(t);let i=0,a=[],o=[],s=Array(e.length),c=Array(e.length),l=0;for(let t of r.values()){let n,r=!0,u=1;for(let i of t.nodes){let t=e[i].reference;t!==void 0&&(r=!1,n===void 0?n=t:t!==n&&(u=0))}r&&i++;for(let e of t.nodes)s[e]=l,c[e]=u;l++;for(let n of cr(t,e)){let e=a.length;a.push(rr(n));for(let t of n.edges)(o[t.pin]??=[])[t.index]=e}}return{blocks:a,edgeBlocks:o,components:r.size,floatingComponents:i,nodeComponents:s,nodeUniform:c}}let ar=e=>e===0?0:e;function or(e){return{instanceId:e.instance,resource:e.name}}var sr=class{parents;constructor(e){this.parents=Array(e);for(let t=0;t<e;t++)this.parents[t]=t}find(e){let t=e;for(;this.parents[t]!==t;)t=this.parents[t];for(;e!==t;){let n=this.parents[e];this.parents[e]=t,e=n}return t}join(e,t){let n=this.find(e),r=this.find(t);n!==r&&(this.parents[Math.max(n,r)]=Math.min(n,r))}};function cr(e,t){let n=0,r,i=!1;for(let a of e.nodes){let e=t[a].reference;e===void 0?n++:r===void 0?r=e:e!==r&&(i=!0)}if(n<2||!i)return[e];let a=/* @__PURE__ */ new Map;for(let n of e.nodes)t[n].reference===void 0&&a.set(n,a.size);let o=new sr(n),s=!1;for(let t of e.edges){let e=a.get(t.from),n=a.get(t.to);e!==void 0&&n!==void 0&&(o.join(e,n),s=!0)}if(!s&&n<=32)return[e];let c=Array(n),l=[];for(let t=0;t<n;t++){let n=c[o.find(t)];n===void 0&&(n={nodes:[],edges:[],physical:e},l.push(n)),c[t]=n}if(l.length===1)return[e];let u=/* @__PURE__ */ new Map;for(let t of e.edges){let e=a.get(t.from),n=a.get(t.to),r=e??n;if(r===void 0)continue;let i=c[r];i.edges.push(t);let o=e===void 0?t.from:n===void 0?t.to:void 0;if(o===void 0)continue;let s=u.get(o);s===void 0&&(s=[],u.set(o,s)),s.push(i)}for(let t of e.nodes){let e=a.get(t);if(e!==void 0)c[e].nodes.push(t);else{let e=u.get(t);if(e===void 0)continue;for(let n of e)n.nodes[n.nodes.length-1]!==t&&n.nodes.push(t)}}return l}function lr(e){let t=0,n=0;for(let r of e){let e=t+r;n+=Math.abs(t)>=Math.abs(r)?t-e+r:r-e+t,t=e}return t+n}function ur(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function dr(e,t){if(e.edges.length!==t.edges.length)return!1;for(let n=0;n<e.edges.length;n++){let r=e.edges[n],i=t.edges[n];if(r.from!==i.from||r.to!==i.to||r.resistance!==i.resistance)return!1}return!0}function fr(e,t,n){let r=t.length;if(e.length===0){for(let e of t)(!(e>0)||!Number.isFinite(e))&&n(`Invalid LDL pivot.`);return{matrix:e,anchors:t,pivots:t,weights:/* @__PURE__ */ new Float64Array}}let i=e.slice(),a=t.slice(),o=new Float64Array(r),s=new Float64Array(r*r);for(let e=0;e<r;e++){let t=e*r,c=[a[e]];for(let n=e+1;n<r;n++)c.push(i[t+n]);let l=lr(c);(!(l>0)||!Number.isFinite(l))&&n(`Invalid LDL pivot.`),o[e]=l;for(let a=e+1;a<r;a++){let e=i[t+a];if(e===0)continue;let r=e/l;(!(r>0)||!Number.isFinite(r))&&n(`Unrepresentable LDL coefficient.`),s[t+a]=r}for(let o=e+1;o<r;o++){let c=i[t+o];if(c===0)continue;let u=c*(a[e]/l);a[e]>0&&!(u>0)&&n(`Reference coefficient underflow.`),a[o]=a[o]+u;for(let e=o+1;e<r;e++){let a=s[t+e];if(a===0)continue;let l=c*a;l>0||n(`Schur coefficient underflow.`);let u=o*r+e;i[u]=i[u]+l}}}return{matrix:e,anchors:t,pivots:o,weights:s}}function pr(e,t,n){let{weights:r,pivots:i}=e,a=t.length,o=new Float64Array(a);if(r.length===0)for(let e=0;e<a;e++)o[e]=t[e]/i[e],Number.isFinite(o[e])||n(`Non-finite backward substitution.`);else{let e=new Float64Array(a);for(let i=0;i<a;i++){let o=[t[i]];for(let t=0;t<i;t++)o.push(r[t*a+i]*e[t]);e[i]=lr(o),Number.isFinite(e[i])||n(`Non-finite forward substitution.`)}for(let t=a-1;t>=0;t--){let s=[e[t]/i[t]];for(let e=t+1;e<a;e++)s.push(r[t*a+e]*o[e]);o[t]=lr(s),Number.isFinite(o[t])||n(`Non-finite backward substitution.`)}}return o}function mr(e,t){return e-t}function hr(e,t){e=0+e;let n=e+t;return n+(Math.abs(e)>=Math.abs(t)?e-n+t:t-n+e)}function gr(e,t,n,r){if(e.length>32||t.length>128)return;let i=Array.from({length:e.length},()=>[]),a=[`unknown.length === ${e.length}`,`edges.length === ${t.length}`],o=[];for(let e=0;e<t.length;e++){let r=t[e],s=n.get(r.from),c=n.get(r.to);if(s!==void 0&&c!==void 0)return;if(s===void 0&&c===void 0){a.push(`nodes[edges[${e}].from].reference !== undefined`,`nodes[edges[${e}].to].reference !== undefined`);continue}let l=s??c;if(i[l].length===2)return;i[l].push(e);let u=s===void 0?`from`:`to`,d=s===void 0?`to`:`from`;o[e]=`nodes[edges[${e}].${u}].reference`,a.push(`edges[${e}].${d} === unknown[${l}]`,`${o[e]} !== undefined`)}if(i.some(e=>e.length===0))return;let s=[];for(let e=0;e<i.length;e++){let t=i[e],n=e=>e.length===1?`(0 + ${e[0]})`:`pair(${e.join(`,`)})`;for(let e of t)s.push(`const g${e} = edges[${e}].conductance / gScale;`);s.push(`anchors[${e}] = ${n(t.map(e=>`g${e}`))};`,`right[${e}] = ${n(t.map(e=>`g${e} * (${o[e]} / vScale)`))};`)}return Function(`pair`,`nodes`,`\"use strict\"; return {\n matches(edges, unknown) { return ${a.join(` && `)}; },\n assemble(edges, gScale, vScale) {\n const anchors = new Float64Array(${e.length});\n const right = new Float64Array(${e.length});\n ${s.join(`\n`)}\n return { anchors, right };\n }\n };`)(hr,r)}function _r(e,t){let n=[...e],r=new Map(n.map((e,t)=>[e,t])),i=new sr(n.length),a=t.map(e=>({id:e.id,pins:[...e.pins],voltage:e.voltage}));for(let e of n)if(e.low===void 0!=(e.high===void 0)||e.low!==void 0&&(!Number.isFinite(e.low)||!Number.isFinite(e.high)||!(e.low<e.high)))throw new Xn(`INVALID_ELECTRICAL_PARAMETER`,`Pin thresholds must both be omitted or finite with low < high.`,or(e));let o=(e,t)=>{let n=r.get(e);if(n===void 0)throw new Xn(`INVALID_ELECTRICAL_PARAMETER`,`Electrical endpoint is not part of this board.`,t===void 0?or(e):{network:t});return n},s=(e,t)=>{let n=r.get(e);if(n===void 0)throw new Xn(`INVALID_ELECTRICAL_PARAMETER`,`Electrical endpoint is not part of this board.`,or(t));return n},c=e=>Number.isFinite(e)&&e>=.001&&e<=1e9;for(let e of a){if(e.voltage!==void 0&&!Number.isFinite(e.voltage))throw new Xn(`INVALID_ELECTRICAL_PARAMETER`,`Reference must be finite.`,{network:e.id});let t;for(let n of e.pins){let r=o(n,e.id);t===void 0?t=r:i.join(t,r)}}let l=[],u=[],d=/* @__PURE__ */ new Map,f=n.map((e,t)=>{let n=i.find(t),r=d.get(n);return r===void 0&&(r=l.length,d.set(n,r),l.push({pins:[],networks:[],reference:void 0}),u.push([])),l[r].pins.push(e),u[r].push(t),r});for(let e of a){if(e.pins.length===0)continue;let t=l[f[o(e.pins[0],e.id)]];if(t.networks.push(e.id),e.voltage===void 0)continue;let n=ar(e.voltage);if(t.reference!==void 0&&t.reference!==n)throw new Xn(`CONFLICTING_REFERENCE`,`Conflicting fixed potentials on a net.`,{network:e.id,networks:Object.freeze([...t.networks])});t.reference=n}let p=/* @__PURE__ */ new Map,m=[],h,g=0,_=/* @__PURE__ */ new Map,v=new Uint32Array(n.length),y=0,b=0;for(let e=0;e<n.length;e++){let t=$n(e,[]);v[e]=t,y+=t,b^=t}let x=(e,t)=>{let n=$n(e,t),r=v[e];n!==r&&(v[e]=n,y+=n-r,b^=r^n)},ee=(e,t)=>{let n=_.get(e);if(n===void 0)return;let r=n.hashes;if(r.length===v.length){for(let e=0;e<r.length;e++){let n=t[e],i=n===void 0?v[e]:$n(e,n);if(r[e]!==i)return}return n}},te=(e,t)=>{if(!(t.cost>Qn))for(_.has(e)?_.get(e)!==t&&_.set(e,t):_.set(e,void 0);_.size>4096;){let e=_.keys().next().value;if(e===void 0)break;_.delete(e)}},S=Array(l.length),C=Array(n.length),w=Array.from({length:n.length},()=>[]),ne=Object.freeze([]),T=new Int32Array(l.length),E=[],re=[],ie=[],ae=Array(n.length),oe=[],se=[],D=[],ce=[],O=new Int32Array(n.length),le=0,k=!1,ue=!1,de=(e,t)=>{for(let n of e)t.indexOf(n)===-1&&(T[n.from]=T[n.from]-1,T[n.to]=T[n.to]-1);for(let n of t)e.indexOf(n)===-1&&(T[n.from]=T[n.from]+1,T[n.to]=T[n.to]+1)},A={solves:0,components:0,floatingComponents:0,factorizations:0,factorizationReuses:0,cacheHits:0,leafPlans:0,leafPropagations:0,topologyPrepares:0},j=Object.freeze([]),M=[],N=[],fe=Array(n.length),pe=[],me=[],he=[],P=[],F=[],I=[],ge=/* @__PURE__ */ new Map,_e=()=>(++le===2147483647&&(O.fill(0),le=1),le),L=(e,t)=>{let n=ge.get(e);n===void 0&&(ge.size>=256&&ge.clear(),n={},ge.set(e,n));let r=n[t];return r===void 0&&(r=Object.freeze({voltage:ar(e),level:t,status:`valid`}),n[t]=r),r},R=(e,t)=>e.low===void 0?`unknown`:t<=e.low?`low`:t>=e.high?`high`:`unknown`,z=(e,t,r,i)=>{let a=f[e],o=u[a],s=l[r].reference,c=[],d=[],p=[];for(let e=0;e<o.length;e++){let t=o[e],r=n[t];c.push(t),d.push(r),p.push(L(s,R(r,s)))}return Object.freeze({targetPin:t.to,resistance:t.resistance,target:r,edges:i,node:a,voltage:s,slots:Object.freeze(c),pins:Object.freeze(d),samples:Object.freeze(p)})},ve=(e,t,n,r)=>{let i=z(e,t,n,r),a=fe[e];if(a===void 0)fe[e]=[i],A.leafPlans++;else{for(let e of a)if(e.targetPin===t.to&&e.resistance===t.resistance)return;a.length<2?a.push(i):a[a.length-1]=i,A.leafPlans++}},ye=()=>{for(let e=0;e<I.length;e++){let t=I[e];ve(t.slot,t.branch,t.target,t.edges)}I.length=0},be=(e,t)=>{if(h===void 0||t.length!==1)return;let n=fe[e];if(n===void 0)return;let r=w[e];if(r.length!==1||l[r[0].to].reference===void 0)return;let i=f[e];if(T[i]!==1||l[i].reference!==void 0)return;let a=t[0];for(let e=0;e<n.length;e++){let t=n[e];if(t.targetPin===a.to&&t.resistance===a.resistance)return l[t.target].reference===void 0?void 0:t}},xe=(e,t)=>{let n=e.length;for(;n>0&&e[n-1]>t;)e[n]=e[n-1],n--;e[n]=t},B=e=>{ue||=(h={...h,nodeComponents:h.nodeComponents.slice(),nodeUniform:h.nodeUniform.slice()},!0);let t=h.nodeComponents,r=h.nodeUniform;N.length=0,D.length=0,ce.length=0;for(let i=0;i<e;i++){let e=f[pe[i]],a=P[i];t[e]=t[a],r[e]=r[a];let o=F[i];if(o!==void 0){if(S[e]===o.voltage)continue;let t=o.slots;for(let e=0;e<t.length;e++){let n=o.pins[e],r=o.samples[e];n.sample!==r&&(xe(N,t[e]),D.push(n),ce.push(r))}continue}let s=l[a].reference;if(S[e]===s)continue;let c=u[e];for(let e=0;e<c.length;e++){let t=c[e],r=n[t],i=r.low===void 0?`unknown`:s<=r.low?`low`:s>=r.high?`high`:`unknown`,a=r.sample;(a.voltage!==s||a.level!==i||a.status!==`valid`)&&(xe(N,t),D.push(r),ce.push(L(s,i)))}}for(let e=0;e<D.length;e++)D[e].sample=ce[e];for(let t=0;t<e;t++){let e=pe[t],n=P[t],r=w[e][0].to;S[f[e]]=l[n].reference,r!==n&&(T[r]=T[r]-1,T[n]=T[n]+1),C[e]=me[t];let i=he[t];w[e]=i,x(e,i)}k=!0,A.solves++,A.leafPropagations++};return{get stats(){return Object.freeze({...A})},solve(e){let t=Ce(V(e));if(t.length===0)return ne;let r=[];for(let e=0;e<t.length;e++)r.push(n[t[e]]);return Object.freeze(r)},solveSlots(e){if(e===void 0)return Ce(void 0);let t=e instanceof Set||Array.isArray(e)||ArrayBuffer.isView(e)&&Symbol.iterator in e;if(!t){M.length=0;for(let t of e)M.push(t)}let r=t?e:M,i=()=>t?Se(e):M;if(h!==void 0){let e=_e(),t=0,a=!0;for(let i of r){if(O[i]===e)continue;O[i]=e;let r=n[i].intent;if(r===C[i])continue;let o=be(i,r);if(o===void 0){a=!1;break}pe[t]=i,me[t]=r,he[t]=o.edges,P[t]=o.target,F[t]=o,t++}if(a)return t===0?Ce(i()):(B(t),N.length===0?j:N)}return Ce(i())}};function V(e){if(e!==void 0){M.length=0;for(let t of e)M.push(o(t));return M}}function Se(e){if(e!==void 0){M.length=0;for(let t of e)M.push(t);return M}}function Ce(e){let t=h===void 0;if(I.length=0,h!==void 0&&!k&&e!==void 0&&e.length===0)return A.solves++,A.cacheHits+=h.blocks.length,j;E.length=0,re.length=0,ie.length=0,se.length=0;let r=_e(),i=t,a=h!==void 0&&e!==void 0;if(a){let t=0;for(let i=0;i<e.length;i++){let a=e[i];if(O[a]===r)continue;O[a]=r;let o=n[a].intent;if(o===C[a])continue;let s=be(a,o);if(s===void 0){t=-1;break}pe[t]=a,me[t]=o,he[t]=s.edges,P[t]=s.target,F[t]=s,t++}if(t>0)return B(t),N.length===0?j:N;r=_e()}let o=t||e===void 0;for(let t=0;t<(o?n.length:e.length);t++){let u=o?t:e[t];if(!o){if(O[u]===r)continue;O[u]=r}let d=n[u],p=d.intent;if(p===C[u])continue;let m=f[u],h=w[u],g=[];for(let e of p){c(e.resistance)||Zn(e.resistance,or(d));let t=f[s(e.to,d)];if(m===t)continue;let n=h[g.length];if(n?.to===t&&n.resistance===e.resistance)g.push(n);else{let r={pin:u,index:g.length,from:m,to:t,resistance:e.resistance,conductance:1/e.resistance};g.push(r),n?.to===t?se.push(n):i=!0}}g.length!==h.length&&(i=!0);let _=h.length===1&&g.length===1&&T[m]===1&&l[m].reference===void 0&&l[h[0].to].reference!==void 0&&l[g[0].to].reference!==void 0;a&&!_&&(a=!1),_&&p.length===1&&g[0]!==h[0]&&I.push({slot:u,branch:p[0],target:g[0].to,edges:g}),E.push(u),re.push(p),ie.push(g)}if(a&&i){for(let e=0;e<E.length;e++)pe[e]=E[e],me[e]=re[e],he[e]=ie[e],P[e]=ie[e][0].to,F[e]=void 0;return ye(),B(E.length),N.length===0?j:N}k&&(k=!1,p=/* @__PURE__ */ new Map,i=!0);let d=/* @__PURE__ */ new Map;for(let e=0;e<E.length;e++)d.set(E[e],{intent:re[e],edges:ie[e]});if(h!==void 0&&!i&&se.length===0){for(let[e,t]of d)C[e]=t.intent,w[e]=t.edges;return A.solves++,A.cacheHits+=h.blocks.length,ye(),j}let _=h,ne,D,ce=/* @__PURE__ */ new Map;for(let e=0;e<oe.length;e++)ae[oe[e]]=void 0;oe.length=0;for(let[e,t]of d)ae[e]=t.edges,oe.push(e);if(i){let e=y,t=b;for(let[n,r]of d){let i=$n(n,r.edges),a=v[n];i!==a&&(e+=i-a,t^=a^i)}if(ne=`${e}:${t}`,D=ee(ne,ae),D!==void 0)_=nr(D.topology,w,ae);else{let e=w.slice();for(let[t,n]of d)e[t]=n.edges;_=ir(l,e),A.topologyPrepares++}}else{let e=/* @__PURE__ */ new Set;for(let t of se){let n=_.edgeBlocks[t.pin]?.[t.index];n!==void 0&&e.add(n)}for(let t of e)ce.set(t,tr(_.blocks[t],w,ae))}let le,M=/* @__PURE__ */ new Map,fe=0,ge=0,L=i?0:_.blocks.length-ce.size;for(let e of i?_.blocks:ce.values()){let{component:t,key:n}=e,r=p.get(n);if(r!==void 0&&dr(r,t)){L++,(le??=/* @__PURE__ */ new Map).set(n,r);continue}let i=new Map(t.nodes.map(e=>[e,l[e].reference??null])),a=t.nodes.filter(e=>l[e].reference!==void 0),o=t.physical??t,s=e=>{let t=o.nodes.flatMap(e=>[...l[e].networks]),n=o.nodes.flatMap(e=>l[e].pins.map(e=>e.id)),r=l[o.nodes[0]].pins[0];throw new Xn(`ELECTRICAL_SOLVE_FAILED`,e,{...or(r),...t[0]===void 0?{}:{network:t[0]},networks:Object.freeze(t),component:Object.freeze(n)})},c,u;if(a.length!==0){let e=t.nodes.filter(e=>l[e].reference===void 0);for(let e of a)i.set(e,l[e].reference);let n=l[a[0]].reference;if(a.every(e=>l[e].reference===n))for(let t of e)i.set(t,n);else if(e.length!==0){let n=e.length,o=new Map(e.map((e,t)=>[e,t])),d=0,f=0,p=!1;for(let e of a)f=Math.max(f,Math.abs(l[e].reference));for(let e of t.edges){let t=o.has(e.from),n=o.has(e.to);(t||n)&&(d=Math.max(d,e.conductance)),t&&n&&(p=!0)}(!(d>0)||!(f>0))&&s(`Invalid equation scaling.`),p||(u=m.find(n=>n.matches(t.edges,e)),u===void 0&&(u=gr(e,t.edges,o,l),u!==void 0&&(m.push(u),m.length>8&&m.shift())));let h=new Float64Array(p?n*n:0),g,_;if(u!==void 0)({anchors:g,right:_}=u.assemble(t.edges,d,f));else{let e=Array.from({length:n},()=>[]),r=Array.from({length:n},()=>[]);for(let i of t.edges){let t=o.get(i.from),a=o.get(i.to),s=i.conductance/d;if(t!==void 0&&a!==void 0){let e=Math.min(t,a)*n+Math.max(t,a);h[e]=h[e]+s}else if(t!==void 0||a!==void 0){let n=t??a,o=l[t===void 0?i.from:i.to].reference;e[n].push(s),r[n].push(o/f*s)}}g=Float64Array.from(e,e=>lr(e)),_=Float64Array.from(r,e=>lr(e))}r?.factorization!==void 0&&ur(r.factorization.matrix,h)&&ur(r.factorization.anchors,g)?(c=r.factorization,ge++):(c=fr(h,g,s),fe++);let v=pr(c,_,s);e.forEach((e,t)=>{let n=ar(v[t]*f);Number.isFinite(n)||s(`Non-finite node voltage.`),i.set(e,n)})}}let d={edges:t.edges,voltages:t.nodes.map(e=>i.get(e)),factorization:c};(le??=/* @__PURE__ */ new Map).set(n,d);for(let[e,t]of i)S[e]!==t&&M.set(e,t)}let R=/* @__PURE__ */ new Map;N.length=0;for(let[e,t]of M){let r=u[e];for(let e=0;e<r.length;e++){let i=r[e],a=n[i],o=t===null||a.low===void 0?`unknown`:t<=a.low?`low`:t>=a.high?`high`:`unknown`,s=t===null?`floating`:`valid`,c=a.sample,l=c.voltage!==t||c.level!==o||c.status!==s;l&&N.push(i),(l||A.solves===0)&&R.set(a,Object.freeze({voltage:t===null?null:ar(t),level:o,status:s}))}}N.length>1&&N.sort(mr);for(let[e,t]of R)e.sample=t;for(let[e,t]of M)S[e]=t;for(let[e,t]of d)de(w[e],t.edges),C[e]=t.intent,w[e]=t.edges,x(e,t.edges);if(i)p=le??/* @__PURE__ */ new Map;else{if(le!==void 0)for(let[e,t]of le)p.set(e,t);for(let[e,t]of ce)_.blocks[e]=t}if(h=_,ue=!1,i){let e=D!==void 0&&_===D.topology?D:{id:D?.id??g++,cost:D?.cost??er(_),topology:_,hashes:D?.hashes??v.slice()};te(ne,e)}return A.solves++,A.components=_.components,A.floatingComponents=_.floatingComponents,A.factorizations+=fe,A.factorizationReuses+=ge,A.cacheHits+=L,ye(),N.length===0?j:N}}var vr=class{heap=[];sequence=0;get time(){return this.heap[0]?.time??1/0}push(e,t){let n={time:e,order:this.sequence++,value:t},r=this.heap.length;for(this.heap.push(n);r>0;){let e=r-1>>>1;if(!this.before(n,this.heap[e]))break;this.heap[r]=this.heap[e],r=e}this.heap[r]=n}pop(){let e=this.heap[0],t=this.heap.pop();if(this.heap.length){let e=0;for(;e*2+1<this.heap.length;){let n=e*2+1;if(n+1<this.heap.length&&this.before(this.heap[n+1],this.heap[n])&&n++,!this.before(this.heap[n],t))break;this.heap[e]=this.heap[n],e=n}this.heap[e]=t}return e.value}clear(){this.heap.length=0}before(e,t){return e.time<t.time||e.time===t.time&&e.order<t.order}},yr=class{entries=[];words=[];activeWords=[];batch=[];get size(){return this.activeWords.length}register(e){return this.entries.push(e)-1}add(e){let t=e>>>5,n=this.words[t]??0;n===0&&this.activeWords.push(t),this.words[t]=n|1<<(e&31)}take(){let e=this.batch;e.length=0,this.activeWords.length>1&&this.activeWords.sort((e,t)=>e-t);for(let t of this.activeWords){let n=this.words[t];for(this.words[t]=0;n!==0;){let r=31-Math.clz32(n&-n);e.push(this.entries[t*32+r]),n&=n-1}}return this.activeWords.length=0,e}clear(){this.entries.length=0,this.words.length=0,this.activeWords.length=0,this.batch.length=0}},br=class{values=[];head=0;get length(){return this.values.length-this.head}push(e){this.values.push(e)}shift(){let e=this.values[this.head];return this.values[this.head++]=void 0,this.head===this.values.length&&this.clear(),e}clear(){this.values.length=0,this.head=0}drain(){let e=this.values.slice(this.head);return this.clear(),e}};let xr={positive:`+`,negate:`-`,not:`!`,bitNot:`~`},Sr={add:`+`,subtract:`-`,multiply:`*`,divide:`/`,remainder:`%`,power:`**`,lessThan:`<`,lessThanOrEqual:`<=`,greaterThan:`>`,greaterThanOrEqual:`>=`,concat:`+`,bitAnd:`&`,bitOr:`|`,bitXor:`^`,shiftLeft:`<<`,shiftRight:`>>`,shiftRightUnsigned:`>>>`},Cr=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`,`abs`,`floor`,`ceil`,`trunc`,`round`,`sqrt`,`min`,`max`,`pow`]),wr=/* @__PURE__ */ new Set([`isNaN`,`isFinite`,`isInteger`,`isSafeInteger`]);function Tr(e,t,n){let r=e.startsWith(`load8`)?1:e.startsWith(`load16`)?2:4,i=h(t.bytes,n,r);return r===1?t.bytes[i]:r===2?t.view.getUint16(i,e.endsWith(`le`)):t.view.getUint32(i,e.endsWith(`le`))}function Er(e,t,n){let r=h(e.bytes,t,n);return e.bytes.slice(r,r+Number(n))}function Dr(e){throw Error(e===void 0?`Assertion failed`:String(e))}function Or(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}let kr=Object.freeze({checkBoolean:Et,createBytes:yt,createEnum:_t,createRecord:vt,equalValues:St,nonNull:Tt,readIndex:wt,load:Tr,copyBytes:Er,assertFalse:Dr,sameBytes:Or});var Ar=class extends Error{};function Y(e){throw new Ar(e)}var jr=class{target;bindings=[];bindingIds=/* @__PURE__ */ new Map;slots=[];nested=[];named=/* @__PURE__ */ new Map;visiting=/* @__PURE__ */ new Set;results=/* @__PURE__ */ new Set;buffers=[[]];depth=0;serial=0;constructor(e){this.target=e,this.bindings.push(e),this.bindingIds.set(e,0)}build(e,t){let n=this.nestedDerived(e);if(t.length===1)this.line(`return ${n}();`);else{this.line(`let projected = ${n}();`);for(let e=1;e<t.length;e++)this.line(`projected = projected[${this.ref(t[e])}];`);this.line(`return projected;`)}return[`function () {`,...this.nested.map(e=>e),...this.buffers[0].map(e=>` ${e}`),`}`].join(`\n`)}slotsUsed(){return this.slots}bindingTable(){return this.bindings}get lines(){return this.buffers[this.buffers.length-1]}line(e){this.lines.push(`${` `.repeat(this.depth)}${e}`)}block(e,t){this.line(`${e} {`),this.depth++,t(),this.depth--,this.line(`}`)}bind(e){if(!(typeof e==`object`&&e)&&Object.is(e,-0))return this.bindings.push(e)-1;let t=this.bindingIds.get(e);if(t!==void 0)return t;let n=this.bindings.push(e)-1;return this.bindingIds.set(e,n),n}ref(e){return`B[${this.bind(e)}]`}slot(e){this.slots.includes(e)||this.slots.push(e)}nestedSource(e,t,n){this.buffers.push([]);let r=this.depth;this.depth=0;try{n()}finally{this.depth=r}let i=this.buffers.pop(),a=[`function ${e}(${t.join(`, `)}) {`,...i,`}`].join(`\n`);return this.nested.push(a),e}nestedDerived(e){let t=`derived:${e.name}`,n=this.named.get(t);if(n)return n;this.visiting.has(t)&&Y(`recursive derived ${e.name}`);let r=`d${this.serial++}`;this.named.set(t,r),this.visiting.add(t);try{this.nestedSource(r,[],()=>this.region(e.value.body,void 0))}finally{this.visiting.delete(t)}return r}nestedFunction(e,t){let n=`function:${e}`,r=this.named.get(n);if(r)return r;this.visiting.has(n)&&Y(`recursive pure call ${e}`);let i=`f${this.serial++}`;this.named.set(n,i),this.visiting.add(n);try{let e=t.params.map((e,t)=>`p${t}`);this.nestedSource(i,e,()=>{let n=this.params;this.params=e;try{this.region(t.body,void 0)}finally{this.params=n}})}finally{this.visiting.delete(n)}return i}params;value(e){return this.results.has(e)||Y(`result ${e} is used before it is defined`),`v${e}`}defineResult(e){return this.results.add(e),`v${e}`}region(e,t){for(let n of e.operations)this.operation(n,t)}valueRegion(e,t){let n=`s${this.serial++}`;this.line(`${n}: {`),this.depth++,this.region(e.body,{slot:t,label:n}),this.depth--,this.line(`}`)}argument(e){return e.kind!==`value`&&Y(`resource argument`),this.value(e.value)}memoryRef(e,t){e.kind===`parameter`&&Y(`parameterised memory ${t}`);let n=this.target.memoryPlan(e.name);return this.slot(n.slot),n}pinRef(e,t){e.kind===`parameter`&&Y(`parameterised pin ${t}`);let n=this.target.pins.get(e.name),r=this.target.sampleResources.get(e.name);return(!n||!r)&&Y(`unknown pin ${e.name}`),this.slot(r),n}operation(e,t){let n=t=>{`result`in e||Y(`resultless operation`),this.line(`const ${this.defineResult(e.result)} = ${t};`)},r=e=>this.region(e,t);switch(e.kind){case`constant`:{let t=e.constant;t.kind===`bytes`?n(`H.createBytes(${this.ref(Object.freeze(Array.from(yt(t.value))))})`):t.kind===`enum`?n(this.ref(_t(t.name,t.member))):t.kind===`record`?n(this.ref(vt(t.fields.map(e=>[e.name,e.value])))):t.kind===`none`?n(`null`):n(this.ref(t.value));break}case`read`:if(e.resource===`state`){let t=this.target.stateResources.get(e.name);(!t||!this.target.states.has(e.name))&&Y(`unknown state ${e.name}`),this.slot(t),n(`${this.ref(this.target.states)}.get(${this.ref(e.name)})`)}else if(e.resource===`derived`){let t=this.target.declarations.get(e.name);t?.kind!==`derived`&&Y(`unknown derived ${e.name}`),n(`${this.nestedDerived(t)}()`)}else n(`${this.ref(this.target)}.read(${this.ref(e.resource)}, ${this.ref(e.name)})`);break;case`parameter`:{let t=this.params;(!t||e.index>=t.length)&&Y(`value parameter outside a call`),n(t[e.index]);break}case`unary`:{let t=xr[e.operator];t||Y(`unsupported unary ${e.operator}`),n(`(${t}${this.value(e.value)})`);break}case`binary`:if(e.operator===`equal`||e.operator===`notEqual`)n(`${e.operator===`notEqual`?`!`:``}H.equalValues(${this.value(e.left)}, ${this.value(e.right)})`);else{let t=Sr[e.operator];t||Y(`unsupported binary ${e.operator}`),n(`(${this.value(e.left)} ${t} ${this.value(e.right)})`)}break;case`numeric`:Cr.has(e.builtin)||Y(`unsupported builtin ${e.builtin}`),n(`${wr.has(e.builtin)?`Number`:`Math`}.${e.builtin}(${e.args.map(e=>this.value(e)).join(`, `)})`);break;case`record`:n(`H.createRecord([${e.fields.map(e=>`[${this.ref(e.name)}, ${this.value(e.value)}]`).join(`, `)}])`);break;case`field`:n(`${this.value(e.value)}[${this.ref(e.field)}]`);break;case`bytes`:n(`H.createBytes([${e.elements.map(e=>this.value(e)).join(`, `)}])`);break;case`length`:n(`${this.value(e.value)}.length`);break;case`index`:n(`H.readIndex(${this.value(e.value)}, ${this.value(e.index)})`);break;case`optional`:n(this.value(e.value));break;case`isNone`:n(`(${this.value(e.value)} === null)`);break;case`nonNull`:n(`H.nonNull(${this.value(e.value)})`);break;case`localRead`:n(`l${e.local}`);break;case`local`:this.line(`let l${e.local} = ${this.value(e.initial)};`);break;case`localWrite`:this.line(`l${e.local} = ${this.value(e.value)};`);break;case`memoryLength`:n(`${this.ref(this.memoryRef(e.memory,e.kind))}.bytes.length`);break;case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:n(`H.load(${this.ref(e.kind)}, ${this.ref(this.memoryRef(e.memory,e.kind))}, ${this.value(e.offset)})`);break;case`copyBytes`:{let t=this.memoryRef(e.memory,e.kind);n(`H.copyBytes(${this.ref(t)}, ${this.value(e.offset)}, ${this.value(e.length)})`);break}case`readSample`:n(`${this.ref(this.pinRef(e.pin,e.kind))}.sample`);break;case`callValue`:{e.pure||Y(`impure call`);let t=this.target.declarations.get(e.name);(t?.kind!==`function`||!t.pure)&&Y(`unknown pure function ${e.name}`),n(`${this.nestedFunction(e.name,t)}(${e.args.map(e=>this.argument(e)).join(`, `)})`);break}case`if`:this.block(`if (H.checkBoolean(${this.value(e.condition)}))`,()=>r(e.yes)),e.no&&this.block(`else`,()=>r(e.no));break;case`match`:e.arms.forEach((t,n)=>{let i=t.pattern,a=i.kind===`none`?null:i.kind===`enum`?_t(i.name,i.member):i.value;this.block(`${n?`else if`:`if`} (H.equalValues(${this.value(e.value)}, ${this.ref(a)}))`,()=>r(t.body))}),e.otherwise&&this.block(e.arms.length?`else`:``,()=>r(e.otherwise));break;case`while`:this.block(`while (true)`,()=>{let t=`s${this.serial++}`;this.line(`let ${t};`),this.valueRegion(e.test,t),this.line(`if (!H.checkBoolean(${t})) break;`),this.block(``,()=>r(e.body))});break;case`loop`:this.block(`while (true)`,()=>r(e.body));break;case`and`:case`or`:{let t=this.defineResult(e.result);this.line(`let ${t} = H.checkBoolean(${this.value(e.left)});`),this.block(`if (${e.kind===`or`?`!`:``}${t})`,()=>{this.valueRegion(e.right,t),this.line(`${t} = H.checkBoolean(${t});`)});break}case`select`:{let t=this.defineResult(e.result);this.line(`let ${t};`),this.block(`if (H.checkBoolean(${this.value(e.condition)}))`,()=>this.valueRegion(e.yes,t)),this.block(`else`,()=>this.valueRegion(e.no,t));break}case`assert`:this.block(`if (!H.checkBoolean(${this.value(e.condition)}))`,()=>{if(e.message){let t=`s${this.serial++}`;this.line(`let ${t};`),this.valueRegion(e.message,t),this.line(`H.assertFalse(${t});`)}else this.line(`H.assertFalse(undefined);`)});break;case`return`:this.line(`return;`);break;case`returnValue`:this.line(`return ${this.value(e.value)};`);break;case`break`:this.line(`break;`);break;case`continue`:this.line(`continue;`);break;case`yield`:t||Y(`yield outside a value region`),this.line(`${t.slot} = ${this.value(e.value)};`),this.line(`break ${t.label};`);break;default:{let t=e.kind;Y(`unsupported operation ${String(t)}`)}}}};function Mr(e,t,n){if(t&&t.kind!==`optional`){if(t.kind===`record`){let r=e.get(t.name);if(r?.kind!==`record`)return;let i=r.fields.find(e=>e.name===n);return i?{kind:i.type}:void 0}if(t.kind===`sample`){if(n===`voltage`)return{kind:`optional`,inner:{kind:`number`}};if(n===`level`||n===`status`)return{kind:`enum`,name:`Logic`}}}}function Nr(e,t,n){let r=t;for(let t=1;t<n.length;t++)r=Mr(e,r,n[t]);return{type:r}}function Pr(e){return e?e.kind===`optional`?Pr(e.inner):[`number`,`bool`,`string`,`enum`].includes(e.kind):!1}function Fr(e,t,n,r){if(t)switch(t.kind){case`number`:return`(${n} === ${r} || (${n} !== ${n} && ${r} !== ${r}))`;case`bool`:case`string`:case`enum`:return`(${n} === ${r})`;case`bytes`:return`(${n} === ${r} || (${n} !== null && ${r} !== null && typeof ${n} === \"object\" && typeof ${r} === \"object\" && ${n}.length === ${r}.length && H.sameBytes(${n}, ${r})))`;case`sample`:{let i=[`voltage`,`level`,`status`].map(i=>Fr(e,Mr(e,t,i),`${n}[${JSON.stringify(i)}]`,`${r}[${JSON.stringify(i)}]`));return i.some(e=>e===void 0)?void 0:`(${n} === ${r} || (${n} !== null && ${r} !== null && typeof ${n} === \"object\" && typeof ${r} === \"object\" && ${i.join(` && `)}))`}case`record`:{let i=e.get(t.name);if(i?.kind!==`record`||!i.fields.length)return;let a=i.fields.map(t=>Fr(e,{kind:t.type},`${n}[${JSON.stringify(t.name)}]`,`${r}[${JSON.stringify(t.name)}]`));return a.some(e=>e===void 0)?void 0:`(${n} === ${r} || (${n} !== null && ${r} !== null && typeof ${n} === \"object\" && typeof ${r} === \"object\" && ${a.join(` && `)}))`}case`optional`:{let i=Fr(e,t.inner,n,r);return i===void 0?void 0:`(${n} === ${r} || (${n} === null ? ${r} === null : (${r} !== null && ${i})))`}default:return}}function Ir(e,t,n){let r=e.declarations.get(n[0]);if(r?.kind!==`derived`)return{ok:!1,reason:`source root is not a derived declaration`};let{type:i}=Nr(e.declarations,r.type,n);if(i===void 0)return{ok:!1,reason:`source field type is not resolvable`};if(i.kind===`intent`)return{ok:!1,reason:`intent has no stable content comparison`};try{let a=new jr(e),o=a.build(r,n),s=Function(`B`,`H`,`\"use strict\"; return (${o});`)(a.bindingTable(),kr),c=`function (a, b) { return ${Fr(e.declarations,i,`a`,`b`)??`H.same(a, b)`}; }`,l=Function(`H`,`\"use strict\"; return (${c});`)({...kr,same:g});return{ok:!0,plan:{key:t,path:[...n],source:o,comparison:c,slots:a.slotsUsed(),evaluate:s,equals:l,needsSnapshot:!Pr(i)}}}catch(e){return{ok:!1,reason:e instanceof Ar?e.message:`unexpected code generation failure: ${e instanceof Error?e.message:String(e)}`}}}let Lr=/* @__PURE__ */ new WeakMap,Rr=/* @__PURE__ */ new WeakMap,zr=/* @__PURE__ */ new WeakMap,Br=72e14;function Vr(e){if(typeof e!=`number`||!Number.isFinite(e)||!Number.isInteger(e))throw TypeError(`Time must be a finite integer`);if(e<0||e>72e14)throw RangeError(`Time out of range`);return e===0?0:e}function Hr(e){let t=Lr.get(e);return t||(t=Yt(e),Lr.set(e,t)),t}function Ur(e){let t=Rr.get(e);return t===void 0&&(t=Vn(e,{bindResources:!0})??null,Rr.set(e,t)),t??void 0}function Wr(e){return{pc:e.start,slots:Array(e.slotCount),kind:0,duration:0,channel:``,value:void 0}}function Gr(e,t){let n=zr.get(e);return n||(n=Xt(e),zr.set(e,n)),n(t)}var Kr=class extends Error{code;diagnostic;related;constructor(e){super(e.message),this.name=`SimulationError`,this.code=e.code,this.diagnostic=e,this.related=e.related}};function qr(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}var Jr=class extends TypeError{code=`ASYNC_HOOK_RESULT`;constructor(){super(`Device hooks must return synchronously`)}},Yr=class extends RangeError{code=`INVALID_ELECTRICAL_PARAMETER`};function Xr(e){if(typeof e!=`number`||!Number.isFinite(e))throw new Yr(`Electrical parameters must be finite numbers`);return e}function Zr(e){if(qr(e))throw Promise.resolve(e).catch(()=>{}),new Jr}function Qr(e){if(!(e instanceof de))return{};let t=e.diagnostics[0];return t?{...t.path?{path:Object.freeze([...t.path])}:{},...t.source?{source:_(t.source)}:{}}:{}}function $r(e,t,n){return new Kr(Object.freeze({code:e,message:t instanceof Error?t.message:String(t),phase:n,time:null,cause:t,...Qr(t),related:Object.freeze([])}))}let ei=Object.freeze([]);function ti(e,t){for(let n of t.keys())if(!e.has(n))return!1;return!0}function ni(e,t){return Object.freeze({get props(){return t.guard(e,!0),Object.freeze(Object.fromEntries([...e.props].map(([e,t])=>[e,ee(t)])))},get inputs(){return e.guard(),e.inputs()},get memory(){return t.guard(e,!0),e.publicMemory()},topics:t.topicBridge(e),reportError:n=>t.report(e,n),attachJit:t=>e.attach(t),loadBytes:(t,n,...r)=>e.loadBytes(t,n,r.length?r[0]:0)})}var ri=class{board;entry;id;declarations=/* @__PURE__ */ new Map;props=/* @__PURE__ */ new Map;constants=/* @__PURE__ */ new Map;states=/* @__PURE__ */ new Map;memories=/* @__PURE__ */ new Map;memoryViews=/* @__PURE__ */ new Map;memorySizes=/* @__PURE__ */ new Map;pins=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;notificationInputs=/* @__PURE__ */ new Set;notificationOutputs=/* @__PURE__ */ new Map;batchInputs=[];batchOutputs=[];batchNotifications=[];emptyOutputs=Object.create(null);resources=[];jits=[];processes=[];reactions=[];derived=/* @__PURE__ */ new Map;derivedBuffers=/* @__PURE__ */ new Map;stateResources=/* @__PURE__ */ new Map;memoryResources=/* @__PURE__ */ new Map;sampleResources=/* @__PURE__ */ new Map;observerRevision=0;dependencyStack=[];observations=/* @__PURE__ */ new WeakMap;staticObservations=/* @__PURE__ */ new WeakMap;resistorIntents=/* @__PURE__ */ new Map;sampleEntries=/* @__PURE__ */ new Map;stateSlots=/* @__PURE__ */ new Map;resourceHandles=/* @__PURE__ */ new Map;memoryPlans=/* @__PURE__ */ new Map;observationFrames=/* @__PURE__ */ new WeakMap;evaluating=/* @__PURE__ */ new Set;random;host;context;adapter;valid=!0;rawProps;constructor(e,t,n,r,i,a){this.board=e,this.entry=t,this.id=n;for(let e of t.model.declarations)`name`in e&&this.declarations.set(e.name,e),(e.kind===`state`||e.kind===`memory`||e.kind===`pin`)&&(e.kind===`state`?this.stateResources:e.kind===`memory`?this.memoryResources:this.sampleResources).set(e.name,{version:0,subscribers:/* @__PURE__ */ new Set});u(r),this.rawProps=r;for(let e of Object.keys(r))if(this.declarations.get(e)?.kind!==`property`)throw TypeError(`Unknown property ${e}`);this.random=te(i,n,a),this.host={read:(e,t)=>this.read(e,t),write:(e,t)=>{let n=this.stateSlot(e);this.states.set(e,_(t)),this.board.invalidate(n)},sample:e=>this.readSample(e),intent:(t,n)=>{let r=this.pin(t);r.intent!==n&&(r.intent=n,e.dirtyElectricalSlots.add(e.electricalSlot(r)),e.electricalDirty=!0)},resistor:(e,t)=>{let n=Xr(t);if(n<.001||n>1e9)throw new Yr(`Resistance outside [0.001, 1e9]`);return this.resistorIntent(e,n)},memoryLength:e=>this.memory(e).length,load:(e,t,n)=>{let r=this.memoryPlan(t),i=e.startsWith(`load8`)?1:e.startsWith(`load16`)?2:4,a=h(r.bytes,n,i),o=this.dependencyStack.at(-1);return o&&o.set(r.slot,r.slot.version),i===1?r.bytes[a]:i===2?r.view.getUint16(a,e.endsWith(`le`)):r.view.getUint32(a,e.endsWith(`le`))},store:(e,t,n,r)=>{let i=this.memoryPlan(t),a=e.startsWith(`store8`)?1:e.startsWith(`store16`)?2:4,o=h(i.bytes,n,a),s=f(r,`stored value`);a===1?i.bytes[o]=s:a===2?i.view.setUint16(o,s,e.endsWith(`le`)):i.view.setUint32(o,s,e.endsWith(`le`)),this.memoryChangedPlan(i)},copyBytes:(e,t,n)=>{this.track(this.memoryResources,String(e));let r=this.memory(e),i=h(r,t,n);return r.slice(i,i+Number(n))},send:(e,t)=>this.send(e,t,!1),notify:t=>{if(!this.notificationOutputs.has(t))throw TypeError(`Unknown notification ${t}`);this.notificationOutputs.set(t,e.time)},now:()=>e.time,random:()=>S(this.random),call:(e,t)=>this.invoke(e,t),assert:(e,t)=>{if(e!==!0)throw Error(t===void 0?`Assertion failed`:String(t))},bind:e=>this.bindResources(e)},this.context=ni(this,e)}track(e,t){this.trackSlot(e.get(t))}trackSlot(e){let t=this.dependencyStack.at(-1);t&&t.set(e,e.version)}bindingReport(){return Object.freeze({instance:this.id,handles:this.resourceHandles.size,bound:Object.freeze([...this.resourceHandles.keys()].sort()),processes:Object.freeze(this.processes.map(e=>Object.freeze({name:e.declaration.kind===`on`?e.declaration.name:`start`,bound:e.frame?.resources?.length??0})))})}dependenciesCurrent(e){if(!e)return!1;for(let[t,n]of e)if(t.version!==n)return!1;return!0}evaluate(e,t){let n=t??/* @__PURE__ */ new Map;this.dependencyStack.push(n);try{return{value:e(),dependencies:n}}finally{this.dependencyStack.pop();let e=this.dependencyStack.at(-1);if(e)for(let[t,r]of n)e.set(t,r)}}evaluateSource(e,t){this.dependencyStack.push(t);try{return _(this.source(e))}finally{this.dependencyStack.pop();let e=this.dependencyStack.at(-1);if(e)for(let[n,r]of t)e.set(n,r)}}observe(e,t){let n=this.staticObservations.get(e);if(n)return n();let r=this.declarations.get(t[0]);if(r?.kind===`pin`||r?.kind===`state`){let n=r.kind===`pin`?this.sampleResources:this.stateResources,i=r.kind===`pin`?this.pin(r.name):void 0;if(i&&t[1]!==`sample`)throw TypeError(`Invalid source ${t.join(`.`)}`);let a=()=>{let e=i?i.sample:this.states.get(r.name);for(let n=i?2:1;n<t.length;n++)e=e[t[n]];return i?e:_(e)},o=a(),s=n.get(r.name);return s.subscribers.size||this.observerRevision++,s.subscribers.add(e),this.staticObservations.set(e,a),o}let i=this.observationFrames.get(e),a;i===void 0?(a=/* @__PURE__ */ new Map,this.observationFrames.set(e,{first:a,second:/* @__PURE__ */ new Map,alternate:!0})):(a=i.alternate?i.second:i.first,i.alternate=!i.alternate,a.clear());let o=this.evaluateSource(t,a),s=this.observations.get(e);if(s===void 0||s.size!==a.size||!ti(s,a)){if(s)for(let t of s.keys())!a.has(t)&&t.subscribers.delete(e)&&!t.subscribers.size&&this.observerRevision++;for(let t of a.keys())s?.has(t)||(t.subscribers.size||this.observerRevision++,t.subscribers.add(e))}return this.observations.set(e,a),o}observationReader(e,t){return this.staticObservations.get(e)??(()=>this.observe(e,t))}read(e,t){if(e===`state`)return this.trackSlot(this.stateSlot(t)),this.states.get(t);if(e===`derived`){let e=this.derived.get(t);if(!e||!this.dependenciesCurrent(e.dependencies)){let n=this.declarations.get(t);if(n?.kind!==`derived`)throw TypeError(`Unknown derived ${t}`);let r=this.derivedBuffers.get(t);r===void 0?(r=/* @__PURE__ */ new Map,this.derivedBuffers.set(t,r)):r.clear(),e=this.evaluate(()=>Gr(n.value,this.host),r),this.derived.set(t,e)}let n=this.dependencyStack.at(-1);if(n)for(let[t,r]of e.dependencies)n.set(t,r);return e.value}let n=e===`property`?this.props:this.constants;if(n.has(t))return n.get(t);if(this.evaluating.has(t))throw TypeError(`Circular creation dependency ${t}`);this.evaluating.add(t);try{let e=this.declarations.get(t);if(e?.kind!==`property`&&e?.kind!==`const`)throw TypeError(`Invalid creation reference ${t}`);let r;if(e.kind===`property`){if(Object.hasOwn(this.rawProps,t))r=x(e.type,this.rawProps[t],this.declarations,!0);else if(e.default)r=x(e.type,Gr(e.default,this.host),this.declarations,!0);else throw TypeError(`Missing property ${t}`)}else r=Gr(e.value,this.host);return n.set(t,r),r}finally{this.evaluating.delete(t)}}invoke(e,t=[]){let n=this.declarations.get(e);if(n?.kind!==`function`)throw TypeError(`Unknown function ${e}`);return Hr(n.body)(this.host,t)}syncCall(e,t=[]){let n=this.invoke(e,t).next();if(!n.done)throw TypeError(`Unexpected suspension in synchronous function`);return n.value}pin(e){let t=this.pins.get(String(e));if(!t)throw TypeError(`Unknown pin ${String(e)}`);return t}resistorIntent(e,t){let n=typeof e==`string`?e:String(e),r=this.resistorIntents.get(n);r===void 0&&(this.resistorIntents.size>=64&&this.resistorIntents.clear(),r=/* @__PURE__ */ new Map,this.resistorIntents.set(n,r));let i=r.get(t);return i===void 0&&(r.size>=8&&r.clear(),i=Object.freeze([Object.freeze({to:this.pin(n),resistance:t})]),r.set(t,i)),i}readSample(e){let t=typeof e==`string`?e:String(e),n=this.sampleEntries.get(t);if(n===void 0){let e=this.pin(t);n={pin:e,slot:this.sampleResources.get(e.name)},this.sampleEntries.size>=512&&this.sampleEntries.clear(),this.sampleEntries.set(t,n)}let r=this.dependencyStack.at(-1);return r&&r.set(n.slot,n.slot.version),n.pin.sample}memory(e){let t=this.memories.get(String(e));if(!t)throw TypeError(`Unknown memory ${String(e)}`);return t}stateSlot(e){let t=this.stateSlots.get(e);if(t===void 0){if(!this.states.has(e))throw TypeError(`Unknown state ${e}`);t=this.stateResources.get(e),this.stateSlots.set(e,t)}return t}memoryPlan(e){let t=typeof e==`string`?e:String(e),n=this.memoryPlans.get(t);if(n===void 0){let e=this.memories.get(t);if(!e)throw TypeError(`Unknown memory ${t}`);n={name:t,bytes:e,view:this.memoryViews.get(t),slot:this.memoryResources.get(t)},this.memoryPlans.set(t,n)}return n}memoryChanged(e){this.memoryChangedSlot(e,this.memoryPlan(e).slot)}memoryChangedPlan(e){this.memoryChangedSlot(e.name,e.slot)}memoryChangedSlot(e,t){this.board.invalidate(t);for(let t of this.jits)t.options.code===e&&(t.cache.clear(),t.revision++,t.directPrograms.clear(),t.directProgramRevision=-1,t.directSkip=void 0,t.direct?.frame.resume?t.direct.frame.stopAfterInstruction=!0:t.direct=void 0)}bindResources(e){let t=Array(e.length);for(let n=0;n<e.length;n++){let r=e[n],i=`${r[0]}\\0${r[1]}`,a=this.resourceHandles.get(i);a===void 0&&(a=this.resourceHandle(r[0],r[1]),this.resourceHandles.set(i,a)),t[n]=a}return t}resourceHandle(e,t){if(e===`pin`){let e,n=-1,r,i=()=>(e===void 0&&(e=this.pin(t),n=this.board.electricalSlot(e),r=this.sampleResources.get(t)),e);return Object.freeze({sample:()=>{let e=i(),t=this.dependencyStack.at(-1);return t&&t.set(r,r.version),e.sample},intent:e=>{let t=i();t.intent!==e&&(t.intent=e,this.board.dirtyElectricalSlots.add(n),this.board.electricalDirty=!0)},resistor:e=>{let n=Xr(e);if(n<.001||n>1e9)throw new Yr(`Resistance outside [0.001, 1e9]`);return this.resistorIntent(t,n)}})}if(e===`state`){let e,n=()=>e??=this.stateSlot(t),r=this.states;return Object.freeze({read:()=>{let e=n(),i=this.dependencyStack.at(-1);return i&&i.set(e,e.version),r.get(t)},write:e=>{let i=n();r.set(t,_(e)),this.board.invalidate(i)}})}let n,r=()=>n??=this.memoryPlan(t),i=(e,t,n)=>{let i=r(),a=h(i.bytes,n,e),o=this.dependencyStack.at(-1);return o&&o.set(i.slot,i.slot.version),e===1?i.bytes[a]:e===2?i.view.getUint16(a,t):i.view.getUint32(a,t)},a=(e,n,i,a)=>{let o=r(),s=h(o.bytes,i,e),c=f(a,`stored value`);e===1?o.bytes[s]=c:e===2?o.view.setUint16(s,c,n):o.view.setUint32(s,c,n),this.memoryChangedSlot(t,o.slot)};return Object.freeze({load8:e=>i(1,!1,e),load16le:e=>i(2,!0,e),load16be:e=>i(2,!1,e),load32le:e=>i(4,!0,e),load32be:e=>i(4,!1,e),store8:(e,t)=>a(1,!1,e,t),store16le:(e,t)=>a(2,!0,e,t),store16be:(e,t)=>a(2,!1,e,t),store32le:(e,t)=>a(4,!0,e,t),store32be:(e,t)=>a(4,!1,e,t),length:()=>this.memory(t).length,copy:(e,n)=>{this.track(this.memoryResources,t);let r=this.memory(t),i=h(r,e,n);return r.slice(i,i+Number(n))}})}prepare(){for(let e of this.entry.model.declarations)e.kind===`pin`&&this.pins.set(e.name,{id:`${this.id}\\0${e.name}`,instance:this.id,name:e.name,intent:[],sample:{voltage:null,level:`unknown`,status:`floating`}});for(let e of this.entry.model.declarations)switch(e.kind){case`property`:case`const`:this.read(e.kind,e.name);break;case`state`:this.states.set(e.name,_(Gr(e.initial,this.host)));break;case`memory`:{let t=p(Gr(e.length,this.host),`memory length`);this.memorySizes.set(e.name,t);break}case`pin`:{let t=this.pins.get(e.name);if(e.low&&e.high){let n=Xr(Gr(e.low,this.host)),r=Xr(Gr(e.high,this.host));if(n>=r)throw new Yr(`Pin thresholds must satisfy low < high`);Object.assign(t,{low:n,high:r})}e.initial&&(t.intent=Gr(e.initial,this.host));break}case`channel`:{let t=p(Gr(e.capacity,this.host),`capacity`);if(t===0)throw RangeError(`Capacity must be positive`);let n;if(e.maxLength&&(n=p(Gr(e.maxLength,this.host),`maxLength`),n===0))throw RangeError(`maxLength must be positive`);this.channels.set(e.name,{declaration:e,capacity:t,...n===void 0?{}:{maxLength:n},overflow:e.overflow?String(Gr(e.overflow,this.host)):`drop_new`,incoming:new br,pending:new br,outgoing:new br});break}case`notification`:e.direction===`output`&&this.notificationOutputs.set(e.name,null);break;case`start`:case`on`:this.processes.push({instance:this,declaration:e,resumable:Ur(e.body),...e.kind===`on`?{source:e.sourcePath}:{},state:`idle`,pending:!1});break;case`reaction`:this.reactions.push({instance:this,declaration:e,previous:void 0,frame:void 0})}for(let[e,t]of this.channels)t.declaration.direction===`input`?this.batchInputs.push(t):(this.batchOutputs.push([e,t]),this.emptyOutputs[e]=ei);for(let e of this.notificationOutputs.keys())this.batchNotifications.push(e),this.emptyOutputs[e]=null;Object.freeze(this.emptyOutputs)}captureBatch(e,t){for(let e of this.batchInputs)e.incoming.length&&e.incoming.clear();let n=this.emptyOutputs;for(let[e,t]of this.batchOutputs)t.outgoing.length&&(n===this.emptyOutputs&&(n=Object.assign(Object.create(null),this.emptyOutputs)),n[e]=Object.freeze(t.outgoing.drain().map(e=>Object.freeze({time:e.time,value:ee(e.value)}))));for(let e of this.batchNotifications){let t=this.notificationOutputs.get(e);t!==null&&(n===this.emptyOutputs&&(n=Object.assign(Object.create(null),this.emptyOutputs)),n[e]=Object.freeze({time:t}),this.notificationOutputs.set(e,null))}return Object.freeze({from:e,to:t,outputs:n===this.emptyOutputs?n:Object.freeze(n)})}assertCreation(){for(let e of this.entry.model.declarations)if(e.kind===`assert`&&!Hr(e.body)(this.host).next().done)throw TypeError(`Creation assertion suspended`)}allocate(){for(let[e,t]of this.memorySizes){let n=new Uint8Array(t);this.memories.set(e,n),this.memoryViews.set(e,new DataView(n.buffer))}this.memorySizes.clear()}guard(){this.board.guard(this)}inputs(){let e=Object.create(null);for(let t of this.entry.model.declarations)t.kind===`channel`&&t.direction===`input`&&(e[t.name]=Object.freeze({send:e=>{this.guard(),this.send(t.name,e,!0)}})),t.kind===`notification`&&t.direction===`input`&&(e[t.name]=Object.freeze({notify:()=>{this.guard(),this.notificationInputs.add(t.name)}}));return Object.freeze(e)}publicMemory(){let e=Object.create(null);for(let t of this.entry.model.declarations)t.kind===`memory`&&t.public&&(e[t.name]=b(this.memory(t.name),()=>{if(this.board.validity(this),![`idle`,`initialize`,`sync`].includes(this.board.phase))throw this.board.error(`INVALID_CALL_STATE`,`Memory cannot be borrowed in this phase`,this);if(this.board.phase===`initialize`&&this.board.current!==this)throw this.board.error(`INVALID_CALL_STATE`,`Another factory is initializing`,this)}));return Object.freeze(e)}send(e,t,n){let r=this.channels.get(e);if(!r||r.declaration.direction!==(n?`input`:`output`))throw TypeError(`Unknown channel ${e}`);let i=x(r.declaration.type,t,this.declarations);if(r.maxLength!==void 0&&i.length>r.maxLength)throw RangeError(`Message exceeds maxLength`);let a=n?r.pending:r.outgoing;if(a.length===r.capacity){if(r.overflow===`drop_new`)return;if(r.overflow===`error`){let t=this.board.error(`CHANNEL_OVERFLOW`,`Channel ${e} overflow`,this);throw this.board.fault(t),t}a.shift()}a.push({time:this.board.time,value:i})}attach(e){if(this.guard(),this.board.phase!==`initialize`||this.board.current!==this)throw this.board.error(`INVALID_CALL_STATE`,`attachJit is initialization-only`,this);if(u(e,[`entry`,`code`,`pc`,`beforeInstruction`,`polling`,`delays`,`translate`]),m(e.entry),m(e.code),m(e.pc),this.jits.some(t=>t.active&&t.options.entry===e.entry))throw this.board.error(`INVALID_BINDING`,`Duplicate JIT entry`,this);if(!this.memories.has(e.code)||this.declarations.get(e.pc)?.kind!==`state`||this.declarations.get(e.pc).type.kind!==`number`||typeof e.translate!=`function`)throw this.board.error(`INVALID_BINDING`,`Invalid JIT binding`,this);if(e.beforeInstruction!==void 0){u(e.beforeInstruction,[`when`,`call`]);let t=this.declarations.get(e.beforeInstruction.when),n=this.declarations.get(e.beforeInstruction.call);if(!t||![`state`,`derived`].includes(t.kind)||!(`type`in t)||t.type.kind!==`bool`||n?.kind!==`function`||n.params.length||n.returns)throw this.board.error(`INVALID_BINDING`,`Invalid instruction hook`,this)}else if(Object.hasOwn(e,`beforeInstruction`))throw TypeError(`Invalid beforeInstruction`);let t=/* @__PURE__ */ new Map;if(Object.hasOwn(e,`polling`)){if(!Array.isArray(e.polling))throw TypeError(`polling must be an array`);for(let n of e.polling){u(n,[`pc`,`predicate`]);let e=d(n.pc,`polling pc`),r=m(n.predicate),i=this.declarations.get(r);if(t.has(e)||i?.kind!==`function`||!i.pure||i.params.length||i.returns?.kind!==`bool`)throw this.board.error(`INVALID_BINDING`,`Invalid polling declaration`,this);t.set(e,r)}}if(Object.hasOwn(e,`delays`)&&!(e.delays instanceof Map))throw TypeError(`delays must be a Map`);let n={instance:this,options:Object.freeze({...e,...e.beforeInstruction?{beforeInstruction:Object.freeze({...e.beforeInstruction})}:{}}),cache:/* @__PURE__ */ new Map,polling:t,delays:e.delays??/* @__PURE__ */ new Map,revision:0,directRevision:-1,directObserverRevision:-1,directStateGuards:/* @__PURE__ */ new Set,directMemoryGuards:/* @__PURE__ */ new Set,directHookReads:/* @__PURE__ */ new Set,directPrograms:/* @__PURE__ */ new Map,directProgramRevision:-1,direct:void 0,directSkip:void 0,pollReads:void 0,currentPc:void 0,automaticPolling:!1,pollingWait:!1,pollingPeriod:0,pollingOrigin:0,active:!0,stopped:!1,queued:!1,execution:void 0};this.jits.push(n),this.board.jits.push(n);let r={dispose:()=>{n.active&&(n.active=!1,n.execution=void 0,delete n.predicate,this.board.waitingJits.delete(n),n.cache.clear(),n.directPrograms.clear(),n.direct=void 0,n.pollReads=void 0)}};return this.resources.push(r),r}loadBytes(e,t,n){if(this.guard(),this.board.phase!==`idle`&&(this.board.phase!==`initialize`||this.board.current!==this))throw this.board.error(`INVALID_CALL_STATE`,`Code loading is not allowed in this phase`,this);if(typeof e!=`string`||!this.jits.some(t=>t.active&&t.options.code===e))throw this.board.error(`INVALID_BINDING`,`Memory is not bound as code`,this);if(!(t instanceof Uint8Array))throw TypeError(`Code must be Uint8Array`);let r=this.memory(e),i=h(r,n,t.length);t.length&&(r.set(t.slice(),i),this.memoryChanged(e))}source(e){let t=this.declarations.get(e[0]),n,r=1;if(t?.kind===`pin`){if(this.track(this.sampleResources,t.name),e[1]!==`sample`)throw TypeError(`Invalid source ${e.join(`.`)}`);n=this.pin(t.name).sample,r=2}else if(t?.kind===`state`||t?.kind===`derived`)n=this.read(t.kind,t.name);else throw TypeError(`Invalid source ${e.join(`.`)}`);for(let t=r;t<e.length;t++)n=n[e[t]];return n}};function ii(e,t,n){let r=/* @__PURE__ */ new Map,i=[],a=e=>{for(let t of e.operations)switch(`result`in t&&r.set(t.result,t),t.kind){case`constant`:case`unary`:case`binary`:case`numeric`:case`field`:case`length`:case`index`:case`isNone`:case`nonNull`:case`optional`:case`local`:case`localRead`:case`localWrite`:case`memoryLength`:case`load8`:case`load16le`:case`load16be`:case`load32le`:case`load32be`:case`readSample`:case`yield`:break;case`read`:if(t.resource===`derived`||t.name===n)return!1;break;case`if`:if(!a(t.yes)||t.no&&!a(t.no))return!1;break;case`select`:if(!a(t.yes.body)||!a(t.no.body))return!1;break;case`and`:case`or`:if(!a(t.right.body))return!1;break;case`match`:if(t.arms.some(e=>!a(e.body))||t.otherwise&&!a(t.otherwise))return!1;break;case`redirect`:i.push(t.target);break;default:return!1}return!0};return a(e)?i.some(e=>{let n=r.get(e);return n?.kind!==`constant`||n.constant.kind===`number`&&n.constant.value===t}):!1}let ai=/* @__PURE__ */ new WeakMap;function oi(e){let t=ai.get(e);return t===void 0&&(t={stateMask:[],memoryMask:[]},ai.set(e,t)),t}function si(e){let t=e;return t.directStats??={directCompiles:0,directCalls:0,directFallbacks:0,directDeadlines:0,directStopped:0}}function ci(e){let t=oi(e),{stateIndex:n,memoryIndex:r}=t;if(n===void 0||r===void 0)return;let i=(e,t,n)=>{e.fill(0);for(let r of n){let n=t.get(r);n!==void 0&&(e[n>>>5]=(e[n>>>5]??0)|1<<(n&31))}};i(t.stateMask,n,e.directStateGuards),i(t.memoryMask,r,e.directMemoryGuards)}function li(e,t){let n=!1,r=e.instance,i=e.directHookReads.size;if(t)for(let n of t.keys())e.directHookReads.add(n);if(e.directObserverRevision!==r.observerRevision||i!==e.directHookReads.size){e.directObserverRevision=r.observerRevision;for(let[t,i]of r.stateResources){let r=i.subscribers.size>0||e.directHookReads.has(i);e.directStateGuards.has(t)!==r&&(r?e.directStateGuards.add(t):e.directStateGuards.delete(t),n=!0)}for(let[t,i]of r.memoryResources){let r=i.subscribers.size>0||e.directHookReads.has(i)||t===e.options.code;e.directMemoryGuards.has(t)!==r&&(r?e.directMemoryGuards.add(t):e.directMemoryGuards.delete(t),n=!0)}n&&(ci(e),e.directSkip=void 0)}}function ui(e,t,n){let r=()=>{e.time=n.time};return{send:(e,n)=>{r(),t.host.send(e,n)},sample:e=>(r(),t.host.sample(e)),intent:(e,n)=>{r(),t.host.intent(e,n)},resistor:(e,n)=>(r(),t.host.resistor(e,n)),notify:e=>{r(),t.host.notify(e)},now:()=>(r(),t.host.now()),random:()=>(r(),t.host.random()),assert:(e,n)=>{r(),t.host.assert(e,n)}}}function di(e,t,n,r,i,a){let o={states:Array(n.length),memories:r.map(e=>t.memory(e)),locals:Array(i.localCount),stateDirty:Array(Math.ceil(n.length/32)).fill(0),memoryDirty:Array(Math.ceil(r.length/32)).fill(0),time:e.time,due:e.time,resume:0};return o.host=ui(e,t,o),o.blockedStates=a.stateMask,o.blockedMemories=a.memoryMask,o}function fi(e,t,n){let r=t.instance,i=!!t.direct?.frame.resume;if(!i){let i=d(r.states.get(t.options.pc),`pc`);if(e.execution!==`throughput`||e.jits.length!==1||t.polling.has(i)||t.cache.get(i)?.polling||(li(t,n),t.directSkip===i))return!1;if(t.directRevision!==t.revision){t.directProgramRevision!==t.revision&&(t.directPrograms.clear(),t.directProgramRevision=t.revision);let n=JSON.stringify([...t.delays.keys()].sort((e,t)=>e-t)),i=t.directPrograms.get(n);if(i)t.direct=i,t.directRevision=t.revision;else{let i=[...r.states.keys()].filter(e=>{let t=r.declarations.get(e);return t.type.kind===`number`||t.type.kind===`bool`}),a=[...r.memories.keys()],o=new Map(i.map((e,t)=>[e,t])),s=new Map(a.map((e,t)=>[e,t])),c=[...t.cache.values()].filter(e=>!e.polling&&!t.polling.has(e.pc)),l=/* @__PURE__ */ new Map;for(let[e,n]of t.delays){let t=o.get(n.counter);t!==void 0&&l.set(e,{counter:t,cycles:n.cycles})}let u=wn(c,{states:o,memories:s,pc:{name:t.options.pc,index:o.get(t.options.pc)},host:!0,split:!0,shardSize:8,delayLoops:l});t.directRevision=t.revision,u&&si(t).directCompiles++;let d=oi(t);d.stateIndex=o,d.memoryIndex=s,d.stateMask.length=Math.ceil(i.length/32),d.memoryMask.length=Math.ceil(a.length/32),ci(t),t.direct=u?{program:u,stateReads:u.readStates.map(e=>[e,o.get(e)]),stateWrites:u.writeStates.map(e=>[e,o.get(e)]),memoryWrites:u.writeMemories.map(e=>[e,s.get(e)]),revision:t.revision,frame:di(e,r,i,a,u,d)}:void 0,t.direct?t.directPrograms.set(n,t.direct):t.directPrograms.delete(n)}}if(!t.direct)return!1}let a=t.direct,o=a.frame;i&&(o.stopAfterInstruction=!0);for(let[e,t]of a.stateReads)o.states[t]=r.states.get(e);o.time=e.time,o.stateDirty.fill(0),o.memoryDirty.fill(0);let s=e.time,c,l=!1,u=si(t);u.directCalls++;try{c=a.program.run(o,Math.min(e.executionEnd,e.events.time))}finally{e.time=o.time;for(let[e,t]of a.stateWrites)o.stateDirty[t>>>5]&1<<(t&31)&&(r.host.write(e,o.states[t]),l=!0);for(let[e,t]of a.memoryWrites)o.memoryDirty[t>>>5]&1<<(t&31)&&(r.memoryChanged(e),l=!0)}if((c!==`fallback`||l||e.time!==s)&&e.boundary(),c===`fallback`){if(u.directFallbacks++,t.directSkip=d(r.states.get(t.options.pc),`pc`),e.time===s&&e.time<e.executionEnd)return!1}else if(c===`stopped`)return u.directStopped++,t.stopped=!0,!0;else c===`invalidated`?(o.stopAfterInstruction=!1,a.revision!==t.revision&&(t.direct=void 0,t.directRevision=-1)):u.directDeadlines++;return o.resume&&o.due>e.time?e.events.push(o.due,()=>e.queueJit(t)):e.queueJit(t),!0}function pi(e,t){let n=new Map(t),r=e.instance;for(let t of[r.stateResources.get(e.options.pc),r.memoryResources.get(e.options.code)])n.set(t,t.version);return n}function mi(e,t,n){if(n.kind===`elapse`){let r=Vr(n.duration);if(r===0)return!1;let i=Vr(e.time+r);return e.events.push(i,()=>e.queueJit(t)),e.boundary(),!0}if(n.kind===`waitUntil`){let r=t.instance.evaluate(()=>t.instance.syncCall(n.predicate));return r.value!==!0&&(t.predicate=n.predicate,t.pollingWait=!1,t.dependencies=r.dependencies,e.waitingJits.add(t),e.boundary(),!0)}if(n.kind===`stop`)return t.stopped=!0,t.execution=void 0,e.boundary(),!0;if(n.kind===`redirect`){d(n.pc,`redirect target`);let r=Vr(n.delay);t.instance.host.write(t.options.pc,n.pc),t.execution=void 0;let i=t.automaticPolling&&r>0&&n.pc===t.currentPc&&t.pollReads,a=i?pi(t,i):void 0;return t.automaticPolling=!1,t.pollReads=void 0,e.boundary(),r===0?e.queueJit(t):e.events.push(Vr(e.time+r),()=>{t.active&&!t.stopped&&(a&&t.instance.dependenciesCurrent(a)?(t.dependencies=a,t.pollingWait=!0,t.pollingPeriod=r,t.pollingOrigin=e.time,e.waitingJits.add(t)):e.queueJit(t))}),!0}throw TypeError(`Invalid JIT suspension`)}function hi(e,t){if(t.queued=!1,t.active&&!t.stopped){if(e.current=t.instance,t.direct?.frame.resume)fi(e,t);else{if(!t.execution){t.automaticPolling=!1,t.pollReads=void 0;let n,r=!1,i=t.options.beforeInstruction;if(i){let a=t.instance.declarations.get(i.when).kind,o=t.instance.states.get(t.options.pc),s=e.execution===`throughput`&&(e.jits.length===1||t.polling.has(o))?t.instance.evaluate(()=>t.instance.read(a,i.when)):void 0,c=(s?s.value:t.instance.read(a,i.when))===!0;if(c){let n=t.instance.invoke(i.call),r=n.next();if(!r.done){if(t.execution=n,mi(e,t,r.value))return;throw TypeError(`Invalid hook suspension`)}}n=s?.dependencies,r=c}let a=d(t.instance.states.get(t.options.pc),`pc`);if(e.execution===`throughput`){let i=t.polling.get(a);if(i){let r=t.instance.evaluate(()=>t.instance.syncCall(i));if(r.value!==!0){t.dependencies=pi(t,new Map([...n??[],...r.dependencies])),t.pollingWait=!0,t.pollingPeriod=0,e.waitingJits.add(t),e.boundary();return}}if(!r&&e.jits.length===1&&fi(e,t,n))return}let o=t.cache.get(a);if(!o){let n=e.phase;e.phase=`translate`;let r=!0;try{let n=b(t.instance.memory(t.options.code),()=>{if(!r)throw e.error(`OBJECT_DISPOSED`,`Translation view expired`,t.instance)}),i=t.options.translate(Object.freeze({pc:a,code:n}),gt({device:t.instance.entry.model}));Zr(i);let s=qe(i,t.instance.entry.model);if(s.instructions[0]?.pc!==a)throw TypeError(`Translated first pc does not match`);let c=s.instructions.map(e=>({pc:e.pc,nextPc:e.nextPc,body:e.body,polling:ii(e.body,e.pc,t.options.pc),execute:Hr(e.body)}));for(let e=c.length-1;e>=0;e--){let n=c[e];t.cache.set(n.pc,n)}t.revision++,t.directSkip=void 0,o=c[0]}catch(n){throw e.wrap(n,`JIT_FAILED`,`translate`,t.instance)}finally{r=!1,e.phase=n}}t.currentPc=a,t.automaticPolling=e.execution===`throughput`&&e.jits.length===1&&o.polling&&!r&&(!i||n!==void 0),t.pollReads=n,t.instance.host.write(t.options.pc,o.nextPc),t.execution=o.execute(t.instance.host)}for(;;){let n=t.automaticPolling?(()=>{let e=t.instance.evaluate(()=>t.execution.next());return t.pollReads=new Map([...t.pollReads??[],...e.dependencies]),e.value})():t.execution.next();if(n.done){t.execution=void 0,e.boundary(),e.queueJit(t);return}if(mi(e,t,n.value))return}}}}let gi=Symbol.for(`mica-js.simulator/observations`),_i=Symbol.for(`mica-js.simulator/processes`),vi=Object.freeze({}),yi=/* @__PURE__ */ new WeakMap;function bi(e){try{if(!Array.isArray(e))throw TypeError(`Expected device entries`);let t=/* @__PURE__ */ new Set,n=e.map(e=>{u(e,[`id`,`model`,`create`]);let n=m(e.id);if(t.has(n))throw TypeError(`Duplicate device type ${n}`);if(t.add(n),typeof e.create!=`function`)throw TypeError(`Expected device factory`);let r;try{r=Ge(e.model)}catch(e){throw $r(e instanceof de&&Object.getOwnPropertyDescriptor(e,`code`)?.value===`CHANNEL_CONSUMER_CONFLICT`?`CHANNEL_CONSUMER_CONFLICT`:`MODEL_VALIDATION_FAILED`,e,`library`)}return Object.freeze({id:n,model:r,create:e.create})}),r=Object.freeze({});return yi.set(r,n),r}catch(e){throw e instanceof Kr?e:$r(`INVALID_CONFIGURATION`,e,`library`)}}var xi=class{time=0;status=`ready`;phase=`assembly`;current;electricalDirty=!0;dirtyElectricalSlots=/* @__PURE__ */ new Set;observations=new yr;reactionBatch=[];changeObservations=[];changePrevious=[];changeCurrent=[];plans=[];skippedPlans=[];sampleSlots=/* @__PURE__ */ new Map;sampleSlotsBySlot=[];electricalSlots=/* @__PURE__ */ new Map;byId=/* @__PURE__ */ new Map;dispatchDepth=0;initialized=!1;errors=new t;diagnostics=new t;listeners=/* @__PURE__ */ new Set;hostListeners=0;models=new br;events=new vr;readyJits=new br;waitingJits=/* @__PURE__ */ new Set;jits=[];instances=[];network;primary;execution;executionEnd=0;onDidError=(e,t,n)=>this.errors.event(n=>{try{e.call(t,n)}catch(e){this.diagnostic(`HOST_LISTENER_FAILED`,e)}},void 0,n);onDidDiagnostic=(e,t,n)=>this.diagnostics.event(n=>{try{e.call(t,n)}catch(e){this.fallback(e)}},void 0,n);topics=this.topicBridge();constructor(e,t,n){try{u(t,[`instances`,`nets`]),u(n,[`seed`,`execution`,`cpuQuantum`]);let r=Object.hasOwn(n,`execution`)?n.execution:`throughput`;if(r!==`throughput`&&r!==`precise`)throw TypeError(`Invalid execution mode`);this.execution=r;let i=Object.hasOwn(n,`cpuQuantum`)?f(n.cpuQuantum,`cpuQuantum`):1e7;if(i<1||i>1e7)throw RangeError(`cpuQuantum outside [1, 10000000]`);if(!Array.isArray(t.instances)||!Array.isArray(t.nets))throw TypeError(`instances and nets are required arrays`);let a=Object.hasOwn(n,`seed`)?f(n.seed,`seed`):0;if(a<0||a>4294967295)throw RangeError(`seed out of uint32 range`);let o=new Map(e.map(e=>[e.id,e])),s=/* @__PURE__ */ new Set;for(let e of t.instances){u(e,[`id`,`type`,`props`,`randomState`]);let t=m(e.id),n=m(e.type);if(s.has(t))throw TypeError(`Duplicate instance ${t}`);s.add(t);let r=o.get(n);if(!r)throw TypeError(`Unknown device type ${n}`);let i=Object.hasOwn(e,`props`)?e.props:{};if(Object.hasOwn(e,`randomState`)&&e.randomState===void 0)throw TypeError(`Invalid randomState`);this.instances.push(new ri(this,r,t,i,a,e.randomState))}for(let e of this.instances)this.byId.set(e.id,e);let c=this.byId,l=/* @__PURE__ */ new Set,p=/* @__PURE__ */ new Set;for(let e of t.nets){u(e,[`id`,`pins`,`voltage`]);let t=m(e.id);if(l.has(t))throw TypeError(`Duplicate network ${t}`);if(l.add(t),!Array.isArray(e.pins))throw TypeError(`Network pins must be an array`);Object.hasOwn(e,`voltage`)&&d(e.voltage,`voltage`);for(let t of e.pins){u(t,[`instance`,`pin`]);let e=m(t.instance),n=m(t.pin);if(c.get(e)?.declarations.get(n)?.kind!==`pin`)throw TypeError(`Unknown pin endpoint`);let r=`${e}\\0${n}`;if(p.has(r))throw TypeError(`Duplicate connected endpoint`);p.add(r)}}try{for(let e of this.instances)this.current=e,e.prepare();for(let e of this.instances)this.current=e,e.assertCreation();for(let e of this.instances)this.current=e,e.allocate()}catch(e){throw this.wrap(e,`MODEL_EXECUTION_FAILED`,`assembly`,this.current)}let h=t.nets.map(e=>({id:e.id,pins:e.pins.map(e=>c.get(e.instance).pin(e.pin)),...Object.hasOwn(e,`voltage`)?{voltage:e.voltage}:{}})),g=[];for(let e of this.instances)for(let t of e.pins.values()){let n=e.sampleResources.get(t.name);g.push(t),this.sampleSlots.set(t,n),this.electricalSlots.set(t,this.sampleSlotsBySlot.length),this.sampleSlotsBySlot.push(n)}this.network=_r(g,h),this.phase=`initialize`;for(let e of this.instances){this.current=e;let t;try{if(t=e.entry.create(e.context),Zr(t),typeof t!=`object`||!t||typeof t.sync!=`function`||typeof t.dispose!=`function`)throw TypeError(`Invalid device adapter`)}catch(t){throw this.wrap(t,`DEVICE_CALLBACK_FAILED`,`initialize`,e)}if(e.adapter=t,this.isFaulted)throw this.primary}this.current=void 0,this.phase=`idle`,Object.defineProperty(this,gi,{value:()=>this.observationReport(),enumerable:!1}),Object.defineProperty(this,_i,{value:()=>this.processReport(),enumerable:!1})}catch(e){let t=e instanceof Kr?e:this.wrap(e,`INVALID_CONFIGURATION`,`assembly`,this.current);this.primary=t;let n=this.cleanup();throw n.length?this.aggregate(t,n):t}}get isFaulted(){return this.status===`faulted`}observationReport(){return Object.freeze({plans:Object.freeze(this.plans.map(e=>Object.freeze({key:e.plan.key,path:Object.freeze([...e.plan.path]),receivers:e.members.length,slots:e.plan.slots.length,source:e.plan.source,comparison:e.plan.comparison}))),skipped:Object.freeze(this.skippedPlans.map(e=>Object.freeze({...e})))})}processReport(){let e=[],t=[];for(let n of this.instances)for(let r of n.processes){let i=`${n.id}/${r.declaration.kind===`on`?r.declaration.name:`start`}`;(r.resumable?e:t).push(i)}return Object.freeze({resumable:Object.freeze(e),generic:Object.freeze(t),bindings:Object.freeze(this.instances.map(e=>e.bindingReport()))})}validity(e){if(this.status===`disposed`||e&&!e.valid)throw this.error(`OBJECT_DISPOSED`,`Object is disposed`,e)}guard(e,t=!1){if(this.validity(e),e&&[`execute`,`translate`,`dispose`,`assembly`].includes(this.phase))throw this.error(`INVALID_CALL_STATE`,`Operation is not allowed in this phase`,e);if(!t&&this.status===`faulted`)throw this.error(`BOARD_FAULTED`,`Board is faulted`,e)}error(e,t,n,r,i){let a=r instanceof Xn?r:void 0;return new Kr(Object.freeze({code:e,message:t,phase:i??(this.phase===`idle`?`host`:this.phase),time:this.time,...a?.instanceId===void 0?n?{instanceId:n.id}:{}:{instanceId:a.instanceId},...a?.resource===void 0?{}:{resource:a.resource},...Qr(r),...r===void 0?{}:{cause:r},related:Object.freeze([])}))}wrap(e,t,n,r){if(e instanceof Kr&&![`DEVICE_CALLBACK_FAILED`,`JIT_FAILED`,`CLEANUP_FAILED`].includes(t))return e;let i=e instanceof Xn||e instanceof Yr||e instanceof Jr?e.code:void 0;return this.error(n!==`dispose`&&i?i:t,e instanceof Error?e.message:String(e),r,e,n)}fault(e){if(this.status===`ready`){this.status=`faulted`,this.primary=e,this.dispatchDepth++;try{this.errors.fire(e.diagnostic)}finally{this.dispatchDepth--}}}diagnostic(e,t,n){let r=this.error(e,t instanceof Error?t.message:String(t),n,t).diagnostic;this.dispatchDepth++;try{this.diagnostics.fire(r)}finally{this.dispatchDepth--}}fallback(e){try{console.error(e)}catch{}}report(e,t){this.status===`disposed`?this.fallback(t):e.valid?this.status===`faulted`?this.diagnostic(`REPORTED_ERROR`,t,e):this.fault(this.error(`REPORTED_ERROR`,t instanceof Error?t.message:String(t),e,t,`report`)):this.diagnostic(`STALE_REPORT`,t,e)}topicBridge(e){let t=()=>this.hostListeners;return Object.freeze({get hostListenerCount(){return t()},onDidReceive:((t,n,r)=>{this.guard(e);let i={...e?{owner:e}:{},call:e=>t.call(n,e)};this.listeners.add(i),e||this.hostListeners++;let a=!0,o={dispose:()=>{a&&(a=!1,this.listeners.delete(i)&&!e&&this.hostListeners--)}};return r?.push(o),e?.resources.push(o),o}),assertCanPublish:()=>this.guard(e),publish:(t,n)=>{if(this.guard(e),typeof t!=`string`)throw TypeError(`Topic must be a string`);this.dispatchDepth++;try{let e=Object.freeze({topic:t,payload:n});for(let t of[...this.listeners])if(!(t.owner&&this.status!==`ready`))try{let n=t.call(e);t.owner&&Zr(n)}catch(e){t.owner?this.fault(this.wrap(e,`DEVICE_CALLBACK_FAILED`,`topic`,t.owner)):this.diagnostic(`HOST_LISTENER_FAILED`,e)}}finally{this.dispatchDepth--}}})}enqueue(e){e.state===`idle`?(e.state=`queued`,this.models.push(e)):e.state!==`queued`&&(e.pending=!0)}queueJit(e){e.active&&!e.stopped&&!e.queued&&(e.queued=!0,this.readyJits.push(e))}invalidate(e){if(e.version++,e.subscribers.size!==0)for(let t of e.subscribers)this.observations.add(t.order)}electricalSlot(e){return this.electricalSlots.get(e)}publish(){if(!this.electricalDirty)return;let e=this.network.solveSlots(this.dirtyElectricalSlots);this.dirtyElectricalSlots.clear(),this.electricalDirty=!1;for(let t=0;t<e.length;t++)this.invalidate(this.sampleSlotsBySlot[e[t]])}bindObservation(e,t){let n=e.instance;e.previous=n.observe(e,t),e.readSource=n.observationReader(e,t),e.order=this.observations.register(e)}baseline(){this.publish();let e=[];for(let t of this.instances){let n=`${t.id}\\0`;for(let r of t.processes)r.source&&t.declarations.get(r.source[0])?.kind!==`notification`&&e.push({observation:r,path:r.source,key:n+r.source.join(`\\0`),instance:t});for(let r of t.reactions){let i=r.declaration.sourcePath;e.push({observation:r,path:i,key:n+i.join(`\\0`),instance:t})}}let t=/* @__PURE__ */ new Map;for(let n of e){if(t.has(n.key))continue;let e=Ir(n.instance,n.key,n.path);if(!e.ok){this.skippedPlans.push({key:n.key,reason:e.reason}),t.set(n.key,void 0);continue}let r={plan:e.plan,instance:n.instance,members:[],dependencies:/* @__PURE__ */ new Map,entry:{dependencies:/* @__PURE__ */ new Map,value:void 0},order:0,previous:void 0,bound:!1};t.set(n.key,r),this.plans.push(r)}for(let n of e){let e=t.get(n.key);e===void 0?this.bindObservation(n.observation,n.path):(e.bound?n.observation.order=this.observations.register(vi):(e.bound=!0,e.order=this.observations.register(e),n.observation.order=e.order,this.bindChain(e)),e.members.push(n.observation),n.observation.previous=e.previous)}}bindChain(e){let t=e.instance;for(let n of e.plan.slots)n.subscribers.size||t.observerRevision++,n.subscribers.add(e);let n=e.plan.evaluate();e.previous=e.plan.needsSnapshot?_(n):n,this.commitChain(e,n)}commitChain(e,t){let n=e.plan.path;if(n.length!==1)return;for(let t of e.plan.slots)e.dependencies.set(t,t.version);let r=e.entry;r.value!==t&&(r.value=t),r.dependencies=e.dependencies,e.instance.derived.get(n[0])!==r&&e.instance.derived.set(n[0],r)}collectChain(e){let t=e.plan.evaluate(),n=e.plan.needsSnapshot?_(t):t;if(this.commitChain(e,t),e.plan.equals(e.previous,n))return;let r=e.previous;e.previous=n;let i=e.members,a=i[0];if(i.length===1&&!this.changeObservations.length)a.previous=n,this.applyChange(a,r,n);else for(let e of i)e.previous=n,this.recordChange(e,r,n)}applyChange(e,t,n){if(e.declaration.kind===`reaction`){let r=e;r.frame={previous:t,current:n,captures:[]},this.reactionBatch.push(r)}else this.enqueue(e)}recordChange(e,t,n){let r=this.changeObservations,i=r.length,a=e.order;for(;i>0&&r[i-1].order>a;)i--;i===r.length?(r.push(e),this.changePrevious.push(t),this.changeCurrent.push(n)):(r.splice(i,0,e),this.changePrevious.splice(i,0,t),this.changeCurrent.splice(i,0,n))}boundary(){for(;;){if(this.publish(),!this.observations.size)return;let e=this.reactionBatch;e.length=0;let t=this.changeObservations;t.length=0,this.changePrevious.length=0,this.changeCurrent.length=0;try{let n=this.observations.take();for(let e=0;e<n.length;e++){let r=n[e];if(`plan`in r){this.collectChain(r);continue}let i=r.readSource();if(g(r.previous,i))continue;let a=r.previous;r.previous=i,t.length?this.recordChange(r,a,i):this.applyChange(r,a,i)}let r=t.length;if(r){for(let e=0;e<r;e++)this.applyChange(t[e],this.changePrevious[e],this.changeCurrent[e]);t.length=0,this.changePrevious.length=0,this.changeCurrent.length=0}if(!e.length)return;for(let t of e)t.declaration.captures.length&&(t.frame={...t.frame,captures:t.declaration.captures.map(e=>_(Gr(e.value,t.instance.host)))});for(let t of e)if(this.current=t.instance,t.execute??=Hr(t.declaration.body),!t.execute(t.instance.host,[],t.frame).next().done)throw TypeError(`Reaction cannot suspend`)}finally{for(let t of e)t.frame=void 0}}}drive(e,t){let n=e.resumable;if(n)this.driveResumable(e,n,t);else for(this.current=e.instance,e.state=`running`,e.execution??=Hr(e.declaration.body)(e.instance.host);;){let n=e.execution.next(t);if(n.done){this.boundary(),e.execution=void 0,e.state=`idle`,e.pending&&(e.pending=!1,this.enqueue(e));return}let r=n.value;if(r.kind===`receive`){let n=e.instance.channels.get(r.channel);if(n.incoming.length){t=n.incoming.shift().value;continue}e.state=`waiting`,n.receiver=e,this.boundary();return}if(r.kind!==`ticks`)throw TypeError(`Invalid process suspension`);let i=Vr(r.duration),a=Vr(this.time+i);e.state=`waiting`,this.boundary(),i===0?(e.state=`queued`,this.models.push(e)):(e.wake??=()=>{e.state=`queued`,this.models.push(e)},this.events.push(a,e.wake));return}}driveResumable(e,t,n){this.current=e.instance,e.state=`running`;let r=e.frame??=Wr(t),i=n;for(;;){if(r.value=i,!t.run(e.instance.host,void 0,void 0,r)){this.boundary(),e.state=`idle`,e.pending&&(e.pending=!1,this.enqueue(e));return}if(r.kind===2){let t=e.instance.channels.get(r.channel);if(t.incoming.length){i=t.incoming.shift().value;continue}e.state=`waiting`,t.receiver=e,this.boundary();return}let n=r.duration,a=Vr(this.time+n);e.state=`waiting`,this.boundary(),n===0?(e.state=`queued`,this.models.push(e)):(e.wake??=()=>{e.state=`queued`,this.models.push(e)},this.events.push(a,e.wake));return}}runUntil(e){if(this.validity(),this.phase!==`idle`||this.dispatchDepth)throw this.error(`INVALID_CALL_STATE`,`Board is busy`);if(this.status===`faulted`)throw this.error(`BOARD_FAULTED`,`Board is faulted`);let t=Vr(e);if(t<this.time)throw RangeError(`Cannot run backwards`);let n=this.time;this.phase=`execute`,this.executionEnd=t;try{if(!this.initialized){this.baseline(),this.initialized=!0;for(let e of this.instances)for(let t of e.processes)t.declaration.kind===`start`&&this.enqueue(t);for(let e of this.jits)this.queueJit(e)}for(let e of this.instances){for(let t of e.channels.values()){if(t.pending.length)for(let e of t.pending.drain())t.incoming.push(e);if(t.receiver&&t.incoming.length){let e=t.receiver;t.receiver=void 0;let n=t.incoming.shift().value;this.events.push(this.time,()=>{e.state=`queued`,e.resumeValue=n,this.models.push(e)})}}for(let t of e.notificationInputs)for(let n of e.processes)n.source?.[0]===t&&this.enqueue(n);e.notificationInputs.clear()}for(;;){for(;this.events.time===this.time;)this.events.pop()();if(this.models.length){let e=this.models.shift(),t=e.resumeValue;if(e.resumeValue=void 0,this.drive(e,t),this.isFaulted)throw this.primary;continue}let e=1/0;if(this.waitingJits.size)for(let n=0;n<this.jits.length;n++){let r=this.jits[n];if(r.active&&!r.stopped&&this.waitingJits.has(r)){if(r.instance.dependenciesCurrent(r.dependencies)){if(r.pollingWait&&r.pollingPeriod>0){let n=Br-(Br-r.pollingOrigin)%r.pollingPeriod;n<72e14&&n<t&&(n===this.time?(r.pollingWait=!1,delete r.dependencies,this.waitingJits.delete(r),this.queueJit(r)):e=Math.min(e,n))}}else if(r.pollingWait){r.pollingWait=!1,delete r.dependencies,this.waitingJits.delete(r);let e=r.pollingPeriod>0?(this.time-r.pollingOrigin)%r.pollingPeriod:0;e?this.events.push(Vr(this.time+(r.pollingPeriod-e)),()=>this.queueJit(r)):this.queueJit(r)}else if(r.predicate){let e=r.instance.evaluate(()=>r.instance.syncCall(r.predicate));r.dependencies=e.dependencies,e.value===!0&&(delete r.predicate,delete r.dependencies,this.waitingJits.delete(r),this.queueJit(r))}}}if(this.time<t&&this.readyJits.length){if(hi(this,this.readyJits.shift()),this.isFaulted)throw this.primary}else if(e<this.events.time&&e<=t)this.time=e;else if(this.events.time<=t)this.time=this.events.time;else{this.time=t;break}}let e=this.instances.map(e=>e.captureBatch(n,t));this.phase=`sync`;for(let t=0;t<this.instances.length;t++){let n=this.instances[t];this.current=n;try{Zr(n.adapter.sync(e[t]))}catch(e){throw this.wrap(e,`DEVICE_CALLBACK_FAILED`,`sync`,n)}if(this.isFaulted)throw this.primary}}catch(e){let t=this.wrap(e,`MODEL_EXECUTION_FAILED`,this.phase===`sync`?`sync`:`execute`,this.current);throw this.fault(t),t}finally{this.current=void 0,this.phase=`idle`}}dispose(){if(this.status===`disposed`)return;if(this.phase!==`idle`||this.dispatchDepth)throw this.error(`INVALID_CALL_STATE`,`Board is busy`);let e=this.cleanup();if(e.length)throw this.primary?this.aggregate(this.primary,e):this.aggregate(e[0],e.slice(1))}aggregate(e,t){return new Kr(Object.freeze({...e.diagnostic,related:Object.freeze([...e.related,...t.map(e=>e.diagnostic)])}))}cleanup(){this.phase=`dispose`;for(let e of this.instances)e.valid=!1;let e=[];for(let t of[...this.instances].reverse()){if(t.adapter)try{Zr(t.adapter.dispose())}catch(n){e.push(this.wrap(n,`CLEANUP_FAILED`,`dispose`,t))}for(let n of[...t.resources].reverse())try{n.dispose()}catch(n){e.push(this.wrap(n,`CLEANUP_FAILED`,`dispose`,t))}t.resources.length=0}return this.events.clear(),this.models.clear(),this.readyJits.clear(),this.observations.clear(),this.reactionBatch.length=0,this.plans.length=0,this.skippedPlans.length=0,this.changeObservations.length=0,this.changePrevious.length=0,this.changeCurrent.length=0,this.sampleSlots.clear(),this.listeners.clear(),this.hostListeners=0,this.errors.dispose(),this.diagnostics.dispose(),this.status=`disposed`,this.phase=`idle`,e}};function Si(e,t,n){let r=yi.get(e);if(!r)throw $r(`INVALID_CONFIGURATION`,/* @__PURE__ */ TypeError(`Unknown device library`),`assembly`);if(arguments.length>=3&&n===void 0)throw $r(`INVALID_CONFIGURATION`,/* @__PURE__ */ TypeError(`Explicit undefined options`),`assembly`);return new xi(r,t,n??{})}var X=class extends Error{name=`SimulationRuntimeError`;code;deviceId;constructor(e,t,n={}){super(t,n.cause===void 0?void 0:{cause:n.cause}),this.code=e,this.deviceId=n.deviceId}};function Ci(e){return e instanceof Error&&e.message.length>0?e.message:String(e)}let wi=[`level`,`message`];function Ti(e){return wi.includes(e)?e:void 0}let Ei={boolean:`level`,number:`level`,vec2d:`level`,vec3d:`level`,string:`message`,bytes:`message`,\"bytes<rgb565>\":`message`,\"bytes<segments>\":`message`};function Di(e){return Ei[e]}function Oi(e,t){return Ti(e)??Di(t)}let ki=[`file`,`inline`,`store`];function Ai(e){return typeof e==`string`&&ki.includes(e)}function ji(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return typeof t.src==`string`&&Ai(t.mode)}function Mi(e){if(e.startsWith(`/`))return`must be relative to the project root, not absolute`;if(/^[A-Za-z]:/.test(e))return`must not carry a drive letter`;if(/^[A-Za-z][A-Za-z0-9+.-]*:/.test(e))return`must not be a URL`;if(e.includes(`\\\\`))return`must use POSIX separators`;let t=e.split(`/`).find(e=>e===`..`||e.startsWith(`~`));if(t!==void 0)return`must stay inside the project root (segment \"${t}\")`}function Ni(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)?void 0:`must be base64 text`}function Pi(e,t){return e===`inline`?Ni(t):e===`file`?Mi(t):void 0}var Fi=class extends Error{diagnostics;constructor(e){super(Ii(e)),this.name=`SchematicError`,this.diagnostics=e}get code(){return this.diagnostics[0]?.code}};function Ii(e){let t=e.filter(e=>e.severity===`error`),[n,...r]=t.length>0?t:e;if(n===void 0)return`Schematic validation failed.`;let i=n.pointer===void 0||n.pointer===``?``:` at ${n.pointer}`,a=r.length===0?``:` (and ${r.length} more)`;return`${n.code}${i}: ${n.message}${a}`}function Li(e){if(e.some(e=>e.severity===`error`))throw new Fi(e)}function Ri(e,t){if(typeof e!=`string`)return{ok:!0,value:e};try{return{ok:!0,value:JSON.parse(e)}}catch(e){let n=e instanceof Error?e.message:String(e);return t.push({severity:`error`,code:`json/invalid`,message:`Invalid JSON: ${n}`}),{ok:!1,value:void 0}}}let zi=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Bi(e){return zi.test(e)}let Vi={\"builtin:label\":`label`,\"builtin:power\":`power`,\"builtin:ground\":`ground`},Hi=/^@[A-Za-z0-9][A-Za-z0-9._+-]*$/,Ui=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,Wi=/^(?:[A-Za-z0-9][A-Za-z0-9._+-]*|-[A-Za-z0-9-]*)$/;function Gi(e){let t=e.indexOf(`:`);if(t<=0||t===e.length-1||e.indexOf(`:`,t+1)!==-1)return;let n=e.slice(0,t),r=e.slice(t+1);if(Ki(n)&&Wi.test(r))return{raw:e,packageId:n,deviceId:r}}function Ki(e){if(e.startsWith(`@`)){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;return n!==void 0&&r!==void 0&&Hi.test(n)&&Ui.test(r)}return Ui.test(e)}function qi(e){return e===`builtin:text`}function Ji(e){return Vi[e]}function Yi(e){switch(Ji(e)){case`label`:return`net-label`;case`power`:return`power`;case`ground`:return`ground`;default:return qi(e)?`text`:`component`}}function Xi(e){return e===`component`}function Zi(e){return e===`net-label`||e===`power`||e===`ground`}function Qi(e){return Xi(Yi(e.device))?e.designator??e.id:void 0}function $i(e){switch(Yi(e.device)){case`power`:return e.net??`VCC`;case`ground`:return e.net??`GND`;case`net-label`:return e.net;default:return}}function ea(e){return e.length===0?``:`/${e.map(e=>e.replace(/~/g,`~0`).replace(/\\//g,`~1`)).join(`/`)}`}function Z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ta(e){return e.some(e=>e.severity===`error`)}function Q(e,t,n,r,i){let a={severity:`error`,code:t,message:n,pointer:ea(r)};e.push(i===void 0?a:{...a,entity:i})}function na(e,t,n,r){for(let i of Object.keys(e))t.includes(i)||Q(r,`schema/unknown-field`,`Unknown field \"${i}\".`,[...n,i])}function ra(e,t,n,r,i={}){let a=[...n,t];if(!Object.prototype.hasOwnProperty.call(e,t)){Q(r,`schema/missing-field`,`Missing required field \"${t}\".`,a);return}let o=e[t];if(typeof o!=`string`)Q(r,`schema/invalid-type`,`Field \"${t}\" must be a string.`,a);else if(i.nonEmpty===!0&&o.length===0)Q(r,`schema/invalid-value`,`Field \"${t}\" must not be empty.`,a);else return o}function ia(e,t,n,r){let i=[...n,t];if(!Object.prototype.hasOwnProperty.call(e,t)){Q(r,`schema/missing-field`,`Missing required field \"${t}\".`,i);return}let a=e[t];if(typeof a!=`number`)Q(r,`schema/invalid-type`,`Field \"${t}\" must be a number.`,i);else if(!Number.isFinite(a))Q(r,`schema/invalid-value`,`Field \"${t}\" must be a finite number.`,i);else return a}function aa(e,t,n,r){let i=ia(e,t,n,r);if(i!==void 0){if(!Number.isInteger(i))Q(r,`schema/invalid-value`,`Field \"${t}\" must be an integer.`,[...n,t]);else return i}}function oa(e,t,n,r){let i=[...n,t];if(!Object.prototype.hasOwnProperty.call(e,t)){Q(r,`schema/missing-field`,`Missing required field \"${t}\".`,i);return}let a=e[t];if(!Array.isArray(a))Q(r,`schema/invalid-type`,`Field \"${t}\" must be an array.`,i);else return a}function sa(e,t,n,r){let i=[...n,t];if(!Object.prototype.hasOwnProperty.call(e,t)){Q(r,`schema/missing-field`,`Missing required field \"${t}\".`,i);return}let a=e[t];if(!Z(a))Q(r,`schema/invalid-type`,`Field \"${t}\" must be an object.`,i);else return a}function ca(e,t,n){if(!Z(e)){Q(n,`schema/invalid-type`,`Point must be an object.`,t);return}na(e,[`x`,`y`],t,n);let r=ia(e,`x`,t,n),i=ia(e,`y`,t,n);if(r!==void 0&&i!==void 0)return{x:r,y:i}}function la(e,t,n){if(!Z(e)){Q(n,`schema/invalid-type`,`Resource reference must be an object.`,t);return}na(e,[`src`,`mode`],t,n);let r=ra(e,`src`,t,n,{nonEmpty:!0}),i;if(Object.prototype.hasOwnProperty.call(e,`mode`)?Ai(e.mode)?i=e.mode:Q(n,`schema/invalid-value`,`Field \"mode\" must be \"file\", \"inline\" or \"store\".`,[...t,`mode`]):Q(n,`schema/missing-field`,`Missing required field \"mode\".`,[...t,`mode`]),r===void 0||i===void 0)return;let a=Pi(i,r);if(a!==void 0)Q(n,`schema/invalid-value`,`Field \"src\" ${a}.`,[...t,`src`]);else return{src:r,mode:i}}function ua(e,t,n){if(!Z(e)){Q(n,`schema/invalid-type`,`Field \"properties\" must be an object.`,t);return}let r=Object.create(null),i=!1;for(let[a,o]of Object.entries(e)){if(a.length===0){Q(n,`schema/invalid-value`,`Property keys must not be empty.`,t),i=!0;continue}let e=[...t,a];if(typeof o==`string`||typeof o==`boolean`)r[a]=o;else if(o===null)r[a]=null;else if(typeof o==`number`){if(!Number.isFinite(o)){Q(n,`schema/invalid-value`,`Property \"${a}\" must be a finite number.`,e),i=!0;continue}r[a]=o}else if(typeof o==`object`&&!Array.isArray(o)){let t=la(o,e,n);if(t===void 0){i=!0;continue}r[a]=t}else Q(n,`schema/invalid-value`,`Property \"${a}\" must be a string, finite number, boolean, resource reference or null.`,e),i=!0}return i?void 0:r}function da(e,t,n){let r=/* @__PURE__ */ new Set;for(let i of e)r.has(i.id)?Q(n,`id/duplicate`,`Duplicate ${t} id \"${i.id}\".`,i.path,{kind:t,id:i.id}):r.add(i.id)}function fa(e){let t=[],n=Ri(e,t);if(!n.ok)throw new Fi(t);let r=pa(n.value,t);if(r===void 0||ta(t))throw new Fi(t);return r}function pa(e,t){if(!Z(e)){Q(t,`json/not-object`,`Schematic must be a JSON object.`,[]);return}na(e,[`version`,`sheet`],[],t);let n=ma(e,t),r=ha(sa(e,`sheet`,[],t),t);if(n!==void 0&&r!==void 0)return{version:n,sheet:r}}function ma(e,t){let n=aa(e,`version`,[],t);if(n!==void 0){if(n!==1)Q(t,`schema/unsupported-version`,`Unsupported version ${n}; expected 1.`,[`version`]);else return 1}}function ha(e,t){if(e===void 0)return;na(e,[`symbols`,`wires`,`junctions`],[`sheet`],t);let n=oa(e,`symbols`,[`sheet`],t)??[],r=oa(e,`wires`,[`sheet`],t)??[],i=oa(e,`junctions`,[`sheet`],t)??[],a=[],o=[];n.forEach((e,n)=>{let r=[`sheet`,`symbols`,String(n)],i=_a(e,r,t);i!==void 0&&(a.push(i),o.push({id:i.id,path:[...r,`id`]}))});let s=[],c=[];r.forEach((e,n)=>{let r=[`sheet`,`wires`,String(n)],i=ya(e,r,t);i!==void 0&&(s.push(i),c.push({id:i.id,path:[...r,`id`]}))});let l=new Set(s.map(e=>e.id)),u=[],d=[];return i.forEach((e,n)=>{let r=[`sheet`,`junctions`,String(n)],i=ba(e,r,t);if(i===void 0)return;let a=/* @__PURE__ */ new Set;i.wires.forEach((e,n)=>{let o=[...r,`wires`,String(n)];a.has(e)?Q(t,`junction/duplicate-wire`,`Junction \"${i.id}\" references wire \"${e}\" more than once.`,o,{kind:`junction`,id:i.id}):a.add(e),l.has(e)||Q(t,`junction/unknown-wire`,`Junction \"${i.id}\" references unknown wire \"${e}\".`,o,{kind:`junction`,id:i.id})}),u.push(i),d.push({id:i.id,path:[...r,`id`]})}),da(o,`symbol`,t),ga(a,t),da(c,`wire`,t),da(d,`junction`,t),{symbols:a,wires:s,junctions:u}}function ga(e,t){let n=/* @__PURE__ */ new Set;e.forEach((e,r)=>{let i=Qi(e);i!==void 0&&(n.has(i)?Q(t,`symbol/designator-duplicate`,`Reference designator ${JSON.stringify(i)} is used more than once.`,[`sheet`,`symbols`,String(r),`designator`],{kind:`symbol`,id:e.id}):n.add(i))})}function _a(e,t,n){if(!Z(e)){Q(n,`schema/invalid-type`,`Symbol must be an object.`,t);return}na(e,[`id`,`device`,`x`,`y`,`rotation`,`properties`,`designator`,`net`,`reference`],t,n);let r=xa(e,t,n),i=ra(e,`device`,t,n,{nonEmpty:!0}),a=ia(e,`x`,t,n),o=ia(e,`y`,t,n),s=ia(e,`rotation`,t,n),c=e.properties===void 0?void 0:ua(e.properties,[...t,`properties`],n),l=e.reference===void 0?void 0:ca(e.reference,[...t,`reference`],n),u=va(e,`designator`,i,t,n,Xi),d=va(e,`net`,i,t,n,Zi);if(i!==void 0){let r=Yi(i);Zi(r)&&d===void 0&&e.net===void 0&&Q(n,`symbol/missing-net`,`Symbols of role \"${r}\" must name the net they attach to.`,[...t,`net`]),!Xi(r)&&e.reference!==void 0&&Q(n,`symbol/unsupported-field`,`Symbols of role \"${r}\" carry no reference designator.`,[...t,`reference`])}if(!(r===void 0||i===void 0||a===void 0||o===void 0||s===void 0||e.reference!==void 0&&l===void 0))return{id:r,device:i,x:a,y:o,rotation:s,...c===void 0?{}:{properties:c},...u===void 0?{}:{designator:u},...d===void 0?{}:{net:d},...l===void 0?{}:{reference:l}}}function va(e,t,n,r,i,a){if(e[t]===void 0||n===void 0)return;let o=Yi(n);if(!a(o))Q(i,`symbol/unsupported-field`,`Symbols of role \"${o}\" must not declare \"${t}\".`,[...r,t]);else return ra(e,t,r,i,{nonEmpty:!0})}function ya(e,t,n){if(!Z(e)){Q(n,`schema/invalid-type`,`Wire must be an object.`,t);return}na(e,[`id`,`points`],t,n);let r=xa(e,t,n),i=oa(e,`points`,t,n),a=[];if(i!==void 0&&(i.length<2&&Q(n,`wire/invalid-points`,`Wire must contain at least two points.`,[...t,`points`]),i.forEach((e,r)=>{let i=ca(e,[...t,`points`,String(r)],n);i!==void 0&&a.push(i)})),r!==void 0&&i!==void 0){for(let e=1;e<a.length;e+=1){let r=a[e-1],i=a[e];if(r!==void 0&&i!==void 0&&r.x!==i.x&&r.y!==i.y){Q(n,`wire/not-orthogonal`,`Wire segments must be horizontal or vertical.`,[...t,`points`,String(e)]);return}}return{id:r,points:a}}}function ba(e,t,n){if(!Z(e)){Q(n,`schema/invalid-type`,`Junction must be an object.`,t);return}na(e,[`id`,`x`,`y`,`wires`],t,n);let r=xa(e,t,n),i=ia(e,`x`,t,n),a=ia(e,`y`,t,n),o=oa(e,`wires`,t,n),s=[];if(o!==void 0&&(o.length<2&&Q(n,`schema/invalid-value`,`Junction must reference at least two wires.`,[...t,`wires`]),o.forEach((e,r)=>{let i=[...t,`wires`,String(r)];typeof e==`string`?e.length===0?Q(n,`schema/invalid-value`,`Junction wire reference must not be empty.`,i):s.push(e):Q(n,`schema/invalid-type`,`Junction wire reference must be a string.`,i)})),r!==void 0&&i!==void 0&&a!==void 0&&o!==void 0)return{id:r,x:i,y:a,wires:s}}function xa(e,t,n){let r=ra(e,`id`,t,n,{nonEmpty:!0});if(r!==void 0){if(!Bi(r))Q(n,`schema/invalid-value`,`Field \"id\" must be a UUID v4.`,[...t,`id`]);else return r}}function Sa(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}function Ca(e,t,n=0){return Sa(e,t)<=n}function wa(e,t,n,r=0){let i=n.x-t.x,a=n.y-t.y,o=Math.hypot(i,a);if(o===0)return Ca(e,t,r);let s=(e.x-t.x)*a-(e.y-t.y)*i;if(Math.abs(s)/o>r)return!1;let c=((e.x-t.x)*i+(e.y-t.y)*a)/(o*o),l=r/o;return c<-l||c>1+l?!1:Ta(e,t,n)<=r}function Ta(e,t,n){let r=n.x-t.x,i=n.y-t.y,a=r*r+i*i;if(a===0)return Sa(e,t);let o=((e.x-t.x)*r+(e.y-t.y)*i)/a,s=o<0?0:o>1?1:o;return Sa(e,{x:t.x+s*r,y:t.y+s*i})}function Ea(e,t,n=0){if(e.length===1){let[r]=e;return r!==void 0&&Ca(r,t,n)}for(let r=1;r<e.length;r+=1){let i=e[r-1],a=e[r];if(i!==void 0&&a!==void 0&&wa(t,i,a,n))return!0}return!1}function Da(e){let[t,...n]=e;if(t===void 0)return;let r=t.x,i=t.y,a=t.x,o=t.y;for(let e of n)r=Math.min(r,e.x),i=Math.min(i,e.y),a=Math.max(a,e.x),o=Math.max(o,e.y);return{x:r,y:i,width:a-r,height:o-i}}function Oa(e,t){if(e===void 0)return t;if(t===void 0)return e;let n=Math.min(e.x,t.x),r=Math.min(e.y,t.y),i=Math.max(e.x+e.width,t.x+t.width),a=Math.max(e.y+e.height,t.y+t.height);return{x:n,y:r,width:i-n,height:a-r}}function ka(e,t){let n=t*Math.PI/180,r=Math.cos(n),i=Math.sin(n);return{x:e.x*r-e.y*i,y:e.x*i+e.y*r}}function Aa(e,t){let n=ka(t,e.rotation);return{x:e.x+n.x,y:e.y+n.y}}function ja(e,t,n){if(t!==void 0)return Da([{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x,y:t.y+t.height},{x:t.x+t.width,y:t.y+t.height}].map(t=>Aa(e,t)));let r=Object.values(n).map(t=>Aa(e,t));return r.length>0?Da(r):{x:e.x,y:e.y,width:0,height:0}}function Ma(e,t={}){let n=[],r=t.tolerance??0,{devices:i}=t,{symbols:a,wires:o,junctions:s}=e.sheet,c=[],l;for(let e of a){l=Oa(l,{x:e.x,y:e.y,width:0,height:0});let t=Ji(e.device);if(t!==void 0){let n=$i(e);n!==void 0&&c.push({kind:t,symbolId:e.id,point:{x:e.x,y:e.y},name:n});continue}let r=Gi(e.device);if(r===void 0){i!==void 0&&n.push({severity:`error`,code:`device/invalid-reference`,message:`Symbol \"${e.id}\" has an invalid device reference ${JSON.stringify(e.device)}.`,entity:{kind:`symbol`,id:e.id}});continue}if(i===void 0)continue;let a=i.getDeviceSymbol(r);if(i.getDeviceName(r)===void 0)n.push({severity:`error`,code:`device/unresolved`,message:`Symbol \"${e.id}\" references unresolved device ${JSON.stringify(e.device)}.`,entity:{kind:`symbol`,id:e.id}});else if(a!==void 0){l=Oa(l,ja(e,a.bounds,a.pins));for(let[t,n]of Object.entries(a.pins)){let r=Aa(e,n);c.push({kind:`pin`,symbolId:e.id,pinId:t,point:r}),l=Oa(l,{x:r.x,y:r.y,width:0,height:0})}}}for(let e of o)l=Oa(l,Da(e.points));let u=/* @__PURE__ */ new Map;o.forEach((e,t)=>u.set(e.id,t));let d=o.length,f=Array(d+c.length);for(let e=0;e<f.length;e+=1)f[e]=e;let p=e=>{let t=e;for(;f[t]!==t;){let e=f[t];f[t]=f[e],t=e}return t},m=(e,t)=>{let n=p(e),r=p(t);n!==r&&(f[r]=n)};for(let e of s){let[t,...n]=e.wires.map(e=>u.get(e)).filter(e=>e!==void 0);if(t!==void 0)for(let e of n)m(t,e)}let h=/* @__PURE__ */ new Map;c.forEach((e,t)=>{o.forEach((n,i)=>{if(!Ea(n.points,e.point,r))return;m(i,d+t);let a=h.get(i);a===void 0?h.set(i,[t]):a.push(t)})});let g=/* @__PURE__ */ new Map,_=e=>{let t=g.get(e);if(t!==void 0)return t;let n={wires:[],connections:[]};return g.set(e,n),n};o.forEach((e,t)=>{_(p(t)).wires.push(t)}),c.forEach((e,t)=>{_(p(d+t)).connections.push(t)});let v=/* @__PURE__ */ new Map,y=[];for(let e of Na(g,c,n)){let t=e.wires.length>0||e.connections.length>=2;if(e.connections.length===0||!t)continue;let n=e.name,r=e.connections.map(e=>c[e]).map(e=>{if(e!==void 0)return e.kind===`pin`?{kind:`pin`,symbolId:e.symbolId,pinId:e.pinId}:{kind:e.kind,symbolId:e.symbolId}}).filter(e=>e!==void 0).sort(Fa),i={name:n,wireIds:e.wires.map(e=>o[e]?.id).filter(e=>e!==void 0).sort(),members:r};y.push(i);for(let t of e.connections)v.set(t,i)}let b=[];c.forEach((e,t)=>{if(e.kind!==`pin`)return;let n=v.get(t);b.push({symbolId:e.symbolId,pinId:e.pinId,position:e.point,open:n===void 0,netName:n?.name??null})}),b.sort((e,t)=>e.symbolId.localeCompare(t.symbolId)||e.pinId.localeCompare(t.pinId));let x=[];return o.forEach((e,t)=>{let n=[{end:`start`,point:e.points[0]},{end:`end`,point:e.points[e.points.length-1]}];for(let{end:i,point:a}of n){if(a===void 0)continue;let n=(h.get(t)??[]).some(e=>{let t=c[e];return t!==void 0&&Ca(t.point,a,r)}),o=s.some(t=>t.wires.includes(e.id)&&Ca({x:t.x,y:t.y},a,r));!n&&!o&&x.push({wireId:e.id,end:i,point:a})}}),x.sort((e,t)=>e.wireId.localeCompare(t.wireId)||e.end.localeCompare(t.end)),Li(n),{nets:y.sort((e,t)=>Ia(e.name,t.name)||Fa(e.members[0],t.members[0])),pins:b,danglingWireEnds:x,bounds:l}}function Na(e,t,n){let r=/* @__PURE__ */ new Map,i=[];for(let a of e.values()){let e=a.connections.map(e=>t[e]).filter(e=>e!==void 0&&e.kind!==`pin`).map(e=>e.name).sort();e.length>1&&n.push({severity:`error`,code:`net/naming-conflict`,message:`Net has conflicting names: ${e.map(e=>JSON.stringify(e)).join(`, `)}.`});let o=e.length===1?e[0]:null;if(o===null||a.wires.length===0&&a.connections.length<2){i.push({wires:a.wires,connections:a.connections,name:o});continue}let s=r.get(o);if(s===void 0){let e={wires:[...a.wires],connections:[...a.connections]};r.set(o,e),i.push({...e,name:o})}else s.wires.push(...a.wires),s.connections.push(...a.connections)}return i}let Pa=[`label`,`power`,`ground`,`pin`];function Fa(e,t){if(e===void 0||t===void 0)return e===void 0?t===void 0?0:1:-1;if(e.kind!==t.kind)return Pa.indexOf(e.kind)-Pa.indexOf(t.kind);let n=e.symbolId.localeCompare(t.symbolId);if(n!==0)return n;let r=e.kind===`pin`?e.pinId:``,i=t.kind===`pin`?t.pinId:``;return r.localeCompare(i)}function Ia(e,t){return e===null||t===null?e===null?t===null?0:1:-1:e.localeCompare(t)}function La(e,t={}){let n=t.pinPitch??10,r=t.stubLength??10,i=t.minWidth??60,a=t.minHeight??40,o=t.horizontalPadding??10,s=t.verticalPadding??10,c=t.characterWidth??5.5,l=t.labelCharacterWidth??4.5,u=t.nameGap??12,d=t.labelInset??10,f={left:[],right:[],top:[],bottom:[]};for(let[t,n]of Object.entries(e.pins))f[n.side??`left`].push(t);let p=Math.max(f.left.length,f.right.length),m=Math.max(f.top.length,f.bottom.length),h=Math.max(a,s*2+Math.max(p-1,0)*n+n,2*(1*c+n/2+d+za(f,l))),g=Math.max(i,o*2+Math.max(m-1,0)*n+n),_=(Ra(f.left)+Ra(f.right))*l+e.name.length*c+o*2+u*2,v=Math.ceil(Math.max(g,_)/n)*n,y=Math.ceil(h/n)*n,b={x:-v/2,y:-y/2,width:v,height:y},x=Object.create(null),ee=(e,t)=>{let i=-((e.length-1)*n)/2;e.forEach((e,a)=>{let o=i+a*n,s=t===`left`?b.x-r:b.x+b.width+r;x[e]={x:s,y:o,side:t}})};ee(f.left,`left`),ee(f.right,`right`);let te=(e,t)=>{let i=-((e.length-1)*n)/2;e.forEach((e,a)=>{let o=i+a*n,s=t===`top`?b.y-r:b.y+b.height+r;x[e]={x:o,y:s,side:t}})};return te(f.top,`top`),te(f.bottom,`bottom`),{name:e.name,pins:x,bounds:b}}function Ra(e){return e.reduce((e,t)=>Math.max(e,t.length),0)}function za(e,t){return Math.max(Ra(e.top),Ra(e.bottom))*t/2}let $=(e,t,n)=>{t.push({severity:`error`,code:`device/invalid-description`,pointer:e,message:n})},Ba=(e,t,n)=>{typeof e!=`string`&&$(t,n,`Expected a string.`)},Va=(e,t,n)=>{(typeof e!=`string`||e.length===0)&&$(t,n,`Expected a nonempty string.`)},Ha=(e,t,n)=>{(typeof e!=`number`||!Number.isFinite(e))&&$(t,n,`Expected a finite number.`)},Ua=(e,t,n)=>{Ha(e,t,n),typeof e==`number`&&e<=0&&$(t,n,`Expected a positive number.`)},Wa=(e,t,n)=>{typeof e!=`boolean`&&$(t,n,`Expected a boolean.`)},Ga=(...e)=>(t,n,r)=>{e.includes(t)||$(n,r,`Expected one of ${e.join(`, `)}.`)},Ka=e=>e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`),qa=(e,t=[])=>(n,r,i)=>{if(!Z(n))$(r,i,`Expected an object.`);else{for(let e of t)Object.hasOwn(n,e)||$(`${r}/${Ka(e)}`,i,`Required field is missing.`);for(let[t,a]of Object.entries(n)){let n=Object.hasOwn(e,t)?e[t]:void 0;n===void 0?$(`${r}/${Ka(t)}`,i,`Unknown field.`):n(a,`${r}/${Ka(t)}`,i)}}},Ja=e=>(t,n,r)=>{if(!Z(t))$(n,r,`Expected a map.`);else for(let[i,a]of Object.entries(t))e(a,`${n}/${Ka(i)}`,r)},Ya=(e,t,n)=>{!Array.isArray(e)||e.length!==2?$(t,n,`Expected two coordinates.`):e.forEach((e,r)=>Ha(e,`${t}/${r}`,n))},Xa=(e,t,n)=>{Array.isArray(e)?(e.forEach((e,r)=>Va(e,`${t}/${r}`,n)),new Set(e).size!==e.length&&$(t,n,`Values must be unique.`)):$(t,n,`Expected an array.`)},Za=Ga(`left`,`center`,`right`),Qa=qa({visible:Wa,position:Ya,align:Za},[`visible`]),$a=(e,t,n)=>{let r={kind:Ga(`number`,`text`,`textarea`,`checkbox`,`file`,`select`)};Z(e)&&e.kind===`number`&&Object.assign(r,{min:Ha,max:Ha,step:Ua}),Z(e)&&e.kind===`file`&&(r.extensions=(e,t,n)=>{Xa(e,t,n),Array.isArray(e)&&e.forEach((e,r)=>{typeof e==`string`&&!/^\\.[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*$/.test(e)&&$(`${t}/${r}`,n,`Expected a dotted filename extension.`)})},r.maxSize=(e,t,n)=>{Ua(e,t,n),typeof e==`number`&&!Number.isInteger(e)&&$(t,n,`Expected an integer byte count.`)}),Z(e)&&e.kind===`select`&&(r.labels=Ja(Ba)),qa(r,[`kind`])(e,t,n)},eo=(e,t,n)=>{qa({type:Ga(`number`,`boolean`,`string`,`enum`,`bytes`),required:Wa,nullable:Wa,default:()=>{},enumName:Va,values:Xa,title:Ba,description:Ba,unit:Ba,group:Ba,order:(e,t,n)=>{(typeof e!=`number`||!Number.isInteger(e)||e<0)&&$(t,n,`Expected a nonnegative integer.`)},editor:$a},[`type`,`required`])(e,t,n),Z(e)&&(e.required===!0&&Object.hasOwn(e,`default`)&&$(`${t}/default`,n,`Required properties cannot declare defaults.`),e.type===`enum`?((!Object.hasOwn(e,`enumName`)||!Object.hasOwn(e,`values`))&&$(t,n,`Enum properties require enumName and values.`),Array.isArray(e.values)&&e.values.length===0&&$(`${t}/values`,n,`Enum values cannot be empty.`)):(Object.hasOwn(e,`enumName`)||Object.hasOwn(e,`values`))&&$(t,n,`Only enum properties declare enumName and values.`))},to=(e,t,n)=>{let r={type:Ga(`line`,`polyline`,`rect`,`circle`,`arc`,`text`),fill:Ga(`none`,`foreground`,`background`),strokeWidth:Ua},i={line:{fields:{from:Ya,to:Ya},required:[`from`,`to`]},polyline:{fields:{points:(e,t,n)=>{!Array.isArray(e)||e.length<2?$(t,n,`Expected at least two points.`):e.forEach((e,r)=>Ya(e,`${t}/${r}`,n))},closed:Wa},required:[`points`]},rect:{fields:{x:Ha,y:Ha,width:Ua,height:Ua},required:[`x`,`y`,`width`,`height`]},circle:{fields:{center:Ya,radius:Ua},required:[`center`,`radius`]},arc:{fields:{center:Ya,radius:Ua,startAngle:Ha,sweepAngle:(e,t,n)=>{Ha(e,t,n),typeof e==`number`&&(e===0||e<-360||e>360)&&$(t,n,`Sweep must be nonzero and within [-360, 360].`)}},required:[`center`,`radius`,`startAngle`,`sweepAngle`]},text:{fields:{position:Ya,text:Ba,align:Za,fontSize:Ua},required:[`position`,`text`]}},a=Z(e)&&typeof e.type==`string`&&Object.hasOwn(i,e.type)?i[e.type]:void 0;qa({...r,...a?.fields},[`type`,...a?.required??[]])(e,t,n)},no=(e,t,n)=>{Array.isArray(e)?e.forEach((e,r)=>to(e,`${t}/${r}`,n)):$(t,n,`Expected graphics array.`)},ro=qa({designator:qa({position:Ya,align:Za},[`position`])}),io=qa({kind:Ga(`device`),id:(e,t,n)=>{(typeof e!=`string`||!/^[A-Za-z0-9-]+$/.test(e))&&$(t,n,`Invalid device id.`)},version:Va,displayName:Va,description:Va,license:Va,tags:Xa,templates:Xa,recommends:qa({widgets:Xa}),designatorPrefix:(e,t,n)=>{(typeof e!=`string`||!/^\\S+$/.test(e))&&$(t,n,`Expected a nonempty prefix without whitespace.`)},properties:Ja(eo),pins:Ja(qa({label:Ba,description:Ba,group:Ba})),ports:Ja(qa({direction:Ga(`input`,`output`),type:Ga(`boolean`,`number`,`string`,`vec2d`,`vec3d`,`bytes`,`bytes<rgb565>`,`bytes<segments>`),title:Ba,description:Ba,delivery:Ga(`level`,`message`)},[`direction`,`type`])),symbol:qa({bounds:qa({x:Ha,y:Ha,width:Ua,height:Ua},[`x`,`y`,`width`,`height`]),graphics:no,pins:Ja(qa({position:Ya,direction:Ga(`left`,`right`,`up`,`down`),label:Qa},[`position`,`direction`])),annotations:ro},[`bounds`,`graphics`,`pins`])},[`kind`,`id`,`version`,`displayName`]);function ao(e){let t=[],n=Ri(e,t);if(n.ok&&io(n.value,``,t),t.length>0)throw new Fi(t);return n.value}function oo(e){let t=e.symbol,n=t===void 0?La({name:e.displayName,pins:Object.fromEntries(Object.keys(e.pins??{}).map(e=>[e,{}]))}):void 0,r=Object.create(null);for(let[i,a]of Object.entries(t?.pins??n.pins)){let n=e.pins?.[i]?.label;if(t!==void 0){let e=t.pins[i];r[i]={x:e.position[0],y:e.position[1],side:e.direction===`up`?`top`:e.direction===`down`?`bottom`:e.direction,...e.label===void 0?{}:{label:e.label},...n===void 0?{}:{displayName:n}}}else r[i]={...a,...n===void 0?{}:{displayName:n}}}return t===void 0?{...n,pins:r}:{name:e.displayName,bounds:t.bounds,graphics:t.graphics,pins:r,...t.annotations===void 0?{}:{annotations:t.annotations}}}async function so(e,t,n){if(!po(e)||!Array.isArray(e.devices))throw new X(`invalid-input`,`Expected schematic and devices`);let r=fa(e.schematic),i=uo(e.assets),a=lo(e.voltageReferences),o=/* @__PURE__ */ new Map;for(let t of e.devices){if(!po(t)||typeof t.id!=`string`||Gi(t.id)===void 0||o.has(t.id)||typeof t.code!=`string`||t.code.trim().length===0)throw new X(`invalid-input`,`Expected unique device ids and self-contained ESM code`);let e;try{e=structuredClone(ao(t.definition))}catch(e){throw new X(`invalid-device`,`Invalid metadata for \"${t.id}\": ${Ci(e)}`,{cause:e})}if(e.id!==Gi(t.id).deviceId)throw new X(`invalid-device`,`Metadata id does not match \"${t.id}\"`,{deviceId:t.id});o.set(t.id,{definition:e,code:t.code})}let s=/* @__PURE__ */ new Map,c=r.sheet.symbols.filter(e=>Yi(e.device)===`component`);for(let e of c){if(s.has(e.device))continue;let r=o.get(e.device);if(r===void 0)throw new X(`unresolved-device`,`Missing prepared device \"${e.device}\"`,{deviceId:e.device});n();try{let i=await t(r.code,e.device);if(n(),!po(i)||!Object.hasOwn(i,`model`)||!Object.hasOwn(i,`create`)||typeof i.create!=`function`)throw TypeError(`SDK device modules must export named model and synchronous create`);let a=Ge(i.model),o=a.declarations.filter(e=>e.kind===`pin`).map(e=>e.name),c=r.definition.pins;if(c!==void 0&&!fo(Object.keys(c),o))throw TypeError(`Metadata pins do not match model pins`);let l={...r.definition,pins:c??Object.fromEntries(o.map(e=>[e,{}]))},u=oo(l);if(!fo(Object.keys(u.pins),o))throw TypeError(`Symbol pins do not match model pins`);s.set(e.device,{id:e.device,definition:l,model:a,create:i.create,topics:new Map(Object.entries(l.ports??{}).map(([e,t])=>[e,{port:e,...t,delivery:Oi(t.delivery,t.type)}]))})}catch(t){throw n(),new X(`invalid-device`,`Device \"${e.device}\" failed to load: ${Ci(t)}`,{deviceId:e.device,cause:t})}}let l=Ma(r,{devices:{getDeviceName:e=>s.get(e.raw)?.definition.displayName,getDeviceSymbol:e=>{let t=s.get(e.raw);return t===void 0?void 0:oo(t.definition)}}}),u=r.sheet.symbols.length===0&&r.sheet.wires.length===0&&r.sheet.junctions.length===0;for(let e of a.keys())if(!u&&!l.nets.some(t=>t.name===e))throw new X(`invalid-input`,`Voltage reference names missing schematic net \"${e}\"`);return{instances:c.map(e=>({symbol:e.id,device:s.get(e.device)})),description:{instances:c.map(e=>({id:e.id,type:e.id,props:co(e,s.get(e.device),i.get(e.id))})),nets:l.nets.map((e,t)=>{let n=e.name===null?void 0:a.get(e.name),r=e.members.some(e=>e.kind===`ground`);if(r&&n!==void 0&&n!==0)throw new X(`invalid-input`,`Conflicting voltage references on ground net \"${e.name}\": 0 and ${n}`);let i=r?0:n;return{id:`net:${t}`,pins:e.members.flatMap(e=>e.kind===`pin`?[{instance:e.symbolId,pin:e.pinId}]:[]),...i===void 0?{}:{voltage:i}}})}}}function co(e,t,n){let r=Object.create(null);for(let[e,n]of Object.entries(t.definition.properties??{}))Object.hasOwn(n,`default`)&&(r[e]=n.default);Object.assign(r,e.properties);let i=Object.create(null);for(let[a,o]of Object.entries(r))if(ji(o)){let r=Pi(o.mode,o.src);if(r!==void 0)throw new X(`invalid-input`,r,{deviceId:t.id});let s=n?.get(o.src);if(s===void 0)throw new X(`unresolved-asset`,`Symbol \"${e.id}\" is missing resource \"${o.src}\"`,{deviceId:t.id});i[a]=new Uint8Array(s)}else if(o instanceof Uint8Array)i[a]=new Uint8Array(o);else if(o===null||typeof o==`number`||typeof o==`boolean`||typeof o==`string`)i[a]=o;else throw new X(`invalid-input`,`Unsupported property \"${e.id}.${a}\"`,{deviceId:t.id});return i}function lo(e){if(e===void 0)return/* @__PURE__ */ new Map;if(!po(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new X(`invalid-input`,`Expected a plain voltageReferences map`);let t=/* @__PURE__ */ new Map;for(let n of Reflect.ownKeys(e)){let r=typeof n==`string`?e[n]:void 0;if(typeof n!=`string`||n.trim().length===0||typeof r!=`number`||!Number.isFinite(r))throw new X(`invalid-input`,`Expected voltageReferences with nonempty net names and finite numeric voltages`);t.set(n,r)}return t}function uo(e){let t=/* @__PURE__ */ new Map;if(e===void 0)return t;if(!po(e))throw new X(`invalid-input`,`Expected assets keyed by symbol id`);for(let[n,r]of Object.entries(e)){if(!po(r))throw new X(`invalid-input`,`Expected asset entries keyed by src`);let e=/* @__PURE__ */ new Map;for(let[t,n]of Object.entries(r)){if(!t||!(n instanceof Uint8Array))throw new X(`invalid-input`,`Resource bytes must be Uint8Array`);e.set(t,new Uint8Array(n))}t.set(n,e)}return t}function fo(e,t){return e.length===t.length&&e.every(e=>t.includes(e))}function po(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mo(e={}){let n=new t,r=new t,i=[],a=/* @__PURE__ */ new Map,o,s=O(0),c=!1,l=0,u=()=>{if(c)throw new X(`disposed`,`Simulation runtime has been disposed`)},d=e=>{if(n.hasListeners)for(let t of e.outputs.splice(0)){if(t.delivery===`level`){let e=C(t.symbol,t.port);if(a.has(e)&&ne(a.get(e),t.payload))continue;n.hasListeners&&a.set(e,ie(t.payload))}n.fire({target:{symbol:t.symbol,port:t.port},payload:t.payload,simTime:s})}else e.outputs.length=0;for(let t of e.diagnostics.splice(0))r.fire(t.runtimeCode===void 0?{...t,simTime:s}:t)},f=e=>{if(e!==void 0)try{e.board.dispose()}catch(e){r.fire({code:`board/diagnostic`,symbol:``,message:Ci(e),simTime:s,phase:`dispose`})}finally{for(let t of e.subscriptions)t.dispose()}},p=e=>{let t=o;o=e,i.length=0,a.clear(),s=O(0),f(t)};return{async load(t){u();let r=++l,i=await so(t,e.importer??vo,u);u(),r===l&&p(ho(i,()=>n.hasListeners))},async reset(){u(),++l,o===void 0?(i.length=0,a.clear(),s=O(0)):p(ho(o.prepared,()=>n.hasListeners))},async tick(e){if(u(),!Number.isSafeInteger(e)||e<=0)throw TypeError(`tick expects a positive integer dt in picoseconds`);let t=le(s,e),n=o;if(n===void 0)return s=t,{simTime:s,executed:0};try{for(let e of i.splice(0))n.board.topics.publish(_o(e.symbol,e.port),e.payload);n.board.runUntil(t)}finally{s=O(n.board.time),d(n)}return{simTime:s,executed:1}},async deliver(e){if(u(),typeof e!=`object`||!e||e.target===null||typeof e.target!=`object`||typeof e.target.symbol!=`string`||typeof e.target.port!=`string`)throw new X(`invalid-input`,`Expected a message with string symbol and port`);if(o===void 0)throw new X(`not-loaded`,`No simulation loaded`);let{symbol:t,port:n}=e.target,r=o.inputs.get(C(t,n));if(r===void 0||!E(r.type,e.payload))throw new X(`invalid-input`,`Unknown input or invalid payload for ${t}.${n}`);if(r.delivery===`level`){let e=i.findIndex(e=>e.symbol===t&&e.port===n);e!==-1&&i.splice(e,1)}i.push({symbol:t,port:n,payload:ie(e.payload)})},onDidPublish:n.event,onDidDiagnostic:r.event,async dispose(){c||(c=!0,++l,i.length=0,a.clear(),f(o),o=void 0,n.dispose(),r.dispose())}}}function ho(e,t){let n=[],r=[],i=/* @__PURE__ */ new Map,a=Si(bi(e.instances.map(e=>{for(let t of e.device.topics.values())t.direction===`input`&&i.set(C(e.symbol,t.port),t);return{id:e.symbol,model:e.device.model,create:i=>e.device.create({...i,topics:go(i.topics,e,n,r,t)})}})),{...e.description,instances:e.description.instances.map(e=>({...e,props:Object.fromEntries(Object.entries(e.props??{}).map(([e,t])=>[e,t instanceof Uint8Array?new Uint8Array(t):t]))}))}),o=(e,t)=>{r.push({code:t?e.phase===`topic`?`device/input-failed`:e.phase===`sync`?`device/output-failed`:`board/error`:`board/diagnostic`,symbol:e.instanceId??``,message:e.message,simTime:O(e.time??a.time),runtimeCode:e.code,phase:e.phase})};return{prepared:e,board:a,inputs:i,outputs:n,diagnostics:r,subscriptions:[a.onDidError(e=>o(e,!0)),a.onDidDiagnostic(e=>o(e,!1))]}}function go(e,t,n,r,i){let a=`${encodeURIComponent(t.symbol)}/`,o=0,s=()=>o===0&&e.hostListenerCount===0&&!i();return{get hostListenerCount(){return e.hostListenerCount},onDidReceive:((n,r,i)=>{let s=e.onDidReceive(e=>{if(!e.topic.startsWith(a))return;let i=e.topic.slice(a.length);if(t.device.topics.get(i)?.direction===`input`)return n.call(r,{topic:i,payload:ie(e.payload)})},void 0,void 0);o++;let c=!0,l={dispose:()=>{c&&(c=!1,o--,s.dispose())}};return i?.push(l),l}),assertCanPublish:()=>e.assertCanPublish(),publish(i,a){let o=t.device.topics.get(i);if(o?.direction!==`output`||!E(o.type,a)){r.push({code:`device/output-failed`,symbol:t.symbol,port:i,message:`Unknown output or invalid payload for ${t.symbol}.${i}`,simTime:O(0)});return}if(s()){e.assertCanPublish();return}let c=ie(a);e.publish(_o(t.symbol,i),c),n.push({symbol:t.symbol,port:i,payload:c,delivery:o.delivery})}}}function _o(e,t){return`${encodeURIComponent(e)}/${t}`}function vo(e){if(typeof URL>`u`||typeof URL.createObjectURL!=`function`||typeof Blob>`u`)return Promise.reject(/* @__PURE__ */ Error(`Inject a module importer outside a browser worker`));let t=URL.createObjectURL(new Blob([e],{type:`text/javascript`}));return import(\n/* @vite-ignore */\nt).finally(()=>URL.revokeObjectURL(t))}function yo(e,t,n){let r=So(t),i=e.register(ae,r,{transfer:se}),a=n===void 0?void 0:n.register(oe,{deliver:r.deliver,onDidPublish:r.onDidPublish},{transfer:se}),o=!1;return{dispose(){if(!o){o=!0;try{a?.dispose()}finally{i.dispose()}}}}}function bo(e,t={}){let n=a(e),r=mo(xo(t)),i=t.ports??[],o=i[0],s=o===void 0?void 0:a(o),c=yo(n,r,s),l=!1;return{rpc:n,ports:i,runtime:r,async dispose(){if(!l){l=!0;try{c.dispose(),await r.dispose()}finally{s?.dispose(),n.dispose(),e.close();for(let e of i)e.close()}}}}}function xo(e){return{...e.importer===void 0?{}:{importer:e.importer}}}function So(e){return{load:t=>e.load(t),reset:()=>e.reset(),tick:t=>e.tick(t),deliver:t=>e.deliver(t),onDidPublish:t=>{let n=e.onDidPublish(e=>t(Co(e)));return()=>n.dispose()},onDidDiagnostic(t){let n=e.onDidDiagnostic(t);return()=>n.dispose()},dispose:()=>e.dispose()}}function Co(e){let t=re(e.payload);return t===e.payload?e:{...e,payload:t}}globalThis.addEventListener(`message`,function e(t){let[n,...r]=t.ports;n!==void 0&&(globalThis.removeEventListener(`message`,e),bo(n,{ports:r}))})})();";
7
7
  //#endregion
8
8
  //#region src/simulation-runtime/adapter.ts
9
9
  /**