@krate/runtime 0.5.0-beta.3 → 0.5.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/actions.js +2 -5
  2. package/dist/base-path.d.ts +7 -0
  3. package/dist/base-path.js +19 -0
  4. package/dist/base-path.test.d.ts +1 -0
  5. package/dist/base-path.test.js +88 -0
  6. package/dist/dev-overlay.js +31 -19
  7. package/dist/dev-overlay.test.js +14 -1
  8. package/dist/dom.d.ts +4 -0
  9. package/dist/dom.js +59 -15
  10. package/dist/dom.test.js +8 -0
  11. package/dist/effect-errors.test.js +37 -1
  12. package/dist/effects.js +41 -8
  13. package/dist/events.d.ts +2 -0
  14. package/dist/events.js +18 -0
  15. package/dist/index.d.ts +5 -0
  16. package/dist/krate-core.js +1 -1
  17. package/dist/krate-dev.js +27 -19
  18. package/dist/krate-f-actions.js +1 -1
  19. package/dist/krate-f-list.js +1 -1
  20. package/dist/krate-f-router-lite.js +1 -1
  21. package/dist/krate-f-router.js +1 -1
  22. package/dist/krate-features.json +1 -0
  23. package/dist/krate-hydrate-lite.js +5 -5
  24. package/dist/krate-hydrate.js +5 -5
  25. package/dist/krate-runtime.js +5 -5
  26. package/dist/krate-suspense.js +1 -1
  27. package/dist/list.js +26 -18
  28. package/dist/list.test.js +91 -0
  29. package/dist/metadata.js +3 -0
  30. package/dist/patterns.test.js +27 -0
  31. package/dist/react-effects.test.js +37 -0
  32. package/dist/router-lite.js +3 -9
  33. package/dist/router-nav.test.js +95 -0
  34. package/dist/router.js +59 -19
  35. package/dist/server-handler.d.ts +1 -0
  36. package/dist/server-handler.js +39 -5
  37. package/dist/server-handler.test.js +46 -0
  38. package/dist/server.js +2 -1
  39. package/dist/signal.js +47 -14
  40. package/dist/slots.test.js +18 -0
  41. package/dist/suspense.js +34 -2
  42. package/dist/suspense.test.js +39 -1
  43. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
