@livetemplate/client 0.1.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";var LiveTemplateClient=(()=>{var se=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var Re=Object.prototype.hasOwnProperty;var _e=(a,e)=>{for(var t in e)se(a,t,{get:e[t],enumerable:!0})},De=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Oe(e))!Re.call(a,n)&&n!==t&&se(a,n,{get:()=>e[n],enumerable:!(r=Fe(e,n))||r.enumerable});return a};var Ie=a=>De(se({},"__esModule",{value:!0}),a);var Xe={};_e(Xe,{LiveTemplateClient:()=>te,compareHTML:()=>Me,loadAndApplyUpdate:()=>Le});var fe=11;function He(a,e){var t=e.attributes,r,n,i,o,s;if(!(e.nodeType===fe||a.nodeType===fe)){for(var l=t.length-1;l>=0;l--)r=t[l],n=r.name,i=r.namespaceURI,o=r.value,i?(n=r.localName||n,s=a.getAttributeNS(i,n),s!==o&&(r.prefix==="xmlns"&&(n=r.name),a.setAttributeNS(i,n,o))):(s=a.getAttribute(n),s!==o&&a.setAttribute(n,o));for(var c=a.attributes,d=c.length-1;d>=0;d--)r=c[d],n=r.name,i=r.namespaceURI,i?(n=r.localName||n,e.hasAttributeNS(i,n)||a.removeAttributeNS(i,n)):e.hasAttribute(n)||a.removeAttribute(n)}}var P,We="http://www.w3.org/1999/xhtml",_=typeof document=="undefined"?void 0:document,Ce=!!_&&"content"in _.createElement("template"),Ne=!!_&&_.createRange&&"createContextualFragment"in _.createRange();function Ue(a){var e=_.createElement("template");return e.innerHTML=a,e.content.childNodes[0]}function $e(a){P||(P=_.createRange(),P.selectNode(_.body));var e=P.createContextualFragment(a);return e.childNodes[0]}function Be(a){var e=_.createElement("body");return e.innerHTML=a,e.childNodes[0]}function Ve(a){return a=a.trim(),Ce?Ue(a):Ne?$e(a):Be(a)}function j(a,e){var t=a.nodeName,r=e.nodeName,n,i;return t===r?!0:(n=t.charCodeAt(0),i=r.charCodeAt(0),n<=90&&i>=97?t===r.toUpperCase():i<=90&&n>=97?r===t.toUpperCase():!1)}function Ke(a,e){return!e||e===We?_.createElement(a):_.createElementNS(e,a)}function Pe(a,e){for(var t=a.firstChild;t;){var r=t.nextSibling;e.appendChild(t),t=r}return e}function ae(a,e,t){a[t]!==e[t]&&(a[t]=e[t],a[t]?a.setAttribute(t,""):a.removeAttribute(t))}var me={OPTION:function(a,e){var t=a.parentNode;if(t){var r=t.nodeName.toUpperCase();r==="OPTGROUP"&&(t=t.parentNode,r=t&&t.nodeName.toUpperCase()),r==="SELECT"&&!t.hasAttribute("multiple")&&(a.hasAttribute("selected")&&!e.selected&&(a.setAttribute("selected","selected"),a.removeAttribute("selected")),t.selectedIndex=-1)}ae(a,e,"selected")},INPUT:function(a,e){ae(a,e,"checked"),ae(a,e,"disabled"),a.value!==e.value&&(a.value=e.value),e.hasAttribute("value")||a.removeAttribute("value")},TEXTAREA:function(a,e){var t=e.value;a.value!==t&&(a.value=t);var r=a.firstChild;if(r){var n=r.nodeValue;if(n==t||!t&&n==a.placeholder)return;r.nodeValue=t}},SELECT:function(a,e){if(!e.hasAttribute("multiple")){for(var t=-1,r=0,n=a.firstChild,i,o;n;)if(o=n.nodeName&&n.nodeName.toUpperCase(),o==="OPTGROUP")i=n,n=i.firstChild,n||(n=i.nextSibling,i=null);else{if(o==="OPTION"){if(n.hasAttribute("selected")){t=r;break}r++}n=n.nextSibling,!n&&i&&(n=i.nextSibling,i=null)}a.selectedIndex=t}}},$=1,ve=11,be=3,ye=8;function W(){}function je(a){if(a)return a.getAttribute&&a.getAttribute("id")||a.id}function qe(a){return function(t,r,n){if(n||(n={}),typeof r=="string")if(t.nodeName==="#document"||t.nodeName==="HTML"||t.nodeName==="BODY"){var i=r;r=_.createElement("html"),r.innerHTML=i}else r=Ve(r);else r.nodeType===ve&&(r=r.firstElementChild);var o=n.getNodeKey||je,s=n.onBeforeNodeAdded||W,l=n.onNodeAdded||W,c=n.onBeforeElUpdated||W,d=n.onElUpdated||W,A=n.onBeforeNodeDiscarded||W,m=n.onNodeDiscarded||W,f=n.onBeforeElChildrenUpdated||W,F=n.skipFromChildren||W,M=n.addChild||function(g,p){return g.appendChild(p)},b=n.childrenOnly===!0,h=Object.create(null),u=[];function y(g){u.push(g)}function O(g,p){if(g.nodeType===$)for(var T=g.firstChild;T;){var v=void 0;p&&(v=o(T))?y(v):(m(T),T.firstChild&&O(T,p)),T=T.nextSibling}}function x(g,p,T){A(g)!==!1&&(p&&p.removeChild(g),m(g),O(g,T))}function w(g){if(g.nodeType===$||g.nodeType===ve)for(var p=g.firstChild;p;){var T=o(p);T&&(h[T]=p),w(p),p=p.nextSibling}}w(t);function S(g){l(g);for(var p=g.firstChild;p;){var T=p.nextSibling,v=o(p);if(v){var E=h[v];E&&j(p,E)?(p.parentNode.replaceChild(E,p),R(E,p)):S(p)}else S(p);p=T}}function k(g,p,T){for(;p;){var v=p.nextSibling;(T=o(p))?y(T):x(p,g,!0),p=v}}function R(g,p,T){var v=o(p);if(v&&delete h[v],!T){var E=c(g,p);if(E===!1||(E instanceof HTMLElement&&(g=E,w(g)),a(g,p),d(g),f(g,p)===!1))return}g.nodeName!=="TEXTAREA"?C(g,p):me.TEXTAREA(g,p)}function C(g,p){var T=F(g,p),v=p.firstChild,E=g.firstChild,N,D,U,V,I;e:for(;v;){for(V=v.nextSibling,N=o(v);!T&&E;){if(U=E.nextSibling,v.isSameNode&&v.isSameNode(E)){v=V,E=U;continue e}D=o(E);var K=E.nodeType,H=void 0;if(K===v.nodeType&&(K===$?(N?N!==D&&((I=h[N])?U===I?H=!1:(g.insertBefore(I,E),D?y(D):x(E,g,!0),E=I,D=o(E)):H=!1):D&&(H=!1),H=H!==!1&&j(E,v),H&&R(E,v)):(K===be||K==ye)&&(H=!0,E.nodeValue!==v.nodeValue&&(E.nodeValue=v.nodeValue))),H){v=V,E=U;continue e}D?y(D):x(E,g,!0),E=U}if(N&&(I=h[N])&&j(I,v))T||M(g,I),R(I,v);else{var ie=s(v);ie!==!1&&(ie&&(v=ie),v.actualize&&(v=v.actualize(g.ownerDocument||_)),M(g,v),S(v))}v=V,E=U}k(g,E,D);var he=me[g.nodeName];he&&he(g,p)}var L=t,B=L.nodeType,pe=r.nodeType;if(!b){if(B===$)pe===$?j(t,r)||(m(t),L=Pe(t,Ke(r.nodeName,r.namespaceURI))):L=r;else if(B===be||B===ye){if(pe===B)return L.nodeValue!==r.nodeValue&&(L.nodeValue=r.nodeValue),L;L=r}}if(L===r)m(t);else{if(r.isSameNode&&r.isSameNode(L))return;if(R(L,r,b),u)for(var ne=0,xe=u.length;ne<xe;ne++){var re=h[u[ne]];re&&x(re,re.parentNode,!1)}}return!b&&L!==t&&t.parentNode&&(L.actualize&&(L=L.actualize(t.ownerDocument||_)),t.parentNode.replaceChild(L,t)),L}}var ze=qe(He),Ee=ze;var oe=["text","textarea","number","email","password","search","tel","url","date","time","datetime-local","color","range"];var q=class{constructor(e){this.logger=e;this.wrapperElement=null;this.focusableElements=[];this.lastFocusedElement=null;this.lastFocusedSelectionStart=null;this.lastFocusedSelectionEnd=null}attach(e){this.wrapperElement=e,e&&(this.updateFocusableElements(),this.setupFocusTracking())}reset(){this.wrapperElement=null,this.focusableElements=[],this.lastFocusedElement=null,this.lastFocusedSelectionStart=null,this.lastFocusedSelectionEnd=null}updateFocusableElements(){if(!this.wrapperElement)return;let r=`${oe.map(n=>n==="textarea"?"textarea:not([disabled])":`input[type="${n}"]:not([disabled])`).join(", ")}, select:not([disabled]), button:not([disabled]), [contenteditable="true"], [tabindex]:not([tabindex="-1"])`;this.focusableElements=Array.from(this.wrapperElement.querySelectorAll(r))}setupFocusTracking(){if(!this.wrapperElement)return;let e=this.wrapperElement.getAttribute("data-lvt-id"),t=`__lvt_focus_tracker_${e}`,r=`__lvt_blur_tracker_${e}`,n=o=>{var l;let s=o.target;!s||!((l=this.wrapperElement)!=null&&l.contains(s))||(this.isTextualInput(s)||s instanceof HTMLSelectElement)&&(this.lastFocusedElement=s,this.logger.debug("[Focus] Tracked focus on:",s.tagName,s.id||s.getAttribute("name")),this.isTextualInput(s)&&(this.lastFocusedSelectionStart=s.selectionStart,this.lastFocusedSelectionEnd=s.selectionEnd))},i=o=>{var l;let s=o.target;!s||!((l=this.wrapperElement)!=null&&l.contains(s))||this.isTextualInput(s)&&s===this.lastFocusedElement&&(this.lastFocusedSelectionStart=s.selectionStart,this.lastFocusedSelectionEnd=s.selectionEnd,this.logger.debug("[Focus] Saved cursor on blur:",this.lastFocusedSelectionStart,"-",this.lastFocusedSelectionEnd))};document[t]&&document.removeEventListener("focus",document[t],!0),document[r]&&document.removeEventListener("blur",document[r],!0),document[t]=n,document[r]=i,document.addEventListener("focus",n,!0),document.addEventListener("blur",i,!0),this.logger.debug("[Focus] Focus tracking set up")}restoreFocusedElement(){var n,i,o;if(this.logger.debug("[Focus] restoreFocusedElement - lastFocusedElement:",(n=this.lastFocusedElement)==null?void 0:n.tagName,((i=this.lastFocusedElement)==null?void 0:i.id)||((o=this.lastFocusedElement)==null?void 0:o.getAttribute("name"))),!this.lastFocusedElement||!this.wrapperElement){this.logger.debug("[Focus] No element to restore");return}let e=this.getElementSelector(this.lastFocusedElement);if(this.logger.debug("[Focus] Selector for last focused:",e),!e){this.logger.debug("[Focus] Could not generate selector");return}let t=null;if(e.startsWith("data-focus-index-")){this.updateFocusableElements();let s=parseInt(e.replace("data-focus-index-",""),10);t=this.focusableElements[s]||null,this.logger.debug("[Focus] Found by index:",s,t==null?void 0:t.tagName)}else t=this.wrapperElement.querySelector(e),this.logger.debug("[Focus] Found by selector:",e,t==null?void 0:t.tagName);if(!t){this.logger.debug("[Focus] Element not found in updated DOM");return}let r=t.matches(":focus");this.logger.debug("[Focus] Already focused:",r),r||(t.focus(),this.logger.debug("[Focus] Restored focus")),this.isTextualInput(t)&&this.lastFocusedSelectionStart!==null&&this.lastFocusedSelectionEnd!==null&&(t.setSelectionRange(this.lastFocusedSelectionStart,this.lastFocusedSelectionEnd),this.logger.debug("[Focus] Restored cursor:",this.lastFocusedSelectionStart,"-",this.lastFocusedSelectionEnd))}isTextualInput(e){return e instanceof HTMLTextAreaElement?!0:e instanceof HTMLInputElement?oe.indexOf(e.type)>=0:!1}getLastFocusedElement(){return this.lastFocusedElement}getElementSelector(e){if(e.id)return`#${e.id}`;if(e.name)return`[name="${e.name}"]`;if(e.getAttribute("data-key"))return`[data-key="${e.getAttribute("data-key")}"]`;let t=this.focusableElements.indexOf(e);return t>=0?`data-focus-index-${t}`:null}};function we(a){a.querySelectorAll("[lvt-scroll]").forEach(t=>{let r=t,n=r.getAttribute("lvt-scroll"),i=r.getAttribute("lvt-scroll-behavior")||"auto",o=parseInt(r.getAttribute("lvt-scroll-threshold")||"100",10);if(n)switch(n){case"bottom":r.scrollTo({top:r.scrollHeight,behavior:i});break;case"bottom-sticky":{r.scrollHeight-r.scrollTop-r.clientHeight<=o&&r.scrollTo({top:r.scrollHeight,behavior:i});break}case"top":r.scrollTo({top:0,behavior:i});break;case"preserve":break;default:console.warn(`Unknown lvt-scroll mode: ${n}`)}})}function Se(a){a.querySelectorAll("[lvt-highlight]").forEach(t=>{let r=t.getAttribute("lvt-highlight"),n=parseInt(t.getAttribute("lvt-highlight-duration")||"500",10),i=t.getAttribute("lvt-highlight-color")||"#ffc107";if(!r)return;let o=t,s=o.style.backgroundColor,l=o.style.transition;o.style.transition=`background-color ${n}ms ease-out`,o.style.backgroundColor=i,setTimeout(()=>{o.style.backgroundColor=s,setTimeout(()=>{o.style.transition=l},n)},50)})}function Ae(a){if(a.querySelectorAll("[lvt-animate]").forEach(t=>{let r=t.getAttribute("lvt-animate"),n=parseInt(t.getAttribute("lvt-animate-duration")||"300",10);if(!r)return;let i=t;switch(i.style.setProperty("--lvt-animate-duration",`${n}ms`),r){case"fade":i.style.animation="lvt-fade-in var(--lvt-animate-duration) ease-out";break;case"slide":i.style.animation="lvt-slide-in var(--lvt-animate-duration) ease-out";break;case"scale":i.style.animation="lvt-scale-in var(--lvt-animate-duration) ease-out";break;default:console.warn(`Unknown lvt-animate mode: ${r}`)}i.addEventListener("animationend",()=>{i.style.animation=""},{once:!0})}),!document.getElementById("lvt-animate-styles")){let t=document.createElement("style");t.id="lvt-animate-styles",t.textContent=`
1
+ "use strict";var LiveTemplateClient=(()=>{var ae=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var Re=Object.prototype.hasOwnProperty;var He=(a,e)=>{for(var t in e)ae(a,t,{get:e[t],enumerable:!0})},Oe=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ce(e))!Re.call(a,r)&&r!==t&&ae(a,r,{get:()=>e[r],enumerable:!(n=_e(e,r))||n.enumerable});return a};var Ie=a=>Oe(ae({},"__esModule",{value:!0}),a);var Qe={};He(Qe,{LiveTemplateClient:()=>re,compareHTML:()=>Fe,loadAndApplyUpdate:()=>xe});var ve=11;function De(a,e){var t=e.attributes,n,r,s,o,i;if(!(e.nodeType===ve||a.nodeType===ve)){for(var l=t.length-1;l>=0;l--)n=t[l],r=n.name,s=n.namespaceURI,o=n.value,s?(r=n.localName||r,i=a.getAttributeNS(s,r),i!==o&&(n.prefix==="xmlns"&&(r=n.name),a.setAttributeNS(s,r,o))):(i=a.getAttribute(r),i!==o&&a.setAttribute(r,o));for(var c=a.attributes,d=c.length-1;d>=0;d--)n=c[d],r=n.name,s=n.namespaceURI,s?(r=n.localName||r,e.hasAttributeNS(s,r)||a.removeAttributeNS(s,r)):e.hasAttribute(r)||a.removeAttribute(r)}}var K,Ne="http://www.w3.org/1999/xhtml",C=typeof document=="undefined"?void 0:document,We=!!C&&"content"in C.createElement("template"),$e=!!C&&C.createRange&&"createContextualFragment"in C.createRange();function Pe(a){var e=C.createElement("template");return e.innerHTML=a,e.content.childNodes[0]}function Be(a){K||(K=C.createRange(),K.selectNode(C.body));var e=K.createContextualFragment(a);return e.childNodes[0]}function Ve(a){var e=C.createElement("body");return e.innerHTML=a,e.childNodes[0]}function Ke(a){return a=a.trim(),We?Pe(a):$e?Be(a):Ve(a)}function j(a,e){var t=a.nodeName,n=e.nodeName,r,s;return t===n?!0:(r=t.charCodeAt(0),s=n.charCodeAt(0),r<=90&&s>=97?t===n.toUpperCase():s<=90&&r>=97?n===t.toUpperCase():!1)}function je(a,e){return!e||e===Ne?C.createElement(a):C.createElementNS(e,a)}function ze(a,e){for(var t=a.firstChild;t;){var n=t.nextSibling;e.appendChild(t),t=n}return e}function le(a,e,t){a[t]!==e[t]&&(a[t]=e[t],a[t]?a.setAttribute(t,""):a.removeAttribute(t))}var be={OPTION:function(a,e){var t=a.parentNode;if(t){var n=t.nodeName.toUpperCase();n==="OPTGROUP"&&(t=t.parentNode,n=t&&t.nodeName.toUpperCase()),n==="SELECT"&&!t.hasAttribute("multiple")&&(a.hasAttribute("selected")&&!e.selected&&(a.setAttribute("selected","selected"),a.removeAttribute("selected")),t.selectedIndex=-1)}le(a,e,"selected")},INPUT:function(a,e){le(a,e,"checked"),le(a,e,"disabled"),a.value!==e.value&&(a.value=e.value),e.hasAttribute("value")||a.removeAttribute("value")},TEXTAREA:function(a,e){var t=e.value;a.value!==t&&(a.value=t);var n=a.firstChild;if(n){var r=n.nodeValue;if(r==t||!t&&r==a.placeholder)return;n.nodeValue=t}},SELECT:function(a,e){if(!e.hasAttribute("multiple")){for(var t=-1,n=0,r=a.firstChild,s,o;r;)if(o=r.nodeName&&r.nodeName.toUpperCase(),o==="OPTGROUP")s=r,r=s.firstChild,r||(r=s.nextSibling,s=null);else{if(o==="OPTION"){if(r.hasAttribute("selected")){t=n;break}n++}r=r.nextSibling,!r&&s&&(r=s.nextSibling,s=null)}a.selectedIndex=t}}},P=1,ye=11,Ee=3,we=8;function N(){}function qe(a){if(a)return a.getAttribute&&a.getAttribute("id")||a.id}function Ge(a){return function(t,n,r){if(r||(r={}),typeof n=="string")if(t.nodeName==="#document"||t.nodeName==="HTML"||t.nodeName==="BODY"){var s=n;n=C.createElement("html"),n.innerHTML=s}else n=Ke(n);else n.nodeType===ye&&(n=n.firstElementChild);var o=r.getNodeKey||qe,i=r.onBeforeNodeAdded||N,l=r.onNodeAdded||N,c=r.onBeforeElUpdated||N,d=r.onElUpdated||N,M=r.onBeforeNodeDiscarded||N,m=r.onNodeDiscarded||N,f=r.onBeforeElChildrenUpdated||N,F=r.skipFromChildren||N,L=r.addChild||function(p,g){return p.appendChild(g)},b=r.childrenOnly===!0,h=Object.create(null),u=[];function y(p){u.push(p)}function U(p,g){if(p.nodeType===P)for(var T=p.firstChild;T;){var v=void 0;g&&(v=o(T))?y(v):(m(T),T.firstChild&&U(T,g)),T=T.nextSibling}}function x(p,g,T){M(p)!==!1&&(g&&g.removeChild(p),m(p),U(p,T))}function w(p){if(p.nodeType===P||p.nodeType===ye)for(var g=p.firstChild;g;){var T=o(g);T&&(h[T]=g),w(g),g=g.nextSibling}}w(t);function S(p){l(p);for(var g=p.firstChild;g;){var T=g.nextSibling,v=o(g);if(v){var E=h[v];E&&j(g,E)?(g.parentNode.replaceChild(E,g),_(E,g)):S(g)}else S(g);g=T}}function k(p,g,T){for(;g;){var v=g.nextSibling;(T=o(g))?y(T):x(g,p,!0),g=v}}function _(p,g,T){var v=o(g);if(v&&delete h[v],!T){var E=c(p,g);if(E===!1||(E instanceof HTMLElement&&(p=E,w(p)),a(p,g),d(p),f(p,g)===!1))return}p.nodeName!=="TEXTAREA"?H(p,g):be.TEXTAREA(p,g)}function H(p,g){var T=F(p,g),v=g.firstChild,E=p.firstChild,W,R,$,B,I;e:for(;v;){for(B=v.nextSibling,W=o(v);!T&&E;){if($=E.nextSibling,v.isSameNode&&v.isSameNode(E)){v=B,E=$;continue e}R=o(E);var V=E.nodeType,D=void 0;if(V===v.nodeType&&(V===P?(W?W!==R&&((I=h[W])?$===I?D=!1:(p.insertBefore(I,E),R?y(R):x(E,p,!0),E=I,R=o(E)):D=!1):R&&(D=!1),D=D!==!1&&j(E,v),D&&_(E,v)):(V===Ee||V==we)&&(D=!0,E.nodeValue!==v.nodeValue&&(E.nodeValue=v.nodeValue))),D){v=B,E=$;continue e}R?y(R):x(E,p,!0),E=$}if(W&&(I=h[W])&&j(I,v))T||L(p,I),_(I,v);else{var oe=i(v);oe!==!1&&(oe&&(v=oe),v.actualize&&(v=v.actualize(p.ownerDocument||C)),L(p,v),S(v))}v=B,E=$}k(p,E,R);var me=be[p.nodeName];me&&me(p,g)}var A=t,O=A.nodeType,fe=n.nodeType;if(!b){if(O===P)fe===P?j(t,n)||(m(t),A=ze(t,je(n.nodeName,n.namespaceURI))):A=n;else if(O===Ee||O===we){if(fe===O)return A.nodeValue!==n.nodeValue&&(A.nodeValue=n.nodeValue),A;A=n}}if(A===n)m(t);else{if(n.isSameNode&&n.isSameNode(A))return;if(_(A,n,b),u)for(var se=0,Ue=u.length;se<Ue;se++){var ie=h[u[se]];ie&&x(ie,ie.parentNode,!1)}}return!b&&A!==t&&t.parentNode&&(A.actualize&&(A=A.actualize(t.ownerDocument||C)),t.parentNode.replaceChild(A,t)),A}}var Je=Ge(De),Se=Je;var ce=["text","textarea","number","email","password","search","tel","url","date","time","datetime-local","color","range"];var z=class{constructor(e){this.logger=e;this.wrapperElement=null;this.focusableElements=[];this.lastFocusedElement=null;this.lastFocusedSelectionStart=null;this.lastFocusedSelectionEnd=null}attach(e){this.wrapperElement=e,e&&(this.updateFocusableElements(),this.setupFocusTracking())}reset(){this.wrapperElement=null,this.focusableElements=[],this.lastFocusedElement=null,this.lastFocusedSelectionStart=null,this.lastFocusedSelectionEnd=null}updateFocusableElements(){if(!this.wrapperElement)return;let n=`${ce.map(r=>r==="textarea"?"textarea:not([disabled])":`input[type="${r}"]:not([disabled])`).join(", ")}, select:not([disabled]), button:not([disabled]), [contenteditable="true"], [tabindex]:not([tabindex="-1"])`;this.focusableElements=Array.from(this.wrapperElement.querySelectorAll(n))}setupFocusTracking(){if(!this.wrapperElement)return;let e=this.wrapperElement.getAttribute("data-lvt-id"),t=`__lvt_focus_tracker_${e}`,n=`__lvt_blur_tracker_${e}`,r=o=>{var l;let i=o.target;!i||!((l=this.wrapperElement)!=null&&l.contains(i))||(this.isTextualInput(i)||i instanceof HTMLSelectElement)&&(this.lastFocusedElement=i,this.logger.debug("[Focus] Tracked focus on:",i.tagName,i.id||i.getAttribute("name")),this.isTextualInput(i)&&(this.lastFocusedSelectionStart=i.selectionStart,this.lastFocusedSelectionEnd=i.selectionEnd))},s=o=>{var l;let i=o.target;!i||!((l=this.wrapperElement)!=null&&l.contains(i))||this.isTextualInput(i)&&i===this.lastFocusedElement&&(this.lastFocusedSelectionStart=i.selectionStart,this.lastFocusedSelectionEnd=i.selectionEnd,this.logger.debug("[Focus] Saved cursor on blur:",this.lastFocusedSelectionStart,"-",this.lastFocusedSelectionEnd))};document[t]&&document.removeEventListener("focus",document[t],!0),document[n]&&document.removeEventListener("blur",document[n],!0),document[t]=r,document[n]=s,document.addEventListener("focus",r,!0),document.addEventListener("blur",s,!0),this.logger.debug("[Focus] Focus tracking set up")}restoreFocusedElement(){var r,s,o;if(this.logger.debug("[Focus] restoreFocusedElement - lastFocusedElement:",(r=this.lastFocusedElement)==null?void 0:r.tagName,((s=this.lastFocusedElement)==null?void 0:s.id)||((o=this.lastFocusedElement)==null?void 0:o.getAttribute("name"))),!this.lastFocusedElement||!this.wrapperElement){this.logger.debug("[Focus] No element to restore");return}let e=this.getElementSelector(this.lastFocusedElement);if(this.logger.debug("[Focus] Selector for last focused:",e),!e){this.logger.debug("[Focus] Could not generate selector");return}let t=null;if(e.startsWith("data-focus-index-")){this.updateFocusableElements();let i=parseInt(e.replace("data-focus-index-",""),10);t=this.focusableElements[i]||null,this.logger.debug("[Focus] Found by index:",i,t==null?void 0:t.tagName)}else t=this.wrapperElement.querySelector(e),this.logger.debug("[Focus] Found by selector:",e,t==null?void 0:t.tagName);if(!t){this.logger.debug("[Focus] Element not found in updated DOM");return}let n=t.matches(":focus");this.logger.debug("[Focus] Already focused:",n),n||(t.focus(),this.logger.debug("[Focus] Restored focus")),this.isTextualInput(t)&&this.lastFocusedSelectionStart!==null&&this.lastFocusedSelectionEnd!==null&&(t.setSelectionRange(this.lastFocusedSelectionStart,this.lastFocusedSelectionEnd),this.logger.debug("[Focus] Restored cursor:",this.lastFocusedSelectionStart,"-",this.lastFocusedSelectionEnd))}isTextualInput(e){return e instanceof HTMLTextAreaElement?!0:e instanceof HTMLInputElement?ce.indexOf(e.type)>=0:!1}getLastFocusedElement(){return this.lastFocusedElement}getElementSelector(e){if(e.id)return`#${e.id}`;if(e.name)return`[name="${e.name}"]`;if(e.getAttribute("data-key"))return`[data-key="${e.getAttribute("data-key")}"]`;let t=this.focusableElements.indexOf(e);return t>=0?`data-focus-index-${t}`:null}};function Me(a){a.querySelectorAll("[lvt-scroll]").forEach(t=>{let n=t,r=n.getAttribute("lvt-scroll"),s=n.getAttribute("lvt-scroll-behavior")||"auto",o=parseInt(n.getAttribute("lvt-scroll-threshold")||"100",10);if(r)switch(r){case"bottom":n.scrollTo({top:n.scrollHeight,behavior:s});break;case"bottom-sticky":{n.scrollHeight-n.scrollTop-n.clientHeight<=o&&n.scrollTo({top:n.scrollHeight,behavior:s});break}case"top":n.scrollTo({top:0,behavior:s});break;case"preserve":break;default:console.warn(`Unknown lvt-scroll mode: ${r}`)}})}function ke(a){a.querySelectorAll("[lvt-highlight]").forEach(t=>{let n=t.getAttribute("lvt-highlight"),r=parseInt(t.getAttribute("lvt-highlight-duration")||"500",10),s=t.getAttribute("lvt-highlight-color")||"#ffc107";if(!n)return;let o=t,i=o.style.backgroundColor,l=o.style.transition;o.style.transition=`background-color ${r}ms ease-out`,o.style.backgroundColor=s,setTimeout(()=>{o.style.backgroundColor=i,setTimeout(()=>{o.style.transition=l},r)},50)})}function Ae(a){if(a.querySelectorAll("[lvt-animate]").forEach(t=>{let n=t.getAttribute("lvt-animate"),r=parseInt(t.getAttribute("lvt-animate-duration")||"300",10);if(!n)return;let s=t;switch(s.style.setProperty("--lvt-animate-duration",`${r}ms`),n){case"fade":s.style.animation="lvt-fade-in var(--lvt-animate-duration) ease-out";break;case"slide":s.style.animation="lvt-slide-in var(--lvt-animate-duration) ease-out";break;case"scale":s.style.animation="lvt-scale-in var(--lvt-animate-duration) ease-out";break;default:console.warn(`Unknown lvt-animate mode: ${n}`)}s.addEventListener("animationend",()=>{s.style.animation=""},{once:!0})}),!document.getElementById("lvt-animate-styles")){let t=document.createElement("style");t.id="lvt-animate-styles",t.textContent=`
2
2
  @keyframes lvt-fade-in {
3
3
  from { opacity: 0; }
4
4
  to { opacity: 1; }
@@ -23,7 +23,7 @@
23
23
  transform: scale(1);
24
24
  }
25
25
  }
26
- `,document.head.appendChild(t)}}function le(a,e){let t=null;return function(...n){let i=this;t!==null&&clearTimeout(t),t=window.setTimeout(()=>{a.apply(i,n)},e)}}function ce(a,e){let t=!1;return function(...n){let i=this;t||(a.apply(i,n),t=!0,setTimeout(()=>{t=!1},e))}}var z=class{constructor(e,t){this.context=e;this.logger=t}setupEventDelegation(){let e=this.context.getWrapperElement();if(!e)return;let t=["click","submit","change","input","keydown","keyup","focus","blur","mouseenter","mouseleave"],r=e.getAttribute("data-lvt-id"),n=this.context.getRateLimitedHandlers();t.forEach(i=>{let o=`__lvt_delegated_${i}_${r}`,s=document[o];s&&document.removeEventListener(i,s,!1);let l=c=>{var M;let d=this.context.getWrapperElement();if(!d)return;i==="submit"&&(window.__lvtSubmitListenerTriggered=!0,window.__lvtSubmitEventTarget=(M=c.target)==null?void 0:M.tagName),this.logger.debug("Event listener triggered:",i,c.target);let A=c.target;if(!A)return;let m=A,f=!1;for(;m;){if(m===d){f=!0;break}m=m.parentElement}if(i==="submit"&&(window.__lvtInWrapper=f,window.__lvtWrapperElement=d.getAttribute("data-lvt-id")),!f)return;let F=`lvt-${i}`;for(m=A;m&&m!==d.parentElement;){let b=m.getAttribute(F),h=m;if(!b&&(i==="change"||i==="input")){let u=m.closest("form");u&&u.hasAttribute("lvt-change")&&(b=u.getAttribute("lvt-change"),h=u)}if(b&&h){if(i==="submit"&&(window.__lvtActionFound=b,window.__lvtActionElement=h.tagName),i==="submit"&&c.preventDefault(),(i==="keydown"||i==="keyup")&&h.hasAttribute("lvt-key")){let w=h.getAttribute("lvt-key");if(w&&c.key!==w){m=m.parentElement;continue}}let u=h,y=()=>{if(this.logger.debug("handleAction called",{action:b,eventType:i,targetElement:u}),b==="delete"&&u.hasAttribute("lvt-confirm")){let S=u.getAttribute("lvt-confirm")||"Are you sure you want to delete this item?";if(!confirm(S)){this.logger.debug("Delete action cancelled by user");return}}let w={action:b,data:{}};if(u instanceof HTMLFormElement){this.logger.debug("Processing form element");let S=new FormData(u),k=Array.from(u.querySelectorAll('input[type="checkbox"][name]')),R=new Set(k.map(C=>C.name));R.forEach(C=>{w.data[C]=!1}),S.forEach((C,L)=>{R.has(L)?(w.data[L]=!0,this.logger.debug("Converted checkbox",L,"to true")):w.data[L]=this.context.parseValue(C)}),this.logger.debug("Form data collected:",w.data)}else if(i==="change"||i==="input"){if(u instanceof HTMLInputElement){let S=u.name||"value";w.data[S]=this.context.parseValue(u.value)}else if(u instanceof HTMLSelectElement){let S=u.name||"value";w.data[S]=this.context.parseValue(u.value)}else if(u instanceof HTMLTextAreaElement){let S=u.name||"value";w.data[S]=this.context.parseValue(u.value)}}if(Array.from(u.attributes).forEach(S=>{if(S.name.startsWith("lvt-data-")){let k=S.name.replace("lvt-data-","");w.data[k]=this.context.parseValue(S.value)}}),Array.from(u.attributes).forEach(S=>{if(S.name.startsWith("lvt-value-")){let k=S.name.replace("lvt-value-","");w.data[k]=this.context.parseValue(S.value)}}),i==="submit"&&u instanceof HTMLFormElement){let k=c.submitter,R=null;k&&k.hasAttribute("lvt-disable-with")&&(R=k.textContent,k.disabled=!0,k.textContent=k.getAttribute("lvt-disable-with"),this.logger.debug("Disabled submit button")),this.context.setActiveSubmission(u,k||null,R),u.dispatchEvent(new CustomEvent("lvt:pending",{detail:w})),this.logger.debug("Emitted lvt:pending event")}this.logger.debug("About to send message:",w),this.logger.debug("WebSocket state:",this.context.getWebSocketReadyState()),this.context.send(w),this.logger.debug("send() called")},O=h.getAttribute("lvt-throttle"),x=h.getAttribute("lvt-debounce");if(O||x){n.has(h)||n.set(h,new Map);let w=n.get(h),S=`${i}:${b}`,k=w.get(S);if(!k){if(O){let R=parseInt(O,10);k=ce(y,R)}else if(x){let R=parseInt(x,10);k=le(y,R)}k&&w.set(S,k)}k&&k()}else i==="submit"&&(window.__lvtBeforeHandleAction=!0),y(),i==="submit"&&(window.__lvtAfterHandleAction=!0);return}m=m.parentElement}};document[o]=l,document.addEventListener(i,l,!1),this.logger.debug("Registered event listener:",i,"with key:",o)})}setupWindowEventDelegation(){let e=this.context.getWrapperElement();if(!e)return;let t=["keydown","keyup","scroll","resize","focus","blur"],r=e.getAttribute("data-lvt-id"),n=this.context.getRateLimitedHandlers();t.forEach(i=>{let o=`__lvt_window_${i}_${r}`,s=window[o];s&&window.removeEventListener(i,s);let l=c=>{let d=this.context.getWrapperElement();if(!d)return;let A=`lvt-window-${i}`;d.querySelectorAll(`[${A}]`).forEach(f=>{let F=f.getAttribute(A);if(!F)return;if((i==="keydown"||i==="keyup")&&f.hasAttribute("lvt-key")){let y=f.getAttribute("lvt-key");if(y&&c.key!==y)return}let M={action:F,data:{}};Array.from(f.attributes).forEach(y=>{if(y.name.startsWith("lvt-data-")){let O=y.name.replace("lvt-data-","");M.data[O]=this.context.parseValue(y.value)}}),Array.from(f.attributes).forEach(y=>{if(y.name.startsWith("lvt-value-")){let O=y.name.replace("lvt-value-","");M.data[O]=this.context.parseValue(y.value)}});let b=f.getAttribute("lvt-throttle"),h=f.getAttribute("lvt-debounce"),u=()=>this.context.send(M);if(b||h){n.has(f)||n.set(f,new Map);let y=n.get(f),O=`window-${i}:${F}`,x=y.get(O);if(!x){if(b){let w=parseInt(b,10);x=ce(u,w)}else if(h){let w=parseInt(h,10);x=le(u,w)}x&&y.set(O,x)}x&&x()}else u()})};window[o]=l,window.addEventListener(i,l)})}setupClickAwayDelegation(){let e=this.context.getWrapperElement();if(!e)return;let r=`__lvt_click_away_${e.getAttribute("data-lvt-id")}`,n=document[r];n&&document.removeEventListener("click",n);let i=o=>{let s=this.context.getWrapperElement();if(!s)return;let l=o.target;s.querySelectorAll("[lvt-click-away]").forEach(d=>{if(!d.contains(l)){let A=d.getAttribute("lvt-click-away");if(!A)return;let m={action:A,data:{}};Array.from(d.attributes).forEach(f=>{if(f.name.startsWith("lvt-data-")){let F=f.name.replace("lvt-data-","");m.data[F]=this.context.parseValue(f.value)}}),Array.from(d.attributes).forEach(f=>{if(f.name.startsWith("lvt-value-")){let F=f.name.replace("lvt-value-","");m.data[F]=this.context.parseValue(f.value)}}),this.context.send(m)}})};document[r]=i,document.addEventListener("click",i)}setupModalDelegation(){let e=this.context.getWrapperElement();if(!e)return;let t=e.getAttribute("data-lvt-id"),r=`__lvt_modal_open_${t}`,n=document[r];n&&document.removeEventListener("click",n);let i=M=>{var y;let b=this.context.getWrapperElement();if(!b)return;let h=(y=M.target)==null?void 0:y.closest("[lvt-modal-open]");if(!h||!b.contains(h))return;let u=h.getAttribute("lvt-modal-open");u&&(M.preventDefault(),this.context.openModal(u))};document[r]=i,document.addEventListener("click",i);let o=`__lvt_modal_close_${t}`,s=document[o];s&&document.removeEventListener("click",s);let l=M=>{var y;let b=this.context.getWrapperElement();if(!b)return;let h=(y=M.target)==null?void 0:y.closest("[lvt-modal-close]");if(!h||!b.contains(h))return;let u=h.getAttribute("lvt-modal-close");u&&(M.preventDefault(),this.context.closeModal(u))};document[o]=l,document.addEventListener("click",l);let c=`__lvt_modal_backdrop_${t}`,d=document[c];d&&document.removeEventListener("click",d);let A=M=>{let b=M.target;if(!b.hasAttribute("data-modal-backdrop"))return;let h=b.getAttribute("data-modal-id");h&&this.context.closeModal(h)};document[c]=A,document.addEventListener("click",A);let m=`__lvt_modal_escape_${t}`,f=document[m];f&&document.removeEventListener("keydown",f);let F=M=>{if(M.key!=="Escape")return;let b=this.context.getWrapperElement();if(!b)return;let h=b.querySelectorAll('[role="dialog"]:not([hidden])');if(h.length>0){let u=h[h.length-1];u.id&&this.context.closeModal(u.id)}};document[m]=F,document.addEventListener("keydown",F)}};var G=class{constructor(e,t){this.context=e;this.logger=t;this.infiniteScrollObserver=null;this.mutationObserver=null}setupInfiniteScrollObserver(){if(!this.context.getWrapperElement())return;let t=document.getElementById("scroll-sentinel");t&&(this.infiniteScrollObserver&&this.infiniteScrollObserver.disconnect(),this.infiniteScrollObserver=new IntersectionObserver(r=>{r[0].isIntersecting&&(this.logger.debug("Sentinel visible, sending load_more action"),this.context.send({action:"load_more"}))},{rootMargin:"200px"}),this.infiniteScrollObserver.observe(t),this.logger.debug("Observer set up successfully"))}setupInfiniteScrollMutationObserver(){let e=this.context.getWrapperElement();e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.setupInfiniteScrollObserver()}),this.mutationObserver.observe(e,{childList:!0,subtree:!0}),this.logger.debug("MutationObserver set up successfully"))}teardown(){this.infiniteScrollObserver&&(this.infiniteScrollObserver.disconnect(),this.infiniteScrollObserver=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}};var J=class{constructor(e){this.logger=e}open(e){let t=document.getElementById(e);if(!t){this.logger.warn(`Modal with id="${e}" not found`);return}t.removeAttribute("hidden"),t.style.display="flex",t.setAttribute("aria-hidden","false"),t.dispatchEvent(new CustomEvent("lvt:modal-opened",{bubbles:!0})),this.logger.info(`Opened modal: ${e}`);let r=t.querySelector("input, textarea, select");r&&setTimeout(()=>{let n=document.activeElement,i=s=>s?s===document.body||s.offsetParent!==null?!0:s.getClientRects().length>0:!1;(!n||!t.contains(n)||!i(n))&&r.focus()},100)}close(e){let t=document.getElementById(e);if(!t){this.logger.warn(`Modal with id="${e}" not found`);return}t.setAttribute("hidden",""),t.style.display="none",t.setAttribute("aria-hidden","true"),t.dispatchEvent(new CustomEvent("lvt:modal-closed",{bubbles:!0})),this.logger.info(`Closed modal: ${e}`)}};var X=class{constructor(){this.bar=null}show(){if(this.bar)return;let e=document.createElement("div");if(e.style.cssText=`
26
+ `,document.head.appendChild(t)}}function de(a,e){let t=null;return function(...r){let s=this;t!==null&&clearTimeout(t),t=window.setTimeout(()=>{a.apply(s,r)},e)}}function ue(a,e){let t=!1;return function(...r){let s=this;t||(a.apply(s,r),t=!0,setTimeout(()=>{t=!1},e))}}var q=class{constructor(e,t){this.context=e;this.logger=t}setupEventDelegation(){let e=this.context.getWrapperElement();if(!e)return;let t=["click","submit","change","input","keydown","keyup","focus","blur","mouseenter","mouseleave"],n=e.getAttribute("data-lvt-id"),r=this.context.getRateLimitedHandlers();t.forEach(s=>{let o=`__lvt_delegated_${s}_${n}`,i=document[o];i&&document.removeEventListener(s,i,!1);let l=c=>{var L;let d=this.context.getWrapperElement();if(!d)return;s==="submit"&&(window.__lvtSubmitListenerTriggered=!0,window.__lvtSubmitEventTarget=(L=c.target)==null?void 0:L.tagName),this.logger.debug("Event listener triggered:",s,c.target);let M=c.target;if(!M)return;let m=M,f=!1;for(;m;){if(m===d){f=!0;break}m=m.parentElement}if(s==="submit"&&(window.__lvtInWrapper=f,window.__lvtWrapperElement=d.getAttribute("data-lvt-id")),!f)return;let F=`lvt-${s}`;for(m=M;m&&m!==d.parentElement;){let b=m.getAttribute(F),h=m;if(!b&&(s==="change"||s==="input")){let u=m.closest("form");u&&u.hasAttribute("lvt-change")&&(b=u.getAttribute("lvt-change"),h=u)}if(b&&h){if(s==="submit"&&(window.__lvtActionFound=b,window.__lvtActionElement=h.tagName),s==="submit"&&c.preventDefault(),(s==="keydown"||s==="keyup")&&h.hasAttribute("lvt-key")){let w=h.getAttribute("lvt-key");if(w&&c.key!==w){m=m.parentElement;continue}}let u=h,y=()=>{if(this.logger.debug("handleAction called",{action:b,eventType:s,targetElement:u}),b==="delete"&&u.hasAttribute("lvt-confirm")){let S=u.getAttribute("lvt-confirm")||"Are you sure you want to delete this item?";if(!confirm(S)){this.logger.debug("Delete action cancelled by user");return}}let w={action:b,data:{}};if(u instanceof HTMLFormElement){this.logger.debug("Processing form element");let S=new FormData(u),k=Array.from(u.querySelectorAll('input[type="checkbox"][name]')),_=new Set(k.map(H=>H.name));_.forEach(H=>{w.data[H]=!1}),S.forEach((H,A)=>{_.has(A)?(w.data[A]=!0,this.logger.debug("Converted checkbox",A,"to true")):w.data[A]=this.context.parseValue(H)}),this.logger.debug("Form data collected:",w.data)}else if(s==="change"||s==="input"){if(u instanceof HTMLInputElement){let S=u.name||"value";w.data[S]=this.context.parseValue(u.value)}else if(u instanceof HTMLSelectElement){let S=u.name||"value";w.data[S]=this.context.parseValue(u.value)}else if(u instanceof HTMLTextAreaElement){let S=u.name||"value";w.data[S]=this.context.parseValue(u.value)}}if(Array.from(u.attributes).forEach(S=>{if(S.name.startsWith("lvt-data-")){let k=S.name.replace("lvt-data-","");w.data[k]=this.context.parseValue(S.value)}}),Array.from(u.attributes).forEach(S=>{if(S.name.startsWith("lvt-value-")){let k=S.name.replace("lvt-value-","");w.data[k]=this.context.parseValue(S.value)}}),s==="submit"&&u instanceof HTMLFormElement){let k=c.submitter,_=null;k&&k.hasAttribute("lvt-disable-with")&&(_=k.textContent,k.disabled=!0,k.textContent=k.getAttribute("lvt-disable-with"),this.logger.debug("Disabled submit button")),this.context.setActiveSubmission(u,k||null,_),u.querySelectorAll('input[type="file"][lvt-upload]').forEach(A=>{let O=A.getAttribute("lvt-upload");O&&(this.logger.debug("Triggering pending uploads for:",O),this.context.triggerPendingUploads(O))}),u.dispatchEvent(new CustomEvent("lvt:pending",{detail:w})),this.logger.debug("Emitted lvt:pending event")}this.logger.debug("About to send message:",w),this.logger.debug("WebSocket state:",this.context.getWebSocketReadyState()),this.context.send(w),this.logger.debug("send() called")},U=h.getAttribute("lvt-throttle"),x=h.getAttribute("lvt-debounce");if(U||x){r.has(h)||r.set(h,new Map);let w=r.get(h),S=`${s}:${b}`,k=w.get(S);if(!k){if(U){let _=parseInt(U,10);k=ue(y,_)}else if(x){let _=parseInt(x,10);k=de(y,_)}k&&w.set(S,k)}k&&k()}else s==="submit"&&(window.__lvtBeforeHandleAction=!0),y(),s==="submit"&&(window.__lvtAfterHandleAction=!0);return}m=m.parentElement}};document[o]=l,document.addEventListener(s,l,!1),this.logger.debug("Registered event listener:",s,"with key:",o)})}setupWindowEventDelegation(){let e=this.context.getWrapperElement();if(!e)return;let t=["keydown","keyup","scroll","resize","focus","blur"],n=e.getAttribute("data-lvt-id"),r=this.context.getRateLimitedHandlers();t.forEach(s=>{let o=`__lvt_window_${s}_${n}`,i=window[o];i&&window.removeEventListener(s,i);let l=c=>{let d=this.context.getWrapperElement();if(!d)return;let M=`lvt-window-${s}`;d.querySelectorAll(`[${M}]`).forEach(f=>{let F=f.getAttribute(M);if(!F)return;if((s==="keydown"||s==="keyup")&&f.hasAttribute("lvt-key")){let y=f.getAttribute("lvt-key");if(y&&c.key!==y)return}let L={action:F,data:{}};Array.from(f.attributes).forEach(y=>{if(y.name.startsWith("lvt-data-")){let U=y.name.replace("lvt-data-","");L.data[U]=this.context.parseValue(y.value)}}),Array.from(f.attributes).forEach(y=>{if(y.name.startsWith("lvt-value-")){let U=y.name.replace("lvt-value-","");L.data[U]=this.context.parseValue(y.value)}});let b=f.getAttribute("lvt-throttle"),h=f.getAttribute("lvt-debounce"),u=()=>this.context.send(L);if(b||h){r.has(f)||r.set(f,new Map);let y=r.get(f),U=`window-${s}:${F}`,x=y.get(U);if(!x){if(b){let w=parseInt(b,10);x=ue(u,w)}else if(h){let w=parseInt(h,10);x=de(u,w)}x&&y.set(U,x)}x&&x()}else u()})};window[o]=l,window.addEventListener(s,l)})}setupClickAwayDelegation(){let e=this.context.getWrapperElement();if(!e)return;let n=`__lvt_click_away_${e.getAttribute("data-lvt-id")}`,r=document[n];r&&document.removeEventListener("click",r);let s=o=>{let i=this.context.getWrapperElement();if(!i)return;let l=o.target;i.querySelectorAll("[lvt-click-away]").forEach(d=>{if(!d.contains(l)){let M=d.getAttribute("lvt-click-away");if(!M)return;let m={action:M,data:{}};Array.from(d.attributes).forEach(f=>{if(f.name.startsWith("lvt-data-")){let F=f.name.replace("lvt-data-","");m.data[F]=this.context.parseValue(f.value)}}),Array.from(d.attributes).forEach(f=>{if(f.name.startsWith("lvt-value-")){let F=f.name.replace("lvt-value-","");m.data[F]=this.context.parseValue(f.value)}}),this.context.send(m)}})};document[n]=s,document.addEventListener("click",s)}setupModalDelegation(){let e=this.context.getWrapperElement();if(!e)return;let t=e.getAttribute("data-lvt-id"),n=`__lvt_modal_open_${t}`,r=document[n];r&&document.removeEventListener("click",r);let s=L=>{var y;let b=this.context.getWrapperElement();if(!b)return;let h=(y=L.target)==null?void 0:y.closest("[lvt-modal-open]");if(!h||!b.contains(h))return;let u=h.getAttribute("lvt-modal-open");u&&(L.preventDefault(),this.context.openModal(u))};document[n]=s,document.addEventListener("click",s);let o=`__lvt_modal_close_${t}`,i=document[o];i&&document.removeEventListener("click",i);let l=L=>{var y;let b=this.context.getWrapperElement();if(!b)return;let h=(y=L.target)==null?void 0:y.closest("[lvt-modal-close]");if(!h||!b.contains(h))return;let u=h.getAttribute("lvt-modal-close");u&&(L.preventDefault(),this.context.closeModal(u))};document[o]=l,document.addEventListener("click",l);let c=`__lvt_modal_backdrop_${t}`,d=document[c];d&&document.removeEventListener("click",d);let M=L=>{let b=L.target;if(!b.hasAttribute("data-modal-backdrop"))return;let h=b.getAttribute("data-modal-id");h&&this.context.closeModal(h)};document[c]=M,document.addEventListener("click",M);let m=`__lvt_modal_escape_${t}`,f=document[m];f&&document.removeEventListener("keydown",f);let F=L=>{if(L.key!=="Escape")return;let b=this.context.getWrapperElement();if(!b)return;let h=b.querySelectorAll('[role="dialog"]:not([hidden])');if(h.length>0){let u=h[h.length-1];u.id&&this.context.closeModal(u.id)}};document[m]=F,document.addEventListener("keydown",F)}};var G=class{constructor(e,t){this.context=e;this.logger=t;this.infiniteScrollObserver=null;this.mutationObserver=null}setupInfiniteScrollObserver(){if(!this.context.getWrapperElement())return;let t=document.getElementById("scroll-sentinel");t&&(this.infiniteScrollObserver&&this.infiniteScrollObserver.disconnect(),this.infiniteScrollObserver=new IntersectionObserver(n=>{n[0].isIntersecting&&(this.logger.debug("Sentinel visible, sending load_more action"),this.context.send({action:"load_more"}))},{rootMargin:"200px"}),this.infiniteScrollObserver.observe(t),this.logger.debug("Observer set up successfully"))}setupInfiniteScrollMutationObserver(){let e=this.context.getWrapperElement();e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.setupInfiniteScrollObserver()}),this.mutationObserver.observe(e,{childList:!0,subtree:!0}),this.logger.debug("MutationObserver set up successfully"))}teardown(){this.infiniteScrollObserver&&(this.infiniteScrollObserver.disconnect(),this.infiniteScrollObserver=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}};var J=class{constructor(e){this.logger=e}open(e){let t=document.getElementById(e);if(!t){this.logger.warn(`Modal with id="${e}" not found`);return}t.removeAttribute("hidden"),t.style.display="flex",t.setAttribute("aria-hidden","false"),t.dispatchEvent(new CustomEvent("lvt:modal-opened",{bubbles:!0})),this.logger.info(`Opened modal: ${e}`);let n=t.querySelector("input, textarea, select");n&&setTimeout(()=>{let r=document.activeElement,s=i=>i?i===document.body||i.offsetParent!==null?!0:i.getClientRects().length>0:!1;(!r||!t.contains(r)||!s(r))&&n.focus()},100)}close(e){let t=document.getElementById(e);if(!t){this.logger.warn(`Modal with id="${e}" not found`);return}t.setAttribute("hidden",""),t.style.display="none",t.setAttribute("aria-hidden","true"),t.dispatchEvent(new CustomEvent("lvt:modal-closed",{bubbles:!0})),this.logger.info(`Closed modal: ${e}`)}};var X=class{constructor(){this.bar=null}show(){if(this.bar)return;let e=document.createElement("div");if(e.style.cssText=`
27
27
  position: fixed;
28
28
  top: 0;
29
29
  left: 0;
@@ -38,7 +38,7 @@
38
38
  0% { background-position: 200% 0; }
39
39
  100% { background-position: -200% 0; }
40
40
  }
41
- `,document.head.appendChild(t)}document.body.insertBefore(e,document.body.firstChild),this.bar=e}hide(){this.bar&&(this.bar.parentNode&&this.bar.parentNode.removeChild(this.bar),this.bar=null)}};var Y=class{disable(e){if(!e)return;e.querySelectorAll("form").forEach(r=>{r.querySelectorAll("input, textarea, select, button").forEach(i=>{i.disabled=!0})})}enable(e){if(!e)return;e.querySelectorAll("form").forEach(r=>{r.querySelectorAll("input, textarea, select, button").forEach(i=>{i.disabled=!1})})}};var Q=class{constructor(e){this.logger=e;this.treeState={};this.rangeState={};this.rangeIdKeys={}}applyUpdate(e){let t=!1;for(let[n,i]of Object.entries(e))if(Array.isArray(i)&&i.length>0&&Array.isArray(i[0])&&typeof i[0][0]=="string")this.treeState[n]=i,t=!0;else{let s=this.treeState[n],l=typeof i=="object"&&i!==null&&!Array.isArray(i)?this.deepMergeTreeNodes(s,i):i;JSON.stringify(s)!==JSON.stringify(l)&&(this.treeState[n]=l,t=!0)}return{html:this.reconstructFromTree(this.treeState,""),changed:t}}reset(){this.treeState={},this.rangeState={},this.rangeIdKeys={}}getTreeState(){return{...this.treeState}}getStaticStructure(){return this.treeState.s||null}deepMergeTreeNodes(e,t){if(typeof t!="object"||t===null||Array.isArray(t)||typeof e!="object"||e===null||Array.isArray(e))return t;let r={...e};for(let[n,i]of Object.entries(t))typeof i=="object"&&i!==null&&!Array.isArray(i)&&typeof r[n]=="object"&&r[n]!==null&&!Array.isArray(r[n])?r[n]=this.deepMergeTreeNodes(r[n],i):r[n]=i;return r}reconstructFromTree(e,t){if(e.s&&Array.isArray(e.s)){let r="";for(let n=0;n<e.s.length;n++){let i=e.s[n];if(r+=i,n<e.s.length-1){let o=n.toString();if(e[o]!==void 0){let s=t?`${t}.${o}`:o;r+=this.renderValue(e[o],o,s)}}}return r=r.replace(/<root>/g,"").replace(/<\/root>/g,""),r}return this.renderValue(e,"",t)}renderValue(e,t,r){if(e==null||typeof e=="string"&&e.startsWith("{{")&&e.endsWith("}}"))return"";if(typeof e=="object"&&!Array.isArray(e)){if(e.d&&Array.isArray(e.d)&&e.s&&Array.isArray(e.s)){let n=r||t||"";return n&&(this.rangeState[n]={items:e.d,statics:e.s},e.m&&typeof e.m=="object"&&typeof e.m.idKey=="string"&&(this.rangeIdKeys[n]=e.m.idKey)),this.renderRangeStructure(e,t,r)}if("s"in e&&Array.isArray(e.s))return this.reconstructFromTree(e,r||"")}return Array.isArray(e)?e.length>0&&Array.isArray(e[0])&&typeof e[0][0]=="string"?this.applyDifferentialOperations(e,r):e.map((n,i)=>{let o=i.toString(),s=r?`${r}.${o}`:o;return typeof n=="object"&&n&&n.s?this.reconstructFromTree(n,s):this.renderValue(n,o,s)}).join(""):(typeof e=="object"&&(this.logger.error("Object value reached string conversion; this will render as [object Object]."),this.logger.isDebugEnabled()&&this.logger.debug("Value diagnostics:",{valueType:typeof e,isArray:Array.isArray(e),keys:Object.keys(e),hasStatics:!!e.s,hasDynamics:!!e.d,value:e})),String(e))}renderRangeStructure(e,t,r){let{d:n,s:i}=e;if(!n||!Array.isArray(n))return"";if(n.length===0){if(e.else){let o="else",s=r?`${r}.else`:"else";return this.renderValue(e.else,o,s)}return""}return i&&Array.isArray(i)?n.map((o,s)=>{let l="";for(let c=0;c<i.length;c++)if(l+=i[c],c<i.length-1){let d=c.toString();if(o[d]!==void 0){let A=r?`${r}.${s}.${d}`:`${s}.${d}`;l+=this.renderValue(o[d],d,A)}}return l}).join(""):n.map((o,s)=>{let l=s.toString(),c=r?`${r}.${l}`:l;return this.renderValue(o,l,c)}).join("")}applyDifferentialOperations(e,t){if(!t||!this.rangeState[t])return"";let r=this.rangeState[t],n=[...r.items],i=r.statics;for(let s of e){if(!Array.isArray(s)||s.length<2)continue;switch(s[0]){case"r":{let c=this.findItemIndexByKey(n,s[1],i,t);c>=0&&n.splice(c,1);break}case"u":{let c=this.findItemIndexByKey(n,s[1],i,t),d=s[2];c>=0&&d&&(n[c]={...n[c],...d});break}case"a":{this.addItemsToRange(n,s[1],s[2],r,!1),s[3]&&typeof s[3]=="object"&&s[3].idKey&&(this.rangeIdKeys[t||""]=s[3].idKey);break}case"p":{this.addItemsToRange(n,s[1],s[2],r,!0);break}case"i":{let c=this.findItemIndexByKey(n,s[1],i,t);if(c>=0){let d=Array.isArray(s[2])?s[2]:[s[2]];n.splice(c+1,0,...d)}break}case"o":{let c=s[1],d=[],A=new Map;for(let m of n){let f=this.getItemKey(m,i,t);f&&A.set(f,m)}for(let m of c){let f=A.get(m);f&&d.push(f)}n.length=0,n.push(...d);break}default:break}}this.rangeState[t]={items:n,statics:r.statics},this.treeState[t]={d:n,s:r.statics};let o=this.getCurrentRangeStructure(t);return o&&o.s?this.renderItemsWithStatics(n,o.s):n.map(s=>this.renderValue(s)).join("")}getCurrentRangeStructure(e){if(this.rangeState[e])return{d:this.rangeState[e].items,s:this.rangeState[e].statics};let t=this.treeState[e];return t&&typeof t=="object"&&t.s?t:null}renderItemsWithStatics(e,t){let r=e.map(n=>{let i="";for(let o=0;o<t.length;o++)if(i+=t[o],o<t.length-1){let s=o.toString();n[s]!==void 0&&(i+=this.renderValue(n[s]))}return i}).join("");return this.logger.isDebugEnabled()&&(this.logger.debug("[renderItemsWithStatics] statics:",t),this.logger.debug("[renderItemsWithStatics] items count:",e.length),this.logger.debug("[renderItemsWithStatics] result snippet:",r.substring(0,200))),r}addItemsToRange(e,t,r,n,i){if(r&&(n.statics=r),!t)return;let o=Array.isArray(t)?t:[t];i?e.unshift(...o):e.push(...o)}getItemKey(e,t,r){if(!r||!this.rangeIdKeys[r])return null;let n=this.rangeIdKeys[r];return e[n]||null}findItemIndexByKey(e,t,r,n){return e.findIndex(i=>this.getItemKey(i,r,n)===t)}};var Z=class{constructor(e){this.modalManager=e;this.activeForm=null;this.activeButton=null;this.originalButtonText=null}setActiveSubmission(e,t,r){this.activeForm=e,this.activeButton=t,this.originalButtonText=r}handleResponse(e){this.activeForm&&this.activeForm.dispatchEvent(new CustomEvent("lvt:done",{detail:e})),e.success?this.handleSuccess(e):this.handleError(e),this.restoreFormState()}reset(){this.restoreFormState()}handleSuccess(e){if(!this.activeForm)return;this.activeForm.dispatchEvent(new CustomEvent("lvt:success",{detail:e}));let t=this.activeForm.closest('[role="dialog"]');t&&t.id&&this.modalManager.close(t.id),this.activeForm.hasAttribute("lvt-preserve")||this.activeForm.reset()}handleError(e){this.activeForm&&this.activeForm.dispatchEvent(new CustomEvent("lvt:error",{detail:e}))}restoreFormState(){this.activeButton&&this.originalButtonText!==null&&(this.activeButton.disabled=!1,this.activeButton.textContent=this.originalButtonText),this.activeForm=null,this.activeButton=null,this.originalButtonText=null}};var de=class{constructor(e){this.options=e;this.socket=null;this.reconnectTimer=null;this.manuallyClosed=!1;this.reconnectAttempts=0}connect(){this.manuallyClosed=!1,this.clearReconnectTimer(),this.socket=new WebSocket(this.options.url);let e=this.socket;e.onopen=()=>{var t,r;this.reconnectAttempts=0,(r=(t=this.options).onOpen)==null||r.call(t,e)},e.onmessage=t=>{var r,n;(n=(r=this.options).onMessage)==null||n.call(r,t)},e.onclose=t=>{var r,n;(n=(r=this.options).onClose)==null||n.call(r,t),!this.manuallyClosed&&this.options.autoReconnect&&this.scheduleReconnect()},e.onerror=t=>{var r,n;(n=(r=this.options).onError)==null||n.call(r,t)}}send(e){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send(e)}disconnect(){this.manuallyClosed=!0,this.clearReconnectTimer(),this.socket&&(this.socket.close(),this.socket=null)}getSocket(){return this.socket}scheduleReconnect(){var s,l,c,d,A;this.clearReconnectTimer();let e=(s=this.options.maxReconnectAttempts)!=null?s:10;if(e>0&&this.reconnectAttempts>=e){(c=(l=this.options).onReconnectFailed)==null||c.call(l);return}this.reconnectAttempts++;let t=(d=this.options.reconnectDelay)!=null?d:1e3,r=(A=this.options.maxReconnectDelay)!=null?A:16e3,n=t*Math.pow(2,this.reconnectAttempts-1),i=Math.random()*1e3,o=Math.min(n+i,r);this.reconnectTimer=window.setTimeout(()=>{var m,f;(f=(m=this.options).onReconnectAttempt)==null||f.call(m,this.reconnectAttempts,o),this.connect()},o)}clearReconnectTimer(){this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}},ee=class{constructor(e){this.config=e;this.transport=null}async connect(){let e=this.getLiveUrl();return await Ge(e,this.config.logger)?(this.transport=new de({url:this.getWebSocketUrl(),autoReconnect:this.config.options.autoReconnect,reconnectDelay:this.config.options.reconnectDelay,maxReconnectDelay:16e3,maxReconnectAttempts:10,onOpen:()=>{this.config.onConnected()},onMessage:r=>{try{let n=JSON.parse(r.data);this.config.onMessage(n,r)}catch(n){this.config.logger.error("Failed to parse WebSocket message:",n)}},onClose:()=>{this.config.onDisconnected()},onReconnectAttempt:(r,n)=>{var i,o;(o=(i=this.config).onReconnectAttempt)==null||o.call(i,r,n)},onReconnectFailed:()=>{var r,n;(n=(r=this.config).onReconnectFailed)==null||n.call(r)},onError:r=>{var n,i;(i=(n=this.config).onError)==null||i.call(n,r)}}),this.transport.connect(),{usingWebSocket:!0}):{usingWebSocket:!1,initialState:await Je(e,this.config.logger)}}disconnect(){var e;(e=this.transport)==null||e.disconnect(),this.transport=null}send(e){var t;(t=this.transport)==null||t.send(e)}getReadyState(){var e,t;return(t=(e=this.transport)==null?void 0:e.getSocket())==null?void 0:t.readyState}getSocket(){var e,t;return(t=(e=this.transport)==null?void 0:e.getSocket())!=null?t:null}getWebSocketUrl(){let e=this.config.options.liveUrl||"/live",t=this.config.options.wsUrl;return t||`ws://${window.location.host}${e}`}getLiveUrl(){return this.config.options.liveUrl||window.location.pathname}};async function Ge(a,e){try{let r=(await fetch(a,{method:"HEAD"})).headers.get("X-LiveTemplate-WebSocket");return r?r==="enabled":!0}catch(t){return e==null||e.warn("Failed to check WebSocket availability:",t),!0}}async function Je(a,e){try{let t=await fetch(a,{method:"GET",credentials:"include",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to fetch initial state: ${t.status}`);return await t.json()}catch(t){return e==null||e.warn("Failed to fetch initial state:",t),null}}var ke={silent:0,error:1,warn:2,info:3,debug:4},Te="LiveTemplate",ue=class a{constructor(e,t=[],r=console){this.state=e;this.scope=t;this.sink=r}setLevel(e){this.state.level=e}getLevel(){return this.state.level}child(e){return new a(this.state,[...this.scope,e],this.sink)}isDebugEnabled(){return this.shouldLog("debug")}error(...e){this.log("error","error",e)}warn(...e){this.log("warn","warn",e)}info(...e){this.log("info","info",e)}debug(...e){this.log("debug","debug",e)}log(e,t,r){if(!this.shouldLog(e))return;(this.sink[t]||console[t]||console.log).apply(this.sink,[this.formatPrefix(),...r])}shouldLog(e){return ke[e]<=ke[this.state.level]}formatPrefix(){return this.scope.length===0?`[${Te}]`:`[${Te}:${this.scope.join(":")}]`}};function ge(a={}){var r,n;let e={level:(r=a.level)!=null?r:"info"},t=Array.isArray(a.scope)?a.scope:a.scope?[a.scope]:[];return new ue(e,t,(n=a.sink)!=null?n:console)}async function Le(a,e){try{let t=globalThis==null?void 0:globalThis.require;if(typeof t=="function"){let i=t("fs"),o=JSON.parse(i.readFileSync(e,"utf8"));return a.applyUpdate(o)}let n=await(await fetch(e)).json();return a.applyUpdate(n)}catch(t){throw new Error(`Failed to load update from ${e}: ${t}`)}}function Me(a,e){let t=[],r=c=>c.replace(/\s+/g," ").replace(/>\s+</g,"><").trim(),n=r(a),i=r(e);if(n===i)return{match:!0,differences:[]};let o=n.split(`
42
- `),s=i.split(`
43
- `),l=Math.max(o.length,s.length);for(let c=0;c<l;c++){let d=o[c]||"",A=s[c]||"";d!==A&&(t.push(`Line ${c+1}:`),t.push(` Expected: ${d}`),t.push(` Actual: ${A}`))}return{match:!1,differences:t}}var te=class a{constructor(e={}){this.lvtId=null;this.ws=null;this.wrapperElement=null;this.useHTTP=!1;this.sessionCookie=null;this.rateLimitedHandlers=new WeakMap;this.isInitialized=!1;this.messageCount=0;let{logger:t,logLevel:r,debug:n,...i}=e,o=r!=null?r:n?"debug":"info",s=t!=null?t:ge({level:o});t?r?t.setLevel(r):n&&t.setLevel("debug"):s.setLevel(o),this.logger=s.child("Client"),this.options={autoReconnect:!1,reconnectDelay:1e3,liveUrl:window.location.pathname,...i},this.treeRenderer=new Q(this.logger.child("TreeRenderer")),this.focusManager=new q(this.logger.child("FocusManager")),this.modalManager=new J(this.logger.child("ModalManager")),this.formLifecycleManager=new Z(this.modalManager),this.loadingIndicator=new X,this.formDisabler=new Y,this.eventDelegator=new z({getWrapperElement:()=>this.wrapperElement,getRateLimitedHandlers:()=>this.rateLimitedHandlers,parseValue:l=>this.parseValue(l),send:l=>this.send(l),setActiveSubmission:(l,c,d)=>this.formLifecycleManager.setActiveSubmission(l,c,d),openModal:l=>this.modalManager.open(l),closeModal:l=>this.modalManager.close(l),getWebSocketReadyState:()=>this.webSocketManager.getReadyState()},this.logger.child("EventDelegator")),this.observerManager=new G({getWrapperElement:()=>this.wrapperElement,send:l=>this.send(l)},this.logger.child("ObserverManager")),this.webSocketManager=new ee({options:this.options,logger:this.logger.child("Transport"),onConnected:()=>{var l,c,d;this.ws=this.webSocketManager.getSocket(),this.logger.info("WebSocket connected"),(c=(l=this.options).onConnect)==null||c.call(l),(d=this.wrapperElement)==null||d.dispatchEvent(new Event("lvt:connected"))},onDisconnected:()=>{var l,c,d;this.ws=null,this.logger.info("WebSocket disconnected"),(c=(l=this.options).onDisconnect)==null||c.call(l),(d=this.wrapperElement)==null||d.dispatchEvent(new Event("lvt:disconnected"))},onMessage:(l,c)=>{this.handleWebSocketPayload(l,c)},onReconnectAttempt:()=>{this.logger.info("Attempting to reconnect...")},onError:l=>{var c,d;this.logger.error("WebSocket error:",l),(d=(c=this.options).onError)==null||d.call(c,l)}})}static autoInit(){let e=ge({scope:"Client:autoInit"}),t=()=>{let r=document.querySelector("[data-lvt-id]");if(r){let n=new a;n.wrapperElement=r,r.getAttribute("data-lvt-loading")==="true"&&(n.loadingIndicator.show(),n.formDisabler.disable(n.wrapperElement)),n.connect().catch(o=>{e.error("Auto-initialization connect failed:",o)}),window.liveTemplateClient=n}};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",t):t()}handleWebSocketPayload(e,t){var r,n;t&&(window.__lastWSMessage=t.data,window.__wsMessages||(window.__wsMessages=[]),window.__wsMessages.push(e)),this.isInitialized||(this.loadingIndicator.hide(),this.formDisabler.enable(this.wrapperElement),this.wrapperElement&&this.wrapperElement.hasAttribute("data-lvt-loading")&&this.wrapperElement.removeAttribute("data-lvt-loading"),this.isInitialized=!0),this.wrapperElement&&(this.updateDOM(this.wrapperElement,e.tree,e.meta),this.messageCount++,window.__wsMessageCount=this.messageCount,this.wrapperElement.dispatchEvent(new CustomEvent("lvt:updated",{detail:{messageCount:this.messageCount,action:(r=e.meta)==null?void 0:r.action,success:(n=e.meta)==null?void 0:n.success}})))}async connect(e="[data-lvt-id]"){var r,n;if(this.wrapperElement=document.querySelector(e),!this.wrapperElement)throw new Error(`LiveTemplate wrapper not found with selector: ${e}`);this.webSocketManager.disconnect();let t=await this.webSocketManager.connect();this.useHTTP=!t.usingWebSocket,this.useHTTP&&(this.ws=null,this.logger.info("WebSocket not available, using HTTP mode"),(n=(r=this.options).onConnect)==null||n.call(r),t.initialState&&this.wrapperElement&&this.handleWebSocketPayload(t.initialState)),this.eventDelegator.setupEventDelegation(),this.eventDelegator.setupWindowEventDelegation(),this.eventDelegator.setupClickAwayDelegation(),this.eventDelegator.setupModalDelegation(),this.focusManager.attach(this.wrapperElement),this.observerManager.setupInfiniteScrollObserver(),this.observerManager.setupInfiniteScrollMutationObserver()}disconnect(){this.webSocketManager.disconnect(),this.ws=null,this.useHTTP=!1,this.observerManager.teardown(),this.formLifecycleManager.reset(),this.loadingIndicator.hide(),this.formDisabler.enable(this.wrapperElement)}isReady(){let e=this.wrapperElement;return!e||e.hasAttribute("data-lvt-loading")?!1:this.useHTTP?!0:this.webSocketManager.getReadyState()===WebSocket.OPEN}send(e){window.__lvtSendCalled=!0,window.__lvtMessageAction=e==null?void 0:e.action;let t=this.webSocketManager.getReadyState();this.logger.isDebugEnabled()&&this.logger.debug("send() invoked",{message:e,useHTTP:this.useHTTP,hasWebSocket:t!==void 0,readyState:t}),this.useHTTP?(this.logger.debug("Using HTTP mode for send"),window.__lvtSendPath="http",this.sendHTTP(e)):t===WebSocket.OPEN?(this.logger.debug("Sending via WebSocket"),window.__lvtSendPath="websocket",window.__lvtWSMessage=JSON.stringify(e),this.webSocketManager.send(JSON.stringify(e)),this.logger.debug("WebSocket send complete"),window.__lvtWSSendComplete=!0):t!==void 0?(this.logger.warn(`WebSocket not ready (state: ${t}), using HTTP fallback`),window.__lvtSendPath="http-fallback",this.sendHTTP(e)):(this.logger.error("No transport available"),window.__lvtSendPath="no-transport")}async sendHTTP(e){try{let t=this.options.liveUrl||"/live",r=await fetch(t,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`HTTP request failed: ${r.status}`);let n=await r.json();this.wrapperElement&&this.updateDOM(this.wrapperElement,n.tree,n.meta)}catch(t){this.logger.error("Failed to send HTTP request:",t)}}parseValue(e){let t=parseFloat(e);return!isNaN(t)&&e.trim()===t.toString()?t:e==="true"?!0:e==="false"?!1:e}applyUpdate(e){return this.treeRenderer.applyUpdate(e)}applyUpdateToHTML(e,t){let r=this.applyUpdate(t);if(!this.lvtId){let c=e.match(/data-lvt-id="([^"]+)"/);c&&(this.lvtId=c[1])}let n=r.html;if(!e.match(/<body>([\s\S]*?)<\/body>/))return e;let l=`<div data-lvt-id="${this.lvtId||"lvt-unknown"}">`+n+"</div>";return e.replace(/<body>[\s\S]*?<\/body>/,`<body>${l}</body>`)}updateDOM(e,t,r){let n=this.applyUpdate(t),i=s=>!s||typeof s!="object"?!1:s.s&&Array.isArray(s.s)?!0:Object.values(s).some(l=>i(l));if(!n.changed&&!i(t))return;let o=document.createElement(e.tagName);this.logger.isDebugEnabled()&&(this.logger.debug("[updateDOM] element.tagName:",e.tagName),this.logger.debug("[updateDOM] result.html (first 500 chars):",n.html.substring(0,500)),this.logger.debug("[updateDOM] Has <table> tag:",n.html.includes("<table>")),this.logger.debug("[updateDOM] Has <tbody> tag:",n.html.includes("<tbody>")),this.logger.debug("[updateDOM] Has <tr> tag:",n.html.includes("<tr"))),o.innerHTML=n.html,this.logger.isDebugEnabled()&&(this.logger.debug("[updateDOM] tempWrapper.innerHTML (first 500 chars):",o.innerHTML.substring(0,500)),this.logger.debug("[updateDOM] tempWrapper has <table>:",o.innerHTML.includes("<table>")),this.logger.debug("[updateDOM] tempWrapper has <tbody>:",o.innerHTML.includes("<tbody>")),this.logger.debug("[updateDOM] tempWrapper has <tr>:",o.innerHTML.includes("<tr"))),Ee(e,o,{childrenOnly:!0,getNodeKey:s=>{if(s.nodeType===1)return s.getAttribute("data-key")||s.getAttribute("data-lvt-key")||void 0},onBeforeElUpdated:(s,l)=>{let c=this.focusManager.getLastFocusedElement();return c&&this.focusManager.isTextualInput(s)&&s===c&&(l.value=s.value),s.isEqualNode(l)?!1:(this.executeLifecycleHook(s,"lvt-updated"),!0)},onNodeAdded:s=>{s.nodeType===Node.ELEMENT_NODE&&this.executeLifecycleHook(s,"lvt-mounted")},onBeforeNodeDiscarded:s=>(s.nodeType===Node.ELEMENT_NODE&&this.executeLifecycleHook(s,"lvt-destroyed"),!0)}),this.focusManager.restoreFocusedElement(),we(e),Se(e),Ae(e),r&&this.formLifecycleManager.handleResponse(r)}executeLifecycleHook(e,t){let r=e.getAttribute(t);if(r)try{new Function("element",r).call(e,e)}catch(n){this.logger.error(`Error executing ${t} hook:`,n)}}reset(){this.treeRenderer.reset(),this.focusManager.reset(),this.observerManager.teardown(),this.formLifecycleManager.reset(),this.loadingIndicator.hide(),this.formDisabler.enable(this.wrapperElement),this.lvtId=null}getTreeState(){return this.treeRenderer.getTreeState()}getStaticStructure(){return this.treeRenderer.getStaticStructure()}};typeof window!="undefined"&&te.autoInit();return Ie(Xe);})();
41
+ `,document.head.appendChild(t)}document.body.insertBefore(e,document.body.firstChild),this.bar=e}hide(){this.bar&&(this.bar.parentNode&&this.bar.parentNode.removeChild(this.bar),this.bar=null)}};var Y=class{disable(e){if(!e)return;e.querySelectorAll("form").forEach(n=>{n.querySelectorAll("input, textarea, select, button").forEach(s=>{s.disabled=!0})})}enable(e){if(!e)return;e.querySelectorAll("form").forEach(n=>{n.querySelectorAll("input, textarea, select, button").forEach(s=>{s.disabled=!1})})}};var Q=class{constructor(e){this.logger=e;this.treeState={};this.rangeState={};this.rangeIdKeys={}}applyUpdate(e){let t=!1;for(let[r,s]of Object.entries(e))if(Array.isArray(s)&&s.length>0&&Array.isArray(s[0])&&typeof s[0][0]=="string")this.treeState[r]=s,t=!0;else{let i=this.treeState[r],l=typeof s=="object"&&s!==null&&!Array.isArray(s)?this.deepMergeTreeNodes(i,s):s;JSON.stringify(i)!==JSON.stringify(l)&&(this.treeState[r]=l,t=!0)}return{html:this.reconstructFromTree(this.treeState,""),changed:t}}reset(){this.treeState={},this.rangeState={},this.rangeIdKeys={}}getTreeState(){return{...this.treeState}}getStaticStructure(){return this.treeState.s||null}deepMergeTreeNodes(e,t){if(typeof t!="object"||t===null||Array.isArray(t)||typeof e!="object"||e===null||Array.isArray(e))return t;let n={...e};for(let[r,s]of Object.entries(t))typeof s=="object"&&s!==null&&!Array.isArray(s)&&typeof n[r]=="object"&&n[r]!==null&&!Array.isArray(n[r])?n[r]=this.deepMergeTreeNodes(n[r],s):n[r]=s;return n}reconstructFromTree(e,t){if(e.s&&Array.isArray(e.s)){let n="";for(let r=0;r<e.s.length;r++){let s=e.s[r];if(n+=s,r<e.s.length-1){let o=r.toString();if(e[o]!==void 0){let i=t?`${t}.${o}`:o;n+=this.renderValue(e[o],o,i)}}}return n=n.replace(/<root>/g,"").replace(/<\/root>/g,""),n}return this.renderValue(e,"",t)}renderValue(e,t,n){if(e==null||typeof e=="string"&&e.startsWith("{{")&&e.endsWith("}}"))return"";if(typeof e=="object"&&!Array.isArray(e)){if(e.d&&Array.isArray(e.d)&&e.s&&Array.isArray(e.s)){let r=n||t||"";return r&&(this.rangeState[r]={items:e.d,statics:e.s},e.m&&typeof e.m=="object"&&typeof e.m.idKey=="string"&&(this.rangeIdKeys[r]=e.m.idKey)),this.renderRangeStructure(e,t,n)}if("s"in e&&Array.isArray(e.s))return this.reconstructFromTree(e,n||"")}return Array.isArray(e)?e.length>0&&Array.isArray(e[0])&&typeof e[0][0]=="string"?this.applyDifferentialOperations(e,n):e.map((r,s)=>{let o=s.toString(),i=n?`${n}.${o}`:o;return typeof r=="object"&&r&&r.s?this.reconstructFromTree(r,i):this.renderValue(r,o,i)}).join(""):(typeof e=="object"&&(this.logger.error("Object value reached string conversion; this will render as [object Object]."),this.logger.isDebugEnabled()&&this.logger.debug("Value diagnostics:",{valueType:typeof e,isArray:Array.isArray(e),keys:Object.keys(e),hasStatics:!!e.s,hasDynamics:!!e.d,value:e})),String(e))}renderRangeStructure(e,t,n){let{d:r,s}=e;if(!r||!Array.isArray(r))return"";if(r.length===0){if(e.else){let o="else",i=n?`${n}.else`:"else";return this.renderValue(e.else,o,i)}return""}return s&&Array.isArray(s)?r.map((o,i)=>{let l="";for(let c=0;c<s.length;c++)if(l+=s[c],c<s.length-1){let d=c.toString();if(o[d]!==void 0){let M=n?`${n}.${i}.${d}`:`${i}.${d}`;l+=this.renderValue(o[d],d,M)}}return l}).join(""):r.map((o,i)=>{let l=i.toString(),c=n?`${n}.${l}`:l;return this.renderValue(o,l,c)}).join("")}applyDifferentialOperations(e,t){if(!t||!this.rangeState[t])return"";let n=this.rangeState[t],r=[...n.items],s=n.statics;for(let i of e){if(!Array.isArray(i)||i.length<2)continue;switch(i[0]){case"r":{let c=this.findItemIndexByKey(r,i[1],s,t);c>=0&&r.splice(c,1);break}case"u":{let c=this.findItemIndexByKey(r,i[1],s,t),d=i[2];c>=0&&d&&(r[c]={...r[c],...d});break}case"a":{this.addItemsToRange(r,i[1],i[2],n,!1),i[3]&&typeof i[3]=="object"&&i[3].idKey&&(this.rangeIdKeys[t||""]=i[3].idKey);break}case"p":{this.addItemsToRange(r,i[1],i[2],n,!0);break}case"i":{let c=this.findItemIndexByKey(r,i[1],s,t);if(c>=0){let d=Array.isArray(i[2])?i[2]:[i[2]];r.splice(c+1,0,...d)}break}case"o":{let c=i[1],d=[],M=new Map;for(let m of r){let f=this.getItemKey(m,s,t);f&&M.set(f,m)}for(let m of c){let f=M.get(m);f&&d.push(f)}r.length=0,r.push(...d);break}default:break}}this.rangeState[t]={items:r,statics:n.statics},this.treeState[t]={d:r,s:n.statics};let o=this.getCurrentRangeStructure(t);return o&&o.s?this.renderItemsWithStatics(r,o.s):r.map(i=>this.renderValue(i)).join("")}getCurrentRangeStructure(e){if(this.rangeState[e])return{d:this.rangeState[e].items,s:this.rangeState[e].statics};let t=this.treeState[e];return t&&typeof t=="object"&&t.s?t:null}renderItemsWithStatics(e,t){let n=e.map(r=>{let s="";for(let o=0;o<t.length;o++)if(s+=t[o],o<t.length-1){let i=o.toString();r[i]!==void 0&&(s+=this.renderValue(r[i]))}return s}).join("");return this.logger.isDebugEnabled()&&(this.logger.debug("[renderItemsWithStatics] statics:",t),this.logger.debug("[renderItemsWithStatics] items count:",e.length),this.logger.debug("[renderItemsWithStatics] result snippet:",n.substring(0,200))),n}addItemsToRange(e,t,n,r,s){if(n&&(r.statics=n),!t)return;let o=Array.isArray(t)?t:[t];s?e.unshift(...o):e.push(...o)}getItemKey(e,t,n){if(!n||!this.rangeIdKeys[n])return null;let r=this.rangeIdKeys[n];return e[r]||null}findItemIndexByKey(e,t,n,r){return e.findIndex(s=>this.getItemKey(s,n,r)===t)}};var Z=class{constructor(e){this.modalManager=e;this.activeForm=null;this.activeButton=null;this.originalButtonText=null}setActiveSubmission(e,t,n){this.activeForm=e,this.activeButton=t,this.originalButtonText=n}handleResponse(e){this.activeForm&&this.activeForm.dispatchEvent(new CustomEvent("lvt:done",{detail:e})),e.success?this.handleSuccess(e):this.handleError(e),this.restoreFormState()}reset(){this.restoreFormState()}handleSuccess(e){if(!this.activeForm)return;this.activeForm.dispatchEvent(new CustomEvent("lvt:success",{detail:e}));let t=this.activeForm.closest('[role="dialog"]');t&&t.id&&this.modalManager.close(t.id),this.activeForm.hasAttribute("lvt-preserve")||this.activeForm.reset()}handleError(e){this.activeForm&&this.activeForm.dispatchEvent(new CustomEvent("lvt:error",{detail:e}))}restoreFormState(){this.activeButton&&this.originalButtonText!==null&&(this.activeButton.disabled=!1,this.activeButton.textContent=this.originalButtonText),this.activeForm=null,this.activeButton=null,this.originalButtonText=null}};var pe=class{constructor(e){this.options=e;this.socket=null;this.reconnectTimer=null;this.manuallyClosed=!1;this.reconnectAttempts=0}connect(){this.manuallyClosed=!1,this.clearReconnectTimer(),this.socket=new WebSocket(this.options.url);let e=this.socket;e.onopen=()=>{var t,n;this.reconnectAttempts=0,(n=(t=this.options).onOpen)==null||n.call(t,e)},e.onmessage=t=>{var n,r;(r=(n=this.options).onMessage)==null||r.call(n,t)},e.onclose=t=>{var n,r;(r=(n=this.options).onClose)==null||r.call(n,t),!this.manuallyClosed&&this.options.autoReconnect&&this.scheduleReconnect()},e.onerror=t=>{var n,r;(r=(n=this.options).onError)==null||r.call(n,t)}}send(e){this.socket&&this.socket.readyState===1&&this.socket.send(e)}disconnect(){this.manuallyClosed=!0,this.clearReconnectTimer(),this.socket&&(this.socket.close(),this.socket=null)}getSocket(){return this.socket}scheduleReconnect(){var i,l,c,d,M;this.clearReconnectTimer();let e=(i=this.options.maxReconnectAttempts)!=null?i:10;if(e>0&&this.reconnectAttempts>=e){(c=(l=this.options).onReconnectFailed)==null||c.call(l);return}this.reconnectAttempts++;let t=(d=this.options.reconnectDelay)!=null?d:1e3,n=(M=this.options.maxReconnectDelay)!=null?M:16e3,r=t*Math.pow(2,this.reconnectAttempts-1),s=Math.random()*1e3,o=Math.min(r+s,n);this.reconnectTimer=window.setTimeout(()=>{var m,f;(f=(m=this.options).onReconnectAttempt)==null||f.call(m,this.reconnectAttempts,o),this.connect()},o)}clearReconnectTimer(){this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}},ee=class{constructor(e){this.config=e;this.transport=null}async connect(){let e=this.getLiveUrl();return await Xe(e,this.config.logger)?(this.transport=new pe({url:this.getWebSocketUrl(),autoReconnect:this.config.options.autoReconnect,reconnectDelay:this.config.options.reconnectDelay,maxReconnectDelay:16e3,maxReconnectAttempts:10,onOpen:()=>{this.config.onConnected()},onMessage:n=>{try{let r=JSON.parse(n.data);this.config.onMessage(r,n)}catch(r){this.config.logger.error("Failed to parse WebSocket message:",r)}},onClose:()=>{this.config.onDisconnected()},onReconnectAttempt:(n,r)=>{var s,o;(o=(s=this.config).onReconnectAttempt)==null||o.call(s,n,r)},onReconnectFailed:()=>{var n,r;(r=(n=this.config).onReconnectFailed)==null||r.call(n)},onError:n=>{var r,s;(s=(r=this.config).onError)==null||s.call(r,n)}}),this.transport.connect(),{usingWebSocket:!0}):{usingWebSocket:!1,initialState:await Ye(e,this.config.logger)}}disconnect(){var e;(e=this.transport)==null||e.disconnect(),this.transport=null}send(e){var t;(t=this.transport)==null||t.send(e)}getReadyState(){var e,t;return(t=(e=this.transport)==null?void 0:e.getSocket())==null?void 0:t.readyState}getSocket(){var e,t;return(t=(e=this.transport)==null?void 0:e.getSocket())!=null?t:null}getWebSocketUrl(){let e=this.config.options.liveUrl||"/live",t=this.config.options.wsUrl;return t||`ws://${window.location.host}${e}`}getLiveUrl(){return this.config.options.liveUrl||window.location.pathname}};async function Xe(a,e){try{let n=(await fetch(a,{method:"HEAD"})).headers.get("X-LiveTemplate-WebSocket");return n?n==="enabled":!0}catch(t){return e==null||e.warn("Failed to check WebSocket availability:",t),!0}}async function Ye(a,e){try{let t=await fetch(a,{method:"GET",credentials:"include",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to fetch initial state: ${t.status}`);return await t.json()}catch(t){return e==null||e.warn("Failed to fetch initial state:",t),null}}var te=class{async upload(e,t,n){let{file:r}=e;e.abortController=new AbortController;try{let s=new XMLHttpRequest;s.upload.addEventListener("progress",i=>{i.lengthComputable&&(e.bytesUploaded=i.loaded,e.progress=Math.round(i.loaded/i.total*100),n&&n(e))}),e.abortController.signal.addEventListener("abort",()=>{s.abort()});let o=new Promise((i,l)=>{s.addEventListener("load",()=>{s.status>=200&&s.status<300?(e.done=!0,e.progress=100,i()):l(new Error(`S3 upload failed with status ${s.status}: ${s.statusText}`))}),s.addEventListener("error",()=>{l(new Error("S3 upload failed: Network error"))}),s.addEventListener("abort",()=>{l(new Error("S3 upload cancelled"))})});if(s.open("PUT",t.url),t.headers)for(let[i,l]of Object.entries(t.headers))s.setRequestHeader(i,l);s.send(r),await o}catch(s){throw e.error=s instanceof Error?s.message:String(s),s}}};var ne=class{constructor(e,t={}){this.sendMessage=e;this.entries=new Map;this.pendingFiles=new Map;this.autoUploadConfig=new Map;this.uploaders=new Map;this.inputHandlers=new WeakMap;this.chunkSize=t.chunkSize||256*1024,this.onProgress=t.onProgress,this.onComplete=t.onComplete,this.onError=t.onError,this.uploaders.set("s3",new te)}initializeFileInputs(e){e.querySelectorAll('input[type="file"][lvt-upload]').forEach(n=>{let r=n.getAttribute("lvt-upload");if(!r)return;let s=this.inputHandlers.get(n);s&&n.removeEventListener("change",s);let o=i=>{let l=i.target.files;!l||l.length===0||this.startUpload(r,Array.from(l))};n.addEventListener("change",o),this.inputHandlers.set(n,o)})}async startUpload(e,t){this.pendingFiles.set(e,t);let n=t.map(s=>({name:s.name,type:s.type||"application/octet-stream",size:s.size})),r={action:"upload_start",upload_name:e,files:n};this.sendMessage(r)}async handleUploadStartResponse(e){let{upload_name:t,entries:n}=e;n.length>0&&this.autoUploadConfig.set(t,n[0].auto_upload);let r=this.pendingFiles.get(t);if(!r){console.error(`No pending files found for upload: ${t}`);return}this.pendingFiles.delete(t);let s=new Map;for(let i of r)s.set(i.name,i);let o=[];for(let i of n){let l=s.get(i.client_name);if(!l){console.warn(`No file found for entry ${i.entry_id} (client_name: ${i.client_name})`);continue}let c={id:i.entry_id,file:l,uploadName:t,progress:0,bytesUploaded:0,valid:i.valid,done:!1,error:i.error,external:i.external};if(this.entries.set(c.id,c),o.push(c),!i.valid){this.onError&&i.error&&this.onError(c,i.error);continue}i.auto_upload&&(i.external?this.uploadExternal(c,i.external):this.uploadChunked(c))}}async uploadExternal(e,t){try{let n=this.uploaders.get(t.uploader);if(!n)throw new Error(`Unknown uploader: ${t.uploader}`);await n.upload(e,t,this.onProgress);let r={action:"upload_complete",upload_name:e.uploadName,entry_ids:[e.id]};this.sendMessage(r),this.onComplete&&this.onComplete(e.uploadName,[e]),this.clearFileInput(e.uploadName),this.cleanupEntries(e.uploadName)}catch(n){let r=n instanceof Error?n.message:String(n);e.error=r,this.onError&&this.onError(e,r),this.cleanupEntries(e.uploadName)}}async uploadChunked(e){let{file:t,id:n}=e,r=0;e.abortController=new AbortController;try{for(;r<t.size;){if(e.abortController.signal.aborted)throw new Error("Upload cancelled");let o=Math.min(r+this.chunkSize,t.size),i=t.slice(r,o),l=await this.fileToBase64(i),c={action:"upload_chunk",entry_id:n,chunk_base64:l,offset:r,total:t.size};this.sendMessage(c),r=o,e.bytesUploaded=r,e.progress=Math.round(r/t.size*100),this.onProgress&&this.onProgress(e)}e.done=!0;let s={action:"upload_complete",upload_name:e.uploadName,entry_ids:[n]};this.sendMessage(s),this.onComplete&&this.onComplete(e.uploadName,[e]),this.clearFileInput(e.uploadName),this.cleanupEntries(e.uploadName)}catch(s){let o=s instanceof Error?s.message:String(s);e.error=o,this.onError&&this.onError(e,o),this.cleanupEntries(e.uploadName)}}handleProgressMessage(e){let t=this.entries.get(e.entry_id);t&&(t.progress=e.progress,t.bytesUploaded=e.bytes_recv,this.onProgress&&this.onProgress(t))}cancelUpload(e){let t=this.entries.get(e);t&&(t.abortController&&t.abortController.abort(),this.sendMessage({action:"cancel_upload",entry_id:e}),this.entries.delete(e))}getEntries(e){let t=[];for(let n of this.entries.values())n.uploadName===e&&t.push(n);return t}triggerPendingUploads(e){let t=[];for(let n of this.entries.values())n.uploadName===e&&n.progress===0&&!n.done&&!n.error&&t.push(n);for(let n of t)n.external?this.uploadExternal(n,n.external):this.uploadChunked(n)}registerUploader(e,t){this.uploaders.set(e,t)}clearFileInput(e){document.querySelectorAll(`input[type="file"][lvt-upload="${e}"]`).forEach(n=>{n.value=""})}cleanupEntries(e,t=5e3){setTimeout(()=>{let n=[];for(let[r,s]of this.entries)e&&s.uploadName!==e||(s.done||s.error)&&n.push(r);for(let r of n)this.entries.delete(r)},t)}fileToBase64(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result.split(",")[1];t(o)},r.onerror=n,r.readAsDataURL(e)})}};var Te={silent:0,error:1,warn:2,info:3,debug:4},Le="LiveTemplate",ge=class a{constructor(e,t=[],n=console){this.state=e;this.scope=t;this.sink=n}setLevel(e){this.state.level=e}getLevel(){return this.state.level}child(e){return new a(this.state,[...this.scope,e],this.sink)}isDebugEnabled(){return this.shouldLog("debug")}error(...e){this.log("error","error",e)}warn(...e){this.log("warn","warn",e)}info(...e){this.log("info","info",e)}debug(...e){this.log("debug","debug",e)}log(e,t,n){if(!this.shouldLog(e))return;(this.sink[t]||console[t]||console.log).apply(this.sink,[this.formatPrefix(),...n])}shouldLog(e){return Te[e]<=Te[this.state.level]}formatPrefix(){return this.scope.length===0?`[${Le}]`:`[${Le}:${this.scope.join(":")}]`}};function he(a={}){var n,r;let e={level:(n=a.level)!=null?n:"info"},t=Array.isArray(a.scope)?a.scope:a.scope?[a.scope]:[];return new ge(e,t,(r=a.sink)!=null?r:console)}async function xe(a,e){try{let t=globalThis==null?void 0:globalThis.require;if(typeof t=="function"){let s=t("fs"),o=JSON.parse(s.readFileSync(e,"utf8"));return a.applyUpdate(o)}let r=await(await fetch(e)).json();return a.applyUpdate(r)}catch(t){throw new Error(`Failed to load update from ${e}: ${t}`)}}function Fe(a,e){let t=[],n=c=>c.replace(/\s+/g," ").replace(/>\s+</g,"><").trim(),r=n(a),s=n(e);if(r===s)return{match:!0,differences:[]};let o=r.split(`
42
+ `),i=s.split(`
43
+ `),l=Math.max(o.length,i.length);for(let c=0;c<l;c++){let d=o[c]||"",M=i[c]||"";d!==M&&(t.push(`Line ${c+1}:`),t.push(` Expected: ${d}`),t.push(` Actual: ${M}`))}return{match:!1,differences:t}}var re=class a{constructor(e={}){this.lvtId=null;this.ws=null;this.wrapperElement=null;this.useHTTP=!1;this.sessionCookie=null;this.rateLimitedHandlers=new WeakMap;this.isInitialized=!1;this.messageCount=0;let{logger:t,logLevel:n,debug:r,...s}=e,o=n!=null?n:r?"debug":"info",i=t!=null?t:he({level:o});t?n?t.setLevel(n):r&&t.setLevel("debug"):i.setLevel(o),this.logger=i.child("Client"),this.options={autoReconnect:!1,reconnectDelay:1e3,liveUrl:window.location.pathname,...s},this.treeRenderer=new Q(this.logger.child("TreeRenderer")),this.focusManager=new z(this.logger.child("FocusManager")),this.modalManager=new J(this.logger.child("ModalManager")),this.formLifecycleManager=new Z(this.modalManager),this.loadingIndicator=new X,this.formDisabler=new Y,this.uploadHandler=new ne(l=>this.send(l),{chunkSize:256*1024,onProgress:l=>{this.wrapperElement&&this.wrapperElement.dispatchEvent(new CustomEvent("lvt:upload:progress",{detail:{entry:l}}))},onComplete:(l,c)=>{this.logger.info(`Upload complete: ${l}`,c),this.wrapperElement&&this.wrapperElement.dispatchEvent(new CustomEvent("lvt:upload:complete",{detail:{uploadName:l,entries:c}}))},onError:(l,c)=>{this.logger.error(`Upload error for ${l.id}:`,c),this.wrapperElement&&this.wrapperElement.dispatchEvent(new CustomEvent("lvt:upload:error",{detail:{entry:l,error:c}}))}}),this.eventDelegator=new q({getWrapperElement:()=>this.wrapperElement,getRateLimitedHandlers:()=>this.rateLimitedHandlers,parseValue:l=>this.parseValue(l),send:l=>this.send(l),setActiveSubmission:(l,c,d)=>this.formLifecycleManager.setActiveSubmission(l,c,d),openModal:l=>this.modalManager.open(l),closeModal:l=>this.modalManager.close(l),getWebSocketReadyState:()=>this.webSocketManager.getReadyState(),triggerPendingUploads:l=>this.uploadHandler.triggerPendingUploads(l)},this.logger.child("EventDelegator")),this.observerManager=new G({getWrapperElement:()=>this.wrapperElement,send:l=>this.send(l)},this.logger.child("ObserverManager")),this.webSocketManager=new ee({options:this.options,logger:this.logger.child("Transport"),onConnected:()=>{var l,c,d;this.ws=this.webSocketManager.getSocket(),this.logger.info("WebSocket connected"),(c=(l=this.options).onConnect)==null||c.call(l),(d=this.wrapperElement)==null||d.dispatchEvent(new Event("lvt:connected"))},onDisconnected:()=>{var l,c,d;this.ws=null,this.logger.info("WebSocket disconnected"),(c=(l=this.options).onDisconnect)==null||c.call(l),(d=this.wrapperElement)==null||d.dispatchEvent(new Event("lvt:disconnected"))},onMessage:(l,c)=>{this.handleWebSocketPayload(l,c)},onReconnectAttempt:()=>{this.logger.info("Attempting to reconnect...")},onError:l=>{var c,d;this.logger.error("WebSocket error:",l),(d=(c=this.options).onError)==null||d.call(c,l)}})}static autoInit(){let e=he({scope:"Client:autoInit"}),t=()=>{let n=document.querySelector("[data-lvt-id]");if(n){let r=new a;r.wrapperElement=n,n.getAttribute("data-lvt-loading")==="true"&&(r.loadingIndicator.show(),r.formDisabler.disable(r.wrapperElement)),r.connect().catch(o=>{e.error("Auto-initialization connect failed:",o)}),window.liveTemplateClient=r}};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",t):t()}handleWebSocketPayload(e,t){var r,s;t&&(window.__lastWSMessage=t.data,window.__wsMessages||(window.__wsMessages=[]),window.__wsMessages.push(e));let n=e;if(n.type==="upload_progress"){this.uploadHandler.handleProgressMessage(n);return}if(n.upload_name&&n.entries){let o=n;try{this.handleUploadStartResponse(o)}catch(i){this.logger.error("Error handling upload start response:",i)}return}if(n.upload_name&&n.hasOwnProperty("success")){n.success?this.logger.info(`Upload complete: ${n.upload_name}`):this.logger.error(`Upload failed: ${n.upload_name}`,n.error);return}this.isInitialized||(this.loadingIndicator.hide(),this.formDisabler.enable(this.wrapperElement),this.wrapperElement&&this.wrapperElement.hasAttribute("data-lvt-loading")&&this.wrapperElement.removeAttribute("data-lvt-loading"),this.isInitialized=!0),this.wrapperElement&&(this.updateDOM(this.wrapperElement,e.tree,e.meta),this.messageCount++,window.__wsMessageCount=this.messageCount,this.wrapperElement.dispatchEvent(new CustomEvent("lvt:updated",{detail:{messageCount:this.messageCount,action:(r=e.meta)==null?void 0:r.action,success:(s=e.meta)==null?void 0:s.success}})))}async connect(e="[data-lvt-id]"){var n,r;if(this.wrapperElement=document.querySelector(e),!this.wrapperElement)throw new Error(`LiveTemplate wrapper not found with selector: ${e}`);this.webSocketManager.disconnect();let t=await this.webSocketManager.connect();this.useHTTP=!t.usingWebSocket,this.useHTTP&&(this.ws=null,this.logger.info("WebSocket not available, using HTTP mode"),(r=(n=this.options).onConnect)==null||r.call(n),t.initialState&&this.wrapperElement&&this.handleWebSocketPayload(t.initialState)),this.eventDelegator.setupEventDelegation(),this.eventDelegator.setupWindowEventDelegation(),this.eventDelegator.setupClickAwayDelegation(),this.eventDelegator.setupModalDelegation(),this.focusManager.attach(this.wrapperElement),this.observerManager.setupInfiniteScrollObserver(),this.observerManager.setupInfiniteScrollMutationObserver()}disconnect(){this.webSocketManager.disconnect(),this.ws=null,this.useHTTP=!1,this.observerManager.teardown(),this.formLifecycleManager.reset(),this.loadingIndicator.hide(),this.formDisabler.enable(this.wrapperElement)}isReady(){let e=this.wrapperElement;return!e||e.hasAttribute("data-lvt-loading")?!1:this.useHTTP?!0:this.webSocketManager.getReadyState()===1}send(e){window.__lvtSendCalled=!0,window.__lvtMessageAction=e==null?void 0:e.action;let t=this.webSocketManager.getReadyState();this.logger.isDebugEnabled()&&this.logger.debug("send() invoked",{message:e,useHTTP:this.useHTTP,hasWebSocket:t!==void 0,readyState:t}),this.useHTTP?(this.logger.debug("Using HTTP mode for send"),window.__lvtSendPath="http",this.sendHTTP(e)):t===1?(this.logger.debug("Sending via WebSocket"),window.__lvtSendPath="websocket",window.__lvtWSMessage=JSON.stringify(e),this.webSocketManager.send(JSON.stringify(e)),this.logger.debug("WebSocket send complete"),window.__lvtWSSendComplete=!0):t!==void 0?(this.logger.warn(`WebSocket not ready (state: ${t}), using HTTP fallback`),window.__lvtSendPath="http-fallback",this.sendHTTP(e)):(this.logger.error("No transport available"),window.__lvtSendPath="no-transport")}async sendHTTP(e){try{let t=this.options.liveUrl||"/live",n=await fetch(t,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!n.ok)throw new Error(`HTTP request failed: ${n.status}`);let r=await n.json();this.wrapperElement&&this.updateDOM(this.wrapperElement,r.tree,r.meta)}catch(t){this.logger.error("Failed to send HTTP request:",t)}}parseValue(e){let t=parseFloat(e);return!isNaN(t)&&e.trim()===t.toString()?t:e==="true"?!0:e==="false"?!1:e}applyUpdate(e){return this.treeRenderer.applyUpdate(e)}applyUpdateToHTML(e,t){let n=this.applyUpdate(t);if(!this.lvtId){let c=e.match(/data-lvt-id="([^"]+)"/);c&&(this.lvtId=c[1])}let r=n.html;if(!e.match(/<body>([\s\S]*?)<\/body>/))return e;let l=`<div data-lvt-id="${this.lvtId||"lvt-unknown"}">`+r+"</div>";return e.replace(/<body>[\s\S]*?<\/body>/,`<body>${l}</body>`)}updateDOM(e,t,n){let r=this.applyUpdate(t),s=i=>!i||typeof i!="object"?!1:i.s&&Array.isArray(i.s)?!0:Object.values(i).some(l=>s(l));if(!r.changed&&!s(t))return;let o=document.createElement(e.tagName);this.logger.isDebugEnabled()&&(this.logger.debug("[updateDOM] element.tagName:",e.tagName),this.logger.debug("[updateDOM] result.html (first 500 chars):",r.html.substring(0,500)),this.logger.debug("[updateDOM] Has <table> tag:",r.html.includes("<table>")),this.logger.debug("[updateDOM] Has <tbody> tag:",r.html.includes("<tbody>")),this.logger.debug("[updateDOM] Has <tr> tag:",r.html.includes("<tr"))),o.innerHTML=r.html,this.logger.isDebugEnabled()&&(this.logger.debug("[updateDOM] tempWrapper.innerHTML (first 500 chars):",o.innerHTML.substring(0,500)),this.logger.debug("[updateDOM] tempWrapper has <table>:",o.innerHTML.includes("<table>")),this.logger.debug("[updateDOM] tempWrapper has <tbody>:",o.innerHTML.includes("<tbody>")),this.logger.debug("[updateDOM] tempWrapper has <tr>:",o.innerHTML.includes("<tr"))),Se(e,o,{childrenOnly:!0,getNodeKey:i=>{if(i.nodeType===1)return i.getAttribute("data-key")||i.getAttribute("data-lvt-key")||void 0},onBeforeElUpdated:(i,l)=>{let c=this.focusManager.getLastFocusedElement();return c&&this.focusManager.isTextualInput(i)&&i===c&&(l.value=i.value),i.isEqualNode(l)?!1:(this.executeLifecycleHook(i,"lvt-updated"),!0)},onNodeAdded:i=>{i.nodeType===Node.ELEMENT_NODE&&this.executeLifecycleHook(i,"lvt-mounted")},onBeforeNodeDiscarded:i=>(i.nodeType===Node.ELEMENT_NODE&&this.executeLifecycleHook(i,"lvt-destroyed"),!0)}),this.focusManager.restoreFocusedElement(),Me(e),ke(e),Ae(e),this.uploadHandler.initializeFileInputs(e),n&&this.formLifecycleManager.handleResponse(n)}handleUploadStartResponse(e){this.uploadHandler.handleUploadStartResponse(e)}executeLifecycleHook(e,t){let n=e.getAttribute(t);if(n)try{new Function("element",n).call(e,e)}catch(r){this.logger.error(`Error executing ${t} hook:`,r)}}reset(){this.treeRenderer.reset(),this.focusManager.reset(),this.observerManager.teardown(),this.formLifecycleManager.reset(),this.loadingIndicator.hide(),this.formDisabler.enable(this.wrapperElement),this.lvtId=null}getTreeState(){return this.treeRenderer.getTreeState()}getStaticStructure(){return this.treeRenderer.getStaticStructure()}};typeof window!="undefined"&&re.autoInit();return Ie(Qe);})();
44
44
  //# sourceMappingURL=livetemplate-client.browser.js.map