@krate/runtime 0.5.0-beta.2 → 0.5.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dev-overlay.js +31 -19
- package/dist/dev-overlay.test.js +14 -1
- package/dist/dom.d.ts +4 -0
- package/dist/dom.js +44 -13
- package/dist/dom.test.js +8 -0
- package/dist/effect-errors.test.js +37 -1
- package/dist/effects.js +41 -8
- package/dist/events.d.ts +2 -0
- package/dist/events.js +18 -0
- package/dist/krate-core.js +1 -1
- package/dist/krate-dev.js +27 -19
- package/dist/krate-f-list.js +1 -1
- package/dist/krate-f-router.js +1 -1
- package/dist/krate-features.json +1 -0
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-runtime.js +5 -5
- package/dist/krate-suspense.js +1 -1
- package/dist/list.js +26 -18
- package/dist/list.test.js +91 -0
- package/dist/patterns.test.js +27 -0
- package/dist/react-effects.test.js +37 -0
- package/dist/router-nav.test.js +95 -0
- package/dist/router.js +47 -2
- package/dist/server-handler.js +9 -3
- package/dist/server-handler.test.js +13 -0
- package/dist/signal.js +47 -14
- package/dist/slots.test.js +18 -0
- package/dist/suspense.js +34 -2
- package/dist/suspense.test.js +39 -1
- package/package.json +1 -1
package/dist/krate-suspense.js
CHANGED
|
@@ -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
|
-
|
|
279
|
-
|
|
280
|
-
|
|
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
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
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
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
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/patterns.test.js
CHANGED
|
@@ -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
|
});
|
package/dist/router-nav.test.js
CHANGED
|
@@ -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
|
@@ -276,11 +276,16 @@ function cacheTake(key) {
|
|
|
276
276
|
* `krate:revalidate` event.
|
|
277
277
|
*/
|
|
278
278
|
export function invalidatePrefetchCache(url) {
|
|
279
|
+
// A prefetch still in flight started before the data changed: forgetting it
|
|
280
|
+
// keeps its (stale) response out of the cache.
|
|
279
281
|
if (url === undefined) {
|
|
280
282
|
prefetchCache.clear();
|
|
283
|
+
prefetchInflight.clear();
|
|
281
284
|
return;
|
|
282
285
|
}
|
|
283
|
-
|
|
286
|
+
const key = cacheKey(url);
|
|
287
|
+
prefetchCache.delete(key);
|
|
288
|
+
prefetchInflight.delete(key);
|
|
284
289
|
}
|
|
285
290
|
function isHTMLType(ct) {
|
|
286
291
|
return /text\/html|application\/xhtml\+xml/i.test(ct);
|
|
@@ -318,6 +323,9 @@ function prefetchPage(url) {
|
|
|
318
323
|
const html = await res.text();
|
|
319
324
|
if (!(isHTMLType(ct) || (ct === '' && looksLikeHTML(html))))
|
|
320
325
|
return;
|
|
326
|
+
// Invalidated while in flight: the response is stale.
|
|
327
|
+
if (prefetchInflight.get(key) !== p)
|
|
328
|
+
return;
|
|
321
329
|
cachePut(key, { html, url: finalUrl, status: res.status, at: now() });
|
|
322
330
|
const loaded = new Set();
|
|
323
331
|
document.querySelectorAll('script[src]').forEach((s) => loaded.add(s.src));
|
|
@@ -329,7 +337,8 @@ function prefetchPage(url) {
|
|
|
329
337
|
// errors through krate:navigate-error.
|
|
330
338
|
})
|
|
331
339
|
.finally(() => {
|
|
332
|
-
prefetchInflight.
|
|
340
|
+
if (prefetchInflight.get(key) === p)
|
|
341
|
+
prefetchInflight.delete(key);
|
|
333
342
|
});
|
|
334
343
|
prefetchInflight.set(key, p);
|
|
335
344
|
return p;
|
|
@@ -658,6 +667,22 @@ function loadScript(script) {
|
|
|
658
667
|
document.body.appendChild(s);
|
|
659
668
|
});
|
|
660
669
|
}
|
|
670
|
+
// Inline boot scripts (data-krate-boot: the CSS ARIA enhancer and the :has()
|
|
671
|
+
// shim) are emitted into the page that needs them. A soft navigation parses
|
|
672
|
+
// but never runs inline scripts, so each distinct one runs here, once.
|
|
673
|
+
const bootRan = new Set();
|
|
674
|
+
function runBootScripts(root) {
|
|
675
|
+
root.querySelectorAll('script[data-krate-boot]').forEach((s) => {
|
|
676
|
+
const code = s.textContent || '';
|
|
677
|
+
if (!code || bootRan.has(code))
|
|
678
|
+
return;
|
|
679
|
+
bootRan.add(code);
|
|
680
|
+
const el = document.createElement('script');
|
|
681
|
+
el.text = code;
|
|
682
|
+
document.head.appendChild(el);
|
|
683
|
+
el.remove();
|
|
684
|
+
});
|
|
685
|
+
}
|
|
661
686
|
// Scroll, focus, announcements
|
|
662
687
|
function hashTarget(hash) {
|
|
663
688
|
if (!hash || hash === '#')
|
|
@@ -992,6 +1017,7 @@ async function commitDocument(loaded, req, seq) {
|
|
|
992
1017
|
// Page scripts re-run against the new DOM; the hydration code of kept
|
|
993
1018
|
// layouts is skipped (krateEnterScope) because their bindings are live.
|
|
994
1019
|
document.querySelectorAll('script[data-krate-spa]').forEach((s) => s.remove());
|
|
1020
|
+
runBootScripts(doc);
|
|
995
1021
|
const srcs = scriptsToLoad(doc, url);
|
|
996
1022
|
keepScopes(plan.skip);
|
|
997
1023
|
const results = await Promise.all(srcs.map(loadScript));
|
|
@@ -1419,6 +1445,7 @@ async function runIntercept(req, hit) {
|
|
|
1419
1445
|
document.head.appendChild(link);
|
|
1420
1446
|
});
|
|
1421
1447
|
setSlotInfo(hit.slot.key, { ...hit.slot, scope: frag.scope, src: 'intercept' });
|
|
1448
|
+
runBootScripts(doc);
|
|
1422
1449
|
const state = { __krate: '', state: req.state === undefined ? null : req.state, __kint: { key: hit.slot.key, base: docPath } };
|
|
1423
1450
|
if (req.kind === 'push') {
|
|
1424
1451
|
currentKey = newKey();
|
|
@@ -1477,8 +1504,22 @@ function restoreSnapshot(snap, key) {
|
|
|
1477
1504
|
function sameDocument(url) {
|
|
1478
1505
|
return pathOf(url) === renderedPath;
|
|
1479
1506
|
}
|
|
1507
|
+
// A newer in-document step (a hash link, or back/forward over a hash entry)
|
|
1508
|
+
// supersedes a page navigation still loading: it must not swap the page in
|
|
1509
|
+
// afterwards.
|
|
1510
|
+
function cancelPending() {
|
|
1511
|
+
if (status !== 'loading')
|
|
1512
|
+
return;
|
|
1513
|
+
navSeq++;
|
|
1514
|
+
if (pendingAbort)
|
|
1515
|
+
pendingAbort.abort();
|
|
1516
|
+
pendingAbort = undefined;
|
|
1517
|
+
endTransition();
|
|
1518
|
+
setStatus('idle');
|
|
1519
|
+
}
|
|
1480
1520
|
/** In-document navigation: only the hash (or nothing) changes. */
|
|
1481
1521
|
function hashNavigate(url, req) {
|
|
1522
|
+
cancelPending();
|
|
1482
1523
|
saveScroll(currentKey);
|
|
1483
1524
|
if (url !== location.href || req.state !== undefined) {
|
|
1484
1525
|
if (req.kind === 'replace') {
|
|
@@ -1592,6 +1633,7 @@ function popstateHandler(e) {
|
|
|
1592
1633
|
const url = location.href;
|
|
1593
1634
|
if (pathOf(url) === renderedPath) {
|
|
1594
1635
|
// Hash-only history step within the rendered document.
|
|
1636
|
+
cancelPending();
|
|
1595
1637
|
currentKey = key || currentKey;
|
|
1596
1638
|
const saved = key ? scrollPositions.get(key) : undefined;
|
|
1597
1639
|
if (saved !== undefined)
|
|
@@ -1749,6 +1791,8 @@ export function initRouter() {
|
|
|
1749
1791
|
return;
|
|
1750
1792
|
}
|
|
1751
1793
|
initialized = true;
|
|
1794
|
+
// The first document ran its own boot scripts.
|
|
1795
|
+
document.querySelectorAll('script[data-krate-boot]').forEach((s) => bootRan.add(s.textContent || ''));
|
|
1752
1796
|
renderedPath = pathOf(location.href);
|
|
1753
1797
|
currentChain = readRouteChain(document);
|
|
1754
1798
|
docPath = renderedPath;
|
|
@@ -1812,6 +1856,7 @@ export function destroyRouter() {
|
|
|
1812
1856
|
prefetchInflight.clear();
|
|
1813
1857
|
scrollPositions.clear();
|
|
1814
1858
|
errorPageCache.clear();
|
|
1859
|
+
bootRan.clear();
|
|
1815
1860
|
listeners.clear();
|
|
1816
1861
|
status = 'idle';
|
|
1817
1862
|
loadingOverlay = [];
|
package/dist/server-handler.js
CHANGED
|
@@ -326,9 +326,15 @@ export function createKrateHandler(options) {
|
|
|
326
326
|
const p = rs.path;
|
|
327
327
|
if (p.startsWith("/__krate/") && !p.startsWith("/__krate/action/"))
|
|
328
328
|
return null;
|
|
329
|
-
|
|
330
|
-
if (!data.hasMiddleware || !mod || typeof mod.middleware !== "function")
|
|
329
|
+
if (!data.hasMiddleware)
|
|
331
330
|
return null;
|
|
331
|
+
const mod = modules.middleware;
|
|
332
|
+
// The named export, then the default one, as the other runtimes do. The app
|
|
333
|
+
// has middleware, so a module with no handler must not let requests through.
|
|
334
|
+
const handler = typeof mod?.middleware === "function" ? mod.middleware : mod?.default;
|
|
335
|
+
if (typeof handler !== "function") {
|
|
336
|
+
return middlewareFailed(rs, new Error("the middleware module does not export a middleware function"));
|
|
337
|
+
}
|
|
332
338
|
let matchers;
|
|
333
339
|
try {
|
|
334
340
|
matchers = middlewareMatchers();
|
|
@@ -343,7 +349,7 @@ export function createKrateHandler(options) {
|
|
|
343
349
|
let result;
|
|
344
350
|
try {
|
|
345
351
|
const request = attachCookies(new Request(fullURL(rs), { method: rs.method, headers: new Headers(rs.request.headers) }));
|
|
346
|
-
result = await
|
|
352
|
+
result = await handler(request);
|
|
347
353
|
}
|
|
348
354
|
catch (e) {
|
|
349
355
|
return middlewareFailed(rs, e);
|
|
@@ -520,3 +520,16 @@ describe("createKrateHandler with a shared cache adapter", () => {
|
|
|
520
520
|
expect(renders).toBe(2);
|
|
521
521
|
});
|
|
522
522
|
});
|
|
523
|
+
describe("middleware exports", () => {
|
|
524
|
+
const deny = () => new Response("no", { status: 403 });
|
|
525
|
+
const run = (middleware) => createKrateHandler({ target: "node", data: data(), modules: { ...modules, middleware } })(new Request("http://localhost/live"));
|
|
526
|
+
it("runs a default export", async () => {
|
|
527
|
+
expect((await run({ default: deny })).status).toBe(403);
|
|
528
|
+
});
|
|
529
|
+
it("fails closed when the module has no handler", async () => {
|
|
530
|
+
const error = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
531
|
+
expect((await run({ other: 1 })).status).toBe(503);
|
|
532
|
+
expect((await run(undefined)).status).toBe(503);
|
|
533
|
+
error.mockRestore();
|
|
534
|
+
});
|
|
535
|
+
});
|