create-prisma-php-app 4.1.0-alpha.16 → 4.1.0-alpha.18
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.
|
@@ -39,4 +39,4 @@ Defaulting to 2020, but this will stop working in the future.`)),e.ecmaVersion=1
|
|
|
39
39
|
console.error('Component:', '${t}');
|
|
40
40
|
console.error('Available context keys:', Object.keys(context));
|
|
41
41
|
}
|
|
42
|
-
`);return this.handlerCache.set(n,r),r}executeHandler(e,t,n){if(!this.componentManager||!this.expressionEvaluator){console.warn("EventDelegationManager dependencies not set");return}try{const i=t.getAttribute(d.ATTR_PREFIXES.CONTEXT),r=t.getAttribute(d.ATTR_PREFIXES.COMPONENT);let a=e.component,o=e.component;if(i)if(i==="app")a="app",r||(o="app");else if(i==="parent"){const g=S.getElementComponent(t);a=S.getParentOfComponent(g,t),r||(o=a)}else a=i,r||(o=i);else{let g=t,C=null;for(;g&&g!==document.body;){const A=g.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(A){const k=g.__originalComponentName;if(A===e.component||k===e.component){C=g;break}}g=g.parentElement}if(C){const A=C.getAttribute(d.ATTR_PREFIXES.COMPONENT);A&&(o=A);const k=C.getAttribute(d.ATTR_PREFIXES.CONTEXT);if(k)if(k==="app")a="app";else if(k==="parent"){const R=S.getElementComponent(C);a=S.getParentOfComponent(R,C)}else a=k}for(g=t;g&&g!==document.body;){const A=g.__uniqueComponentName,k=g.__originalComponentName;if(A){a=A,(!C||!C.__originalComponentName)&&(o=k||e.component);break}g=g.parentElement}}r&&(o=r);const c=i==="app"||i==="parent"||a==="app",l=a==="app",p=S.findElementForComponent(t,a);let h;if(c||l)h=this.componentManager.buildComponentContextWithProps(a,p||void 0);else if(h=this.componentManager.buildRestrictedComponentContext(a,!1),p){const g=this.componentManager.evaluateProps(p);Object.assign(h,g)}let f=t.parentElement,E=0;for(;f&&f!==document.body&&E<10;){if(E++,f.getAttribute(d.ATTR_PREFIXES.COMPONENT)&&this.componentManager.hasStoredProps(f)){const C=this.componentManager.evaluateProps(f);Object.assign(h,C);break}f=f.parentElement}if(o&&o!==a&&!o.includes("_loop_")){const g=this.getComponentOwnState(o);Object.assign(h,g)}if(a!==o&&window[a]){const g=window[a];for(const[C,A]of Object.entries(g))typeof A!="function"&&!(C in h)&&(h[C]=A)}const m={...h};for(const[g,C]of Object.entries(h))typeof C=="function"&&"__pphp_key"in C&&(m[g]=C.value);const b=this.loopManager?.getLoopContextForElement(t);if(b){const g={};for(const[C,A]of Object.entries(b)){if(typeof A=="function")continue;const k=`set${C.charAt(0).toUpperCase()}${C.slice(1)}`,R=`${C}Getter`,V=k in b&&typeof b[k]=="function",L=R in b&&typeof b[R]=="function";if(V||L)if(L){const Q=b[R],j=typeof Q.value<"u"?Q.value:Q();g[C]=j}else{const Q=m[C];Q!==void 0?g[C]=Q:g[C]=A}else g[C]=A}h={...m,...g}}else h=m;e.compiledFn||(e.compiledFn=this.compileHandler(e.code,o)),e.compiledFn&&e.compiledFn(n,t,h)}catch(i){console.error("💥 Event handler execution failed:",i),console.error("Handler code:",e.code),console.error("Handler component:",e.component)}}getComponentOwnState(e){const t={};window[e]&&Object.assign(t,window[e]);const n=this.stateManager?.getState();if(n){const i=Object.keys(n).filter(r=>r.startsWith(e+"."));for(const r of i){const a=r.substring(e.length+1);a in t||(t[a]=n[r])}}return t}attachDirectListener(e,t,n){const i=r=>{this.executeHandler(n,e,r)};e.addEventListener(t,i),e[`__${t}_listener`]=i}removeEventHandler(e,t){const n=this.elementHandlers.get(e);n&&(n.delete(t),n.size===0&&this.elementHandlers.delete(e));const i=this.delegatedEvents.get(t);i&&i.elements.delete?.(e);const r=e[`__${t}_listener`];r&&(e.removeEventListener(t,r),delete e[`__${t}_listener`])}cleanup(){for(const[e,t]of this.delegatedEvents)document.removeEventListener(e,t.listener,!0);this.delegatedEvents.clear(),this.handlerCache.clear(),this.setupEvents.clear()}}class Bs{stateManager=new Ls;expressionEvaluator=new me;componentManager=new Vs(this.stateManager);domBindingManager=new Ds(this.stateManager,this.componentManager,this.expressionEvaluator);hydrationCallbacks=new Set;portalManager=new Ns;static instance=null;initialized=!1;hydrationDone=!1;hydrationResolve;hydrationPromise;portalHydrationPromises=new Set;portalHydrationResolvers=new Map;constructor(){document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.initialize()):setTimeout(()=>this.initialize(),0),this.hydrationPromise=new Promise(e=>this.hydrationResolve=e)}initialize(){this.initialized||(this.initialized=!0,this.markHydrationStart(),this.componentManager.setExpressionEvaluator(this.expressionEvaluator),this.portalManager.setDependencies(this.componentManager,this.domBindingManager,this.stateManager,this),this.componentManager.executePhpScripts(document.body),this.domBindingManager.processElement(document.body,!0),this.domBindingManager.processPendingBindings(),Promise.resolve().then(()=>{requestAnimationFrame(()=>{this.markHydrated()})}))}createPortal(e,t,n){const i=this.portalManager.createPortal(e,t,n),r=new Promise(a=>{this.portalHydrationResolvers.set(i,a)});return this.portalHydrationPromises.add(r),r.finally(()=>{this.portalHydrationPromises.delete(r),this.portalHydrationResolvers.delete(i)}),i}removePortal(e){return this.markPortalHydrated(e),this.portalManager.removePortal(e)}markPortalHydrated(e){const t=this.portalHydrationResolvers.get(e);t&&t()}updatePortal(e,t,n){return this.portalManager.updatePortal(e,t,n)}cleanup(){this.portalManager.destroy(),this.domBindingManager.destroy(),this.componentManager.destroy(),this.stateManager.clearState(),this.stateManager.clearSubscriptions(),this.expressionEvaluator.clearAllCaches(),this.hydrationCallbacks.clear(),this.deleteAllComponentObjects()}ref(e=null){return{current:e}}async hydrated(){await Promise.all([this.hydrationPromise,...Array.from(this.portalHydrationPromises)])}onHydrated(e){this.hydrationDone?queueMicrotask(e):this.hydrationCallbacks.add(e)}get isHydrated(){return this.hydrationDone}markHydrationStart(){document.dispatchEvent(new CustomEvent("pp:hydrationstart"))}markHydrated(){if(!this.hydrationDone){this.hydrationDone=!0,this.hydrationResolve();for(const e of this.hydrationCallbacks)try{e()}catch{}this.hydrationCallbacks.clear(),document.dispatchEvent(new CustomEvent("pp:hydrated",{detail:{at:performance.now()}}))}}state(e,t){const n=this.componentManager.getCurrentComponent();let i,r;typeof e=="string"&&arguments.length===2?(i=e,r=t):typeof e=="string"&&arguments.length===1?this.looksLikeVariableName(e)?(i=e,r=void 0):(console.warn("pp.state() called with string that doesn't look like variable name:",e),i="unknownState",r=e):(console.warn("pp.state() called without explicit key - this should be handled by AST transformation"),i="unknownState",r=e),r&&typeof r=="function"&&"__pphp_key"in r&&(r=r.value);let a;const o=this.getLoopExecutionContext();if(o){const h=this.generateLoopInstanceId(o);a=`${n}.${h}.${i}`}else a=`${n}.${i}`;this.stateManager.hasState(a)||this.stateManager.setInitialState(a,r);const c=(()=>this.stateManager.getState()[a]),l=new Proxy(c,{get(h,f,E){if(f==="__pphp_key"||f==="__pphp_fullKey"||f==="__pphp_component"||f==="value"||f==="valueOf"||f==="toString")return Reflect.get(h,f,E);const m=h();if(m!=null){if(f in Object(m)){const b=m[f];return typeof b=="function"?b.bind(m):b}return Reflect.get(h,f,E)}},has(h,f){if(f==="__pphp_key"||f==="__pphp_fullKey"||f==="__pphp_component"||f==="value"||f==="valueOf"||f==="toString")return Reflect.has(h,f);const E=h();return E!=null&&f in Object(E)?!0:Reflect.has(h,f)},apply(h,f,E){return Reflect.apply(h,f,E)}});Object.defineProperty(l,"__pphp_key",{value:i,enumerable:!1,writable:!1}),Object.defineProperty(l,"__pphp_fullKey",{value:a,enumerable:!1,writable:!1}),Object.defineProperty(l,"__pphp_component",{value:n,enumerable:!1,writable:!1}),Object.defineProperty(l,"value",{get:()=>this.stateManager.getState()[a],enumerable:!0,configurable:!0}),c.valueOf=()=>this.stateManager.getState()[a],c.toString=()=>ue(this.stateManager.getState()[a]);const p=h=>{const f=this.stateManager.getState()[a],E=typeof h=="function"?h(f):h;this.stateManager.setState(a,E)};return this.createComponentScopedGlobals(n,i,l,p),[l,p]}currentLoopContext=null;getLoopExecutionContext(){return this.currentLoopContext}generateLoopInstanceId(e){const n=Object.keys(e).sort().map(r=>{const a=e[r];return a&&typeof a=="object"&&"id"in a?`${r}:${a.id}`:`${r}:${JSON.stringify(a)}`});return`loop_${btoa(n.join("|")).replace(/[^a-zA-Z0-9]/g,"").substring(0,8)}`}looksLikeVariableName(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)&&e.length<=50&&!e.includes(" ")&&!Se.has(e)}effect(e,t){const n=`effect_${Date.now()}_${Math.random()}`,i=this.componentManager.getCurrentComponent();let r,a=!1,o,c;if(arguments.length===1)o="always",c={immediate:!0,detectDeps:!0};else if(Array.isArray(t)){const p=this.extractDependencyNames(t,i);p.length===0?(o="once",c={deps:p,immediate:!0}):(o="deps",c={deps:p,immediate:!0})}else{const p={immediate:!0,...t||{}};if(!p.deps||p.deps.length===0)o="always",c={immediate:p.immediate,detectDeps:!0};else{const h=this.extractDependencyNames(p.deps,i);o="deps",c={deps:h,immediate:p.immediate,detectDeps:p.detectDeps}}}const l=()=>{a||this.stateManager.onDOMUpdateComplete(()=>{if(!a){if(r&&typeof r=="function")try{r()}catch(p){console.error("Effect cleanup error:",p)}try{r=e()}catch(p){console.error("Effect callback error:",p)}}})};switch(o){case"always":const p=["*"],h={id:n,selector:"",dependencies:new Set(p),callback:l,component:i};this.stateManager.addSubscription(h);break;case"once":break;case"deps":const f=this.resolveDependencies(c.deps,i);if(f.length){const E={id:n,selector:"",dependencies:new Set(f),callback:l,component:i};this.stateManager.addSubscription(E)}break}return c.immediate!==!1&&l(),()=>{if(a=!0,r&&typeof r=="function")try{r()}catch(p){console.error("Effect cleanup error:",p)}this.stateManager.removeSubscription(n)}}extractDependencyNames(e,t){const n=[];for(const i of e)typeof i=="string"?n.push(i):typeof i=="function"&&i.__pphp_key?n.push(i.__pphp_key):console.warn("Invalid dependency in effect:",i);return n.filter(Boolean)}resolveDependencies(e,t){const n=[],i=this.stateManager.getState();for(const r of e)if(r.includes(".")){const a=r.split("."),o=a[0],c=a.slice(1).join("."),l=this.componentManager.getPropDependencies(o,t);if(l.length>0)n.push(...l);else{const p=He.findExistingStateKey(o,t,i);p?n.push(`${p}.${c}`):n.push(`${t}.${r}`)}}else{const a=this.componentManager.getPropDependencies(r,t);if(a.length>0)n.push(...a);else{const o=He.findExistingStateKey(r,t,i);o?n.push(o):n.push(`${t}.${r}`)}}return Array.from(new Set(n))}createComponentScopedGlobals(e,t,n,i){window[e]||(window[e]={});const r=`set${$t(t)}`;Object.defineProperty(window[e],t,{get:()=>n.valueOf(),configurable:!0,enumerable:!0}),window[e][r]=i,window[e][`${t}Getter`]=n}deleteAllComponentObjects(){const e=Object.keys(window),t=new Set(["window","self","document","location","customElements","history","navigation","locationbar","menubar","personalbar","scrollbars","statusbar","toolbar","frames","top","parent","navigator","external","screen","visualViewport","crypto","performance","localStorage","sessionStorage","indexedDB","fetch","XMLHttpRequest","WebSocket","Worker","SharedWorker","MessageChannel","MessagePort","Notification","Push","BroadcastChannel","Cache","CacheStorage","requestAnimationFrame","cancelAnimationFrame","requestIdleCallback","cancelIdleCallback","setInterval","clearInterval","setTimeout","clearTimeout","queueMicrotask","atob","btoa","alert","confirm","prompt","open","close","focus","blur","print","stop","getComputedStyle","getSelection","matchMedia","scroll","scrollBy","scrollTo","resizeBy","resizeTo","moveBy","moveTo","pp","store","searchParams"]);for(const n of e){if(t.has(n))continue;const i=window[n];(/^s[a-z0-9]+$/i.test(n)||n==="app")&&i&&typeof i=="object"&&delete window[n]}}static resetInstance(){this.instance&&(this.instance.destroy(),this.instance=null)}destroy(){this.cleanup(),this.initialized=!1,this.hydrationDone=!1}}export{Bs as P};
|
|
42
|
+
`);return this.handlerCache.set(n,r),r}executeHandler(e,t,n){if(!this.componentManager||!this.expressionEvaluator){console.warn("EventDelegationManager dependencies not set");return}try{const i=t.getAttribute(d.ATTR_PREFIXES.CONTEXT),r=t.getAttribute(d.ATTR_PREFIXES.COMPONENT);let a=e.component,o=e.component;if(i)if(i==="app")a="app",r||(o="app");else if(i==="parent"){const g=S.getElementComponent(t);a=S.getParentOfComponent(g,t),r||(o=a)}else a=i,r||(o=i);else{let g=t,C=null;for(;g&&g!==document.body;){const A=g.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(A){const k=g.__originalComponentName;if(A===e.component||k===e.component){C=g;break}}g=g.parentElement}if(C){const A=C.getAttribute(d.ATTR_PREFIXES.COMPONENT);A&&(o=A);const k=C.getAttribute(d.ATTR_PREFIXES.CONTEXT);if(k)if(k==="app")a="app";else if(k==="parent"){const R=S.getElementComponent(C);a=S.getParentOfComponent(R,C)}else a=k}for(g=t;g&&g!==document.body;){const A=g.__uniqueComponentName,k=g.__originalComponentName;if(A){a=A,(!C||!C.__originalComponentName)&&(o=k||e.component);break}g=g.parentElement}}r&&(o=r);const c=i==="app"||i==="parent"||a==="app",l=a==="app",p=S.findElementForComponent(t,a);let h;if(c||l)h=this.componentManager.buildComponentContextWithProps(a,p||void 0);else if(h=this.componentManager.buildRestrictedComponentContext(a,!1),p){const g=this.componentManager.evaluateProps(p);Object.assign(h,g)}let f=t.parentElement,E=0;for(;f&&f!==document.body&&E<10;){if(E++,f.getAttribute(d.ATTR_PREFIXES.COMPONENT)&&this.componentManager.hasStoredProps(f)){const C=this.componentManager.evaluateProps(f);Object.assign(h,C);break}f=f.parentElement}if(o&&o!==a&&!o.includes("_loop_")){const g=this.getComponentOwnState(o);Object.assign(h,g)}if(a!==o&&window[a]){const g=window[a];for(const[C,A]of Object.entries(g))typeof A!="function"&&!(C in h)&&(h[C]=A)}const m={...h};for(const[g,C]of Object.entries(h))typeof C=="function"&&"__pphp_key"in C&&(m[g]=C.value);const b=this.loopManager?.getLoopContextForElement(t);if(b){const g={};for(const[C,A]of Object.entries(b)){if(typeof A=="function")continue;const k=`set${C.charAt(0).toUpperCase()}${C.slice(1)}`,R=`${C}Getter`,V=k in b&&typeof b[k]=="function",L=R in b&&typeof b[R]=="function";if(V||L)if(L){const Q=b[R],j=typeof Q.value<"u"?Q.value:Q();g[C]=j}else{const Q=m[C];Q!==void 0?g[C]=Q:g[C]=A}else g[C]=A}h={...m,...g}}else h=m;e.compiledFn||(e.compiledFn=this.compileHandler(e.code,o)),e.compiledFn&&e.compiledFn(n,t,h)}catch(i){console.error("💥 Event handler execution failed:",i),console.error("Handler code:",e.code),console.error("Handler component:",e.component)}}getComponentOwnState(e){const t={};window[e]&&Object.assign(t,window[e]);const n=this.stateManager?.getState();if(n){const i=Object.keys(n).filter(r=>r.startsWith(e+"."));for(const r of i){const a=r.substring(e.length+1);a in t||(t[a]=n[r])}}return t}attachDirectListener(e,t,n){const i=r=>{this.executeHandler(n,e,r)};e.addEventListener(t,i),e[`__${t}_listener`]=i}removeEventHandler(e,t){const n=this.elementHandlers.get(e);n&&(n.delete(t),n.size===0&&this.elementHandlers.delete(e));const i=this.delegatedEvents.get(t);i&&i.elements.delete?.(e);const r=e[`__${t}_listener`];r&&(e.removeEventListener(t,r),delete e[`__${t}_listener`])}cleanup(){for(const[e,t]of this.delegatedEvents)document.removeEventListener(e,t.listener,!0);this.delegatedEvents.clear(),this.handlerCache.clear(),this.setupEvents.clear()}}class Bs{static instance=null;stateManager=new Ls;expressionEvaluator=new me;componentManager=new Vs(this.stateManager);domBindingManager=new Ds(this.stateManager,this.componentManager,this.expressionEvaluator);hydrationCallbacks=new Set;portalManager=new Ns;initialized=!1;hydrationDone=!1;hydrationResolve;hydrationPromise;portalHydrationPromises=new Set;portalHydrationResolvers=new Map;constructor(){document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.initialize()):setTimeout(()=>this.initialize(),0),this.hydrationPromise=new Promise(e=>this.hydrationResolve=e)}initialize(){this.initialized||(this.initialized=!0,this.markHydrationStart(),this.componentManager.setExpressionEvaluator(this.expressionEvaluator),this.portalManager.setDependencies(this.componentManager,this.domBindingManager,this.stateManager,this),this.componentManager.executePhpScripts(document.body),this.domBindingManager.processElement(document.body,!0),this.domBindingManager.processPendingBindings(),Promise.resolve().then(()=>{requestAnimationFrame(()=>{this.markHydrated()})}))}createPortal(e,t,n){const i=this.portalManager.createPortal(e,t,n),r=new Promise(a=>{this.portalHydrationResolvers.set(i,a)});return this.portalHydrationPromises.add(r),r.finally(()=>{this.portalHydrationPromises.delete(r),this.portalHydrationResolvers.delete(i)}),i}removePortal(e){return this.markPortalHydrated(e),this.portalManager.removePortal(e)}markPortalHydrated(e){const t=this.portalHydrationResolvers.get(e);t&&t()}updatePortal(e,t,n){return this.portalManager.updatePortal(e,t,n)}cleanup(){this.portalManager.destroy(),this.domBindingManager.destroy(),this.componentManager.destroy(),this.stateManager.clearState(),this.stateManager.clearSubscriptions(),this.expressionEvaluator.clearAllCaches(),this.hydrationCallbacks.clear(),this.deleteAllComponentObjects()}ref(e=null){return{current:e}}async hydrated(){await Promise.all([this.hydrationPromise,...Array.from(this.portalHydrationPromises)])}onHydrated(e){this.hydrationDone?queueMicrotask(e):this.hydrationCallbacks.add(e)}get isHydrated(){return this.hydrationDone}markHydrationStart(){document.dispatchEvent(new CustomEvent("pp:hydrationstart"))}markHydrated(){if(!this.hydrationDone){this.hydrationDone=!0,this.hydrationResolve();for(const e of this.hydrationCallbacks)try{e()}catch{}this.hydrationCallbacks.clear(),document.dispatchEvent(new CustomEvent("pp:hydrated",{detail:{at:performance.now()}}))}}state(e,t){const n=this.componentManager.getCurrentComponent();let i,r;typeof e=="string"&&arguments.length===2?(i=e,r=t):typeof e=="string"&&arguments.length===1?this.looksLikeVariableName(e)?(i=e,r=void 0):(console.warn("pp.state() called with string that doesn't look like variable name:",e),i="unknownState",r=e):(console.warn("pp.state() called without explicit key - this should be handled by AST transformation"),i="unknownState",r=e),r&&typeof r=="function"&&"__pphp_key"in r&&(r=r.value);let a;const o=this.getLoopExecutionContext();if(o){const h=this.generateLoopInstanceId(o);a=`${n}.${h}.${i}`}else a=`${n}.${i}`;this.stateManager.hasState(a)||this.stateManager.setInitialState(a,r);const c=(()=>this.stateManager.getState()[a]),l=new Proxy(c,{get(h,f,E){if(f==="__pphp_key"||f==="__pphp_fullKey"||f==="__pphp_component"||f==="value"||f==="valueOf"||f==="toString")return Reflect.get(h,f,E);const m=h();if(m!=null){if(f in Object(m)){const b=m[f];return typeof b=="function"?b.bind(m):b}return Reflect.get(h,f,E)}},has(h,f){if(f==="__pphp_key"||f==="__pphp_fullKey"||f==="__pphp_component"||f==="value"||f==="valueOf"||f==="toString")return Reflect.has(h,f);const E=h();return E!=null&&f in Object(E)?!0:Reflect.has(h,f)},apply(h,f,E){return Reflect.apply(h,f,E)}});Object.defineProperty(l,"__pphp_key",{value:i,enumerable:!1,writable:!1}),Object.defineProperty(l,"__pphp_fullKey",{value:a,enumerable:!1,writable:!1}),Object.defineProperty(l,"__pphp_component",{value:n,enumerable:!1,writable:!1}),Object.defineProperty(l,"value",{get:()=>this.stateManager.getState()[a],enumerable:!0,configurable:!0}),c.valueOf=()=>this.stateManager.getState()[a],c.toString=()=>ue(this.stateManager.getState()[a]);const p=h=>{const f=this.stateManager.getState()[a],E=typeof h=="function"?h(f):h;this.stateManager.setState(a,E)};return this.createComponentScopedGlobals(n,i,l,p),[l,p]}currentLoopContext=null;getLoopExecutionContext(){return this.currentLoopContext}generateLoopInstanceId(e){const n=Object.keys(e).sort().map(r=>{const a=e[r];return a&&typeof a=="object"&&"id"in a?`${r}:${a.id}`:`${r}:${JSON.stringify(a)}`});return`loop_${btoa(n.join("|")).replace(/[^a-zA-Z0-9]/g,"").substring(0,8)}`}looksLikeVariableName(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)&&e.length<=50&&!e.includes(" ")&&!Se.has(e)}effect(e,t){const n=`effect_${Date.now()}_${Math.random()}`,i=this.componentManager.getCurrentComponent();let r,a=!1,o,c;if(arguments.length===1)o="always",c={immediate:!0,detectDeps:!0};else if(Array.isArray(t)){const p=this.extractDependencyNames(t,i);p.length===0?(o="once",c={deps:p,immediate:!0}):(o="deps",c={deps:p,immediate:!0})}else{const p={immediate:!0,...t||{}};if(!p.deps||p.deps.length===0)o="always",c={immediate:p.immediate,detectDeps:!0};else{const h=this.extractDependencyNames(p.deps,i);o="deps",c={deps:h,immediate:p.immediate,detectDeps:p.detectDeps}}}const l=()=>{a||this.stateManager.onDOMUpdateComplete(()=>{if(!a){if(r&&typeof r=="function")try{r()}catch(p){console.error("Effect cleanup error:",p)}try{r=e()}catch(p){console.error("Effect callback error:",p)}}})};switch(o){case"always":const p=["*"],h={id:n,selector:"",dependencies:new Set(p),callback:l,component:i};this.stateManager.addSubscription(h);break;case"once":break;case"deps":const f=this.resolveDependencies(c.deps,i);if(f.length){const E={id:n,selector:"",dependencies:new Set(f),callback:l,component:i};this.stateManager.addSubscription(E)}break}return c.immediate!==!1&&l(),()=>{if(a=!0,r&&typeof r=="function")try{r()}catch(p){console.error("Effect cleanup error:",p)}this.stateManager.removeSubscription(n)}}extractDependencyNames(e,t){const n=[];for(const i of e)typeof i=="string"?n.push(i):typeof i=="function"&&i.__pphp_key?n.push(i.__pphp_key):console.warn("Invalid dependency in effect:",i);return n.filter(Boolean)}resolveDependencies(e,t){const n=[],i=this.stateManager.getState();for(const r of e)if(r.includes(".")){const a=r.split("."),o=a[0],c=a.slice(1).join("."),l=this.componentManager.getPropDependencies(o,t);if(l.length>0)n.push(...l);else{const p=He.findExistingStateKey(o,t,i);p?n.push(`${p}.${c}`):n.push(`${t}.${r}`)}}else{const a=this.componentManager.getPropDependencies(r,t);if(a.length>0)n.push(...a);else{const o=He.findExistingStateKey(r,t,i);o?n.push(o):n.push(`${t}.${r}`)}}return Array.from(new Set(n))}createComponentScopedGlobals(e,t,n,i){window[e]||(window[e]={});const r=`set${$t(t)}`;Object.defineProperty(window[e],t,{get:()=>n.valueOf(),configurable:!0,enumerable:!0}),window[e][r]=i,window[e][`${t}Getter`]=n}deleteAllComponentObjects(){const e=Object.keys(window),t=new Set(["window","self","document","location","customElements","history","navigation","locationbar","menubar","personalbar","scrollbars","statusbar","toolbar","frames","top","parent","navigator","external","screen","visualViewport","crypto","performance","localStorage","sessionStorage","indexedDB","fetch","XMLHttpRequest","WebSocket","Worker","SharedWorker","MessageChannel","MessagePort","Notification","Push","BroadcastChannel","Cache","CacheStorage","requestAnimationFrame","cancelAnimationFrame","requestIdleCallback","cancelIdleCallback","setInterval","clearInterval","setTimeout","clearTimeout","queueMicrotask","atob","btoa","alert","confirm","prompt","open","close","focus","blur","print","stop","getComputedStyle","getSelection","matchMedia","scroll","scrollBy","scrollTo","resizeBy","resizeTo","moveBy","moveTo","pp","store","searchParams"]);for(const n of e){if(t.has(n))continue;const i=window[n];(/^s[a-z0-9]+$/i.test(n)||n==="app")&&i&&typeof i=="object"&&delete window[n]}}static resetInstance(){this.instance&&(this.instance.destroy(),this.instance=null)}destroy(){this.cleanup(),this.initialized=!1,this.hydrationDone=!1}}export{Bs as P};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{P as ce}from"./pp-reactive-v1.js";var ee=11;function le(i,e){var t=e.attributes,n,a,r,s,u;if(!(e.nodeType===ee||i.nodeType===ee)){for(var f=t.length-1;f>=0;f--)n=t[f],a=n.name,r=n.namespaceURI,s=n.value,r?(a=n.localName||a,u=i.getAttributeNS(r,a),u!==s&&(n.prefix==="xmlns"&&(a=n.name),i.setAttributeNS(r,a,s))):(u=i.getAttribute(a),u!==s&&i.setAttribute(a,s));for(var b=i.attributes,g=b.length-1;g>=0;g--)n=b[g],a=n.name,r=n.namespaceURI,r?(a=n.localName||a,e.hasAttributeNS(r,a)||i.removeAttributeNS(r,a)):e.hasAttribute(a)||i.removeAttribute(a)}}var D,de="http://www.w3.org/1999/xhtml",v=typeof document>"u"?void 0:document,ue=!!v&&"content"in v.createElement("template"),he=!!v&&v.createRange&&"createContextualFragment"in v.createRange();function fe(i){var e=v.createElement("template");return e.innerHTML=i,e.content.childNodes[0]}function pe(i){D||(D=v.createRange(),D.selectNode(v.body));var e=D.createContextualFragment(i);return e.childNodes[0]}function ve(i){var e=v.createElement("body");return e.innerHTML=i,e.childNodes[0]}function ye(i){return i=i.trim(),ue?fe(i):he?pe(i):ve(i)}function $(i,e){var t=i.nodeName,n=e.nodeName,a,r;return t===n?!0:(a=t.charCodeAt(0),r=n.charCodeAt(0),a<=90&&r>=97?t===n.toUpperCase():r<=90&&a>=97?n===t.toUpperCase():!1)}function ge(i,e){return!e||e===de?v.createElement(i):v.createElementNS(e,i)}function me(i,e){for(var t=i.firstChild;t;){var n=t.nextSibling;e.appendChild(t),t=n}return e}function j(i,e,t){i[t]!==e[t]&&(i[t]=e[t],i[t]?i.setAttribute(t,""):i.removeAttribute(t))}var te={OPTION:function(i,e){var t=i.parentNode;if(t){var n=t.nodeName.toUpperCase();n==="OPTGROUP"&&(t=t.parentNode,n=t&&t.nodeName.toUpperCase()),n==="SELECT"&&!t.hasAttribute("multiple")&&(i.hasAttribute("selected")&&!e.selected&&(i.setAttribute("selected","selected"),i.removeAttribute("selected")),t.selectedIndex=-1)}j(i,e,"selected")},INPUT:function(i,e){j(i,e,"checked"),j(i,e,"disabled"),i.value!==e.value&&(i.value=e.value),e.hasAttribute("value")||i.removeAttribute("value")},TEXTAREA:function(i,e){var t=e.value;i.value!==t&&(i.value=t);var n=i.firstChild;if(n){var a=n.nodeValue;if(a==t||!t&&a==i.placeholder)return;n.nodeValue=t}},SELECT:function(i,e){if(!e.hasAttribute("multiple")){for(var t=-1,n=0,a=i.firstChild,r,s;a;)if(s=a.nodeName&&a.nodeName.toUpperCase(),s==="OPTGROUP")r=a,a=r.firstChild,a||(a=r.nextSibling,r=null);else{if(s==="OPTION"){if(a.hasAttribute("selected")){t=n;break}n++}a=a.nextSibling,!a&&r&&(a=r.nextSibling,r=null)}i.selectedIndex=t}}},R=1,ne=11,ae=3,ie=8;function T(){}function we(i){if(i)return i.getAttribute&&i.getAttribute("id")||i.id}function be(i){return function(t,n,a){if(a||(a={}),typeof n=="string")if(t.nodeName==="#document"||t.nodeName==="HTML"||t.nodeName==="BODY"){var r=n;n=v.createElement("html"),n.innerHTML=r}else n=ye(n);else n.nodeType===ne&&(n=n.firstElementChild);var s=a.getNodeKey||we,u=a.onBeforeNodeAdded||T,f=a.onNodeAdded||T,b=a.onBeforeElUpdated||T,g=a.onElUpdated||T,I=a.onBeforeNodeDiscarded||T,y=a.onNodeDiscarded||T,m=a.onBeforeElChildrenUpdated||T,E=a.skipFromChildren||T,x=a.addChild||function(o,c){return o.appendChild(c)},q=a.childrenOnly===!0,C=Object.create(null),U=[];function _(o){U.push(o)}function X(o,c){if(o.nodeType===R)for(var h=o.firstChild;h;){var l=void 0;c&&(l=s(h))?_(l):(y(h),h.firstChild&&X(h,c)),h=h.nextSibling}}function K(o,c,h){I(o)!==!1&&(c&&c.removeChild(o),y(o),X(o,h))}function G(o){if(o.nodeType===R||o.nodeType===ne)for(var c=o.firstChild;c;){var h=s(c);h&&(C[h]=c),G(c),c=c.nextSibling}}G(t);function M(o){f(o);for(var c=o.firstChild;c;){var h=c.nextSibling,l=s(c);if(l){var d=C[l];d&&$(c,d)?(c.parentNode.replaceChild(d,c),H(d,c)):M(c)}else M(c);c=h}}function re(o,c,h){for(;c;){var l=c.nextSibling;(h=s(c))?_(h):K(c,o,!0),c=l}}function H(o,c,h){var l=s(c);if(l&&delete C[l],!h){var d=b(o,c);if(d===!1||(d instanceof HTMLElement&&(o=d,G(o)),i(o,c),g(o),m(o,c)===!1))return}o.nodeName!=="TEXTAREA"?se(o,c):te.TEXTAREA(o,c)}function se(o,c){var h=E(o,c),l=c.firstChild,d=o.firstChild,N,w,O,B,S;e:for(;l;){for(B=l.nextSibling,N=s(l);!h&&d;){if(O=d.nextSibling,l.isSameNode&&l.isSameNode(d)){l=B,d=O;continue e}w=s(d);var V=d.nodeType,A=void 0;if(V===l.nodeType&&(V===R?(N?N!==w&&((S=C[N])?O===S?A=!1:(o.insertBefore(S,d),w?_(w):K(d,o,!0),d=S,w=s(d)):A=!1):w&&(A=!1),A=A!==!1&&$(d,l),A&&H(d,l)):(V===ae||V==ie)&&(A=!0,d.nodeValue!==l.nodeValue&&(d.nodeValue=l.nodeValue))),A){l=B,d=O;continue e}w?_(w):K(d,o,!0),d=O}if(N&&(S=C[N])&&$(S,l))h||x(o,S),H(S,l);else{var W=u(l);W!==!1&&(W&&(l=W),l.actualize&&(l=l.actualize(o.ownerDocument||v)),x(o,l),M(l))}l=B,d=O}re(o,d,w);var Z=te[o.nodeName];Z&&Z(o,c)}var p=t,F=p.nodeType,Q=n.nodeType;if(!q){if(F===R)Q===R?$(t,n)||(y(t),p=me(t,ge(n.nodeName,n.namespaceURI))):p=n;else if(F===ae||F===ie){if(Q===F)return p.nodeValue!==n.nodeValue&&(p.nodeValue=n.nodeValue),p;p=n}}if(p===n)y(t);else{if(n.isSameNode&&n.isSameNode(p))return;if(H(p,n,q),U)for(var Y=0,oe=U.length;Y<oe;Y++){var J=C[U[Y]];J&&K(J,J.parentNode,!1)}}return!q&&p!==t&&t.parentNode&&(p.actualize&&(p=p.actualize(t.ownerDocument||v)),t.parentNode.replaceChild(p,t)),p}}var Se=be(le);class P extends ce{static instance=null;cryptoKey=null;activeAbortController=null;navigationEnabled=!1;boundHandleLinkClick=null;boundHandlePopState=null;isNavigating=!1;constructor(){super(),this.hydrated().then(()=>{this.isNavigating||(document.body.hidden=!1,document.body.style.opacity="1"),this.enableSPANavigation()}).catch(e=>{console.error("PPHPUtilities hydration error:",e),document.body.hidden=!1,document.body.style.opacity="1"})}static resetInstance(){this.instance&&(this.instance.navigationEnabled&&this.instance.disableSPANavigation(),this.instance.activeAbortController&&(this.instance.activeAbortController.abort(),this.instance.activeAbortController=null),this.instance.expressionEvaluator.clearAllCaches(),this.instance.destroy(),this.instance=null)}static getInstance(){return this.instance||(this.instance=new P),this.instance}enableSPANavigation(){this.navigationEnabled||(this.navigationEnabled=!0,this.boundHandleLinkClick=this.handleLinkClick.bind(this),this.boundHandlePopState=this.handlePopState.bind(this),document.addEventListener("click",this.boundHandleLinkClick),window.addEventListener("popstate",this.boundHandlePopState))}disableSPANavigation(){this.navigationEnabled=!1,this.boundHandleLinkClick&&(document.removeEventListener("click",this.boundHandleLinkClick),this.boundHandleLinkClick=null),this.boundHandlePopState&&(window.removeEventListener("popstate",this.boundHandlePopState),this.boundHandlePopState=null)}handleLinkClick(e){if(!this.navigationEnabled)return;const n=e.target.closest("a");if(!(!n||!n.href))try{const a=new URL(n.href),r=a.origin!==window.location.origin,s=a.pathname===window.location.pathname&&a.search===window.location.search;if(r||n.target==="_blank"||n.hasAttribute("download")||n.getAttribute("pp-no-spa")==="true"||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;if(e.preventDefault(),s){const u=a.hash;if(u){const f=document.querySelector(u);f&&f.scrollIntoView({behavior:"smooth"})}else window.scrollTo({top:0,behavior:"smooth"});return}this.navigateTo(a.pathname+a.search+a.hash)}catch(a){console.error("Link click navigation error:",a)}}async handlePopState(){const e=window.location.pathname+window.location.search+window.location.hash;await this.navigateTo(e,!1)}async navigateTo(e,t=!0){this.isNavigating=!0;try{this.dispatchNavigationEvent("start",e),await this.showLoadingTransition();const n=await this.fetchPageContent(e);this.performCleanup(),this.updateBrowserHistory(e,t);const a=document.getElementById("loading-file-1B87E"),r="startViewTransition"in document;!a&&r?await this.updatePageContentWithViewTransition(n):this.updatePageContent(n),await this.reinitializeApp(),await this.handleNavigationCompletion(e),this.dispatchNavigationEvent("complete",e)}catch(n){this.handleNavigationError(e,n)}finally{this.isNavigating=!1}}async updatePageContentWithViewTransition(e){if(this.isNavigating){this.updatePageContent(e);return}const t=document.startViewTransition(()=>{this.updatePageContent(e)});try{await t.finished}catch(n){console.warn("View transition failed, continuing anyway:",n)}}dispatchNavigationEvent(e,t,n){const a=`pp:navigation:${e}`,r=n?{url:t,error:n}:{url:t};document.dispatchEvent(new CustomEvent(a,{detail:r}))}async showLoadingTransition(){const e=document.getElementById("loading-file-1B87E");if(e){const n=this.findLoadingElement(e,window.location.pathname);if(n){await this.updateContentWithTransition(n);return}}const t=document.querySelector("[pp-loading-content='true']")||document.body;t&&!("startViewTransition"in document)&&await this.fadeOut(t,250)}async fetchPageContent(e){const t=await fetch(e,{headers:{"X-Requested-With":"XMLHttpRequest",Accept:"text/html"}});if(!t.ok)throw new Error(`Navigation failed: ${t.status} ${t.statusText}`);const n=await t.text();return new DOMParser().parseFromString(n,"text/html")}performCleanup(){this.cleanup(),this.disableSPANavigation()}updateBrowserHistory(e,t){t&&history.pushState(null,"",e)}updatePageContent(e){e.title&&(document.title=e.title),this.reconcileHead(e);const t=e.body;Se(document.body,t,{childrenOnly:!0,onBeforeElUpdated:(n,a)=>!n.isEqualNode(a)})}async reinitializeApp(){window.pp=null,P.instance=null;const e=window.pp;return await e.hydrated(),e}async handleNavigationCompletion(e){const t=new URL(e,window.location.origin).hash;if(t){const a=document.querySelector(t);a&&a.scrollIntoView({behavior:"smooth"})}else window.scrollTo({top:0,behavior:"instant"});const n=document.querySelector("[pp-loading-content='true']")||document.body;n?requestAnimationFrame(()=>{document.body.hidden=!1,this.fadeIn(n,150)}):(document.body.hidden=!1,document.body.style.opacity="1")}handleNavigationError(e,t){console.error("Navigation error:",t),document.body.hidden=!1,document.body.style.opacity="1",this.dispatchNavigationEvent("error",e,t),window.location.href=e}findLoadingElement(e,t){let n=t;for(;;){const a=e.querySelector(`div[pp-loading-url='${n}']`);if(a)return a;if(n==="/")break;const r=n.lastIndexOf("/");r<=0?n="/":n=n.substring(0,r)}return e.querySelector("div[pp-loading-url='/' ]")}async updateContentWithTransition(e){const t=document.querySelector("[pp-loading-content='true']")||document.body;if(!t)return;const{fadeIn:n,fadeOut:a}=this.parseTransition(e);await this.fadeOut(t,a),t.innerHTML=e.innerHTML,this.fadeIn(t,n)}parseTransition(e){let t=250,n=250;const r=e.querySelector("[pp-loading-transition]")?.getAttribute("pp-loading-transition");if(r){let s=JSON.parse(r);s&&typeof s=="object"?(t=this.parseTime(s.fadeIn??t),n=this.parseTime(s.fadeOut??n)):console.warn("pp-loading-transition is not valid JSON → default values (250 ms) will be used. String:",r)}return{fadeIn:t,fadeOut:n}}fadeOut(e,t){return new Promise(n=>{e.style.transition=`opacity ${t}ms ease-out`,e.style.opacity="0",setTimeout(()=>{e.style.transition="",n()},t)})}fadeIn(e,t){e.style.transition=`opacity ${t}ms ease-in`,e.style.opacity="1",setTimeout(()=>{e.style.transition=""},t)}parseTime(e){if(typeof e=="number")return e;const t=e.match(/^(\d+)(ms|s|m)?$/);if(t){const n=parseInt(t[1],10);switch(t[2]||"ms"){case"ms":return n;case"s":return n*1e3;case"m":return n*60*1e3;default:return n}}return 0}reconcileHead(e){const t="pp-dynamic-script",n="pp-dynamic-meta",a="pp-dynamic-link";document.head.querySelectorAll(`[${n}]`).forEach(r=>r.remove()),document.head.querySelectorAll(`[${a}]`).forEach(r=>r.remove()),document.head.querySelectorAll(`[${t}]`).forEach(r=>r.remove()),Array.from(e.head.children).forEach(r=>{switch(r.tagName){case"SCRIPT":if(r.hasAttribute(t)){const s=document.createElement("script");Array.from(r.attributes).forEach(u=>s.setAttribute(u.name,u.value)),s.textContent=r.textContent,document.head.appendChild(s)}break;case"META":{const s=r;if(s.getAttribute("charset")||s.name==="viewport")break;const u=s.name?`meta[name="${s.name}"]`:`meta[property="${s.getAttribute("property")}"]`,f=s.cloneNode(!0),b=document.head.querySelector(u);b?document.head.replaceChild(f,b):document.head.insertBefore(f,document.head.querySelector("title")?.nextSibling||null);break}case"TITLE":{const s=r.cloneNode(!0),u=document.head.querySelector("title");u?document.head.replaceChild(s,u):document.head.appendChild(s);break}case"LINK":{const s=r;if(s.rel==="icon"){const u=s.cloneNode(!0),f=document.head.querySelector('link[rel="icon"]');f?document.head.replaceChild(u,f):document.head.appendChild(u)}else s.hasAttribute(a)&&document.head.appendChild(s.cloneNode(!0));break}}})}async redirect(e){if(e)try{const t=new URL(e,window.location.origin);t.origin!==window.location.origin?window.location.href=e:this.navigationEnabled?await this.navigateTo(t.pathname+t.search+t.hash):window.location.href=e}catch(t){console.error("Redirect error:",t)}}async initCryptoKey(){const e=document.cookie.split("; ").find(u=>u.startsWith("pp_function_call_jwt="))?.split("=",2)[1];if(!e)throw new Error("Missing function-call token");const[,t]=e.split("."),n=atob(t.replace(/-/g,"+").replace(/_/g,"/")),{k:a,exp:r}=JSON.parse(n);if(Date.now()/1e3>r)throw new Error("Function-call token expired");const s=Uint8Array.from(atob(a),u=>u.charCodeAt(0));this.cryptoKey=await crypto.subtle.importKey("raw",s,{name:"AES-CBC"},!1,["encrypt","decrypt"])}async encryptCallbackName(e){await this.initCryptoKey();const t=crypto.getRandomValues(new Uint8Array(16)),n=new TextEncoder().encode(e),a=await crypto.subtle.encrypt({name:"AES-CBC",iv:t},this.cryptoKey,n),r=btoa(String.fromCharCode(...t)),s=btoa(String.fromCharCode(...new Uint8Array(a)));return`${r}:${s}`}createFetchOptions(e){return{method:"POST",headers:{"Content-Type":"application/json",HTTP_PP_WIRE_REQUEST:"true"},body:JSON.stringify(e)}}async fetchFunction(e,t={},n=!1){let a=null;try{n&&this.activeAbortController&&(this.activeAbortController.abort(),this.activeAbortController=null),a=new AbortController,n&&(this.activeAbortController=a);const s={callback:await this.encryptCallbackName(e),...t},u=window.location.href;let f;if(Object.keys(s).some(y=>{const m=s[y];return m instanceof File||m instanceof FileList&&m.length>0})){const y=new FormData;Object.keys(s).forEach(m=>{const E=s[m];E instanceof File?y.append(m,E):E instanceof FileList?Array.from(E).forEach(x=>y.append(m,x)):y.append(m,E)}),f={method:"POST",headers:{HTTP_PP_WIRE_REQUEST:"true"},body:y,signal:a.signal}}else f={signal:a.signal,...this.createFetchOptions(s)};const g=await fetch(u,f);if(!g.ok)throw new Error(`Fetch failed with status: ${g.status} ${g.statusText}`);const I=await g.text();a&&this.activeAbortController===a&&(this.activeAbortController=null);try{return JSON.parse(I)}catch{return I}}catch(r){if(a&&this.activeAbortController===a&&(this.activeAbortController=null),r instanceof Error&&r.name==="AbortError")return console.log("Request was cancelled"),{cancelled:!0};throw console.error("Error in fetchFunction:",r),new Error("Failed to fetch data.")}}}class k{state;static instance=null;listeners;pp;STORAGE_KEY;lastSyncedState=null;constructor(e={}){this.state=e,this.listeners=[],this.pp=P.getInstance(),this.STORAGE_KEY=this.getCookie("pp_local_store_key")||"pp_local_store_59e13",this.lastSyncedState=localStorage.getItem(this.STORAGE_KEY),this.loadState()}static getInstance(e={}){return k.instance||(k.instance=new k(e)),k.instance}getCookie(e){return document.cookie.split("; ").find(t=>t.startsWith(e+"="))?.split("=")[1]||null}setState(e,t=!1){const n={...this.state,...e};if(JSON.stringify(n)!==JSON.stringify(this.state)&&(this.state=n,this.listeners.forEach(a=>a(this.state)),this.saveState(),t)){const a=localStorage.getItem(this.STORAGE_KEY);a&&a!==this.lastSyncedState&&(this.pp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:a}),this.lastSyncedState=a)}}saveState(){localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.state))}loadState(){const e=localStorage.getItem(this.STORAGE_KEY);e&&(this.state=JSON.parse(e),this.listeners.forEach(t=>t(this.state)))}resetState(e,t=!1){if(e?(delete this.state[e],this.saveState()):(this.state={},localStorage.removeItem(this.STORAGE_KEY)),this.listeners.forEach(n=>n(this.state)),t){const n=e?localStorage.getItem(this.STORAGE_KEY):null;this.pp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:n}),this.lastSyncedState=n}}}class L{static instance=null;listeners=[];constructor(){}static getInstance(){return L.instance||(L.instance=new L),L.instance}get params(){return new URLSearchParams(window.location.search)}get(e){return this.params.get(e)}set(e,t){const n=this.params;n.set(e,t),this.updateURL(n)}delete(e){const t=this.params;t.delete(e),this.updateURL(t)}replace(e){const t=new URLSearchParams;for(const n in e){const a=e[n];a!==null&&t.set(n,a)}this.updateURL(t,!0)}updateURL(e,t=!1){const n=`${window.location.pathname}?${e.toString()}`;t?history.replaceState(null,"",n):history.pushState(null,"",n),this.notifyListeners(e)}listen(e){this.listeners.push(e)}notifyListeners(e){for(const t of this.listeners)t(e)}enablePopStateListener(){window.addEventListener("popstate",()=>{this.notifyListeners(this.params)})}}function z(i,e,t=window,n=!0){let a=null;if(Object.defineProperty(t,i,{get(){if(a!==null)return a;if(e&&typeof e=="object"&&!Array.isArray(e)&&"getInstance"in e&&typeof e.getInstance=="function")return a=e.getInstance(),a;if(typeof e=="function")try{return a=e.getInstance(),a}catch{return a=e,a}else return a=e,a},set(r){r===null?a=null:console.warn(`Cannot override global ${i}`)},configurable:!0,enumerable:!0}),n)try{t[i]}catch(r){console.error(`Failed to initialize ${i}:`,r)}}z("pp",P);z("store",k);z("searchParams",L);
|
|
1
|
+
import{P as ce}from"./pp-reactive-v1.js";var ee=11;function le(i,e){var t=e.attributes,n,a,r,s,u;if(!(e.nodeType===ee||i.nodeType===ee)){for(var f=t.length-1;f>=0;f--)n=t[f],a=n.name,r=n.namespaceURI,s=n.value,r?(a=n.localName||a,u=i.getAttributeNS(r,a),u!==s&&(n.prefix==="xmlns"&&(a=n.name),i.setAttributeNS(r,a,s))):(u=i.getAttribute(a),u!==s&&i.setAttribute(a,s));for(var b=i.attributes,y=b.length-1;y>=0;y--)n=b[y],a=n.name,r=n.namespaceURI,r?(a=n.localName||a,e.hasAttributeNS(r,a)||i.removeAttributeNS(r,a)):e.hasAttribute(a)||i.removeAttribute(a)}}var D,de="http://www.w3.org/1999/xhtml",v=typeof document>"u"?void 0:document,ue=!!v&&"content"in v.createElement("template"),he=!!v&&v.createRange&&"createContextualFragment"in v.createRange();function fe(i){var e=v.createElement("template");return e.innerHTML=i,e.content.childNodes[0]}function pe(i){D||(D=v.createRange(),D.selectNode(v.body));var e=D.createContextualFragment(i);return e.childNodes[0]}function ve(i){var e=v.createElement("body");return e.innerHTML=i,e.childNodes[0]}function ge(i){return i=i.trim(),ue?fe(i):he?pe(i):ve(i)}function $(i,e){var t=i.nodeName,n=e.nodeName,a,r;return t===n?!0:(a=t.charCodeAt(0),r=n.charCodeAt(0),a<=90&&r>=97?t===n.toUpperCase():r<=90&&a>=97?n===t.toUpperCase():!1)}function ye(i,e){return!e||e===de?v.createElement(i):v.createElementNS(e,i)}function me(i,e){for(var t=i.firstChild;t;){var n=t.nextSibling;e.appendChild(t),t=n}return e}function j(i,e,t){i[t]!==e[t]&&(i[t]=e[t],i[t]?i.setAttribute(t,""):i.removeAttribute(t))}var te={OPTION:function(i,e){var t=i.parentNode;if(t){var n=t.nodeName.toUpperCase();n==="OPTGROUP"&&(t=t.parentNode,n=t&&t.nodeName.toUpperCase()),n==="SELECT"&&!t.hasAttribute("multiple")&&(i.hasAttribute("selected")&&!e.selected&&(i.setAttribute("selected","selected"),i.removeAttribute("selected")),t.selectedIndex=-1)}j(i,e,"selected")},INPUT:function(i,e){j(i,e,"checked"),j(i,e,"disabled"),i.value!==e.value&&(i.value=e.value),e.hasAttribute("value")||i.removeAttribute("value")},TEXTAREA:function(i,e){var t=e.value;i.value!==t&&(i.value=t);var n=i.firstChild;if(n){var a=n.nodeValue;if(a==t||!t&&a==i.placeholder)return;n.nodeValue=t}},SELECT:function(i,e){if(!e.hasAttribute("multiple")){for(var t=-1,n=0,a=i.firstChild,r,s;a;)if(s=a.nodeName&&a.nodeName.toUpperCase(),s==="OPTGROUP")r=a,a=r.firstChild,a||(a=r.nextSibling,r=null);else{if(s==="OPTION"){if(a.hasAttribute("selected")){t=n;break}n++}a=a.nextSibling,!a&&r&&(a=r.nextSibling,r=null)}i.selectedIndex=t}}},R=1,ne=11,ae=3,ie=8;function T(){}function we(i){if(i)return i.getAttribute&&i.getAttribute("id")||i.id}function be(i){return function(t,n,a){if(a||(a={}),typeof n=="string")if(t.nodeName==="#document"||t.nodeName==="HTML"||t.nodeName==="BODY"){var r=n;n=v.createElement("html"),n.innerHTML=r}else n=ge(n);else n.nodeType===ne&&(n=n.firstElementChild);var s=a.getNodeKey||we,u=a.onBeforeNodeAdded||T,f=a.onNodeAdded||T,b=a.onBeforeElUpdated||T,y=a.onElUpdated||T,I=a.onBeforeNodeDiscarded||T,g=a.onNodeDiscarded||T,m=a.onBeforeElChildrenUpdated||T,E=a.skipFromChildren||T,x=a.addChild||function(o,c){return o.appendChild(c)},q=a.childrenOnly===!0,C=Object.create(null),U=[];function _(o){U.push(o)}function X(o,c){if(o.nodeType===R)for(var h=o.firstChild;h;){var l=void 0;c&&(l=s(h))?_(l):(g(h),h.firstChild&&X(h,c)),h=h.nextSibling}}function K(o,c,h){I(o)!==!1&&(c&&c.removeChild(o),g(o),X(o,h))}function G(o){if(o.nodeType===R||o.nodeType===ne)for(var c=o.firstChild;c;){var h=s(c);h&&(C[h]=c),G(c),c=c.nextSibling}}G(t);function M(o){f(o);for(var c=o.firstChild;c;){var h=c.nextSibling,l=s(c);if(l){var d=C[l];d&&$(c,d)?(c.parentNode.replaceChild(d,c),H(d,c)):M(c)}else M(c);c=h}}function re(o,c,h){for(;c;){var l=c.nextSibling;(h=s(c))?_(h):K(c,o,!0),c=l}}function H(o,c,h){var l=s(c);if(l&&delete C[l],!h){var d=b(o,c);if(d===!1||(d instanceof HTMLElement&&(o=d,G(o)),i(o,c),y(o),m(o,c)===!1))return}o.nodeName!=="TEXTAREA"?se(o,c):te.TEXTAREA(o,c)}function se(o,c){var h=E(o,c),l=c.firstChild,d=o.firstChild,N,w,O,B,S;e:for(;l;){for(B=l.nextSibling,N=s(l);!h&&d;){if(O=d.nextSibling,l.isSameNode&&l.isSameNode(d)){l=B,d=O;continue e}w=s(d);var V=d.nodeType,A=void 0;if(V===l.nodeType&&(V===R?(N?N!==w&&((S=C[N])?O===S?A=!1:(o.insertBefore(S,d),w?_(w):K(d,o,!0),d=S,w=s(d)):A=!1):w&&(A=!1),A=A!==!1&&$(d,l),A&&H(d,l)):(V===ae||V==ie)&&(A=!0,d.nodeValue!==l.nodeValue&&(d.nodeValue=l.nodeValue))),A){l=B,d=O;continue e}w?_(w):K(d,o,!0),d=O}if(N&&(S=C[N])&&$(S,l))h||x(o,S),H(S,l);else{var W=u(l);W!==!1&&(W&&(l=W),l.actualize&&(l=l.actualize(o.ownerDocument||v)),x(o,l),M(l))}l=B,d=O}re(o,d,w);var Z=te[o.nodeName];Z&&Z(o,c)}var p=t,F=p.nodeType,Q=n.nodeType;if(!q){if(F===R)Q===R?$(t,n)||(g(t),p=me(t,ye(n.nodeName,n.namespaceURI))):p=n;else if(F===ae||F===ie){if(Q===F)return p.nodeValue!==n.nodeValue&&(p.nodeValue=n.nodeValue),p;p=n}}if(p===n)g(t);else{if(n.isSameNode&&n.isSameNode(p))return;if(H(p,n,q),U)for(var Y=0,oe=U.length;Y<oe;Y++){var J=C[U[Y]];J&&K(J,J.parentNode,!1)}}return!q&&p!==t&&t.parentNode&&(p.actualize&&(p=p.actualize(t.ownerDocument||v)),t.parentNode.replaceChild(p,t)),p}}var Se=be(le);class P extends ce{static instance=null;cryptoKey=null;activeAbortController=null;navigationEnabled=!1;boundHandleLinkClick=null;boundHandlePopState=null;isNavigating=!1;constructor(){super(),this.hydrated().then(()=>{this.isNavigating||(document.body.hidden=!1),this.enableSPANavigation()}).catch(e=>{console.error("PPHPUtilities hydration error:",e),document.body.hidden=!1})}static resetInstance(){this.instance&&(this.instance.navigationEnabled&&this.instance.disableSPANavigation(),this.instance.activeAbortController&&(this.instance.activeAbortController.abort(),this.instance.activeAbortController=null),this.instance.destroy(),this.instance=null)}static getInstance(){return this.instance||(this.instance=new P),this.instance}enableSPANavigation(){this.navigationEnabled||(this.navigationEnabled=!0,this.boundHandleLinkClick=this.handleLinkClick.bind(this),this.boundHandlePopState=this.handlePopState.bind(this),document.addEventListener("click",this.boundHandleLinkClick),window.addEventListener("popstate",this.boundHandlePopState))}disableSPANavigation(){this.navigationEnabled=!1,this.boundHandleLinkClick&&(document.removeEventListener("click",this.boundHandleLinkClick),this.boundHandleLinkClick=null),this.boundHandlePopState&&(window.removeEventListener("popstate",this.boundHandlePopState),this.boundHandlePopState=null)}handleLinkClick(e){if(!this.navigationEnabled)return;const n=e.target.closest("a");if(!(!n||!n.href))try{const a=new URL(n.href),r=a.origin!==window.location.origin,s=a.pathname===window.location.pathname&&a.search===window.location.search;if(r||n.target==="_blank"||n.hasAttribute("download")||n.getAttribute("pp-no-spa")==="true"||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;if(e.preventDefault(),s){const u=a.hash;if(u){const f=document.querySelector(u);f&&f.scrollIntoView({behavior:"smooth"})}else window.scrollTo({top:0,behavior:"smooth"});return}this.navigateTo(a.pathname+a.search+a.hash)}catch(a){console.error("Link click navigation error:",a)}}async handlePopState(){const e=window.location.pathname+window.location.search+window.location.hash;await this.navigateTo(e,!1)}async navigateTo(e,t=!0){this.isNavigating=!0;try{this.dispatchNavigationEvent("start",e),await this.showLoadingTransition();const n=await this.fetchPageContent(e);this.performCleanup(),this.updateBrowserHistory(e,t);const a=document.getElementById("loading-file-1B87E"),r="startViewTransition"in document;!a&&r?await this.updatePageContentWithViewTransition(n):this.updatePageContent(n),await this.reinitializeApp(),await this.handleNavigationCompletion(e),this.dispatchNavigationEvent("complete",e)}catch(n){this.handleNavigationError(e,n)}finally{this.isNavigating=!1}}async updatePageContentWithViewTransition(e){if(this.isNavigating){this.updatePageContent(e);return}const t=document.startViewTransition(()=>{this.updatePageContent(e)});try{await t.finished}catch(n){console.warn("View transition failed, continuing anyway:",n)}}dispatchNavigationEvent(e,t,n){const a=`pp:navigation:${e}`,r=n?{url:t,error:n}:{url:t};document.dispatchEvent(new CustomEvent(a,{detail:r}))}async showLoadingTransition(){const e=document.getElementById("loading-file-1B87E");if(e){const n=this.findLoadingElement(e,window.location.pathname);if(n){await this.updateContentWithTransition(n);return}}const t=document.querySelector("[pp-loading-content='true']")||document.body;t&&!("startViewTransition"in document)&&await this.fadeOut(t,250)}async fetchPageContent(e){const t=await fetch(e,{headers:{"X-Requested-With":"XMLHttpRequest",Accept:"text/html"}});if(!t.ok)throw new Error(`Navigation failed: ${t.status} ${t.statusText}`);const n=await t.text();return new DOMParser().parseFromString(n,"text/html")}performCleanup(){this.cleanup(),this.disableSPANavigation()}updateBrowserHistory(e,t){t&&history.pushState(null,"",e)}updatePageContent(e){e.title&&(document.title=e.title),this.reconcileHead(e);const t=e.body;Se(document.body,t,{childrenOnly:!0,onBeforeElUpdated:(n,a)=>!n.isEqualNode(a)})}async reinitializeApp(){window.pp=null,P.instance=null;const e=window.pp;return await e.hydrated(),e}async handleNavigationCompletion(e){const t=new URL(e,window.location.origin).hash;if(t){const a=document.querySelector(t);a&&a.scrollIntoView({behavior:"smooth"})}else window.scrollTo({top:0,behavior:"instant"});const n=document.querySelector("[pp-loading-content='true']")||document.body;n?requestAnimationFrame(()=>{document.body.hidden=!1,this.fadeIn(n,150)}):document.body.hidden=!1}handleNavigationError(e,t){console.error("Navigation error:",t),document.body.hidden=!1,this.dispatchNavigationEvent("error",e,t),window.location.href=e}findLoadingElement(e,t){let n=t;for(;;){const a=e.querySelector(`div[pp-loading-url='${n}']`);if(a)return a;if(n==="/")break;const r=n.lastIndexOf("/");r<=0?n="/":n=n.substring(0,r)}return e.querySelector("div[pp-loading-url='/' ]")}async updateContentWithTransition(e){const t=document.querySelector("[pp-loading-content='true']")||document.body;if(!t)return;const{fadeIn:n,fadeOut:a}=this.parseTransition(e);await this.fadeOut(t,a),t.innerHTML=e.innerHTML,this.fadeIn(t,n)}parseTransition(e){let t=250,n=250;const r=e.querySelector("[pp-loading-transition]")?.getAttribute("pp-loading-transition");if(r){let s=JSON.parse(r);s&&typeof s=="object"?(t=this.parseTime(s.fadeIn??t),n=this.parseTime(s.fadeOut??n)):console.warn("pp-loading-transition is not valid JSON → default values (250 ms) will be used. String:",r)}return{fadeIn:t,fadeOut:n}}fadeOut(e,t){return new Promise(n=>{e.style.transition=`opacity ${t}ms ease-out`,setTimeout(()=>{e.style.transition="",n()},t)})}fadeIn(e,t){e.style.transition=`opacity ${t}ms ease-in`,setTimeout(()=>{e.style.transition=""},t)}parseTime(e){if(typeof e=="number")return e;const t=e.match(/^(\d+)(ms|s|m)?$/);if(t){const n=parseInt(t[1],10);switch(t[2]||"ms"){case"ms":return n;case"s":return n*1e3;case"m":return n*60*1e3;default:return n}}return 0}reconcileHead(e){const t="pp-dynamic-script",n="pp-dynamic-meta",a="pp-dynamic-link";document.head.querySelectorAll(`[${n}]`).forEach(r=>r.remove()),document.head.querySelectorAll(`[${a}]`).forEach(r=>r.remove()),document.head.querySelectorAll(`[${t}]`).forEach(r=>r.remove()),Array.from(e.head.children).forEach(r=>{switch(r.tagName){case"SCRIPT":if(r.hasAttribute(t)){const s=document.createElement("script");Array.from(r.attributes).forEach(u=>s.setAttribute(u.name,u.value)),s.textContent=r.textContent,document.head.appendChild(s)}break;case"META":{const s=r;if(s.getAttribute("charset")||s.name==="viewport")break;const u=s.name?`meta[name="${s.name}"]`:`meta[property="${s.getAttribute("property")}"]`,f=s.cloneNode(!0),b=document.head.querySelector(u);b?document.head.replaceChild(f,b):document.head.insertBefore(f,document.head.querySelector("title")?.nextSibling||null);break}case"TITLE":{const s=r.cloneNode(!0),u=document.head.querySelector("title");u?document.head.replaceChild(s,u):document.head.appendChild(s);break}case"LINK":{const s=r;if(s.rel==="icon"){const u=s.cloneNode(!0),f=document.head.querySelector('link[rel="icon"]');f?document.head.replaceChild(u,f):document.head.appendChild(u)}else s.hasAttribute(a)&&document.head.appendChild(s.cloneNode(!0));break}}})}async redirect(e){if(e)try{const t=new URL(e,window.location.origin);t.origin!==window.location.origin?window.location.href=e:this.navigationEnabled?await this.navigateTo(t.pathname+t.search+t.hash):window.location.href=e}catch(t){console.error("Redirect error:",t)}}async initCryptoKey(){const e=document.cookie.split("; ").find(u=>u.startsWith("pp_function_call_jwt="))?.split("=",2)[1];if(!e)throw new Error("Missing function-call token");const[,t]=e.split("."),n=atob(t.replace(/-/g,"+").replace(/_/g,"/")),{k:a,exp:r}=JSON.parse(n);if(Date.now()/1e3>r)throw new Error("Function-call token expired");const s=Uint8Array.from(atob(a),u=>u.charCodeAt(0));this.cryptoKey=await crypto.subtle.importKey("raw",s,{name:"AES-CBC"},!1,["encrypt","decrypt"])}async encryptCallbackName(e){await this.initCryptoKey();const t=crypto.getRandomValues(new Uint8Array(16)),n=new TextEncoder().encode(e),a=await crypto.subtle.encrypt({name:"AES-CBC",iv:t},this.cryptoKey,n),r=btoa(String.fromCharCode(...t)),s=btoa(String.fromCharCode(...new Uint8Array(a)));return`${r}:${s}`}createFetchOptions(e){return{method:"POST",headers:{"Content-Type":"application/json",HTTP_PP_WIRE_REQUEST:"true"},body:JSON.stringify(e)}}async fetchFunction(e,t={},n=!1){let a=null;try{n&&this.activeAbortController&&(this.activeAbortController.abort(),this.activeAbortController=null),a=new AbortController,n&&(this.activeAbortController=a);const s={callback:await this.encryptCallbackName(e),...t},u=window.location.href;let f;if(Object.keys(s).some(g=>{const m=s[g];return m instanceof File||m instanceof FileList&&m.length>0})){const g=new FormData;Object.keys(s).forEach(m=>{const E=s[m];E instanceof File?g.append(m,E):E instanceof FileList?Array.from(E).forEach(x=>g.append(m,x)):g.append(m,E)}),f={method:"POST",headers:{HTTP_PP_WIRE_REQUEST:"true"},body:g,signal:a.signal}}else f={signal:a.signal,...this.createFetchOptions(s)};const y=await fetch(u,f);if(!y.ok)throw new Error(`Fetch failed with status: ${y.status} ${y.statusText}`);const I=await y.text();a&&this.activeAbortController===a&&(this.activeAbortController=null);try{return JSON.parse(I)}catch{return I}}catch(r){if(a&&this.activeAbortController===a&&(this.activeAbortController=null),r instanceof Error&&r.name==="AbortError")return console.log("Request was cancelled"),{cancelled:!0};throw console.error("Error in fetchFunction:",r),new Error("Failed to fetch data.")}}}class k{state;static instance=null;listeners;pp;STORAGE_KEY;lastSyncedState=null;constructor(e={}){this.state=e,this.listeners=[],this.pp=P.getInstance(),this.STORAGE_KEY=this.getCookie("pp_local_store_key")||"pp_local_store_59e13",this.lastSyncedState=localStorage.getItem(this.STORAGE_KEY),this.loadState()}static getInstance(e={}){return k.instance||(k.instance=new k(e)),k.instance}getCookie(e){return document.cookie.split("; ").find(t=>t.startsWith(e+"="))?.split("=")[1]||null}setState(e,t=!1){const n={...this.state,...e};if(JSON.stringify(n)!==JSON.stringify(this.state)&&(this.state=n,this.listeners.forEach(a=>a(this.state)),this.saveState(),t)){const a=localStorage.getItem(this.STORAGE_KEY);a&&a!==this.lastSyncedState&&(this.pp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:a}),this.lastSyncedState=a)}}saveState(){localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.state))}loadState(){const e=localStorage.getItem(this.STORAGE_KEY);e&&(this.state=JSON.parse(e),this.listeners.forEach(t=>t(this.state)))}resetState(e,t=!1){if(e?(delete this.state[e],this.saveState()):(this.state={},localStorage.removeItem(this.STORAGE_KEY)),this.listeners.forEach(n=>n(this.state)),t){const n=e?localStorage.getItem(this.STORAGE_KEY):null;this.pp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:n}),this.lastSyncedState=n}}}class L{static instance=null;listeners=[];constructor(){}static getInstance(){return L.instance||(L.instance=new L),L.instance}get params(){return new URLSearchParams(window.location.search)}get(e){return this.params.get(e)}set(e,t){const n=this.params;n.set(e,t),this.updateURL(n)}delete(e){const t=this.params;t.delete(e),this.updateURL(t)}replace(e){const t=new URLSearchParams;for(const n in e){const a=e[n];a!==null&&t.set(n,a)}this.updateURL(t,!0)}updateURL(e,t=!1){const n=`${window.location.pathname}?${e.toString()}`;t?history.replaceState(null,"",n):history.pushState(null,"",n),this.notifyListeners(e)}listen(e){this.listeners.push(e)}notifyListeners(e){for(const t of this.listeners)t(e)}enablePopStateListener(){window.addEventListener("popstate",()=>{this.notifyListeners(this.params)})}}function z(i,e,t=window,n=!0){let a=null;if(Object.defineProperty(t,i,{get(){if(a!==null)return a;if(e&&typeof e=="object"&&!Array.isArray(e)&&"getInstance"in e&&typeof e.getInstance=="function")return a=e.getInstance(),a;if(typeof e=="function")try{return a=e.getInstance(),a}catch{return a=e,a}else return a=e,a},set(r){r===null?a=null:console.warn(`Cannot override global ${i}`)},configurable:!0,enumerable:!0}),n)try{t[i]}catch(r){console.error(`Failed to initialize ${i}:`,r)}}z("pp",P);z("store",k);z("searchParams",L);
|
package/dist/ts/main.ts
CHANGED
|
@@ -1,2 +1,7 @@
|
|
|
1
|
-
import "
|
|
2
|
-
import "
|
|
1
|
+
import "./pp-reactive-v1.js";
|
|
2
|
+
import "./pp-utilities.js";
|
|
3
|
+
|
|
4
|
+
// The following global names have already been declared elsewhere in the project:
|
|
5
|
+
// - pp: Used for the Reactive Core functionality.
|
|
6
|
+
// - store: Handles local storage synchronization with the server.
|
|
7
|
+
// - searchParams: Manages URL manipulation and query parameters.
|