- var __krate_exports=(()=>{var O=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var pe=Object.getOwnPropertyNames;var he=Object.prototype.hasOwnProperty;var Te=(e,n)=>{for(var t in n)O(e,t,{get:n[t],enumerable:!0})},we=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of pe(n))!he.call(e,r)&&r!==t&&O(e,r,{get:()=>n[r],enumerable:!(o=fe(n,r))||o.enumerable});return e};var ve=e=>we(O({},"__esModule",{value:!0}),e);var De={};Te(De,{SuspenseSignal:()=>g,__krateBoundary:()=>Be,__krateLazy:()=>Re,__krateLazyPayload:()=>Ne,__krateLazyRun:()=>Me,__krateRead:()=>Oe,__krateTransitionStarter:()=>te,__krateUse:()=>Ce,boundarySlotId:()=>le,connectActionTransitions:()=>ne,connectErrorBoundaries:()=>be,createBoundary:()=>se,createDeferredValue:()=>ce,createExternalStore:()=>de,currentBoundary:()=>ue,getBoundary:()=>q,isInTransition:()=>Z,isSuspenseSignal:()=>D,isThenable:()=>_,noteFallbackShown:()=>m,readValue:()=>Q,registerBoundary:()=>Ae,reportSuspenseError:()=>y,resetBoundaries:()=>Ee,runAsyncTransition:()=>C,setFallbackThrottle:()=>Pe,setLazyChunkImporter:()=>je,setSuspenseErrorHandler:()=>ge,startTransition:()=>xe,suspendOn:()=>$,trackThenable:()=>z,useDeferredValue:()=>Ve,useSyncExternalStore:()=>ze,useTransition:()=>Se,withReplayScope:()=>ke});var w=(...e)=>window.createSignal(...e),R=(...e)=>window.createEffect(...e),F=(...e)=>window.onCleanup(...e),G=(...e)=>window.krateGetOwner(...e),L=(...e)=>window.krateSetOwner(...e);var W=new WeakSet;function _(e){return e!=null&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}function z(e){return W.has(e)||(W.add(e),e.status==="fulfilled"||e.status==="rejected")||(e.status="pending",e.then(n=>{e.status==="pending"&&(e.status="fulfilled",e.value=n)},n=>{e.status==="pending"&&(e.status="rejected",e.reason=n)})),e}var g=class{constructor(n){this.thenable=n}};function D(e){return e instanceof g}function A(){}var ye=Symbol.for("krate.context"),S=null;function E(e,n){let t=S;S=e;try{return n()}finally{S=t}}function ke(e,n){return e.i=0,E(e,n)}function Q(e){let n=e;if(n&&(typeof n=="object"||typeof n=="function")&&typeof n.useContext=="function"&&(n.$$typeof===ye||!_(e)))return n.useContext();if(!_(e))return e;let t=e,o=S;if(o){let r=o.i++,i=o.list[r];i!==void 0&&i!==t?(t.then(A,A),t=i):o.list[r]=t}if(z(t),t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:new g(t)}var N=null;function ge(e){N=e}var j=null;function be(e){j=e}function Y(){if(j)return j;let e=globalThis;return typeof e.getOwner=="function"&&typeof e.handleError=="function"?{getOwner:e.getOwner,handleError:e.handleError}:null}function I(){let e=Y();return e?e.getOwner():null}function y(e,n,t){if(N&&N(e,n)===!0)return;let o=t?Y():null;if(o){o.handleError(e,t);return}let r=globalThis;typeof r.__krateReportError=="function"&&r.__krateReportError(e,n?n.anchor:null)===!0||console.error("[krate] uncaught error in suspended work:",e)}var M=class{constructor(){this.count=0;this.error=void 0;this.failed=!1;this.settled=!1;this.signal=null;this.pending=()=>(this.signal||(this.signal=w(!this.settled)),this.signal[0]());this.promise=new Promise((n,t)=>{this.resolve=n,this.reject=t}),this.promise.catch(A)}add(){this.count++}release(){--this.count>0||(this.settled=!0,this.signal?.[1](!1),this.failed?this.reject(this.error):this.resolve())}wait(n){this.add();let t=()=>this.release();n.then(t,t)}},k=null;function Z(){return B()!==null}function C(e,n){let t=n?.report!==!1,o=new M,r=me();o.promise.then(r,r),o.add();let i=k;k=o;let l;try{l=e()}catch(s){return o.failed=!0,o.error=s,k=i,o.release(),t&&y(s,null),o}return k=i,_(l)&&(o.add(),l.then(()=>o.release(),s=>{o.failed=!0,o.error=s,o.release(),t&&y(s,null)})),P=o,queueMicrotask(()=>{P===o&&(P=null),o.release()}),o}var ee=null;function me(){let e=ee??globalThis.__krateBeginAction;return typeof e=="function"?e():A}function ne(e){let n=e??globalThis;e?.__krateBeginAction&&(ee=e.__krateBeginAction),typeof n.setActionTransitionRunner=="function"&&n.setActionTransitionRunner(t=>{let o,r=!1,i,l=C(()=>{try{o=t()}catch(s){throw r=!0,i=s,s}return o},{report:!1});return r?Promise.reject(i):Promise.resolve(o).then(s=>l.promise.then(()=>s))})}var P=null;function B(){return k??P}function xe(e){C(e)}function te(e){let n=0;return t=>{n++,e(!0);let o=C(t),r=()=>{--n===0&&e(!1)};o.promise.then(r,r)}}function Se(){let[e,n]=w(!1);return[e,te(n)]}var oe=300,re=-1/0;function ie(){return typeof performance<"u"?performance.now():Date.now()}function m(){re=ie()}function Pe(e){oe=e}var H=class{constructor(n,t,o,r){this.pending=new Set;this.holds=0;this.scheduled=!1;this.throttle=null;this.id=n,this.anchor=t,this.content=o,this.apply=r}get pendingCount(){return this.pending.size}showingContent(){return this.content}suspend(n,t=!1){if(t&&this.content){B()?.wait(n);return}if(this.pending.has(n))return;this.pending.add(n),this.update();let o=()=>{this.pending.delete(n),this.schedule()};n.then(o,o)}hold(){this.holds++}release(){this.holds>0&&this.holds--,this.schedule()}schedule(){this.scheduled||(this.scheduled=!0,queueMicrotask(()=>{queueMicrotask(()=>{this.scheduled=!1,this.update()})}))}update(){let n=this.pending.size===0&&this.holds===0;if(n!==this.content){if(n){let t=re+oe-ie();if(t>0){this.throttle===null&&(this.throttle=setTimeout(()=>{this.throttle=null,this.update()},t));return}}else m();this.content=n,this.apply(n),n&&V&&V(this)}}},V=null;function se(e,n,t){return new H(e,t?.anchor??null,t?.initialContent??!0,n)}var b=new Map;function le(e){return"s"+e}function q(e){let n=le(e),t=globalThis,o=typeof t.findSlot=="function"?t.findSlot(n):null,r=b.get(e);if(r&&(o===null||r.anchor===o))return r;let i=typeof document<"u"?document.querySelector('template[data-kc="'+n+'"]'):null,l=!i||i.getAttribute("data-kb")!=="c",s=globalThis.krateCondActivity,c=o&&o.nodeType===8?_e(o,i,l):null,p=se(e,h=>{c&&(s&&!h&&s(n,"a"),c(h),s&&h&&s(n,"c"))},{anchor:o,initialContent:l});return!l&&o&&o.isConnected&&m(),b.set(e,p),p}V=e=>{for(let n of b.values())if(n!==e&&!n.showingContent()&&n.anchor&&n.anchor.isConnected){m();return}};function _e(e,n,t){let o="/"+(e.nodeValue||""),r=()=>{for(let d=e.nextSibling;d;d=d.nextSibling)if(d.nodeType===8&&d.nodeValue===o)return d;return null},i=()=>{let d=[],u=r();for(let a=e.nextSibling;a&&a!==u;a=a.nextSibling)d.push(a);return d},l=t?i():[],s=t?[]:i(),c=!1,f=()=>!n||c?[]:(c=!0,Array.from(n.content.childNodes)),p=new Map,h=d=>{let u=e.parentNode;if(!u)return;let a=r();for(let T of d)u.insertBefore(T,a)},x=d=>{for(let u of d)u.parentNode?.removeChild(u)};return d=>{if(d){if(x(s),l.length===0){l=f(),h(l),K();return}for(let u of l){let a=p.get(u);a!==void 0&&(typeof a=="string"?u.nodeValue=a:a[0]===""?u.style.removeProperty("display"):u.style.setProperty("display",a[0],a[1]))}p.clear();return}for(let u of l)if(!p.has(u))if(u.nodeType===1&&u.style){let a=u.style;p.set(u,[a.getPropertyValue("display"),a.getPropertyPriority("display")]),a.setProperty("display","none","important")}else u.nodeType===3&&(p.set(u,u.nodeValue||""),u.nodeValue="");s.length===0&&(s=f()),h(s),K()}}function K(){let e=globalThis.krateRefsEnter;typeof e=="function"&&e()}function Ae(e){b.set(e.id,e)}function Ee(){b.clear()}function $(e,n){let t=B()!==null;e?e.suspend(n,t):t&&B()?.wait(n)}var v=null;function ue(){return v?v.boundary:null}function Be(e,n){let t=e?q(e):null,o={boundary:t,scope:{list:[],i:0},disposers:[]},r=I();t?.hold();let i=()=>{o.scope.i=0;let l=v;v=o;let s=G();try{E(o.scope,n),v=l,L(s),t?.release()}catch(c){v=l,L(s);for(let f of o.disposers.splice(0))f();if(D(c)){c.thenable.then(i,i);return}t?.release(),y(c,t,r)}};i()}function Ce(e){let n=v,t=n?n.boundary:null,o=I(),r=n?n.scope:{list:[],i:0},i=r.i,l=E(r,e),s=r.list.slice(i,r.i),[c,f]=w(l),[p,h]=w(0),x=()=>h(a=>a+1),d=!0,u=R(()=>{p();let a=d?{list:s,i:0}:null;d=!1;try{let T=E(a,e);f(()=>T)}catch(T){if(D(T)){T.thenable.then(x,x),$(t,T.thenable);return}y(T,t,o)}});return n&&n.disposers.push(u),c}function Oe(e){return Q(e)}var U=new Map;function Re(e,n){let t=n?q(n):null,o=I();t?.hold();let r=U.get(e);if(!r){let i=t?t.anchor:null;r=i&&!i.isConnected?Le(i).then(()=>(m(),J(e))):J(e),U.set(e,r)}return r.then(()=>t?.release(),i=>{t?.release(),y(i,t,o)}),r}function Le(e){return e.isConnected||typeof MutationObserver>"u"?Promise.resolve():new Promise(n=>{let t=new MutationObserver(()=>{e.isConnected&&(t.disconnect(),n())});t.observe(document.documentElement,{childList:!0,subtree:!0})})}var X=new WeakMap;function Ne(e){let n=X.get(e);return n||(n=Promise.resolve().then(()=>e()).then(t=>{if(typeof(t&&typeof t=="object"?t.default:void 0)!="function")throw new Error("lazy: the loader did not resolve to a module with a component as its default export (resolve to { default: Component })");return t}),z(n),X.set(e,n)),n}var ae=e=>import(e);function je(e){ae=e}function J(e){try{return Promise.resolve(ae(e))}catch(n){return Promise.reject(n)}}function Me(e){e()}function He(e){setTimeout(e,0)}function ce(e,...n){let t=n.length>0,o,r,i=!1,[l,s]=w(void 0),c=()=>{i=!1,Object.is(o,r)||(r=o,s(()=>o))},f=!0;return R(()=>{if(o=e(),!(f&&(f=!1,r=t?n[0]:o,s(()=>r),!t||Object.is(r,o)))&&!Object.is(o,r)){if(Z()){c();return}i||(i=!0,He(c))}}),l}function Ve(e,...n){return typeof e=="function"?ce(e,...n):e}function de(e,n,t){let o=n();Object.is(o,n())||console.error("[krate] The result of getSnapshot should be cached to avoid an infinite loop");let[r,i]=w(o),l=()=>{let c=n();Object.is(c,o)||(o=c,i(()=>c))},s=e(l);return l(),F(()=>{typeof s=="function"&&s()}),r}function ze(e,n,t){return de(e,n,t)}ne();globalThis.__krateSuspenseHook={current:ue,suspend:(e,n)=>$(e,n)};return ve(De);})();
1
+ var __krate_exports=(()=>{var L=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var ye=Object.prototype.hasOwnProperty;var ve=(e,n)=>{for(var t in n)L(e,t,{get:n[t],enumerable:!0})},ke=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of we(n))!ye.call(e,r)&&r!==t&&L(e,r,{get:()=>n[r],enumerable:!(o=Te(n,r))||o.enumerable});return e};var be=e=>ke(L({},"__esModule",{value:!0}),e);var $e={};ve($e,{SuspenseSignal:()=>m,__krateBoundary:()=>Re,__krateLazy:()=>je,__krateLazyPayload:()=>He,__krateLazyRun:()=>ze,__krateRead:()=>Ne,__krateTransitionStarter:()=>ie,__krateUse:()=>Le,boundarySlotId:()=>ce,connectActionTransitions:()=>re,connectErrorBoundaries:()=>Se,createBoundary:()=>ue,createDeferredValue:()=>pe,createExternalStore:()=>he,currentBoundary:()=>de,getBoundary:()=>F,isInTransition:()=>te,isSuspenseSignal:()=>q,isThenable:()=>A,noteFallbackShown:()=>x,readValue:()=>ee,registerBoundary:()=>Ee,reportSuspenseError:()=>k,resetBoundaries:()=>Be,runAsyncTransition:()=>R,setFallbackThrottle:()=>Ce,setLazyChunkImporter:()=>Ve,setSuspenseErrorHandler:()=>xe,startTransition:()=>_e,suspendOn:()=>G,trackThenable:()=>I,useDeferredValue:()=>Ie,useSyncExternalStore:()=>qe,useTransition:()=>Ae,withReplayScope:()=>me});var w=(...e)=>window.createSignal(...e),N=(...e)=>window.createEffect(...e),W=(...e)=>window.onCleanup(...e),K=(...e)=>window.krateGetOwner(...e),j=(...e)=>window.krateSetOwner(...e),U=(...e)=>window.krateOnDispose(...e),M=(...e)=>window.krateCurrentScope(...e);var X=new WeakSet;function A(e){return e!=null&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}function I(e){return X.has(e)||(X.add(e),e.status==="fulfilled"||e.status==="rejected")||(e.status="pending",e.then(n=>{e.status==="pending"&&(e.status="fulfilled",e.value=n)},n=>{e.status==="pending"&&(e.status="rejected",e.reason=n)})),e}var m=class{constructor(n){this.thenable=n}};function q(e){return e instanceof m}function C(){}var ge=Symbol.for("krate.context"),P=null;function O(e,n){let t=P;P=e;try{return n()}finally{P=t}}function me(e,n){return e.i=0,O(e,n)}function ee(e){let n=e;if(n&&(typeof n=="object"||typeof n=="function")&&typeof n.useContext=="function"&&(n.$$typeof===ge||!A(e)))return n.useContext();if(!A(e))return e;let t=e,o=P;if(o){let r=o.i++,i=o.list[r];i!==void 0&&i!==t?(t.then(C,C),t=i):o.list[r]=t}if(I(t),t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:new m(t)}var H=null;function xe(e){H=e}var V=null;function Se(e){V=e}function ne(){if(V)return V;let e=globalThis;return typeof e.getOwner=="function"&&typeof e.handleError=="function"?{getOwner:e.getOwner,handleError:e.handleError}:null}function $(){let e=ne();return e?e.getOwner():null}function k(e,n,t){if(H&&H(e,n)===!0)return;let o=t?ne():null;if(o){o.handleError(e,t);return}let r=globalThis;typeof r.__krateReportError=="function"&&r.__krateReportError(e,n?n.anchor:null)===!0||console.error("[krate] uncaught error in suspended work:",e)}var z=class{constructor(){this.count=0;this.error=void 0;this.failed=!1;this.settled=!1;this.signal=null;this.pending=()=>(this.signal||(this.signal=w(!this.settled)),this.signal[0]());this.promise=new Promise((n,t)=>{this.resolve=n,this.reject=t}),this.promise.catch(C)}add(){this.count++}release(){--this.count>0||(this.settled=!0,this.signal?.[1](!1),this.failed?this.reject(this.error):this.resolve())}wait(n){this.add();let t=()=>this.release();n.then(t,t)}},b=null;function te(){return E()!==null}function R(e,n){let t=n?.report!==!1,o=new z,r=Pe();o.promise.then(r,r),o.add();let i=b;b=o;let l;try{l=e()}catch(s){return o.failed=!0,o.error=s,b=i,o.release(),t&&k(s,null),o}return b=i,A(l)&&(o.add(),l.then(()=>o.release(),s=>{o.failed=!0,o.error=s,o.release(),t&&k(s,null)})),_=o,queueMicrotask(()=>{_===o&&(_=null),o.release()}),o}var oe=null;function Pe(){let e=oe??globalThis.__krateBeginAction;return typeof e=="function"?e():C}function re(e){let n=e??globalThis;e?.__krateBeginAction&&(oe=e.__krateBeginAction),typeof n.setActionTransitionRunner=="function"&&n.setActionTransitionRunner(t=>{let o,r=!1,i,l=R(()=>{try{o=t()}catch(s){throw r=!0,i=s,s}return o},{report:!1});return r?Promise.reject(i):Promise.resolve(o).then(s=>l.promise.then(()=>s))})}var _=null;function E(){return b??_}function _e(e){R(e)}function ie(e){let n=0;return t=>{n++,e(!0);let o=R(t),r=()=>{--n===0&&e(!1)};o.promise.then(r,r)}}function Ae(){let[e,n]=w(!1);return[e,ie(n)]}var se=300,le=-1/0;function ae(){return typeof performance<"u"?performance.now():Date.now()}function x(){le=ae()}function Ce(e){se=e}var B=class{constructor(n,t,o,r){this.pending=new Set;this.holds=0;this.scheduled=!1;this.route=M();this.dead=!1;this.throttle=null;this.id=n,this.anchor=t,this.content=o,this.apply=r}get pendingCount(){return this.pending.size}showingContent(){return this.content}suspend(n,t=!1){if(t&&this.content){E()?.wait(n);return}if(this.pending.has(n))return;this.pending.add(n),this.update();let o=()=>{this.pending.delete(n),this.schedule()};n.then(o,o)}hold(){this.holds++}release(){this.holds>0&&this.holds--,this.schedule()}schedule(){this.scheduled||(this.scheduled=!0,queueMicrotask(()=>{queueMicrotask(()=>{this.scheduled=!1,this.update()})}))}update(){if(this.dead)return;let n=this.pending.size===0&&this.holds===0;if(n!==this.content){if(n){let t=le+se-ae();if(t>0){this.throttle===null&&(this.throttle=setTimeout(()=>{this.throttle=null,this.update()},t));return}}else x();this.content=n,this.apply(n),n&&D&&D(this)}}},D=null;function ue(e,n,t){return new B(e,t?.anchor??null,t?.initialContent??!0,n)}var v=new Map;function ce(e){return"s"+e}function F(e){let n=ce(e),t=globalThis,o=typeof t.findSlot=="function"?t.findSlot(n):null,r=v.get(e);if(r&&(o===null||r.anchor===o))return r;let i=typeof document<"u"?document.querySelector('template[data-kc="'+n+'"]'):null,l=!i||i.getAttribute("data-kb")!=="c",s=globalThis.krateCondActivity,c=o&&o.nodeType===8?Oe(o,i,l):null,p=ue(e,h=>{c&&(s&&!h&&s(n,"a"),c(h),s&&h&&s(n,"c"))},{anchor:o,initialContent:l});return!l&&o&&o.isConnected&&x(),v.set(e,p),p}D=e=>{for(let n of v.values())if(n!==e&&!n.showingContent()&&n.anchor&&n.anchor.isConnected){x();return}};function Oe(e,n,t){let o="/"+(e.nodeValue||""),r=()=>{for(let d=e.nextSibling;d;d=d.nextSibling)if(d.nodeType===8&&d.nodeValue===o)return d;return null},i=()=>{let d=[],a=r();for(let u=e.nextSibling;u&&u!==a;u=u.nextSibling)d.push(u);return d},l=t?i():[],s=t?[]:i(),c=!1,f=()=>!n||c?[]:(c=!0,Array.from(n.content.childNodes)),p=new Map,h=d=>{let a=e.parentNode;if(!a)return;let u=r();for(let T of d)a.insertBefore(T,u)},S=d=>{for(let a of d)a.parentNode?.removeChild(a)};return d=>{if(d){if(S(s),l.length===0){l=f(),h(l),J();return}for(let a of l){let u=p.get(a);u!==void 0&&(typeof u=="string"?a.nodeValue=u:u[0]===""?a.style.removeProperty("display"):a.style.setProperty("display",u[0],u[1]))}p.clear();return}for(let a of l)if(!p.has(a))if(a.nodeType===1&&a.style){let u=a.style;p.set(a,[u.getPropertyValue("display"),u.getPropertyPriority("display")]),u.setProperty("display","none","important")}else a.nodeType===3&&(p.set(a,a.nodeValue||""),a.nodeValue="");s.length===0&&(s=f()),h(s),J()}}function J(){let e=globalThis.krateRefsEnter;typeof e=="function"&&e()}function Ee(e){v.set(e.id,e)}function Be(){v.clear()}var g=new Set;U(e=>{for(let n of g)(e===null||e(n.route))&&(n.dead=!0);for(let[n,t]of Array.from(v))t instanceof B&&(e===null||e(t.route))&&(t.dead=!0,v.delete(n))});function G(e,n){let t=E()!==null;e?e.suspend(n,t):t&&E()?.wait(n)}var y=null;function de(){return y?y.boundary:null}function Re(e,n){let t=e?F(e):null,o={boundary:t,scope:{list:[],i:0},disposers:[],route:M(),dead:!1},r=$();t?.hold();let i=()=>{if(o.dead){g.delete(o);return}o.scope.i=0;let l=y;y=o;let s=K();try{O(o.scope,n),y=l,j(s),g.delete(o),t?.release()}catch(c){y=l,j(s);for(let f of o.disposers.splice(0))f();if(q(c)){g.add(o),c.thenable.then(i,i);return}g.delete(o),t?.release(),k(c,t,r)}};i()}function Le(e){let n=y,t=n?n.boundary:null,o=$(),r=n?n.scope:{list:[],i:0},i=r.i,l=O(r,e),s=r.list.slice(i,r.i),[c,f]=w(l),[p,h]=w(0),S=()=>h(u=>u+1),d=!0,a=N(()=>{p();let u=d?{list:s,i:0}:null;d=!1;try{let T=O(u,e);f(()=>T)}catch(T){if(q(T)){T.thenable.then(S,S),G(t,T.thenable);return}k(T,t,o)}});return n&&n.disposers.push(a),c}function Ne(e){return ee(e)}var Q=new Map;function je(e,n){let t=n?F(n):null,o=$();t?.hold();let r=Q.get(e);if(!r){let i=t?t.anchor:null;r=i&&!i.isConnected?Me(i).then(()=>(x(),Z(e))):Z(e),Q.set(e,r)}return r.then(()=>t?.release(),i=>{t?.release(),k(i,t,o)}),r}function Me(e){return e.isConnected||typeof MutationObserver>"u"?Promise.resolve():new Promise(n=>{let t=new MutationObserver(()=>{e.isConnected&&(t.disconnect(),n())});t.observe(document.documentElement,{childList:!0,subtree:!0})})}var Y=new WeakMap;function He(e){let n=Y.get(e);return n||(n=Promise.resolve().then(()=>e()).then(t=>{if(typeof(t&&typeof t=="object"?t.default:void 0)!="function")throw new Error("lazy: the loader did not resolve to a module with a component as its default export (resolve to { default: Component })");return t}),I(n),Y.set(e,n)),n}var fe=e=>import(e);function Ve(e){fe=e}function Z(e){try{return Promise.resolve(fe(e))}catch(n){return Promise.reject(n)}}function ze(e){e()}function De(e){setTimeout(e,0)}function pe(e,...n){let t=n.length>0,o,r,i=!1,[l,s]=w(void 0),c=()=>{i=!1,Object.is(o,r)||(r=o,s(()=>o))},f=!0;return N(()=>{if(o=e(),!(f&&(f=!1,r=t?n[0]:o,s(()=>r),!t||Object.is(r,o)))&&!Object.is(o,r)){if(te()){c();return}i||(i=!0,De(c))}}),l}function Ie(e,...n){return typeof e=="function"?pe(e,...n):e}function he(e,n,t){let o=n();Object.is(o,n())||console.error("[krate] The result of getSnapshot should be cached to avoid an infinite loop");let[r,i]=w(o),l=()=>{let c=n();Object.is(c,o)||(o=c,i(()=>c))},s=e(l);return l(),W(()=>{typeof s=="function"&&s()}),r}function qe(e,n,t){return he(e,n,t)}re();globalThis.__krateSuspenseHook={current:de,suspend:(e,n)=>G(e,n)};return be($e);})();
2
2
  for (const k in __krate_exports) { window[k] = __krate_exports[k]; }
