diff --git a/shared/static/scripts/htmx.min.js b/shared/static/scripts/htmx.min.js
new file mode 100644
index 00000000..59937d71
--- /dev/null
+++ b/shared/static/scripts/htmx.min.js
@@ -0,0 +1 @@
+var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/
]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q(''+t+"");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function D(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e=0}function le(e){return e.getRootNode({composed:true})===document}function F(e){return e.trim().split(/\s+/)}function ce(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){O(e);return null}}function B(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function U(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function e(e){return vn(ne().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function u(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return u(ne(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(ne(),e)}}function E(){return window}function z(e,t){e=y(e);if(t){E().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function $(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function f(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ue(y(e));if(!e){return}if(n){E().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ue(y(e));if(!r){return}if(n){E().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function Z(e,t){e=y(e);se(e.parentElement.children,function(e){G(e,t)});K(ue(e),t)}function g(e,t){e=ue(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&ue(c(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function ge(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function p(t,r,n){if(r.indexOf("global ")===0){return p(t,r.slice(7),true)}t=y(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=ge(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),ge(r.substr(8)))}else if(r.indexOf("find ")===0){e=u(f(t),ge(r.substr(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,ge(r.substr(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,ge(r.substr(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=m(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=f(m(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ae(e,t){if(typeof e!=="string"){return p(e,t)[0]}else{return p(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return u(f(t)||document,e)}else{return e}}function xe(e,t,n,r){if(k(t)){return{target:ne().body,event:J(e),listener:t,options:n}}else{return{target:y(e),event:J(t),listener:n,options:r}}}function ye(t,n,r,o){Vn(function(){const e=xe(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function be(t,n,r){Vn(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const ve=ne().createElement("output");function we(e,t){const n=re(e,t);if(n){if(n==="this"){return[Se(e,t)]}else{const r=p(e,n);if(r.length===0){O('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ue(o(e,function(e){return te(ue(e),t)!=null}))}function Ee(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ae(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Ce(t){const n=Q.config.attributesToSettle;for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=p(t,n,false);if(r){se(r,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!Re(s,e)){t=f(n)}const r={shouldSwap:true,target:e,fragment:t};if(!he(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);_e(s,e,e,t,i);Te()}se(i.elts,function(e){he(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Te(){const e=u("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=u("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){se(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){if(e.moveBefore){let e=u("#--htmx-preserve-pantry--");if(e==null){ne().body.insertAdjacentHTML("afterend","");e=u("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Le(l,e,c){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=f(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Ae(e){return function(){G(e,Q.config.addedClass);kt(ue(e));Ne(f(e));he(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=$(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function a(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ue(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n0}function $e(e,t,r,o){if(!o){o={}}e=y(e);const i=o.contextElement?m(o.contextElement,false):ne();const n=document.activeElement;let s={};try{s={elt:n,start:n?n.selectionStart:null,end:n?n.selectionEnd:null}}catch(e){}const l=xn(e);if(r.swapStyle==="textContent"){e.textContent=t}else{let n=P(t);l.title=n.title;if(o.selectOOB){const u=o.selectOOB.split(",");for(let t=0;t0){E().setTimeout(c,r.settleDelay)}else{c()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(D(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}he(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(ne().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function C(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=C(e,Qe).trim();e.shift()}else{t=C(e,v)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{C(o,w);const l=o.length;const c=C(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};C(o,w);u.pollInterval=d(C(o,/[,\[\s]/));C(o,w);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const a={trigger:c};var i=nt(e,o,"event");if(i){a.eventFilter=i}C(o,w);while(o.length>0&&o[0]!==","){const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=d(C(o,v))}else if(f==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=C(o,v);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=rt(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=d(C(o,v))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=C(o,v)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=rt(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=C(o,v)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}r.push(a)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=te(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!gt(n,e,Mt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function at(e){return g(e,Q.config.disableSelector)}function ft(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=ne().location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){pt(t,function(e,t){const n=ue(e);if(at(n)){b(n);return}de(r,o,n,t)},n,e,true)})}}function ht(e,t){const n=ue(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(h(n,'input[type="submit"], button')&&(h(n,"[form]")||g(n,"form")!==null)){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function dt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function gt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function pt(l,c,e,u,a){const f=ie(l);let t;if(u.from){t=p(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in f)){f.lastValue=new WeakMap}t.forEach(function(e){if(!f.lastValue.has(u)){f.lastValue.set(u,new WeakMap)}f.lastValue.get(u).set(e,e.value)})}se(t,function(i){const s=function(e){if(!le(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(a||ht(e,l)){e.preventDefault()}if(gt(u,l,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ue(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=event.target;const r=n.value;const o=f.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){he(l,"htmx:trigger");c(l,e);f.throttle=E().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=E().setTimeout(function(){he(l,"htmx:trigger");c(l,e)},u.delay)}else{he(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let xt=null;function yt(){if(!xt){xt=function(){mt=true};window.addEventListener("scroll",xt);window.addEventListener("resize",xt);setInterval(function(){if(mt){mt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&X(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){he(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){he(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;he(e,"htmx:trigger");t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;se(r,function(r){if(s(t,"hx-"+r)){const o=te(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ue(e);if(g(n,Q.config.disableSelector)){b(n);return}de(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){yt();pt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ae(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ue(r),n,e)}else{pt(r,n,t,e)}}function Et(e){const t=ue(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Tt(e){const t=g(ue(e.target),"button, input[type='submit']");const n=Lt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function Lt(e){const t=g(ue(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",Tt);e.addEventListener("focusin",Tt);e.addEventListener("focusout",qt)}function Nt(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(at(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function It(t){ke(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Vt(t){if(!B()){return null}t=U(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){he(ne().body,"htmx:historyCacheMissLoad",i);const e=P(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=Ut();const r=xn(n);kn(e.title);qe(e);Ve(n,t,r);Te();Kt(r.tasks);Bt=o;he(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{fe(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Wt(e){zt();e=e||location.pathname+location.search;const t=Vt(e);if(t){const n=P(t.content);const r=Ut();const o=xn(r);kn(t.title);qe(n);Ve(r,n,o);Te();Kt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Bt=e;he(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Gt(e)}}}function Zt(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Yt(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function Qt(e,t){se(e.concat(t),function(e){const t=ie(e);t.requestCount=(t.requestCount||1)-1});se(e,function(e){const t=ie(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function en(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function on(t,n,r,o,i){if(o==null||en(t,o)){return}else{t.push(o)}if(tn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=M(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=M(o.files)}nn(s,e,n);if(i){sn(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){rn(e.name,e.value,n)}else{t.push(e)}if(i){sn(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}nn(t,e,n)})}}function sn(e,t){const n=e;if(n.willValidate){he(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});he(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function ln(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){on(n,o,i,g(e,"form"),l)}on(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const a=ee(u,"name");nn(a,u.value,o)}const c=we(e,"hx-include");se(c,function(e){on(n,r,i,ue(e),l);if(!h(e,"form")){se(f(e).querySelectorAll(ot),function(e){on(n,r,i,e,l)})}});ln(r,o);return{errors:i,formData:r,values:An(r)}}function un(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function an(e){e=qn(e);let n="";e.forEach(function(e,t){n=un(n,t,e)});return n}function fn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};bn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function hn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function dn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function gn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!dn(e)){r.show="top"}if(n){const s=F(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.slice(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{O("Unknown modifier in hx-swap: "+l)}}}}return r}function pn(e){return re(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function mn(t,n,r){let o=null;Ft(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(pn(n)){return ln(new FormData,qn(r))}else{return an(r)}}}function xn(e){return{tasks:[],elts:[e]}}function yn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ae(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ae(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function bn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return bn(ue(c(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function wn(e,t){return bn(e,"hx-vars",true,t)}function Sn(e,t){return bn(e,"hx-vals",false,t)}function En(e){return ce(wn(e),Sn(e))}function Cn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function On(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function R(e,t){return t.test(e.getAllResponseHeaders())}function Rn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return de(t,n,null,null,{targetOverride:y(r)||ve,returnPromise:true})}else{let e=y(r.target);if(r.target&&!e||r.source&&!e&&!y(r.source)){e=ve}return de(t,n,y(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return de(t,n,null,null,{returnPromise:true})}}function Hn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Tn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return he(e,"htmx:validateUrl",ce({url:o,sameHost:r},n))}function qn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Ln(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function An(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}else{return e[t]}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Ln(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function de(t,n,r,o,i,D){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ne().body}const M=i.handler||Dn;const X=i.select||null;if(!le(r)){oe(s);return e}const c=i.targetOverride||ue(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let u=ie(r);const a=u.lastButtonClicked;if(a){const L=ee(a,"formaction");if(L!=null){n=L}const A=ee(a,"formmethod");if(A!=null){if(A.toLowerCase()!=="dialog"){t=A}}}const f=re(r,"hx-confirm");if(D===undefined){const K=function(e){return de(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(he(r,"htmx:confirm",G)===false){oe(s);return e}}let h=r;let d=re(r,"hx-sync");let g=null;let F=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ue(ae(r,I))}d=(N[1]||"drop").trim();u=ie(h);if(d==="drop"&&u.xhr&&u.abortable!==true){oe(s);return e}else if(d==="abort"){if(u.xhr){oe(s);return e}else{F=true}}else if(d==="replace"){he(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");g=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){he(h,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(g==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="all"){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){de(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;u.xhr=p;u.abortable=F;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const B=re(r,"hx-prompt");if(B){var x=prompt(B);if(x===null||!he(r,"htmx:prompt",{prompt:x,target:c})){oe(s);m();return e}}if(f&&!D){if(!confirm(f)){oe(s);m();return e}}let y=fn(r,c,x);if(t!=="get"&&!pn(r)){y["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){y=ce(y,i.headers)}const U=cn(r,t);let b=U.errors;const j=U.formData;if(i.values){ln(j,qn(i.values))}const V=qn(En(r));const v=ln(j,V);let w=hn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=bn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:w,parameters:An(w),unfilteredFormData:v,unfilteredParameters:An(v),headers:y,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!he(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;y=C.headers;w=qn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){he(r,"htmx:validation:halted",C);oe(s);m();return e}const z=n.split("#");const $=z[0];const O=z[1];let R=n;if(E){R=$;const Z=!w.keys().next().done;if(Z){if(R.indexOf("?")<0){R+="?"}else{R+="&"}R+=an(w);if(O){R+="#"+O}}}if(!Tn(r,R,C)){fe(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),R,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const k in y){if(y.hasOwnProperty(k)){const Y=y[k];Cn(p,k,Y)}}}const H={xhr:p,target:c,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:R,responsePath:null,anchor:O}};p.onload=function(){try{const t=Hn(r);H.pathInfo.responsePath=On(p);M(r,H);if(H.keepIndicators!==true){Qt(T,q)}he(r,"htmx:afterRequest",H);he(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){he(e,"htmx:afterRequest",H);he(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){fe(r,"htmx:onLoadError",ce({error:e},H));throw e}};p.onerror=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:timeout",H);oe(l);m()};if(!he(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Zt(r);var q=Yt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){he(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});he(r,"htmx:beforeSend",H);const J=E?null:mn(p,r,w);p.send(J);return e}function Nn(e,t){const n=t.xhr;let r=null;let o=null;if(R(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(R(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(R(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=re(e,"hx-push-url");const c=re(e,"hx-replace-url");const u=ie(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(c){a="replace";f=c}else if(u){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function In(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Pn(e){for(var t=0;t0){E().setTimeout(e,x.swapDelay)}else{e()}}if(f){fe(o,"htmx:responseError",ce({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Mn={};function Xn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Fn(e,t){if(t.init){t.init(n)}Mn[e]=ce(Xn(),t)}function Bn(e){delete Mn[e]}function Un(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Mn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return Un(ue(c(e)),n,r)}var jn=false;ne().addEventListener("DOMContentLoaded",function(){jn=true});function Vn(e){if(jn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function _n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend","")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function $n(){const e=zn();if(e){Q.config=ce(Q.config,e)}}Vn(function(){$n();_n();let e=ne().body;kt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){Wt();se(t,function(e){he(e,"htmx:restored",{document:ne(),triggerEvent:he})})}else{if(n){n(e)}}};E().setTimeout(function(){he(e,"htmx:load",{});e=null},0)});return Q}();
\ No newline at end of file
diff --git a/spec/tests/test-cek-try-seq.sx b/spec/tests/test-cek-try-seq.sx
new file mode 100644
index 00000000..5d969606
--- /dev/null
+++ b/spec/tests/test-cek-try-seq.sx
@@ -0,0 +1,64 @@
+;; Tests for cek-try sequential execution
+;; Bug: hydrate-island fallback leaves hydrating? scope active
+
+(defsuite
+ "cek-try-sequential"
+ (deftest
+ "code after cek-try runs on success"
+ (let
+ ((result (list)))
+ (append! result "before")
+ (cek-try (fn () (append! result "body") 42) (fn (e) nil))
+ (append! result "after")
+ (assert= 3 (len result))
+ (assert= "after" (nth result 2))))
+ (deftest
+ "code after cek-try runs on error"
+ (let
+ ((result (list)))
+ (append! result "before")
+ (cek-try (fn () (error "boom")) (fn (e) (append! result "caught")))
+ (append! result "after")
+ (assert= 3 (len result))
+ (assert= "after" (nth result 2))))
+ (deftest
+ "error in error handler propagates — skips post-try code"
+ (let
+ ((result (list)))
+ (append! result "before")
+ (guard
+ (outer-err (true (append! result "outer-caught")))
+ (cek-try (fn () (error "boom")) (fn (e) (error "handler-boom")))
+ (append! result "after-try"))
+ (assert-true (contains? result "before"))
+ (assert-true (contains? result "outer-caught"))
+ (assert= false (contains? result "after-try"))))
+ (deftest
+ "scope-pop after cek-try executes on error"
+ (scope-push! "test-scope" "value")
+ (cek-try (fn () (error "boom")) (fn (e) nil))
+ (scope-pop! "test-scope")
+ (assert= nil (scope-peek "test-scope")))
+ (deftest
+ "scope-push/pop balanced across cek-try error"
+ (let
+ ((result nil))
+ (scope-push! "bal-test" "pushed")
+ (cek-try (fn () (error "fail")) (fn (e) nil))
+ (set! result (scope-peek "bal-test"))
+ (scope-pop! "bal-test")
+ (assert= "pushed" result)
+ (assert= nil (scope-peek "bal-test"))))
+ (deftest
+ "error handler that errors skips cleanup"
+ (let
+ ((cleaned false))
+ (scope-push! "cleanup-test" "val")
+ (guard
+ (e (true nil))
+ (cek-try (fn () (error "first")) (fn (e) (error "second")))
+ (scope-pop! "cleanup-test")
+ (set! cleaned true))
+ (assert= false cleaned)
+ (assert= "val" (scope-peek "cleanup-test"))
+ (scope-pop! "cleanup-test"))))
\ No newline at end of file
diff --git a/spec/tests/test-hs-diag.sx b/spec/tests/test-hs-diag.sx
new file mode 100644
index 00000000..e1ec1316
--- /dev/null
+++ b/spec/tests/test-hs-diag.sx
@@ -0,0 +1,17 @@
+(defsuite
+ "hs-diag"
+ (deftest
+ "put into #id compiled"
+ (let
+ ((sx (hs-to-sx-from-source "on click put \"foo\" into #d1")))
+ (assert= (serialize sx) "SHOW")))
+ (deftest
+ "put into #id works"
+ (let
+ ((el (dom-create-element "div")))
+ (dom-set-attr el "id" "d1")
+ (dom-set-attr el "_" "on click put \"foo\" into #d1")
+ (dom-append (dom-body) el)
+ (hs-activate! el)
+ (dom-dispatch el "click" nil)
+ (assert= (dom-text-content el) "foo"))))
\ No newline at end of file
diff --git a/spec/tests/test-htmx.sx b/spec/tests/test-htmx.sx
new file mode 100644
index 00000000..44326fa8
--- /dev/null
+++ b/spec/tests/test-htmx.sx
@@ -0,0 +1,292 @@
+;; test-htmx.sx — Tests for htmx 4.0 compatibility layer
+;;
+;; Tests the attribute-to-handler translator: pure parsing functions,
+;; swap mode resolution, trigger parsing, and DOM integration via harness.
+
+;; ── Time parsing ────────────────────────────────────────────────
+
+(defsuite
+ "htmx-parse-time"
+ (deftest "parses milliseconds" (assert= (hx-parse-time "500ms") 500))
+ (deftest "parses seconds" (assert= (hx-parse-time "1s") 1000))
+ (deftest "parses fractional seconds" (assert= (hx-parse-time "0.5s") 500))
+ (deftest "parses minutes" (assert= (hx-parse-time "2m") 120000))
+ (deftest "parses bare number" (assert= (hx-parse-time "100") 100))
+ (deftest "returns nil for nil" (assert= (hx-parse-time nil) nil)))
+
+;; ── Swap mode normalization (v4 aliases) ────────────────────────
+
+(defsuite
+ "htmx-swap-aliases"
+ (deftest
+ "before → beforebegin"
+ (assert= (hx-normalize-swap-mode "before") "beforebegin"))
+ (deftest
+ "after → afterend"
+ (assert= (hx-normalize-swap-mode "after") "afterend"))
+ (deftest
+ "prepend → afterbegin"
+ (assert= (hx-normalize-swap-mode "prepend") "afterbegin"))
+ (deftest
+ "append → beforeend"
+ (assert= (hx-normalize-swap-mode "append") "beforeend"))
+ (deftest
+ "innerHTML passes through"
+ (assert= (hx-normalize-swap-mode "innerHTML") "innerHTML"))
+ (deftest
+ "outerHTML passes through"
+ (assert= (hx-normalize-swap-mode "outerHTML") "outerHTML"))
+ (deftest
+ "delete passes through"
+ (assert= (hx-normalize-swap-mode "delete") "delete"))
+ (deftest
+ "innerMorph passes through"
+ (assert= (hx-normalize-swap-mode "innerMorph") "innerMorph"))
+ (deftest
+ "outerMorph passes through"
+ (assert= (hx-normalize-swap-mode "outerMorph") "outerMorph"))
+ (deftest
+ "textContent passes through"
+ (assert= (hx-normalize-swap-mode "textContent") "textContent")))
+
+;; ── Swap spec parsing ───────────────────────────────────────────
+
+(defsuite
+ "htmx-parse-swap-spec"
+ (deftest
+ "nil defaults to innerHTML"
+ (let
+ ((spec (hx-parse-swap-spec nil)))
+ (assert= (get spec :mode) "innerHTML")))
+ (deftest
+ "bare mode"
+ (let
+ ((spec (hx-parse-swap-spec "outerHTML")))
+ (assert= (get spec :mode) "outerHTML")
+ (assert= (get spec :swap-delay) nil)))
+ (deftest
+ "mode with swap delay"
+ (let
+ ((spec (hx-parse-swap-spec "innerHTML swap:100ms")))
+ (assert= (get spec :mode) "innerHTML")
+ (assert= (get spec :swap-delay) 100)))
+ (deftest
+ "mode with settle delay"
+ (let
+ ((spec (hx-parse-swap-spec "innerHTML settle:200ms")))
+ (assert= (get spec :settle-delay) 200)))
+ (deftest
+ "mode with scroll"
+ (let
+ ((spec (hx-parse-swap-spec "innerHTML scroll:top")))
+ (assert= (get spec :scroll) "top")))
+ (deftest
+ "v4 alias normalized in spec"
+ (let
+ ((spec (hx-parse-swap-spec "append settle:500ms")))
+ (assert= (get spec :mode) "beforeend")
+ (assert= (get spec :settle-delay) 500)))
+ (deftest
+ "full spec with multiple modifiers"
+ (let
+ ((spec (hx-parse-swap-spec "innerHTML swap:50ms settle:100ms scroll:top")))
+ (assert= (get spec :mode) "innerHTML")
+ (assert= (get spec :swap-delay) 50)
+ (assert= (get spec :settle-delay) 100)
+ (assert= (get spec :scroll) "top"))))
+
+;; ── Trigger parsing ─────────────────────────────────────────────
+
+(defsuite
+ "htmx-parse-trigger"
+ (deftest
+ "simple event"
+ (let
+ ((spec (hx-parse-trigger "click" nil)))
+ (assert= (get spec :event) "click")
+ (assert= (get spec :delay) nil)
+ (assert= (get spec :once) false)))
+ (deftest
+ "event with delay"
+ (let
+ ((spec (hx-parse-trigger "keyup delay:500ms" nil)))
+ (assert= (get spec :event) "keyup")
+ (assert= (get spec :delay) 500)))
+ (deftest
+ "event with throttle"
+ (let
+ ((spec (hx-parse-trigger "click throttle:1s" nil)))
+ (assert= (get spec :event) "click")
+ (assert= (get spec :throttle) 1000)))
+ (deftest
+ "event with once"
+ (let
+ ((spec (hx-parse-trigger "click once" nil)))
+ (assert= (get spec :event) "click")
+ (assert= (get spec :once) true)))
+ (deftest
+ "event with changed"
+ (let
+ ((spec (hx-parse-trigger "keyup changed delay:500ms" nil)))
+ (assert= (get spec :event) "keyup")
+ (assert= (get spec :changed) true)
+ (assert= (get spec :delay) 500)))
+ (deftest
+ "event with from selector"
+ (let
+ ((spec (hx-parse-trigger "click from:body" nil)))
+ (assert= (get spec :event) "click")
+ (assert= (get spec :from) "body")))
+ (deftest
+ "event with filter"
+ (let
+ ((spec (hx-parse-trigger "keyup [key=='Enter']" nil)))
+ (assert= (get spec :event) "keyup")
+ (assert= (get spec :filter) "[key=='Enter']")))
+ (deftest
+ "every trigger"
+ (let
+ ((spec (hx-parse-trigger "every delay:2s" nil)))
+ (assert= (get spec :event) "every")
+ (assert= (get spec :delay) 2000))))
+
+;; ── URL encoding ────────────────────────────────────────────────
+
+(defsuite
+ "htmx-url-encode"
+ (deftest
+ "encodes single param"
+ (assert= (url-encode-params {:q "search"}) "q=search"))
+ (deftest
+ "encodes numeric values"
+ (assert= (url-encode-params {:page 1}) "page=1")))
+
+(defsuite
+ "htmx-status-matches"
+ (deftest "exact match" (assert= (hx-status-matches? "404" "404") true))
+ (deftest
+ "exact non-match"
+ (assert= (hx-status-matches? "404" "500") false))
+ (deftest
+ "1-digit wildcard 5xx matches 503"
+ (assert= (hx-status-matches? "503" "5xx") true))
+ (deftest
+ "1-digit wildcard 4xx does not match 503"
+ (assert= (hx-status-matches? "503" "4xx") false))
+ (deftest
+ "2-digit wildcard 50x matches 503"
+ (assert= (hx-status-matches? "503" "50x") true))
+ (deftest
+ "2-digit wildcard 50x does not match 522"
+ (assert= (hx-status-matches? "522" "50x") false))
+ (deftest "2xx matches 200" (assert= (hx-status-matches? "200" "2xx") true)))
+
+(defsuite
+ "htmx-status-modifiers"
+ (deftest
+ "parses swap target push"
+ (let
+ ((m (hx-parse-status-modifiers "swap:innerHTML target:#errors push:false")))
+ (assert= (get m :swap) "innerHTML")
+ (assert= (get m :target) "#errors")
+ (assert= (get m :push) "false")))
+ (deftest
+ "parses transition"
+ (let
+ ((m (hx-parse-status-modifiers "swap:none transition:true")))
+ (assert= (get m :swap) "none")
+ (assert= (get m :transition) "true"))))
+
+(defsuite
+ "htmx-match-status"
+ (deftest
+ "exact match wins over wildcard"
+ (let
+ ((rules (list {:target nil :transition nil :swap "none" :select nil :push nil :specificity 1 :code "5xx" :replace nil} {:target nil :transition nil :swap "outerHTML" :select nil :push nil :specificity 3 :code "503" :replace nil})))
+ (assert= (get (hx-match-status 503 rules) :swap) "outerHTML")))
+ (deftest
+ "2-digit wildcard wins over 1-digit"
+ (let
+ ((rules (list {:target nil :transition nil :swap "none" :select nil :push nil :specificity 1 :code "5xx" :replace nil} {:target nil :transition nil :swap "innerHTML" :select nil :push nil :specificity 2 :code "50x" :replace nil})))
+ (assert= (get (hx-match-status 501 rules) :swap) "innerHTML")))
+ (deftest
+ "nil when no match"
+ (let
+ ((rules (list {:target nil :transition nil :swap "none" :select nil :push nil :specificity 1 :code "5xx" :replace nil})))
+ (assert= (hx-match-status 404 rules) nil))))
+
+(defsuite
+ "htmx-sync-spec"
+ (deftest
+ "parses selector:strategy"
+ (let
+ ((s (hx-parse-sync-spec "closest form:abort")))
+ (assert= (get s :selector) "closest form")
+ (assert= (get s :strategy) "abort")))
+ (deftest
+ "parses queue with mode"
+ (let
+ ((s (hx-parse-sync-spec "this:queue last")))
+ (assert= (get s :selector) "this")
+ (assert= (get s :strategy) "queue")
+ (assert= (get s :queue-mode) "last")))
+ (deftest
+ "defaults to drop strategy"
+ (let
+ ((s (hx-parse-sync-spec "this:drop")))
+ (assert= (get s :strategy) "drop")))
+ (deftest "nil for nil input" (assert= (hx-parse-sync-spec nil) nil)))
+
+(defsuite
+ "htmx-sse-swap-parse"
+ (deftest
+ "parses single spec"
+ (let
+ ((specs (hx-parse-sse-swap "message:#target")))
+ (assert= (len specs) 1)
+ (assert= (get (first specs) :event) "message")
+ (assert= (get (first specs) :target) "#target")))
+ (deftest
+ "parses multiple specs with swap mode"
+ (let
+ ((specs (hx-parse-sse-swap "message:#target,update:#list:outerHTML")))
+ (assert= (len specs) 2)
+ (assert= (get (nth specs 1) :event) "update")
+ (assert= (get (nth specs 1) :swap) "outerHTML")))
+ (deftest
+ "nil returns empty list"
+ (assert= (hx-parse-sse-swap nil) (list))))
+
+(defsuite
+ "htmx-swap-spec-v4-modifiers"
+ (deftest
+ "transition modifier"
+ (let
+ ((spec (hx-parse-swap-spec "innerHTML transition:true")))
+ (assert= (get spec :transition) true)
+ (assert= (get spec :mode) "innerHTML")))
+ (deftest
+ "strip modifier"
+ (let
+ ((spec (hx-parse-swap-spec "outerHTML strip:true")))
+ (assert= (get spec :strip) true)))
+ (deftest
+ "target override in swap spec"
+ (let
+ ((spec (hx-parse-swap-spec "innerHTML target:#alt")))
+ (assert= (get spec :target) "#alt")))
+ (deftest
+ "ignoreTitle modifier"
+ (let
+ ((spec (hx-parse-swap-spec "innerHTML ignoreTitle:true")))
+ (assert= (get spec :ignore-title) true)))
+ (deftest
+ "all modifiers together"
+ (let
+ ((spec (hx-parse-swap-spec "append swap:50ms settle:100ms scroll:top transition:true strip:true")))
+ (assert= (get spec :mode) "beforeend")
+ (assert= (get spec :swap-delay) 50)
+ (assert= (get spec :settle-delay) 100)
+ (assert= (get spec :scroll) "top")
+ (assert= (get spec :transition) true)
+ (assert= (get spec :strip) true))))
\ No newline at end of file
diff --git a/spec/tests/test-perform-chain.sx b/spec/tests/test-perform-chain.sx
new file mode 100644
index 00000000..3cb4a075
--- /dev/null
+++ b/spec/tests/test-perform-chain.sx
@@ -0,0 +1,63 @@
+;; Tests for perform/IO suspension chaining through for-each
+;; Bug: after resume from first perform inside for-each,
+;; subsequent iterations' performs don't suspend — they complete
+;; synchronously, breaking multi-step async sequences like test runners.
+
+(defsuite
+ "perform-for-each-chain"
+ (deftest
+ "for-each with perform suspends on each iteration"
+ (let
+ ((state1 (cek-step-loop (make-cek-state (quote (let ((results (list))) (for-each (fn (item) (let ((val (perform {:op "fetch" :key item}))) (append! results val))) (list "a" "b" "c")) results)) (make-env) (list)))))
+ (assert-true (cek-suspended? state1))
+ (assert= "a" (get (cek-io-request state1) :key))
+ (let
+ ((state2 (cek-resume state1 "result-a")))
+ (assert-true (cek-suspended? state2))
+ (assert= "b" (get (cek-io-request state2) :key))
+ (let
+ ((state3 (cek-resume state2 "result-b")))
+ (assert-true (cek-suspended? state3))
+ (assert= "c" (get (cek-io-request state3) :key))
+ (let
+ ((final (cek-resume state3 "result-c")))
+ (assert-true (cek-terminal? final))
+ (assert= 3 (len (cek-value final))))))))
+ (deftest
+ "for-each with guard and perform chains correctly"
+ (let
+ ((state1 (cek-step-loop (make-cek-state (quote (let ((results (list))) (for-each (fn (item) (guard (e (true (append! results (str "fail:" item)))) (let ((val (perform {:op "fetch" :key item}))) (append! results (str "ok:" val))))) (list "x" "y")) results)) (make-env) (list)))))
+ (assert-true (cek-suspended? state1))
+ (let
+ ((state2 (cek-resume state1 "X")))
+ (assert-true (cek-suspended? state2))
+ (let
+ ((final (cek-resume state2 "Y")))
+ (assert-true (cek-terminal? final))
+ (let
+ ((results (cek-value final)))
+ (assert= 2 (len results))
+ (assert= "ok:X" (nth results 0))
+ (assert= "ok:Y" (nth results 1)))))))
+ (deftest
+ "nested performs in for-each — reload + wait pattern"
+ (let
+ ((state1 (cek-step-loop (make-cek-state (quote (let ((log (list))) (for-each (fn (name) (perform {:op "wait" :ms 1000}) (append! log (str "reloaded:" name)) (perform {:op "wait" :ms 500}) (append! log (str "done:" name))) (list "t1" "t2")) log)) (make-env) (list)))))
+ (assert-true (cek-suspended? state1))
+ (assert= 1000 (get (cek-io-request state1) :ms))
+ (let
+ ((s2 (cek-resume state1 nil)))
+ (assert-true (cek-suspended? s2))
+ (assert= 500 (get (cek-io-request s2) :ms))
+ (let
+ ((s3 (cek-resume s2 nil)))
+ (assert-true (cek-suspended? s3))
+ (assert= 1000 (get (cek-io-request s3) :ms))
+ (let
+ ((s4 (cek-resume s3 nil)))
+ (assert-true (cek-suspended? s4))
+ (assert= 500 (get (cek-io-request s4) :ms))
+ (let
+ ((final (cek-resume s4 nil)))
+ (assert-true (cek-terminal? final))
+ (assert= 4 (len (cek-value final))))))))))
\ No newline at end of file
diff --git a/tests/hs-behavioral-node.js b/tests/hs-behavioral-node.js
new file mode 100644
index 00000000..d16303f5
--- /dev/null
+++ b/tests/hs-behavioral-node.js
@@ -0,0 +1,448 @@
+#!/usr/bin/env node
+/**
+ * Run hyperscript behavioral tests in Node.js using the WASM kernel.
+ * No browser needed — uses a minimal DOM mock.
+ */
+const fs = require('fs');
+const path = require('path');
+
+const PROJECT = path.resolve(__dirname, '..');
+const WASM_DIR = path.join(PROJECT, 'shared/static/wasm');
+const SX_DIR = path.join(WASM_DIR, 'sx');
+
+// Load WASM kernel
+eval(fs.readFileSync(path.join(WASM_DIR, 'sx_browser.bc.js'), 'utf8'));
+const K = globalThis.SxKernel;
+
+// ─── Minimal DOM mock ───────────────────────────────────────────
+class MockElement {
+ constructor(tag) {
+ this.tagName = tag.toUpperCase();
+ this.nodeName = this.tagName;
+ this.nodeType = 1;
+ this.id = '';
+ this.className = '';
+ this.classList = new MockClassList(this);
+ this.style = {};
+ this.attributes = {};
+ this.children = [];
+ this.childNodes = [];
+ this.parentElement = null;
+ this.parentNode = null;
+ this.textContent = '';
+ this.innerHTML = '';
+ this.outerHTML = '';
+ this._listeners = {};
+ this._hs = {}; // hyperscript data
+ this.dataset = {};
+ this.open = false; // for dialog
+ }
+ setAttribute(name, val) { this.attributes[name] = val; if (name === 'id') this.id = val; if (name === 'class') { this.className = val; this.classList._sync(val); } }
+ getAttribute(name) { return this.attributes[name] !== undefined ? this.attributes[name] : null; }
+ removeAttribute(name) { delete this.attributes[name]; }
+ hasAttribute(name) { return name in this.attributes; }
+ addEventListener(evt, fn, opts) {
+ if (!this._listeners[evt]) this._listeners[evt] = [];
+ this._listeners[evt].push(fn);
+ }
+ removeEventListener(evt, fn) {
+ if (this._listeners[evt]) this._listeners[evt] = this._listeners[evt].filter(f => f !== fn);
+ }
+ dispatchEvent(event) {
+ event.target = this;
+ event.currentTarget = this;
+ const fns = this._listeners[event.type] || [];
+ for (const fn of fns) {
+ try { fn(event); } catch(e) {}
+ }
+ // Bubble
+ if (event.bubbles && !event._stopped && this.parentElement) {
+ event.currentTarget = this.parentElement;
+ this.parentElement.dispatchEvent(event);
+ }
+ return !event.defaultPrevented;
+ }
+ appendChild(child) {
+ if (child.parentElement) child.parentElement.removeChild(child);
+ child.parentElement = this;
+ child.parentNode = this;
+ this.children.push(child);
+ this.childNodes.push(child);
+ return child;
+ }
+ removeChild(child) {
+ this.children = this.children.filter(c => c !== child);
+ this.childNodes = this.childNodes.filter(c => c !== child);
+ child.parentElement = null;
+ child.parentNode = null;
+ return child;
+ }
+ insertBefore(newChild, refChild) {
+ const idx = this.children.indexOf(refChild);
+ if (idx >= 0) { this.children.splice(idx, 0, newChild); this.childNodes.splice(idx, 0, newChild); }
+ else { this.children.push(newChild); this.childNodes.push(newChild); }
+ newChild.parentElement = this;
+ newChild.parentNode = this;
+ return newChild;
+ }
+ replaceChild(newChild, oldChild) {
+ const idx = this.children.indexOf(oldChild);
+ if (idx >= 0) { this.children[idx] = newChild; this.childNodes[idx] = newChild; }
+ newChild.parentElement = this;
+ newChild.parentNode = this;
+ oldChild.parentElement = null;
+ oldChild.parentNode = null;
+ return oldChild;
+ }
+ querySelector(sel) { return findInTree(this, sel); }
+ querySelectorAll(sel) { return findAllInTree(this, sel); }
+ closest(sel) {
+ let el = this;
+ while (el) { if (matchesSelector(el, sel)) return el; el = el.parentElement; }
+ return null;
+ }
+ matches(sel) { return matchesSelector(this, sel); }
+ contains(other) {
+ if (other === this) return true;
+ for (const c of this.children) { if (c === other || c.contains(other)) return true; }
+ return false;
+ }
+ cloneNode(deep) {
+ const el = new MockElement(this.tagName.toLowerCase());
+ Object.assign(el.attributes, this.attributes);
+ el.id = this.id;
+ el.className = this.className;
+ el.classList._sync(this.className);
+ Object.assign(el.style, this.style);
+ el.textContent = this.textContent;
+ el.innerHTML = this.innerHTML;
+ if (deep) { for (const c of this.children) el.appendChild(c.cloneNode(true)); }
+ return el;
+ }
+ focus() {}
+ blur() {}
+ click() { this.dispatchEvent(new MockEvent('click', { bubbles: true })); }
+ remove() { if (this.parentElement) this.parentElement.removeChild(this); }
+ get firstElementChild() { return this.children[0] || null; }
+ get lastElementChild() { return this.children[this.children.length - 1] || null; }
+ get nextElementSibling() {
+ if (!this.parentElement) return null;
+ const idx = this.parentElement.children.indexOf(this);
+ return this.parentElement.children[idx + 1] || null;
+ }
+ get previousElementSibling() {
+ if (!this.parentElement) return null;
+ const idx = this.parentElement.children.indexOf(this);
+ return idx > 0 ? this.parentElement.children[idx - 1] : null;
+ }
+ // Dialog methods
+ showModal() { this.open = true; this.setAttribute('open', ''); }
+ show() { this.open = true; this.setAttribute('open', ''); }
+ close() { this.open = false; this.removeAttribute('open'); }
+ // Transition stub
+ getAnimations() { return []; }
+ getBoundingClientRect() { return { top: 0, left: 0, width: 100, height: 100, right: 100, bottom: 100 }; }
+ scrollIntoView() {}
+}
+
+class MockClassList {
+ constructor(el) { this._el = el; this._set = new Set(); }
+ _sync(str) { this._set = new Set((str || '').split(/\s+/).filter(Boolean)); }
+ add(...cls) { for (const c of cls) this._set.add(c); this._el.className = [...this._set].join(' '); }
+ remove(...cls) { for (const c of cls) this._set.delete(c); this._el.className = [...this._set].join(' '); }
+ toggle(cls, force) {
+ if (force !== undefined) { if (force) this.add(cls); else this.remove(cls); return force; }
+ if (this._set.has(cls)) { this.remove(cls); return false; }
+ else { this.add(cls); return true; }
+ }
+ contains(cls) { return this._set.has(cls); }
+ get length() { return this._set.size; }
+ [Symbol.iterator]() { return this._set[Symbol.iterator](); }
+}
+
+class MockEvent {
+ constructor(type, opts = {}) {
+ this.type = type;
+ this.bubbles = opts.bubbles || false;
+ this.cancelable = opts.cancelable !== false;
+ this.defaultPrevented = false;
+ this._stopped = false;
+ this._stoppedImmediate = false;
+ this.target = null;
+ this.currentTarget = null;
+ this.detail = opts.detail || null;
+ }
+ preventDefault() { this.defaultPrevented = true; }
+ stopPropagation() { this._stopped = true; }
+ stopImmediatePropagation() { this._stopped = true; this._stoppedImmediate = true; }
+}
+
+class MockCustomEvent extends MockEvent {
+ constructor(type, opts = {}) { super(type, opts); this.detail = opts.detail || null; }
+}
+
+function matchesSelector(el, sel) {
+ if (!el || !el.tagName) return false;
+ if (sel.startsWith('#')) return el.id === sel.slice(1);
+ if (sel.startsWith('.')) return el.classList.contains(sel.slice(1));
+ if (sel.includes('#')) { const [tag, id] = sel.split('#'); return el.tagName.toLowerCase() === tag && el.id === id; }
+ return el.tagName.toLowerCase() === sel.toLowerCase();
+}
+
+function findInTree(el, sel) {
+ for (const c of (el.children || [])) {
+ if (matchesSelector(c, sel)) return c;
+ const found = findInTree(c, sel);
+ if (found) return found;
+ }
+ return null;
+}
+
+function findAllInTree(el, sel) {
+ const results = [];
+ for (const c of (el.children || [])) {
+ if (matchesSelector(c, sel)) results.push(c);
+ results.push(...findAllInTree(c, sel));
+ }
+ return results;
+}
+
+// ─── Global DOM mock ────────────────────────────────────────────
+const _body = new MockElement('body');
+const _html = new MockElement('html');
+_html.appendChild(_body);
+
+const document = {
+ body: _body,
+ documentElement: _html,
+ createElement(tag) { return new MockElement(tag); },
+ createElementNS(ns, tag) { return new MockElement(tag); },
+ createDocumentFragment() { return new MockElement('fragment'); },
+ createTextNode(text) { const t = { nodeType: 3, textContent: text, data: text }; return t; },
+ getElementById(id) { return findInTree(_body, '#' + id); },
+ querySelector(sel) { return findInTree(_body, sel); },
+ querySelectorAll(sel) { return findAllInTree(_body, sel); },
+ createEvent(type) { return new MockEvent(type); },
+ addEventListener() {},
+ removeEventListener() {},
+};
+
+globalThis.document = document;
+globalThis.window = globalThis;
+globalThis.HTMLElement = MockElement;
+globalThis.Element = MockElement;
+globalThis.Event = MockEvent;
+globalThis.CustomEvent = MockCustomEvent;
+globalThis.NodeList = Array;
+globalThis.HTMLCollection = Array;
+globalThis.getComputedStyle = (el) => el.style;
+globalThis.requestAnimationFrame = (fn) => setTimeout(fn, 0);
+globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
+globalThis.MutationObserver = class { observe() {} disconnect() {} };
+globalThis.ResizeObserver = class { observe() {} disconnect() {} };
+globalThis.IntersectionObserver = class { observe() {} disconnect() {} };
+globalThis.navigator = { userAgent: 'node-test' };
+globalThis.location = { href: 'http://localhost/', pathname: '/', search: '', hash: '' };
+globalThis.history = { pushState() {}, replaceState() {}, back() {}, forward() {} };
+
+// ─── Host FFI ───────────────────────────────────────────────────
+K.registerNative('host-global', a => { const n = a[0]; return (n in globalThis) ? globalThis[n] : null; });
+K.registerNative('host-get', a => { if (a[0] == null) return null; const v = a[0][a[1]]; return v === undefined ? null : v; });
+K.registerNative('host-set!', a => { if (a[0] != null) a[0][a[1]] = a[2]; return a[2]; });
+K.registerNative('host-call', a => {
+ const [o, m, ...r] = a;
+ if (o == null) { const f = globalThis[m]; return typeof f === 'function' ? f.apply(null, r) : null; }
+ if (typeof o[m] !== 'function') return null;
+ try { const v = o[m].apply(o, r); return v === undefined ? null : v; } catch(e) { return null; }
+});
+K.registerNative('host-new', a => {
+ const C = typeof a[0] === 'string' ? globalThis[a[0]] : a[0];
+ return typeof C === 'function' ? new C(...a.slice(1)) : null;
+});
+K.registerNative('host-callback', a => {
+ const fn = a[0];
+ if (typeof fn === 'function' && fn.__sx_handle === undefined) return fn;
+ if (fn && fn.__sx_handle !== undefined) {
+ return function() {
+ const r = K.callFn(fn, Array.from(arguments));
+ if (globalThis._driveAsync) globalThis._driveAsync(r);
+ return r;
+ };
+ }
+ return function() {};
+});
+K.registerNative('host-typeof', a => {
+ const o = a[0]; if (o == null) return 'nil';
+ if (o instanceof MockElement) return 'element';
+ if (o && o.nodeType === 3) return 'text';
+ if (o instanceof MockEvent || o instanceof MockCustomEvent) return 'event';
+ if (o instanceof Promise) return 'promise';
+ return typeof o;
+});
+K.registerNative('host-await', a => {
+ const [p, cb] = a;
+ if (p && typeof p.then === 'function') {
+ const f = (cb && cb.__sx_handle !== undefined) ? v => K.callFn(cb, [v]) : () => {};
+ p.then(f);
+ }
+});
+K.registerNative('load-library!', () => false);
+
+// Drive async suspension — synchronous, with depth limit
+globalThis._driveAsync = function driveAsync(result, depth) {
+ depth = depth || 0;
+ if (depth > 200) return; // prevent infinite loops
+ if (!result || !result.suspended) return;
+ const req = result.request;
+ const items = req && (req.items || req);
+ const op = items && items[0];
+ const opName = typeof op === 'string' ? op : (op && op.name) || String(op);
+ const arg = items && items[1];
+ function doResume(val) {
+ try { const r = result.resume(val); driveAsync(r, depth + 1); } catch(e) {}
+ }
+ if (opName === 'io-sleep' || opName === 'wait') doResume(null);
+ else if (opName === 'io-fetch') doResume({ ok: true, text: '' });
+ else if (opName === 'io-settle') doResume(null);
+ else if (opName === 'io-wait-event') doResume(null);
+ else if (opName === 'io-transition') doResume(null);
+};
+
+K.eval('(define SX_VERSION "hs-test-1.0")');
+K.eval('(define SX_ENGINE "ocaml-vm-sandbox")');
+K.eval('(define parse sx-parse)');
+K.eval('(define serialize sx-serialize)');
+
+// ─── Load modules ───────────────────────────────────────────────
+const WEB_MODULES = [
+ 'render', 'core-signals', 'signals', 'deps', 'router',
+ 'page-helpers', 'freeze', 'dom', 'browser',
+ 'adapter-html', 'adapter-sx', 'adapter-dom',
+ 'boot-helpers', 'hypersx', 'engine', 'orchestration', 'boot',
+];
+const HS_MODULES = ['hs-tokenizer', 'hs-parser', 'hs-compiler', 'hs-runtime', 'hs-integration'];
+
+K.beginModuleLoad();
+for (const mod of [...WEB_MODULES, ...HS_MODULES]) {
+ const sxPath = path.join(SX_DIR, mod + '.sx');
+ const libPath = path.join(PROJECT, 'lib/hyperscript', mod.replace(/^hs-/, '') + '.sx');
+ let src;
+ try { src = fs.existsSync(sxPath) ? fs.readFileSync(sxPath, 'utf8') : fs.readFileSync(libPath, 'utf8'); }
+ catch(e) { console.error(`SKIP: ${mod}`); continue; }
+ try { K.load(src); } catch(e) { console.error(`LOAD ERROR: ${mod}: ${e.message}`); }
+}
+K.endModuleLoad();
+
+// ─── Register tests ─────────────────────────────────────────────
+K.eval('(define _test-registry (list))');
+K.eval('(define _test-suite "")');
+K.eval('(define push-suite (fn (name) (set! _test-suite name)))');
+K.eval('(define pop-suite (fn () (set! _test-suite "")))');
+K.eval(`(define try-call (fn (thunk)
+ (set! _test-registry (append _test-registry (list {:suite _test-suite :thunk thunk})))
+ {:ok true}))`);
+K.eval(`(define report-pass (fn (name)
+ (let ((i (- (len _test-registry) 1)))
+ (when (>= i 0) (dict-set! (nth _test-registry i) "name" name)))))`);
+K.eval(`(define report-fail (fn (name error)
+ (let ((i (- (len _test-registry) 1)))
+ (when (>= i 0) (dict-set! (nth _test-registry i) "name" name)))))`);
+
+// Load test files
+for (const f of ['spec/harness.sx', 'spec/tests/test-framework.sx', 'spec/tests/test-hyperscript-behavioral.sx']) {
+ try { K.load(fs.readFileSync(path.join(PROJECT, f), 'utf8')); }
+ catch(e) { console.error(`LOAD ERROR: ${f}: ${e.message}`); }
+}
+
+// ─── Run tests ──────────────────────────────────────────────────
+const testCount = K.eval('(len _test-registry)');
+console.log(`Loaded ${testCount} tests`);
+
+let passed = 0, failed = 0;
+const cats = {};
+const errTypes = {};
+const failDetails = [];
+
+for (let i = 0; i < testCount; i++) {
+ const suite = K.eval(`(get (nth _test-registry ${i}) "suite")`) || '';
+ const name = K.eval(`(get (nth _test-registry ${i}) "name")`) || `test-${i}`;
+
+ // Reset body
+ _body.children = [];
+ _body.childNodes = [];
+ _body.innerHTML = '';
+
+ process.stderr.write(` [${i}/${testCount}] ${suite} > ${name}\n`);
+
+ let ok = false;
+ let err = null;
+ try {
+ const thunk = K.eval(`(get (nth _test-registry ${i}) "thunk")`);
+ if (!thunk) { err = 'no thunk'; }
+ else {
+ const r = K.callFn(thunk, []);
+ if (r && r.suspended) globalThis._driveAsync(r);
+ ok = true;
+ }
+ } catch(e) {
+ err = (e.message || '').slice(0, 150);
+ }
+
+ if (!cats[suite]) cats[suite] = { p: 0, f: 0, errs: [] };
+ if (ok) {
+ passed++;
+ cats[suite].p++;
+ } else {
+ failed++;
+ cats[suite].f++;
+ cats[suite].errs.push({ name, err });
+
+ let t = 'other';
+ if (err === 'TIMEOUT') t = 'timeout';
+ else if (err && err.includes('NOT IMPLEMENTED')) t = 'stub';
+ else if (err && err.includes('Assertion')) t = 'assert-fail';
+ else if (err && err.includes('Expected')) t = 'wrong-value';
+ else if (err && err.includes('Undefined symbol')) t = 'undef-sym';
+ else if (err && err.includes('Unhandled')) t = 'unhandled';
+ errTypes[t] = (errTypes[t] || 0) + 1;
+ }
+}
+
+// ─── Report ─────────────────────────────────────────────────────
+console.log(`\nResults: ${passed}/${passed + failed} (${(100 * passed / (passed + failed)).toFixed(0)}%)\n`);
+
+console.log('By category:');
+for (const [cat, s] of Object.entries(cats).sort((a, b) => (b[1].p / (b[1].p + b[1].f)) - (a[1].p / (a[1].p + a[1].f)))) {
+ const mark = s.f === 0 ? `✓ ${s.p}` : `${s.p}/${s.p + s.f}`;
+ console.log(` ${cat}: ${mark}`);
+}
+
+console.log('\nFailure types:');
+for (const [t, n] of Object.entries(errTypes).sort((a, b) => b[1] - a[1])) {
+ console.log(` ${t}: ${n}`);
+}
+
+// Unique errors
+const uniqueErrors = {};
+for (const [cat, s] of Object.entries(cats)) {
+ for (const { name, err } of s.errs) {
+ const e = (err || '').slice(0, 100);
+ if (!uniqueErrors[e]) uniqueErrors[e] = 0;
+ uniqueErrors[e]++;
+ }
+}
+console.log(`\nUnique errors (${Object.keys(uniqueErrors).length}):`);
+for (const [e, n] of Object.entries(uniqueErrors).sort((a, b) => b[1] - a[1]).slice(0, 30)) {
+ console.log(` [${n}x] ${e}`);
+}
+
+// Show per-category failures for categories with < 5 failures
+console.log('\nDetailed failures (categories with <10 fails):');
+for (const [cat, s] of Object.entries(cats).sort((a, b) => a[1].f - b[1].f)) {
+ if (s.f > 0 && s.f < 10) {
+ console.log(` ${cat} (${s.p}/${s.p + s.f}):`);
+ for (const { name, err } of s.errs) {
+ console.log(` FAIL: ${name}: ${(err || '').slice(0, 100)}`);
+ }
+ }
+}
diff --git a/tests/hs-behavioral-runner.js b/tests/hs-behavioral-runner.js
new file mode 100644
index 00000000..9b6e3014
--- /dev/null
+++ b/tests/hs-behavioral-runner.js
@@ -0,0 +1,222 @@
+#!/usr/bin/env node
+/**
+ * Run hyperscript behavioral tests in Node.js with per-test timeout via worker_threads.
+ */
+const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
+const fs = require('fs');
+const path = require('path');
+
+if (!isMainThread) {
+ // ─── Worker: run a single test ─────────────────────────────────
+ const { testIdx } = workerData;
+ const PROJECT = path.resolve(__dirname, '..');
+ const WASM_DIR = path.join(PROJECT, 'shared/static/wasm');
+ const SX_DIR = path.join(WASM_DIR, 'sx');
+
+ eval(fs.readFileSync(path.join(WASM_DIR, 'sx_browser.bc.js'), 'utf8'));
+ const K = globalThis.SxKernel;
+
+ // Minimal DOM mock
+ class El {
+ constructor(t) { this.tagName=t.toUpperCase(); this.nodeName=this.tagName; this.nodeType=1; this.id=''; this.className=''; this.classList=new CL(this); this.style={}; this.attributes={}; this.children=[]; this.childNodes=[]; this.parentElement=null; this.parentNode=null; this.textContent=''; this.innerHTML=''; this._listeners={}; this.dataset={}; this.open=false; }
+ setAttribute(n,v) { this.attributes[n]=v; if(n==='id')this.id=v; if(n==='class'){this.className=v;this.classList._s(v);} }
+ getAttribute(n) { return this.attributes[n]!==undefined?this.attributes[n]:null; }
+ removeAttribute(n) { delete this.attributes[n]; }
+ hasAttribute(n) { return n in this.attributes; }
+ addEventListener(e,f) { if(!this._listeners[e])this._listeners[e]=[]; this._listeners[e].push(f); }
+ removeEventListener(e,f) { if(this._listeners[e])this._listeners[e]=this._listeners[e].filter(x=>x!==f); }
+ dispatchEvent(ev) { ev.target=this; ev.currentTarget=this; for(const f of (this._listeners[ev.type]||[])){try{f(ev);}catch(e){}} if(ev.bubbles&&!ev._s&&this.parentElement){ev.currentTarget=this.parentElement;this.parentElement.dispatchEvent(ev);} return !ev.defaultPrevented; }
+ appendChild(c) { if(c.parentElement)c.parentElement.removeChild(c); c.parentElement=this; c.parentNode=this; this.children.push(c); this.childNodes.push(c); return c; }
+ removeChild(c) { this.children=this.children.filter(x=>x!==c); this.childNodes=this.childNodes.filter(x=>x!==c); c.parentElement=null; c.parentNode=null; return c; }
+ insertBefore(n,r) { const i=this.children.indexOf(r); if(i>=0){this.children.splice(i,0,n);this.childNodes.splice(i,0,n);}else{this.children.push(n);this.childNodes.push(n);} n.parentElement=this;n.parentNode=this; return n; }
+ replaceChild(n,o) { const i=this.children.indexOf(o); if(i>=0){this.children[i]=n;this.childNodes[i]=n;} n.parentElement=this;n.parentNode=this; o.parentElement=null;o.parentNode=null; return o; }
+ querySelector(s) { return fnd(this,s); }
+ querySelectorAll(s) { return fndAll(this,s); }
+ closest(s) { let e=this; while(e){if(mt(e,s))return e; e=e.parentElement;} return null; }
+ matches(s) { return mt(this,s); }
+ contains(o) { if(o===this)return true; for(const c of this.children)if(c===o||c.contains(o))return true; return false; }
+ cloneNode(d) { const e=new El(this.tagName.toLowerCase()); Object.assign(e.attributes,this.attributes); e.id=this.id; e.className=this.className; e.classList._s(this.className); Object.assign(e.style,this.style); e.textContent=this.textContent; e.innerHTML=this.innerHTML; if(d)for(const c of this.children)e.appendChild(c.cloneNode(true)); return e; }
+ focus(){} blur(){} click(){ this.dispatchEvent(new Ev('click',{bubbles:true})); } remove(){ if(this.parentElement)this.parentElement.removeChild(this); }
+ get firstElementChild() { return this.children[0]||null; }
+ get lastElementChild() { return this.children[this.children.length-1]||null; }
+ get nextElementSibling() { if(!this.parentElement)return null; const i=this.parentElement.children.indexOf(this); return this.parentElement.children[i+1]||null; }
+ get previousElementSibling() { if(!this.parentElement)return null; const i=this.parentElement.children.indexOf(this); return i>0?this.parentElement.children[i-1]:null; }
+ showModal(){this.open=true;this.setAttribute('open','');} show(){this.open=true;} close(){this.open=false;this.removeAttribute('open');}
+ getAnimations(){return [];} getBoundingClientRect(){return{top:0,left:0,width:100,height:100};} scrollIntoView(){}
+ }
+ class CL { constructor(e){this._e=e;this._s=new Set();} _s(str){this._s=new Set((str||'').split(/\s+/).filter(Boolean));} add(...c){for(const x of c)this._s.add(x);this._e.className=[...this._s].join(' ');} remove(...c){for(const x of c)this._s.delete(x);this._e.className=[...this._s].join(' ');} toggle(c,f){if(f!==undefined){if(f)this.add(c);else this.remove(c);return f;} if(this._s.has(c)){this.remove(c);return false;}else{this.add(c);return true;}} contains(c){return this._s.has(c);} get length(){return this._s.size;} }
+ class Ev { constructor(t,o={}){this.type=t;this.bubbles=o.bubbles||false;this.cancelable=o.cancelable!==false;this.defaultPrevented=false;this._s=false;this.target=null;this.currentTarget=null;this.detail=o.detail||null;} preventDefault(){this.defaultPrevented=true;} stopPropagation(){this._s=true;} stopImmediatePropagation(){this._s=true;} }
+ function mt(e,s){if(!e||!e.tagName)return false;if(s.startsWith('#'))return e.id===s.slice(1);if(s.startsWith('.'))return e.classList.contains(s.slice(1));if(s.includes('#')){const[t,i]=s.split('#');return e.tagName.toLowerCase()===t&&e.id===i;} return e.tagName.toLowerCase()===s.toLowerCase();}
+ function fnd(e,s){for(const c of(e.children||[])){if(mt(c,s))return c;const f=fnd(c,s);if(f)return f;}return null;}
+ function fndAll(e,s){const r=[];for(const c of(e.children||[])){if(mt(c,s))r.push(c);r.push(...fndAll(c,s));}return r;}
+
+ const _body=new El('body'); const _html=new El('html'); _html.appendChild(_body);
+ const document={body:_body,documentElement:_html,createElement(t){return new El(t);},createElementNS(n,t){return new El(t);},createDocumentFragment(){return new El('fragment');},createTextNode(t){return{nodeType:3,textContent:t,data:t};},getElementById(i){return fnd(_body,'#'+i);},querySelector(s){return fnd(_body,s);},querySelectorAll(s){return fndAll(_body,s);},createEvent(t){return new Ev(t);},addEventListener(){},removeEventListener(){}};
+ globalThis.document=document; globalThis.window=globalThis; globalThis.HTMLElement=El; globalThis.Element=El; globalThis.Event=Ev; globalThis.CustomEvent=Ev; globalThis.NodeList=Array; globalThis.HTMLCollection=Array;
+ globalThis.getComputedStyle=(e)=>e.style; globalThis.requestAnimationFrame=(f)=>setTimeout(f,0); globalThis.cancelAnimationFrame=(i)=>clearTimeout(i);
+ globalThis.MutationObserver=class{observe(){}disconnect(){}}; globalThis.ResizeObserver=class{observe(){}disconnect(){}}; globalThis.IntersectionObserver=class{observe(){}disconnect(){}};
+ globalThis.navigator={userAgent:'node'}; globalThis.location={href:'http://localhost/',pathname:'/',search:'',hash:''}; globalThis.history={pushState(){},replaceState(){},back(){},forward(){}};
+
+ K.registerNative('host-global',a=>{const n=a[0];return(n in globalThis)?globalThis[n]:null;});
+ K.registerNative('host-get',a=>{if(a[0]==null)return null;const v=a[0][a[1]];return v===undefined?null:v;});
+ K.registerNative('host-set!',a=>{if(a[0]!=null)a[0][a[1]]=a[2];return a[2];});
+ K.registerNative('host-call',a=>{const[o,m,...r]=a;if(o==null){const f=globalThis[m];return typeof f==='function'?f.apply(null,r):null;}if(typeof o[m]!=='function')return null;try{return o[m].apply(o,r)||null;}catch(e){return null;}});
+ K.registerNative('host-new',a=>{const C=typeof a[0]==='string'?globalThis[a[0]]:a[0];return typeof C==='function'?new C(...a.slice(1)):null;});
+ K.registerNative('host-callback',a=>{const fn=a[0];if(typeof fn==='function'&&fn.__sx_handle===undefined)return fn;if(fn&&fn.__sx_handle!==undefined)return function(){const r=K.callFn(fn,Array.from(arguments));if(globalThis._driveAsync)globalThis._driveAsync(r);return r;};return function(){};});
+ K.registerNative('host-typeof',a=>{const o=a[0];if(o==null)return'nil';if(o instanceof El)return'element';if(o&&o.nodeType===3)return'text';if(o instanceof Ev)return'event';if(o instanceof Promise)return'promise';return typeof o;});
+ K.registerNative('host-await',a=>{const[p,cb]=a;if(p&&typeof p.then==='function'){const f=(cb&&cb.__sx_handle!==undefined)?v=>K.callFn(cb,[v]):()=>{};p.then(f);}});
+ K.registerNative('load-library!',()=>false);
+
+ globalThis._driveAsync=function driveAsync(r,d){d=d||0;if(d>200||!r||!r.suspended)return;const req=r.request;const items=req&&(req.items||req);const op=items&&items[0];const opName=typeof op==='string'?op:(op&&op.name)||String(op);function doResume(v){try{const x=r.resume(v);driveAsync(x,d+1);}catch(e){}}if(opName==='io-sleep'||opName==='wait')doResume(null);else if(opName==='io-fetch')doResume({ok:true,text:''});else if(opName==='io-settle')doResume(null);else if(opName==='io-wait-event')doResume(null);else if(opName==='io-transition')doResume(null);};
+
+ K.eval('(define SX_VERSION "hs-test-1.0")');
+ K.eval('(define SX_ENGINE "ocaml-vm-sandbox")');
+ K.eval('(define parse sx-parse)');
+ K.eval('(define serialize sx-serialize)');
+
+ const WEB=['render','core-signals','signals','deps','router','page-helpers','freeze','dom','browser','adapter-html','adapter-sx','adapter-dom','boot-helpers','hypersx','engine','orchestration','boot'];
+ const HS=['hs-tokenizer','hs-parser','hs-compiler','hs-runtime','hs-integration'];
+ K.beginModuleLoad();
+ for(const mod of[...WEB,...HS]){const sp=path.join(SX_DIR,mod+'.sx');const lp=path.join(PROJECT,'lib/hyperscript',mod.replace(/^hs-/,'')+'.sx');let s;try{s=fs.existsSync(sp)?fs.readFileSync(sp,'utf8'):fs.readFileSync(lp,'utf8');}catch(e){continue;}try{K.load(s);}catch(e){}}
+ K.endModuleLoad();
+
+ K.eval('(define _test-registry (list))'); K.eval('(define _test-suite "")');
+ K.eval('(define push-suite (fn (name) (set! _test-suite name)))');
+ K.eval('(define pop-suite (fn () (set! _test-suite "")))');
+ K.eval('(define try-call (fn (thunk) (set! _test-registry (append _test-registry (list {:suite _test-suite :thunk thunk}))) {:ok true}))');
+ K.eval('(define report-pass (fn (name) (let ((i (- (len _test-registry) 1))) (when (>= i 0) (dict-set! (nth _test-registry i) "name" name)))))');
+ K.eval('(define report-fail (fn (name error) (let ((i (- (len _test-registry) 1))) (when (>= i 0) (dict-set! (nth _test-registry i) "name" name)))))');
+
+ for(const f of['spec/harness.sx','spec/tests/test-framework.sx','spec/tests/test-hyperscript-behavioral.sx']){try{K.load(fs.readFileSync(path.join(PROJECT,f),'utf8'));}catch(e){}}
+
+ // Run single test
+ _body.children=[]; _body.childNodes=[]; _body.innerHTML='';
+ const suite=K.eval(`(get (nth _test-registry ${testIdx}) "suite")`)||'';
+ const name=K.eval(`(get (nth _test-registry ${testIdx}) "name")`)||`test-${testIdx}`;
+ let ok=false, err=null;
+ try{
+ const thunk=K.eval(`(get (nth _test-registry ${testIdx}) "thunk")`);
+ if(!thunk){err='no thunk';}else{const r=K.callFn(thunk,[]);if(r&&r.suspended)globalThis._driveAsync(r);ok=true;}
+ }catch(e){err=(e.message||'').slice(0,150);}
+ parentPort.postMessage({suite,name,ok,err});
+ process.exit(0);
+}
+
+// ─── Main thread ─────────────────────────────────────────────────
+const PROJECT = path.resolve(__dirname, '..');
+
+async function runTest(idx) {
+ return new Promise((resolve) => {
+ const worker = new Worker(__filename, { workerData: { testIdx: idx } });
+ const timer = setTimeout(() => { worker.terminate(); resolve({ suite: '', name: `test-${idx}`, ok: false, err: 'TIMEOUT' }); }, 8000);
+ worker.on('message', (msg) => { clearTimeout(timer); resolve(msg); });
+ worker.on('error', (e) => { clearTimeout(timer); resolve({ suite: '', name: `test-${idx}`, ok: false, err: 'CRASH: ' + (e.message || '').slice(0, 80) }); });
+ worker.on('exit', (code) => { if (code !== 0) { clearTimeout(timer); resolve({ suite: '', name: `test-${idx}`, ok: false, err: 'EXIT: ' + code }); } });
+ });
+}
+
+async function main() {
+ // First, get test count by loading in main thread
+ const WASM_DIR = path.join(PROJECT, 'shared/static/wasm');
+ eval(fs.readFileSync(path.join(WASM_DIR, 'sx_browser.bc.js'), 'utf8'));
+ const K = globalThis.SxKernel;
+ K.registerNative('host-global',a=>null);K.registerNative('host-get',a=>null);K.registerNative('host-set!',a=>null);K.registerNative('host-call',a=>null);K.registerNative('host-new',a=>null);K.registerNative('host-callback',a=>function(){});K.registerNative('host-typeof',a=>'nil');K.registerNative('host-await',a=>null);K.registerNative('load-library!',()=>false);
+ K.eval('(define SX_VERSION "hs-test-1.0")');K.eval('(define SX_ENGINE "ocaml-vm-sandbox")');K.eval('(define parse sx-parse)');K.eval('(define serialize sx-serialize)');
+ const SX_DIR=path.join(WASM_DIR,'sx');
+ const WEB=['render','core-signals','signals','deps','router','page-helpers','freeze','dom','browser','adapter-html','adapter-sx','adapter-dom','boot-helpers','hypersx','engine','orchestration','boot'];
+ const HS=['hs-tokenizer','hs-parser','hs-compiler','hs-runtime','hs-integration'];
+ K.beginModuleLoad();
+ for(const mod of[...WEB,...HS]){const sp=path.join(SX_DIR,mod+'.sx');const lp=path.join(PROJECT,'lib/hyperscript',mod.replace(/^hs-/,'')+'.sx');let s;try{s=fs.existsSync(sp)?fs.readFileSync(sp,'utf8'):fs.readFileSync(lp,'utf8');}catch(e){continue;}try{K.load(s);}catch(e){}}
+ K.endModuleLoad();
+ K.eval('(define _test-registry (list))');K.eval('(define _test-suite "")');
+ K.eval('(define push-suite (fn (name) (set! _test-suite name)))');
+ K.eval('(define pop-suite (fn () (set! _test-suite "")))');
+ K.eval('(define try-call (fn (thunk) (set! _test-registry (append _test-registry (list {:suite _test-suite :thunk thunk}))) {:ok true}))');
+ K.eval('(define report-pass (fn (n) true))');K.eval('(define report-fail (fn (n e) true))');
+ for(const f of['spec/harness.sx','spec/tests/test-framework.sx','spec/tests/test-hyperscript-behavioral.sx']){try{K.load(fs.readFileSync(path.join(PROJECT,f),'utf8'));}catch(e){}}
+
+ const testCount = K.eval('(len _test-registry)');
+ // Get names
+ const testNames = [];
+ for (let i = 0; i < testCount; i++) {
+ testNames.push({
+ s: K.eval(`(get (nth _test-registry ${i}) "suite")`) || '',
+ n: K.eval(`(get (nth _test-registry ${i}) "name")`) || `test-${i}`,
+ });
+ }
+
+ console.log(`Running ${testCount} tests...`);
+
+ // Run tests — 4 workers at a time
+ const results = [];
+ const BATCH = 4;
+ for (let i = 0; i < testCount; i += BATCH) {
+ const batch = [];
+ for (let j = i; j < Math.min(i + BATCH, testCount); j++) {
+ batch.push(runTest(j).then(r => {
+ r.suite = r.suite || testNames[j].s;
+ r.name = r.name || testNames[j].n;
+ return r;
+ }));
+ }
+ const batchResults = await Promise.all(batch);
+ results.push(...batchResults);
+ if ((i + BATCH) % 100 < BATCH) process.stderr.write(` ${Math.min(i + BATCH, testCount)}/${testCount}...\n`);
+ }
+
+ // Tally
+ let passed = 0, failed = 0;
+ const cats = {};
+ const errTypes = {};
+ for (const r of results) {
+ if (!cats[r.suite]) cats[r.suite] = { p: 0, f: 0, errs: [] };
+ if (r.ok) { passed++; cats[r.suite].p++; }
+ else {
+ failed++;
+ cats[r.suite].f++;
+ cats[r.suite].errs.push({ name: r.name, err: r.err });
+ let t = 'other';
+ if (r.err === 'TIMEOUT') t = 'timeout';
+ else if (r.err && r.err.includes('NOT IMPLEMENTED')) t = 'stub';
+ else if (r.err && r.err.includes('Assertion')) t = 'assert-fail';
+ else if (r.err && r.err.includes('Expected')) t = 'wrong-value';
+ else if (r.err && r.err.includes('Undefined symbol')) t = 'undef-sym';
+ else if (r.err && r.err.includes('Unhandled')) t = 'unhandled';
+ else if (r.err && r.err.includes('CRASH')) t = 'crash';
+ else if (r.err && r.err.includes('EXIT')) t = 'exit';
+ errTypes[t] = (errTypes[t] || 0) + 1;
+ }
+ }
+
+ console.log(`\nResults: ${passed}/${passed + failed} (${(100 * passed / (passed + failed)).toFixed(0)}%)\n`);
+
+ console.log('By category (sorted by pass rate):');
+ for (const [cat, s] of Object.entries(cats).sort((a, b) => {
+ const ra = a[1].p / (a[1].p + a[1].f);
+ const rb = b[1].p / (b[1].p + b[1].f);
+ return rb - ra;
+ })) {
+ const total = s.p + s.f;
+ const pct = (100 * s.p / total).toFixed(0);
+ const mark = s.f === 0 ? `✓ ${s.p}` : `${s.p}/${total} (${pct}%)`;
+ console.log(` ${cat}: ${mark}`);
+ }
+
+ console.log('\nFailure types:');
+ for (const [t, n] of Object.entries(errTypes).sort((a, b) => b[1] - a[1])) {
+ console.log(` ${t}: ${n}`);
+ }
+
+ const uniqueErrors = {};
+ for (const r of results.filter(r => !r.ok)) {
+ const e = (r.err || '').slice(0, 100);
+ if (!uniqueErrors[e]) uniqueErrors[e] = 0;
+ uniqueErrors[e]++;
+ }
+ console.log(`\nUnique errors (${Object.keys(uniqueErrors).length}):`);
+ for (const [e, n] of Object.entries(uniqueErrors).sort((a, b) => b[1] - a[1]).slice(0, 25)) {
+ console.log(` [${n}x] ${e}`);
+ }
+}
+
+main().catch(e => { console.error(e); process.exit(1); });
diff --git a/tests/hs-parse-audit.js b/tests/hs-parse-audit.js
new file mode 100644
index 00000000..4770eb76
--- /dev/null
+++ b/tests/hs-parse-audit.js
@@ -0,0 +1,117 @@
+#!/usr/bin/env node
+/**
+ * Audit: extract all HS sources from behavioral tests and check parse/compile.
+ * Uses child_process.execSync with timeout to handle hangs.
+ */
+const fs = require('fs');
+const path = require('path');
+const { execSync } = require('child_process');
+
+const PROJECT = path.resolve(__dirname, '..');
+
+// Extract HS sources from test file with their suite/test names
+const testSx = fs.readFileSync(path.join(PROJECT, 'spec/tests/test-hyperscript-behavioral.sx'), 'utf8');
+
+// Extract suites and their test counts from comments
+const suitePattern = /;; ── (\S+) \((\d+) tests\)/g;
+const suites = [];
+let m;
+while ((m = suitePattern.exec(testSx)) !== null) {
+ suites.push({ name: m[1], count: parseInt(m[2]) });
+}
+
+console.log('Test suites (831 total):');
+let grandTotal = 0;
+for (const s of suites) {
+ grandTotal += s.count;
+ console.log(` ${s.name}: ${s.count}`);
+}
+console.log(` TOTAL: ${grandTotal}`);
+
+// Categorize tests by type: DOM-action tests vs eval-only tests vs stub tests
+const lines = testSx.split('\n');
+let currentSuite = '';
+let inDeftest = false;
+let testName = '';
+let testBody = '';
+let depth = 0;
+
+const testCategories = {};
+
+for (const line of lines) {
+ const suiteMatch = line.match(/\(defsuite\s+"([^"]+)"/);
+ if (suiteMatch) { currentSuite = suiteMatch[1]; continue; }
+
+ const testMatch = line.match(/\(deftest\s+"([^"]+)"/);
+ if (testMatch) { inDeftest = true; testName = testMatch[1]; testBody = line; depth = 1; continue; }
+
+ if (inDeftest) {
+ testBody += '\n' + line;
+ depth += (line.match(/\(/g) || []).length - (line.match(/\)/g) || []).length;
+ if (depth <= 0) {
+ // Categorize this test
+ if (!testCategories[currentSuite]) testCategories[currentSuite] = { domAction: 0, evalOnly: 0, stub: 0, notImpl: 0, names: [] };
+
+ if (testBody.includes('NOT IMPLEMENTED') || testBody.includes('not-implemented')) {
+ testCategories[currentSuite].stub++;
+ } else if (testBody.includes('dom-dispatch') || testBody.includes('dom-set-inner-html') && testBody.includes('hs-activate!')) {
+ testCategories[currentSuite].domAction++;
+ testCategories[currentSuite].names.push(testName);
+ } else if (testBody.includes('eval-hs') || testBody.includes('hs-eval')) {
+ testCategories[currentSuite].evalOnly++;
+ } else {
+ testCategories[currentSuite].domAction++;
+ testCategories[currentSuite].names.push(testName);
+ }
+
+ inDeftest = false;
+ testBody = '';
+ }
+ }
+}
+
+// Count unique HS sources
+const attrPattern = /dom-set-attr\s+\S+\s+"_"\s+"([^"]+)"/g;
+const hsSources = new Set();
+while ((m = attrPattern.exec(testSx)) !== null) {
+ hsSources.add(m[1].replace(/\\"/g, '"'));
+}
+
+console.log(`\n${hsSources.size} unique HS sources across ${grandTotal} tests`);
+
+// Analyze HS source complexity
+const features = {
+ 'on click': 0, 'on load': 0, 'on keyup': 0, 'on mouseenter': 0,
+ 'on mutation': 0, 'on intersect': 0, 'on every': 0,
+ 'add .': 0, 'remove .': 0, 'toggle .': 0, 'set ': 0, 'put ': 0,
+ 'if ': 0, 'repeat': 0, 'wait ': 0, 'send ': 0, 'take ': 0,
+ 'transition': 0, 'hide': 0, 'show': 0, 'log': 0,
+ 'call ': 0, 'fetch ': 0, 'tell ': 0, 'halt': 0,
+ 'morph': 0, 'go ': 0, 'append': 0, 'settle': 0,
+ 'def ': 0, 'increment': 0, 'decrement': 0,
+ 'bind ': 0, 'closest': 0, 'in ': 0, 'as ': 0,
+ 'init': 0, 'every ': 0, 'measure': 0,
+};
+
+for (const src of hsSources) {
+ for (const feat of Object.keys(features)) {
+ if (src.includes(feat)) features[feat]++;
+ }
+}
+
+console.log('\nFeature usage in test sources:');
+for (const [feat, count] of Object.entries(features).sort((a,b) => b[1] - a[1])) {
+ if (count > 0) console.log(` ${feat.trim()}: ${count}`);
+}
+
+// Summarize categories
+console.log('\nPer-suite breakdown:');
+let totalDom = 0, totalEval = 0, totalStub = 0;
+for (const [suite, cat] of Object.entries(testCategories).sort((a,b) => (b[1].domAction+b[1].evalOnly) - (a[1].domAction+a[1].evalOnly))) {
+ const total = cat.domAction + cat.evalOnly + cat.stub;
+ totalDom += cat.domAction;
+ totalEval += cat.evalOnly;
+ totalStub += cat.stub;
+ console.log(` ${suite}: ${total} tests (${cat.domAction} DOM, ${cat.evalOnly} eval, ${cat.stub} stub)`);
+}
+console.log(`\nTotals: ${totalDom} DOM-action, ${totalEval} eval-only, ${totalStub} stubs`);
diff --git a/tests/hs-run-timed.js b/tests/hs-run-timed.js
new file mode 100644
index 00000000..201fc6d1
--- /dev/null
+++ b/tests/hs-run-timed.js
@@ -0,0 +1,269 @@
+#!/usr/bin/env node
+/**
+ * Run HS behavioral tests with per-test fork-based timeout.
+ * Forks itself for each test to handle infinite loops.
+ */
+const { execFileSync } = require('child_process');
+const fs = require('fs');
+const path = require('path');
+
+const PROJECT = path.resolve(__dirname, '..');
+const WASM_DIR = path.join(PROJECT, 'shared/static/wasm');
+const SX_DIR = path.join(WASM_DIR, 'sx');
+
+// If called with --run-single N, run just that one test
+if (process.argv.includes('--run-single')) {
+ const idx = parseInt(process.argv[process.argv.indexOf('--run-single') + 1]);
+
+ eval(fs.readFileSync(path.join(WASM_DIR, 'sx_browser.bc.js'), 'utf8'));
+ const K = globalThis.SxKernel;
+
+ // Minimal DOM mock
+ class El {
+ constructor(t) { this.tagName=t.toUpperCase(); this.nodeName=this.tagName; this.nodeType=1; this.id=''; this.className=''; this.classList=new CL(this); this.style={}; this.attributes={}; this.children=[]; this.childNodes=[]; this.parentElement=null; this.parentNode=null; this.textContent=''; this.innerHTML=''; this._listeners={}; this.dataset={}; this.open=false; this.value=''; this.checked=false; this.disabled=false; this.type=''; this.name=''; this.selectedIndex=-1; this.options=[]; }
+ setAttribute(n,v) { this.attributes[n]=String(v); if(n==='id')this.id=v; if(n==='class'){this.className=v;this.classList._sync(v);} if(n==='value')this.value=v; if(n==='disabled')this.disabled=true; }
+ getAttribute(n) { return this.attributes[n]!==undefined?this.attributes[n]:null; }
+ removeAttribute(n) { delete this.attributes[n]; if(n==='disabled')this.disabled=false; }
+ hasAttribute(n) { return n in this.attributes; }
+ addEventListener(e,f) { if(!this._listeners[e])this._listeners[e]=[]; this._listeners[e].push(f); }
+ removeEventListener(e,f) { if(this._listeners[e])this._listeners[e]=this._listeners[e].filter(x=>x!==f); }
+ dispatchEvent(ev) { ev.target=ev.target||this; ev.currentTarget=this; const fns=[...(this._listeners[ev.type]||[])]; for(const f of fns){if(ev._si)break;try{f.call(this,ev);}catch(e){}} if(ev.bubbles&&!ev._sp&&this.parentElement){this.parentElement.dispatchEvent(ev);} return !ev.defaultPrevented; }
+ appendChild(c) { if(c.parentElement)c.parentElement.removeChild(c); c.parentElement=this; c.parentNode=this; this.children.push(c); this.childNodes.push(c); this._updateText(); return c; }
+ removeChild(c) { this.children=this.children.filter(x=>x!==c); this.childNodes=this.childNodes.filter(x=>x!==c); c.parentElement=null; c.parentNode=null; this._updateText(); return c; }
+ insertBefore(n,r) { if(n.parentElement)n.parentElement.removeChild(n); const i=this.children.indexOf(r); if(i>=0){this.children.splice(i,0,n);this.childNodes.splice(i,0,n);}else{this.children.push(n);this.childNodes.push(n);} n.parentElement=this;n.parentNode=this; return n; }
+ replaceChild(n,o) { const i=this.children.indexOf(o); if(i>=0){this.children[i]=n;this.childNodes[i]=n;} n.parentElement=this;n.parentNode=this; o.parentElement=null;o.parentNode=null; return o; }
+ querySelector(s) { return fnd(this,s); }
+ querySelectorAll(s) { return fndAll(this,s); }
+ closest(s) { let e=this; while(e){if(mt(e,s))return e; e=e.parentElement;} return null; }
+ matches(s) { return mt(this,s); }
+ contains(o) { if(o===this)return true; for(const c of this.children)if(c===o||c.contains(o))return true; return false; }
+ cloneNode(d) { const e=new El(this.tagName.toLowerCase()); Object.assign(e.attributes,this.attributes); e.id=this.id; e.className=this.className; e.classList._sync(this.className); Object.assign(e.style,this.style); e.textContent=this.textContent; e.innerHTML=this.innerHTML; e.value=this.value; if(d)for(const c of this.children)e.appendChild(c.cloneNode(true)); return e; }
+ focus(){} blur(){} click(){this.dispatchEvent(new Ev('click',{bubbles:true}));} remove(){if(this.parentElement)this.parentElement.removeChild(this);}
+ _updateText() {}
+ get firstElementChild() { return this.children[0]||null; }
+ get lastElementChild() { return this.children[this.children.length-1]||null; }
+ get nextElementSibling() { if(!this.parentElement)return null; const i=this.parentElement.children.indexOf(this); return this.parentElement.children[i+1]||null; }
+ get previousElementSibling() { if(!this.parentElement)return null; const i=this.parentElement.children.indexOf(this); return i>0?this.parentElement.children[i-1]:null; }
+ showModal(){this.open=true;this.setAttribute('open','');} show(){this.open=true;} close(){this.open=false;this.removeAttribute('open');}
+ getAnimations(){return [];} getBoundingClientRect(){return{top:0,left:0,width:100,height:100,right:100,bottom:100};} scrollIntoView(){}
+ get ownerDocument() { return document; }
+ get offsetParent() { return this.parentElement; }
+ get offsetTop() { return 0; } get offsetLeft() { return 0; }
+ get scrollTop() { return 0; } set scrollTop(v) {} get scrollLeft() { return 0; } set scrollLeft(v) {}
+ get scrollHeight() { return 100; } get scrollWidth() { return 100; }
+ get clientHeight() { return 100; } get clientWidth() { return 100; }
+ insertAdjacentHTML(pos, html) {
+ const el = parseHTMLFragment(html);
+ if (pos === 'beforeend' || pos === 'beforeEnd') this.appendChild(el);
+ else if (pos === 'afterbegin' || pos === 'afterBegin') { if (this.children.length) this.insertBefore(el, this.children[0]); else this.appendChild(el); }
+ else if (pos === 'beforebegin' || pos === 'beforeBegin') { if (this.parentElement) this.parentElement.insertBefore(el, this); }
+ else if (pos === 'afterend' || pos === 'afterEnd') { if (this.parentElement) { const i = this.parentElement.children.indexOf(this); if (i >= 0 && i < this.parentElement.children.length - 1) this.parentElement.insertBefore(el, this.parentElement.children[i+1]); else this.parentElement.appendChild(el); } }
+ }
+ }
+ class CL { constructor(e){this._el=e;this._set=new Set();} _sync(str){this._set=new Set((str||'').split(/\s+/).filter(Boolean));} add(...c){for(const x of c)this._set.add(x);this._el.className=[...this._set].join(' ');this._el.attributes['class']=this._el.className;} remove(...c){for(const x of c)this._set.delete(x);this._el.className=[...this._set].join(' ');this._el.attributes['class']=this._el.className;} toggle(c,f){if(f!==undefined){if(f)this.add(c);else this.remove(c);return f;} if(this._set.has(c)){this.remove(c);return false;}else{this.add(c);return true;}} contains(c){return this._set.has(c);} get length(){return this._set.size;} [Symbol.iterator](){return this._set[Symbol.iterator]();} }
+ class Ev { constructor(t,o={}){this.type=t;this.bubbles=o.bubbles||false;this.cancelable=o.cancelable!==false;this.defaultPrevented=false;this._sp=false;this._si=false;this.target=null;this.currentTarget=null;this.detail=o.detail||null;} preventDefault(){this.defaultPrevented=true;} stopPropagation(){this._sp=true;} stopImmediatePropagation(){this._sp=true;this._si=true;} }
+
+ function parseHTMLFragment(html) {
+ // Minimal HTML parser for test setup
+ const el = new El('div');
+ const m = html.match(/^<(\w+)([^>]*)>([\s\S]*?)<\/\1>$/);
+ if (m) {
+ const tag = m[1]; const attrs = m[2]; const inner = m[3];
+ const child = new El(tag);
+ const attrRe = /(\w[\w-]*)="([^"]*)"/g; let am;
+ while ((am = attrRe.exec(attrs))) child.setAttribute(am[1], am[2]);
+ if (inner) { child.textContent = inner; child.innerHTML = inner; }
+ return child;
+ }
+ el.innerHTML = html; el.textContent = html;
+ return el;
+ }
+
+ function mt(e,s) {
+ if(!e||!e.tagName)return false;
+ s = s.trim();
+ if(s.startsWith('#'))return e.id===s.slice(1);
+ if(s.startsWith('.'))return e.classList.contains(s.slice(1));
+ if(s.startsWith('[')) {
+ const m = s.match(/^\[([^\]=]+)(?:="([^"]*)")?\]$/);
+ if(m) return m[2] !== undefined ? e.getAttribute(m[1]) === m[2] : e.hasAttribute(m[1]);
+ }
+ if(s.includes('.')) { const [tag, cls] = s.split('.'); return e.tagName.toLowerCase() === tag && e.classList.contains(cls); }
+ if(s.includes('#')) { const [tag, id] = s.split('#'); return e.tagName.toLowerCase() === tag && e.id === id; }
+ return e.tagName.toLowerCase() === s.toLowerCase();
+ }
+ function fnd(e,s) { for(const c of(e.children||[])){if(mt(c,s))return c;const f=fnd(c,s);if(f)return f;} return null; }
+ function fndAll(e,s) { const r=[];for(const c of(e.children||[])){if(mt(c,s))r.push(c);r.push(...fndAll(c,s));}return r; }
+
+ const _body = new El('body');
+ const _html = new El('html'); _html.appendChild(_body);
+ const document = {
+ body: _body, documentElement: _html,
+ createElement(t){return new El(t);}, createElementNS(n,t){return new El(t);},
+ createDocumentFragment(){const f=new El('fragment');f.nodeType=11;return f;},
+ createTextNode(t){return{nodeType:3,textContent:t,data:t};},
+ getElementById(i){return fnd(_body,'#'+i);},
+ querySelector(s){return fnd(_body,s);}, querySelectorAll(s){return fndAll(_body,s);},
+ createEvent(t){return new Ev(t);}, addEventListener(){}, removeEventListener(){},
+ };
+ globalThis.document=document; globalThis.window=globalThis; globalThis.HTMLElement=El; globalThis.Element=El;
+ globalThis.Event=Ev; globalThis.CustomEvent=Ev; globalThis.NodeList=Array; globalThis.HTMLCollection=Array;
+ globalThis.getComputedStyle=(e)=>e?e.style:{}; globalThis.requestAnimationFrame=(f)=>{f();return 0;};
+ globalThis.cancelAnimationFrame=()=>{}; globalThis.MutationObserver=class{observe(){}disconnect(){}};
+ globalThis.ResizeObserver=class{observe(){}disconnect(){}}; globalThis.IntersectionObserver=class{observe(){}disconnect(){}};
+ globalThis.navigator={userAgent:'node'}; globalThis.location={href:'http://localhost/',pathname:'/',search:'',hash:''};
+ globalThis.history={pushState(){},replaceState(){},back(){},forward(){}};
+ globalThis.console = { ...console, error: () => {}, warn: () => {} };
+
+ K.registerNative('host-global',a=>{const n=a[0];return(n in globalThis)?globalThis[n]:null;});
+ K.registerNative('host-get',a=>{if(a[0]==null)return null;const v=a[0][a[1]];return v===undefined?null:v;});
+ K.registerNative('host-set!',a=>{if(a[0]!=null)a[0][a[1]]=a[2];return a[2];});
+ K.registerNative('host-call',a=>{const[o,m,...r]=a;if(o==null){const f=globalThis[m];return typeof f==='function'?f.apply(null,r):null;}if(o&&typeof o[m]==='function'){try{const v=o[m].apply(o,r);return v===undefined?null:v;}catch(e){return null;}}return null;});
+ K.registerNative('host-new',a=>{const C=typeof a[0]==='string'?globalThis[a[0]]:a[0];return typeof C==='function'?new C(...a.slice(1)):null;});
+ K.registerNative('host-callback',a=>{const fn=a[0];if(typeof fn==='function'&&fn.__sx_handle===undefined)return fn;if(fn&&fn.__sx_handle!==undefined)return function(){const r=K.callFn(fn,Array.from(arguments));if(globalThis._driveAsync)globalThis._driveAsync(r);return r;};return function(){};});
+ K.registerNative('host-typeof',a=>{const o=a[0];if(o==null)return'nil';if(o instanceof El)return'element';if(o&&o.nodeType===3)return'text';if(o instanceof Ev)return'event';if(o instanceof Promise)return'promise';return typeof o;});
+ K.registerNative('host-await',a=>{});
+ K.registerNative('load-library!',()=>false);
+
+ globalThis._driveAsync=function driveAsync(r,d){d=d||0;if(d>500||!r||!r.suspended)return;const req=r.request;const items=req&&(req.items||req);const op=items&&items[0];const opName=typeof op==='string'?op:(op&&op.name)||String(op);function doResume(v){try{const x=r.resume(v);driveAsync(x,d+1);}catch(e){}}if(opName==='io-sleep'||opName==='wait')doResume(null);else if(opName==='io-fetch')doResume({ok:true,text:''});else if(opName==='io-settle')doResume(null);else if(opName==='io-wait-event')doResume(null);else if(opName==='io-transition')doResume(null);};
+
+ K.eval('(define SX_VERSION "hs-test-1.0")');K.eval('(define SX_ENGINE "ocaml-vm-sandbox")');
+ K.eval('(define parse sx-parse)');K.eval('(define serialize sx-serialize)');
+
+ const WEB=['render','core-signals','signals','deps','router','page-helpers','freeze','dom','browser','adapter-html','adapter-sx','adapter-dom','boot-helpers','hypersx','engine','orchestration','boot'];
+ const HS=['hs-tokenizer','hs-parser','hs-compiler','hs-runtime','hs-integration'];
+ K.beginModuleLoad();
+ for(const mod of[...WEB,...HS]){const sp=path.join(SX_DIR,mod+'.sx');const lp=path.join(PROJECT,'lib/hyperscript',mod.replace(/^hs-/,'')+'.sx');let s;try{s=fs.existsSync(sp)?fs.readFileSync(sp,'utf8'):fs.readFileSync(lp,'utf8');}catch(e){continue;}try{K.load(s);}catch(e){process.stderr.write(`LOAD ERROR: ${mod}: ${e.message}\n`);}}
+ K.endModuleLoad();
+
+ K.eval('(define _test-registry (list))');K.eval('(define _test-suite "")');
+ K.eval('(define push-suite (fn (name) (set! _test-suite name)))');
+ K.eval('(define pop-suite (fn () (set! _test-suite "")))');
+ K.eval('(define try-call (fn (thunk) (set! _test-registry (append _test-registry (list {:suite _test-suite :thunk thunk}))) {:ok true}))');
+ K.eval('(define report-pass (fn (n) true))');
+ K.eval('(define report-fail (fn (n e) true))');
+ for(const f of['spec/harness.sx','spec/tests/test-framework.sx','spec/tests/test-hyperscript-behavioral.sx']){
+ try{K.load(fs.readFileSync(path.join(PROJECT,f),'utf8'));}catch(e){process.stderr.write(`TEST LOAD ERROR: ${f}: ${e.message}\n`);}}
+
+ const thunk=K.eval(`(get (nth _test-registry ${idx}) "thunk")`);
+ const suite=K.eval(`(get (nth _test-registry ${idx}) "suite")`)||'';
+ if(!thunk){process.stdout.write(JSON.stringify({ok:false,err:'no thunk',suite}));process.exit(0);}
+ try{const r=K.callFn(thunk,[]);if(r&&r.suspended)globalThis._driveAsync(r);process.stdout.write(JSON.stringify({ok:true,suite}));}
+ catch(e){process.stdout.write(JSON.stringify({ok:false,err:(e.message||'').slice(0,200),suite}));}
+ process.exit(0);
+}
+
+// ─── Main process ────────────────────────────────────────────────
+// First pass: load kernel to get test count and names
+eval(fs.readFileSync(path.join(WASM_DIR, 'sx_browser.bc.js'), 'utf8'));
+const K = globalThis.SxKernel;
+K.registerNative('host-global',a=>null);K.registerNative('host-get',a=>null);
+K.registerNative('host-set!',a=>null);K.registerNative('host-call',a=>null);
+K.registerNative('host-new',a=>null);K.registerNative('host-callback',a=>function(){});
+K.registerNative('host-typeof',a=>'nil');K.registerNative('host-await',a=>null);
+K.registerNative('load-library!',()=>false);
+K.eval('(define SX_VERSION "hs-test-1.0")');K.eval('(define SX_ENGINE "ocaml-vm-sandbox")');
+K.eval('(define parse sx-parse)');K.eval('(define serialize sx-serialize)');
+const WEB=['render','core-signals','signals','deps','router','page-helpers','freeze','dom','browser','adapter-html','adapter-sx','adapter-dom','boot-helpers','hypersx','engine','orchestration','boot'];
+const HS=['hs-tokenizer','hs-parser','hs-compiler','hs-runtime','hs-integration'];
+K.beginModuleLoad();
+for(const mod of[...WEB,...HS]){const sp=path.join(SX_DIR,mod+'.sx');const lp=path.join(PROJECT,'lib/hyperscript',mod.replace(/^hs-/,'')+'.sx');let s;try{s=fs.existsSync(sp)?fs.readFileSync(sp,'utf8'):fs.readFileSync(lp,'utf8');}catch(e){continue;}try{K.load(s);}catch(e){}}
+K.endModuleLoad();
+K.eval('(define _test-registry (list))');K.eval('(define _test-suite "")');
+K.eval('(define push-suite (fn (name) (set! _test-suite name)))');
+K.eval('(define pop-suite (fn () (set! _test-suite "")))');
+K.eval('(define try-call (fn (thunk) (set! _test-registry (append _test-registry (list {:suite _test-suite :thunk thunk}))) {:ok true}))');
+K.eval('(define report-pass (fn (n) true))');K.eval('(define report-fail (fn (n e) true))');
+for(const f of['spec/harness.sx','spec/tests/test-framework.sx','spec/tests/test-hyperscript-behavioral.sx']){try{K.load(fs.readFileSync(path.join(PROJECT,f),'utf8'));}catch(e){}}
+
+const testCount = K.eval('(len _test-registry)');
+const names = [];
+for(let i=0;i {
+ const child = require('child_process').fork(__filename, ['--run-single', String(i)], {
+ stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
+ timeout: TIMEOUT_MS,
+ });
+ let stdout = '';
+ child.stdout.on('data', d => stdout += d);
+ child.on('close', (code, signal) => {
+ if (signal === 'SIGTERM' || code === null) {
+ resolve({ ok: false, err: 'TIMEOUT', suite: names[i].s });
+ } else {
+ try { resolve(JSON.parse(stdout)); }
+ catch(e) { resolve({ ok: false, err: stdout.slice(0,150) || `exit ${code}`, suite: names[i].s }); }
+ }
+ });
+ child.on('error', (e) => {
+ resolve({ ok: false, err: 'FORK: ' + (e.message||'').slice(0,100), suite: names[i].s });
+ });
+ });
+}
+
+async function main() {
+ // Run in batches
+ for (let i = startFrom; i < endAt; i += CONCURRENCY) {
+ const batch = [];
+ for (let j = i; j < Math.min(i + CONCURRENCY, endAt); j++) batch.push(j);
+ const results = await Promise.all(batch.map(runTest));
+
+ for (let k = 0; k < results.length; k++) {
+ const r = results[k];
+ const idx = batch[k];
+ const suite = r.suite || names[idx].s;
+ if (!cats[suite]) cats[suite] = { p: 0, f: 0, errs: [] };
+
+ if (r.ok) { passed++; cats[suite].p++; }
+ else {
+ failed++; cats[suite].f++; cats[suite].errs.push({ name: names[idx].n, err: r.err });
+ let t = 'other';
+ if (r.err === 'TIMEOUT') t = 'timeout';
+ else if (r.err && r.err.includes('NOT IMPLEMENTED')) t = 'stub';
+ else if (r.err && r.err.includes('Assertion')) t = 'assert-fail';
+ else if (r.err && r.err.includes('Expected')) t = 'wrong-value';
+ else if (r.err && r.err.includes('Undefined symbol')) t = 'undef-sym';
+ else if (r.err && r.err.includes('Unhandled')) t = 'unhandled';
+ errTypes[t] = (errTypes[t] || 0) + 1;
+ }
+ }
+ if ((i + CONCURRENCY) % 50 < CONCURRENCY) {
+ process.stderr.write(` ${Math.min(i + CONCURRENCY, endAt)}/${endAt} (${passed} pass)...\n`);
+ }
+ }
+
+ console.log(`\nResults: ${passed}/${passed+failed} (${(100*passed/(passed+failed)).toFixed(0)}%)\n`);
+
+ console.log('By category:');
+ for (const [cat, s] of Object.entries(cats).sort((a, b) => {
+ const ra = a[1].p / (a[1].p + a[1].f); const rb = b[1].p / (b[1].p + b[1].f); return rb - ra;
+ })) {
+ const total = s.p + s.f; const pct = (100 * s.p / total).toFixed(0);
+ const mark = s.f === 0 ? `\u2713 ${s.p}` : `${s.p}/${total} (${pct}%)`;
+ console.log(` ${cat}: ${mark}`);
+ }
+
+ console.log('\nFailure types:');
+ for (const [t, n] of Object.entries(errTypes).sort((a, b) => b[1] - a[1])) console.log(` ${t}: ${n}`);
+
+ const ue = {};
+ for (const [cat, s] of Object.entries(cats)) for (const { err } of s.errs) { const e = (err || '').slice(0, 120); ue[e] = (ue[e] || 0) + 1; }
+ console.log(`\nUnique errors (${Object.keys(ue).length}):`);
+ for (const [e, n] of Object.entries(ue).sort((a, b) => b[1] - a[1]).slice(0, 30)) console.log(` [${n}x] ${e}`);
+}
+
+main().catch(e => { console.error(e); process.exit(1); });