package/dist/list.js CHANGED
@@ -25,6 +25,7 @@
25
25
  import { createEffect, createRoot, createSignal, onCleanup, untrack } from './signal.js';
26
26
  import { krateUnmount, krateWithOwner } from './effects.js';
27
27
  import { adoptValue, appendChild, disposeNode, insertAt, removeRest, trackEffect, withDOM, withVNodes, } from './dom.js';
28
+ import { krateMuteEvents } from './events.js';
28
29
  import { krateWithIdScope } from './use-id.js';
29
30
  /** Canonical key: explicit keys are `$` + String(key); implicit keys are the index. */
30
31
  function keyOf(keyFn, item, i) {
@@ -275,10 +276,14 @@ function update(state, items) {
275
276
  next[i] = row;
276
277
  }
277
278
  // Unmount removed rows first, so their cleanups run before new rows mount.
278
- for (let i = 0; i < oldRows.length; i++) {
279
- if (!kept[i])
280
- removeRow(oldRows[i]);
281
- }
279
+ // A browser blurs a focused node it removes; React's commit hides that from
280
+ // handlers, and so does this.
281
+ krateMuteEvents(() => {
282
+ for (let i = 0; i < oldRows.length; i++) {
283
+ if (!kept[i])
284
+ removeRow(oldRows[i]);
285
+ }
286
+ });
282
287
  // Update or adopt the rows that stay.
283
288
  for (let i = 0; i < n; i++) {
284
289
  const row = next[i];
@@ -324,21 +329,24 @@ function update(state, items) {
324
329
  const stay = new Uint8Array(n);
325
330
  for (const i of longestIncreasingSubsequence(sources))
326
331
  stay[i] = 1;
327
- let anchor = end;
328
- for (let i = n - 1; i >= 0; i--) {
329
- const row = next[i];
330
- const pending = runs[i];
331
- if (pending) {
332
- parent.insertBefore(pending, anchor);
333
- }
334
- else if (sources[i] >= 0 && !stay[i]) {
335
- moveRow(row, anchor);
332
+ // The blur and focus a move causes are not user events (see above).
333
+ krateMuteEvents(() => {
334
+ let anchor = end;
335
+ for (let i = n - 1; i >= 0; i--) {
336
+ const row = next[i];
337
+ const pending = runs[i];
338
+ if (pending) {
339
+ parent.insertBefore(pending, anchor);
340
+ }
341
+ else if (sources[i] >= 0 && !stay[i]) {
342
+ moveRow(row, anchor);
343
+ }
344
+ anchor = row.start;
336
345
  }
337
- anchor = row.start;
338
- }
339
- state.rows = next;
340
- if (restoreFocus)
341
- restoreFocus();
346
+ state.rows = next;
347
+ if (restoreFocus)
348
+ restoreFocus();
349
+ });
342
350
  }
343
351
  // Collect the server-rendered rows between the list markers. Anything else
344
352
  // between the markers (stray text, unexpected nodes) is removed.
package/dist/list.test.js CHANGED
@@ -310,6 +310,97 @@ describe('hydration adoption', () => {
310
310
  expect(root.querySelectorAll('li')).toHaveLength(1);
311
311
  });
312
312
  });
313
+ describe('focus events during list updates', () => {
314
+ // Chromium blurs a focused node it moves or removes; emulate that, since
315
+ // happy-dom does not.
316
+ function blurOnMove() {
317
+ const orig = Node.prototype.insertBefore;
318
+ Node.prototype.insertBefore = function (node, ref) {
319
+ const active = document.activeElement;
320
+ const moving = active && active !== document.body && node.nodeType === 1 && node.contains(active) ? active : null;
321
+ const out = orig.call(this, node, ref);
322
+ if (moving) {
323
+ moving.blur();
324
+ moving.dispatchEvent(new FocusEvent('focusout', { bubbles: true }));
325
+ }
326
+ return out;
327
+ };
328
+ return () => {
329
+ Node.prototype.insertBefore = orig;
330
+ };
331
+ }
332
+ it('does not fire onBlur/onFocus when a reorder moves the focused row', async () => {
333
+ const events = [];
334
+ const [items, setItems] = createSignal([1, 2, 3]);
335
+ const root = mountList(krateList(() => items(), (n) => n, (n) => h('div', { class: 'row' }, h('input', { onFocus: () => events.push('focus ' + n()), onBlur: () => events.push('blur ' + n()) })), 1).mount());
336
+ const input = root.querySelectorAll('input')[1];
337
+ input.focus();
338
+ events.length = 0;
339
+ const restore = blurOnMove();
340
+ try {
341
+ setItems([3, 2, 1]);
342
+ await tick();
343
+ }
344
+ finally {
345
+ restore();
346
+ }
347
+ expect(Array.from(root.querySelectorAll('input'))[1]).toBe(input);
348
+ expect(document.activeElement).toBe(input);
349
+ expect(events).toEqual([]);
350
+ // A real blur afterwards still reaches the handler.
351
+ input.blur();
352
+ await tick();
353
+ expect(events).toEqual(['blur 2']);
354
+ });
355
+ });
356
+ describe('nested components in adopted rows', () => {
357
+ it('orders effects children-first on mount and parent-first on removal, as for fresh rows', async () => {
358
+ const settle = async () => {
359
+ for (let i = 0; i < 3; i++)
360
+ await tick();
361
+ };
362
+ const log = [];
363
+ function Leaf(props) {
364
+ createEffectDeps(() => {
365
+ log.push('leaf ' + props.id);
366
+ return () => log.push('leaf cleanup ' + props.id);
367
+ }, () => []);
368
+ return h('i', null, () => props.id);
369
+ }
370
+ function Row(props) {
371
+ createEffectDeps(() => {
372
+ log.push('row ' + props.id);
373
+ return () => log.push('row cleanup ' + props.id);
374
+ }, () => []);
375
+ return h('li', null, krateList(() => [1], (n) => props.id + n, () => h(Leaf, { get id() { return props.id; } }), 1));
376
+ }
377
+ const render = (n) => h(Row, { get id() { return n(); } });
378
+ // A fresh list is the reference.
379
+ const [fresh, setFresh] = createSignal(['a', 'b']);
380
+ mountList(krateList(() => fresh(), (n) => n, render, 1).mount());
381
+ await settle();
382
+ const freshMount = log.splice(0);
383
+ setFresh(['b']);
384
+ await settle();
385
+ const freshRemove = log.splice(0);
386
+ expect(freshMount).toEqual(['leaf a', 'row a', 'leaf b', 'row b']);
387
+ expect(freshRemove).toEqual(['row cleanup a', 'leaf cleanup a']);
388
+ // The same list adopted from server-rendered HTML must behave alike.
389
+ document.body.innerHTML = '';
390
+ const root = document.createElement('ul');
391
+ root.innerHTML =
392
+ '<!--k:Q--><!--k:Q:$a--><li><!--k:R--><!--k:R:$a1--><i>a</i><!--/k:R:$a1--><!--/k:R--></li><!--/k:Q:$a-->' +
393
+ '<!--k:Q:$b--><li><!--k:S--><!--k:S:$b1--><i>b</i><!--/k:S:$b1--><!--/k:S--></li><!--/k:Q:$b--><!--/k:Q-->';
394
+ document.body.appendChild(root);
395
+ const [adopted, setAdopted] = createSignal(['a', 'b']);
396
+ krateBindList(root.firstChild, () => adopted(), (n) => n, render, 1);
397
+ await settle();
398
+ expect(log.splice(0)).toEqual(freshMount);
399
+ setAdopted(['b']);
400
+ await settle();
401
+ expect(log.splice(0)).toEqual(freshRemove);
402
+ });
403
+ });
313
404
  describe('list performance', () => {
314
405
  it('reorders, inserts and removes 1000 rows in roughly linear time', async () => {
315
406
  const make = (n) => Array.from({ length: n }, (_, i) => ({ id: i, label: 'row ' + i }));
package/dist/metadata.js CHANGED
@@ -170,6 +170,9 @@ function resolveBaseJoin(value, base) {
170
170
  // metadataBase's path is a prefix: "/docs" + "/a" = "/docs/a".
171
171
  const prefix = b.pathname.replace(/\/$/, '');
172
172
  const path = s.startsWith('/') ? s : '/' + s;
173
+ // A convention image URL already carries the site base path.
174
+ if (prefix && (path === prefix || path.startsWith(prefix + '/')))
175
+ return b.origin + path;
173
176
  return b.origin + prefix + path;
174
177
  }
175
178
  catch {
@@ -59,6 +59,33 @@ describe('krateSpread', () => {
59
59
  expect(clicks).toBe(1);
60
60
  });
61
61
  });
62
+ describe('krateSpread with function values', () => {
63
+ it('writes no attribute for a function and binds on* handlers as events', async () => {
64
+ const [n, setN] = createSignal(1);
65
+ const el = document.createElement('div');
66
+ document.body.appendChild(el);
67
+ let clicks = 0;
68
+ const props = { id: 'd', title: n, 'data-count': () => 1, onClick: () => clicks++, onclick2: () => 0 };
69
+ krateSpread(el, () => props);
70
+ expect(el.id).toBe('d');
71
+ expect(el.hasAttribute('title')).toBe(false);
72
+ expect(el.hasAttribute('data-count')).toBe(false);
73
+ expect(el.hasAttribute('onclick2')).toBe(false);
74
+ expect(el.outerHTML).not.toContain('=>');
75
+ el.dispatchEvent(new Event('click', { bubbles: true }));
76
+ expect(clicks).toBe(1);
77
+ // A string that later becomes a function drops the attribute.
78
+ const [v, setV] = createSignal('t');
79
+ const el2 = document.createElement('div');
80
+ document.body.appendChild(el2);
81
+ krateSpread(el2, () => ({ title: v() }));
82
+ expect(el2.getAttribute('title')).toBe('t');
83
+ setV(() => () => 5);
84
+ await tick();
85
+ expect(el2.hasAttribute('title')).toBe(false);
86
+ setN(2);
87
+ });
88
+ });
62
89
  describe('krateContextRows', () => {
63
90
  it('shows live provider values to rows created under it', async () => {
64
91
  const Sel = createContext('');
@@ -1,6 +1,7 @@
1
1
  import { describe, it, expect, beforeEach } from 'vitest';
2
2
  import { useEffect, useLayoutEffect, useInsertionEffect, useState, useReducer, useMemo, useCallback, useImperativeHandle, createElement, } from './react';
3
3
  import { disposeAll } from './signal';
4
+ import { flushPassive } from './effects';
4
5
  import { disposeNode } from './dom';
5
6
  const tick = () => new Promise((r) => setTimeout(r, 0));
6
7
  async function settle() {
@@ -93,4 +94,40 @@ describe('React compat hooks (unlowered code paths)', () => {
93
94
  disposeNode(node);
94
95
  expect(ref.current).toBe(null);
95
96
  });
97
+ it('a passive cleanup that throws does not drop the effects queued behind it', async () => {
98
+ const log = [];
99
+ let set;
100
+ const A = () => {
101
+ const [n, s] = useState(0);
102
+ set = s;
103
+ useEffect(() => {
104
+ log.push('A setup ' + n());
105
+ return () => {
106
+ log.push('A cleanup');
107
+ throw new Error('cleanup boom');
108
+ };
109
+ }, [n]);
110
+ return createElement('i', null);
111
+ };
112
+ const B = () => {
113
+ const [m] = useState(0);
114
+ useEffect(() => {
115
+ log.push('B setup');
116
+ return () => void log.push('B cleanup');
117
+ }, [m]);
118
+ return createElement('b', null);
119
+ };
120
+ createElement('div', null, createElement(A, null), createElement(B, null));
121
+ await settle();
122
+ set(1);
123
+ // The passive phase reports the error after running everything queued.
124
+ let failure;
125
+ const onError = (e) => (failure = e);
126
+ process.once('uncaughtException', onError);
127
+ await settle();
128
+ process.off('uncaughtException', onError);
129
+ expect(String(failure)).toContain('cleanup boom');
130
+ expect(log).toEqual(['A setup 0', 'B setup', 'A cleanup', 'A setup 1']);
131
+ flushPassive();
132
+ });
96
133
  });
@@ -1,13 +1,7 @@
1
1
  // Router API for sites with the SPA router disabled (`spa: false`). Every
2
2
  // navigation is a full document load; the API surface matches router.ts so
3
3
  // application code (and the Next.js migration shim) works unchanged.
4
- function basePath() {
5
- const cfg = globalThis.__KRATE_CFG__;
6
- const bp = (cfg && cfg.basePath) || '';
7
- if (!bp || bp === '/')
8
- return '';
9
- return '/' + bp.replace(/^\/+|\/+$/g, '');
10
- }
4
+ import { basePath, withBase } from './base-path.js';
11
5
  export function getNavigationState() {
12
6
  if (typeof location === 'undefined')
13
7
  return { url: '', pathname: '/', search: '', hash: '', status: 'idle' };
@@ -39,9 +33,9 @@ export function navigate(url, opts = {}) {
39
33
  if (typeof location === 'undefined')
40
34
  return true;
41
35
  if (opts.replace)
42
- location.replace(url);
36
+ location.replace(withBase(url));
43
37
  else
44
- location.assign(url);
38
+ location.assign(withBase(url));
45
39
  return true;
46
40
  }
47
41
  export const krateRouter = {
@@ -311,6 +311,36 @@ describe('races', () => {
311
311
  expect(location.pathname).toBe('/about');
312
312
  });
313
313
  });
314
+ describe('in-document steps while a page loads', () => {
315
+ it('a hash link cancels the navigation still loading', async () => {
316
+ let open;
317
+ routes['/slow'] = { body: page('Slow', '<h1>Slow</h1>'), gate: new Promise((r) => (open = r)) };
318
+ const loading = krateRouter.push('/slow');
319
+ await settle();
320
+ await krateRouter.push('/#top');
321
+ open();
322
+ await loading;
323
+ await settle();
324
+ expect(location.pathname + location.hash).toBe('/#top');
325
+ expect(document.querySelector('#root h1').textContent).toBe('Home');
326
+ expect(krateRouter.getState().status).toBe('idle');
327
+ });
328
+ it('going back over a hash entry cancels the navigation still loading', async () => {
329
+ await krateRouter.push('/#a');
330
+ await krateRouter.push('/#b');
331
+ let open;
332
+ routes['/slow'] = { body: page('Slow', '<h1>Slow</h1>'), gate: new Promise((r) => (open = r)) };
333
+ const loading = krateRouter.push('/slow');
334
+ await settle();
335
+ history.back();
336
+ await settle();
337
+ open();
338
+ await loading;
339
+ await settle();
340
+ expect(location.pathname + location.hash).toBe('/#a');
341
+ expect(document.querySelector('#root h1').textContent).toBe('Home');
342
+ });
343
+ });
314
344
  describe('prefetch cache', () => {
315
345
  it('serves a prefetched document once, then refetches', async () => {
316
346
  await krateRouter.prefetch('/about');
@@ -352,6 +382,29 @@ describe('prefetch cache', () => {
352
382
  await krateRouter.push('/about');
353
383
  expect(fetchMock).toHaveBeenCalledTimes(2);
354
384
  });
385
+ it('a prefetch in flight when the cache is invalidated does not repopulate it', async () => {
386
+ let release;
387
+ routes['/about'].gate = new Promise((r) => (release = r));
388
+ const inflight = krateRouter.prefetch('/about');
389
+ await settle();
390
+ invalidatePrefetchCache();
391
+ release();
392
+ await inflight;
393
+ await krateRouter.push('/about');
394
+ // The stale response was dropped, so navigating fetched again.
395
+ expect(fetchMock).toHaveBeenCalledTimes(2);
396
+ });
397
+ it('invalidating one URL also drops its prefetch in flight', async () => {
398
+ let release;
399
+ routes['/about'].gate = new Promise((r) => (release = r));
400
+ const inflight = krateRouter.prefetch('/about');
401
+ await settle();
402
+ invalidatePrefetchCache('/about');
403
+ release();
404
+ await inflight;
405
+ await krateRouter.push('/about');
406
+ expect(fetchMock).toHaveBeenCalledTimes(2);
407
+ });
355
408
  it('does not cache error responses', async () => {
356
409
  routes['/missing'] = { status: 404, body: page('Not found', '') };
357
410
  await krateRouter.prefetch('/missing');
@@ -462,3 +515,45 @@ describe('fallback fade and reduced motion', () => {
462
515
  expect(document.querySelector('#root h1').textContent).toBe('About');
463
516
  });
464
517
  });
518
+ describe('inline boot scripts', () => {
519
+ const bootPage = (title) => page(title, `<h1>${title}</h1>${link('/', 'Home')}<script data-krate-boot>window.__boots=1;</script>`);
520
+ // happy-dom does not execute inline scripts: count the ones handed to the document.
521
+ let ran;
522
+ beforeEach(() => {
523
+ ran = [];
524
+ const append = document.head.appendChild.bind(document.head);
525
+ vi.spyOn(document.head, 'appendChild').mockImplementation(((node) => {
526
+ if (node instanceof HTMLScriptElement && !node.src)
527
+ ran.push(node.text);
528
+ return append(node);
529
+ }));
530
+ });
531
+ afterEach(() => vi.restoreAllMocks());
532
+ it('runs a boot script of the new page once, not on every visit', async () => {
533
+ routes['/aria'] = { body: bootPage('Aria') };
534
+ routes['/aria2'] = { body: bootPage('Aria2') };
535
+ await krateRouter.push('/aria');
536
+ await settle();
537
+ expect(ran).toEqual(['window.__boots=1;']);
538
+ await krateRouter.push('/aria2');
539
+ await krateRouter.push('/about');
540
+ await krateRouter.push('/aria');
541
+ await settle();
542
+ expect(ran).toEqual(['window.__boots=1;']);
543
+ });
544
+ it('does not rerun the boot script the first document already ran', async () => {
545
+ destroyRouter();
546
+ document.body.innerHTML += '<script data-krate-boot>window.__boots=1;</script>';
547
+ initRouter();
548
+ routes['/aria'] = { body: bootPage('Aria') };
549
+ await krateRouter.push('/aria');
550
+ await settle();
551
+ expect(ran).toEqual([]);
552
+ });
553
+ it('leaves ordinary inline scripts alone', async () => {
554
+ routes['/plain'] = { body: page('Plain', '<h1>Plain</h1><script>window.__boots=99;</script>') };
555
+ await krateRouter.push('/plain');
556
+ await settle();
557
+ expect(ran).toEqual([]);
558
+ });
559
+ });
package/dist/router.js CHANGED
@@ -5,6 +5,7 @@
5
5
  // place. All router state lives at module scope so `reinitRouter()` (called
6
6
  // by every page's hydration script) only refreshes per-page bindings and never
7
7
  // loses the prefetch cache, saved scroll positions or the in-flight navigation.
8
+ import { basePath, withBase } from './base-path.js';
8
9
  /**
9
10
  * The shared runtime chunk is loaded once and must persist across SPA
10
11
  * navigations. Page-specific hydration scripts, in contrast, must be
@@ -15,13 +16,6 @@ const RUNTIME_CHUNK_RE = /\/chunks\/runtime\.[^/]+\.js$/;
15
16
  function runtimeConfig() {
16
17
  return globalThis.__KRATE_CFG__ || {};
17
18
  }
18
- /** Normalizes the configured base path to "" or "/prefix" (no trailing slash). */
19
- function basePath() {
20
- const bp = runtimeConfig().basePath || '';
21
- if (!bp || bp === '/')
22
- return '';
23
- return '/' + bp.replace(/^\/+|\/+$/g, '');
24
- }
25
19
  /** Strips the base path from a pathname so route comparisons are consistent. */
26
20
  function stripBase(pathname) {
27
21
  const bp = basePath();
@@ -276,11 +270,16 @@ function cacheTake(key) {
276
270
  * `krate:revalidate` event.
277
271
  */
278
272
  export function invalidatePrefetchCache(url) {
273
+ // A prefetch still in flight started before the data changed: forgetting it
274
+ // keeps its (stale) response out of the cache.
279
275
  if (url === undefined) {
280
276
  prefetchCache.clear();
277
+ prefetchInflight.clear();
281
278
  return;
282
279
  }
283
- prefetchCache.delete(cacheKey(url));
280
+ const key = cacheKey(url);
281
+ prefetchCache.delete(key);
282
+ prefetchInflight.delete(key);
284
283
  }
285
284
  function isHTMLType(ct) {
286
285
  return /text\/html|application\/xhtml\+xml/i.test(ct);
@@ -318,6 +317,9 @@ function prefetchPage(url) {
318
317
  const html = await res.text();
319
318
  if (!(isHTMLType(ct) || (ct === '' && looksLikeHTML(html))))
320
319
  return;
320
+ // Invalidated while in flight: the response is stale.
321
+ if (prefetchInflight.get(key) !== p)
322
+ return;
321
323
  cachePut(key, { html, url: finalUrl, status: res.status, at: now() });
322
324
  const loaded = new Set();
323
325
  document.querySelectorAll('script[src]').forEach((s) => loaded.add(s.src));
@@ -329,7 +331,8 @@ function prefetchPage(url) {
329
331
  // errors through krate:navigate-error.
330
332
  })
331
333
  .finally(() => {
332
- prefetchInflight.delete(key);
334
+ if (prefetchInflight.get(key) === p)
335
+ prefetchInflight.delete(key);
333
336
  });
334
337
  prefetchInflight.set(key, p);
335
338
  return p;
@@ -436,14 +439,15 @@ function setupSpeculationRules() {
436
439
  try {
437
440
  const script = document.createElement('script');
438
441
  script.type = 'speculationrules';
442
+ const bp = basePath();
439
443
  script.textContent = JSON.stringify({
440
444
  prefetch: [
441
445
  {
442
446
  where: {
443
447
  and: [
444
- { href_matches: '/*' },
445
- { not: { href_matches: '/__krate/*' } },
446
- { not: { href_matches: '/api/*' } },
448
+ { href_matches: bp + '/*' },
449
+ { not: { href_matches: bp + '/__krate/*' } },
450
+ { not: { href_matches: bp + '/api/*' } },
447
451
  ],
448
452
  },
449
453
  eagerness: 'moderate',
@@ -658,6 +662,22 @@ function loadScript(script) {
658
662
  document.body.appendChild(s);
659
663
  });
660
664
  }
665
+ // Inline boot scripts (data-krate-boot: the CSS ARIA enhancer and the :has()
666
+ // shim) are emitted into the page that needs them. A soft navigation parses
667
+ // but never runs inline scripts, so each distinct one runs here, once.
668
+ const bootRan = new Set();
669
+ function runBootScripts(root) {
670
+ root.querySelectorAll('script[data-krate-boot]').forEach((s) => {
671
+ const code = s.textContent || '';
672
+ if (!code || bootRan.has(code))
673
+ return;
674
+ bootRan.add(code);
675
+ const el = document.createElement('script');
676
+ el.text = code;
677
+ document.head.appendChild(el);
678
+ el.remove();
679
+ });
680
+ }
661
681
  // Scroll, focus, announcements
662
682
  function hashTarget(hash) {
663
683
  if (!hash || hash === '#')
@@ -992,6 +1012,7 @@ async function commitDocument(loaded, req, seq) {
992
1012
  // Page scripts re-run against the new DOM; the hydration code of kept
993
1013
  // layouts is skipped (krateEnterScope) because their bindings are live.
994
1014
  document.querySelectorAll('script[data-krate-spa]').forEach((s) => s.remove());
1015
+ runBootScripts(doc);
995
1016
  const srcs = scriptsToLoad(doc, url);
996
1017
  keepScopes(plan.skip);
997
1018
  const results = await Promise.all(srcs.map(loadScript));
@@ -1419,6 +1440,7 @@ async function runIntercept(req, hit) {
1419
1440
  document.head.appendChild(link);
1420
1441
  });
1421
1442
  setSlotInfo(hit.slot.key, { ...hit.slot, scope: frag.scope, src: 'intercept' });
1443
+ runBootScripts(doc);
1422
1444
  const state = { __krate: '', state: req.state === undefined ? null : req.state, __kint: { key: hit.slot.key, base: docPath } };
1423
1445
  if (req.kind === 'push') {
1424
1446
  currentKey = newKey();
@@ -1477,8 +1499,22 @@ function restoreSnapshot(snap, key) {
1477
1499
  function sameDocument(url) {
1478
1500
  return pathOf(url) === renderedPath;
1479
1501
  }
1502
+ // A newer in-document step (a hash link, or back/forward over a hash entry)
1503
+ // supersedes a page navigation still loading: it must not swap the page in
1504
+ // afterwards.
1505
+ function cancelPending() {
1506
+ if (status !== 'loading')
1507
+ return;
1508
+ navSeq++;
1509
+ if (pendingAbort)
1510
+ pendingAbort.abort();
1511
+ pendingAbort = undefined;
1512
+ endTransition();
1513
+ setStatus('idle');
1514
+ }
1480
1515
  /** In-document navigation: only the hash (or nothing) changes. */
1481
1516
  function hashNavigate(url, req) {
1517
+ cancelPending();
1482
1518
  saveScroll(currentKey);
1483
1519
  if (url !== location.href || req.state !== undefined) {
1484
1520
  if (req.kind === 'replace') {
@@ -1592,6 +1628,7 @@ function popstateHandler(e) {
1592
1628
  const url = location.href;
1593
1629
  if (pathOf(url) === renderedPath) {
1594
1630
  // Hash-only history step within the rendered document.
1631
+ cancelPending();
1595
1632
  currentKey = key || currentKey;
1596
1633
  const saved = key ? scrollPositions.get(key) : undefined;
1597
1634
  if (saved !== undefined)
@@ -1670,18 +1707,18 @@ function refresh() {
1670
1707
  function push(url, opts = {}) {
1671
1708
  if (!initialized) {
1672
1709
  if (typeof location !== 'undefined')
1673
- location.assign(url);
1710
+ location.assign(withBase(url));
1674
1711
  return Promise.resolve();
1675
1712
  }
1676
- return start({ url, kind: 'push', scroll: opts.scroll !== false, state: opts.state });
1713
+ return start({ url: withBase(url), kind: 'push', scroll: opts.scroll !== false, state: opts.state });
1677
1714
  }
1678
1715
  function replace(url, opts = {}) {
1679
1716
  if (!initialized) {
1680
1717
  if (typeof location !== 'undefined')
1681
- location.replace(url);
1718
+ location.replace(withBase(url));
1682
1719
  return Promise.resolve();
1683
1720
  }
1684
- return start({ url, kind: 'replace', scroll: opts.scroll !== false, state: opts.state });
1721
+ return start({ url: withBase(url), kind: 'replace', scroll: opts.scroll !== false, state: opts.state });
1685
1722
  }
1686
1723
  /**
1687
1724
  * The router API. Every navigation method resolves once the new route's DOM
@@ -1710,7 +1747,7 @@ export const krateRouter = {
1710
1747
  return Promise.resolve();
1711
1748
  let u;
1712
1749
  try {
1713
- u = new URL(url, location.href);
1750
+ u = new URL(withBase(url), location.href);
1714
1751
  }
1715
1752
  catch {
1716
1753
  return Promise.resolve();
@@ -1735,9 +1772,9 @@ export function navigate(url, opts = {}) {
1735
1772
  }
1736
1773
  if (typeof location !== 'undefined') {
1737
1774
  if (opts.replace)
1738
- location.replace(url);
1775
+ location.replace(withBase(url));
1739
1776
  else
1740
- location.assign(url);
1777
+ location.assign(withBase(url));
1741
1778
  }
1742
1779
  return true;
1743
1780
  }
@@ -1749,6 +1786,8 @@ export function initRouter() {
1749
1786
  return;
1750
1787
  }
1751
1788
  initialized = true;
1789
+ // The first document ran its own boot scripts.
1790
+ document.querySelectorAll('script[data-krate-boot]').forEach((s) => bootRan.add(s.textContent || ''));
1752
1791
  renderedPath = pathOf(location.href);
1753
1792
  currentChain = readRouteChain(document);
1754
1793
  docPath = renderedPath;
@@ -1812,6 +1851,7 @@ export function destroyRouter() {
1812
1851
  prefetchInflight.clear();
1813
1852
  scrollPositions.clear();
1814
1853
  errorPageCache.clear();
1854
+ bootRan.clear();
1815
1855
  listeners.clear();
1816
1856
  status = 'idle';
1817
1857
  loadingOverlay = [];