@livetemplate/client 0.8.5 → 0.8.6

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,2 +1,3 @@
1
+ export declare const DEFAULT_CHANGE_DEBOUNCE_MS = 300;
1
2
  export declare const FOCUSABLE_INPUTS: string[];
2
3
  //# sourceMappingURL=constants.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,gBAAgB,UAc5B,CAAC"}
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,0BAA0B,MAAM,CAAC;AAE9C,eAAO,MAAM,gBAAgB,UAc5B,CAAC"}
package/dist/constants.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FOCUSABLE_INPUTS = void 0;
3
+ exports.FOCUSABLE_INPUTS = exports.DEFAULT_CHANGE_DEBOUNCE_MS = void 0;
4
+ exports.DEFAULT_CHANGE_DEBOUNCE_MS = 300;
4
5
  exports.FOCUSABLE_INPUTS = [
5
6
  "text",
6
7
  "textarea",
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,gBAAgB,GAAG;IAC9B,MAAM;IACN,UAAU;IACV,QAAQ;IACR,OAAO;IACP,UAAU;IACV,QAAQ;IACR,KAAK;IACL,KAAK;IACL,MAAM;IACN,MAAM;IACN,gBAAgB;IAChB,OAAO;IACP,OAAO;CACR,CAAC"}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,0BAA0B,GAAG,GAAG,CAAC;AAEjC,QAAA,gBAAgB,GAAG;IAC9B,MAAM;IACN,UAAU;IACV,QAAQ;IACR,OAAO;IACP,UAAU;IACV,QAAQ;IACR,KAAK;IACL,KAAK;IACL,MAAM;IACN,MAAM;IACN,gBAAgB;IAChB,OAAO;IACP,OAAO;CACR,CAAC"}
@@ -1,4 +1,4 @@
1
- "use strict";var LiveTemplateClient=(()=>{var pe=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var $e=Object.prototype.hasOwnProperty;var Be=(a,e)=>{for(var t in e)pe(a,t,{get:e[t],enumerable:!0})},Pe=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of We(e))!$e.call(a,r)&&r!==t&&pe(a,r,{get:()=>e[r],enumerable:!(n=De(e,r))||n.enumerable});return a};var Ke=a=>Pe(pe({},"__esModule",{value:!0}),a);var pt={};Be(pt,{LiveTemplateClient:()=>de,checkLvtConfirm:()=>Y,compareHTML:()=>Oe,extractLvtData:()=>Ce,loadAndApplyUpdate:()=>Ue,setupReactiveAttributeListeners:()=>se});var Ae=11;function Ve(a,e){var t=e.attributes,n,r,s,o,i;if(!(e.nodeType===Ae||a.nodeType===Ae)){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 X,je="http://www.w3.org/1999/xhtml",F=typeof document=="undefined"?void 0:document,qe=!!F&&"content"in F.createElement("template"),ze=!!F&&F.createRange&&"createContextualFragment"in F.createRange();function Xe(a){var e=F.createElement("template");return e.innerHTML=a,e.content.childNodes[0]}function Je(a){X||(X=F.createRange(),X.selectNode(F.body));var e=X.createContextualFragment(a);return e.childNodes[0]}function Ge(a){var e=F.createElement("body");return e.innerHTML=a,e.childNodes[0]}function Ye(a){return a=a.trim(),qe?Xe(a):ze?Je(a):Ge(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 Qe(a,e){return!e||e===je?F.createElement(a):F.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 ge(a,e,t){a[t]!==e[t]&&(a[t]=e[t],a[t]?a.setAttribute(t,""):a.removeAttribute(t))}var Se={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)}ge(a,e,"selected")},INPUT:function(a,e){ge(a,e,"checked"),ge(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}}},V=1,Me=11,Le=3,Te=8;function $(){}function et(a){if(a)return a.getAttribute&&a.getAttribute("id")||a.id}function tt(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=F.createElement("html"),n.innerHTML=s}else n=Ye(n);else n.nodeType===Me&&(n=n.firstElementChild);var o=r.getNodeKey||et,i=r.onBeforeNodeAdded||$,l=r.onNodeAdded||$,c=r.onBeforeElUpdated||$,d=r.onElUpdated||$,g=r.onBeforeNodeDiscarded||$,p=r.onNodeDiscarded||$,h=r.onBeforeElChildrenUpdated||$,S=r.skipFromChildren||$,_=r.addChild||function(f,v){return f.appendChild(v)},w=r.childrenOnly===!0,y=Object.create(null),m=[];function u(f){m.push(f)}function L(f,v){if(f.nodeType===V)for(var k=f.firstChild;k;){var b=void 0;v&&(b=o(k))?u(b):(p(k),k.firstChild&&L(k,v)),k=k.nextSibling}}function C(f,v,k){g(f)!==!1&&(v&&v.removeChild(f),p(f),L(f,k))}function N(f){if(f.nodeType===V||f.nodeType===Me)for(var v=f.firstChild;v;){var k=o(v);k&&(y[k]=v),N(v),v=v.nextSibling}}N(t);function j(f){l(f);for(var v=f.firstChild;v;){var k=v.nextSibling,b=o(v);if(b){var A=y[b];A&&J(v,A)?(v.parentNode.replaceChild(A,v),E(A,v)):j(v)}else j(v);v=k}}function T(f,v,k){for(;v;){var b=v.nextSibling;(k=o(v))?u(k):C(v,f,!0),v=b}}function E(f,v,k){var b=o(v);if(b&&delete y[b],!k){var A=c(f,v);if(A===!1||(A instanceof HTMLElement&&(f=A,N(f)),a(f,v),d(f),h(f,v)===!1))return}f.nodeName!=="TEXTAREA"?x(f,v):Se.TEXTAREA(f,v)}function x(f,v){var k=S(f,v),b=v.firstChild,A=f.firstChild,P,O,K,q,D;e:for(;b;){for(q=b.nextSibling,P=o(b);!k&&A;){if(K=A.nextSibling,b.isSameNode&&b.isSameNode(A)){b=q,A=K;continue e}O=o(A);var z=A.nodeType,W=void 0;if(z===b.nodeType&&(z===V?(P?P!==O&&((D=y[P])?K===D?W=!1:(f.insertBefore(D,A),O?u(O):C(A,f,!0),A=D,O=o(A)):W=!1):O&&(W=!1),W=W!==!1&&J(A,b),W&&E(A,b)):(z===Le||z==Te)&&(W=!0,A.nodeValue!==b.nodeValue&&(A.nodeValue=b.nodeValue))),W){b=q,A=K;continue e}O?u(O):C(A,f,!0),A=K}if(P&&(D=y[P])&&J(D,b))k||_(f,D),E(D,b);else{var ue=i(b);ue!==!1&&(ue&&(b=ue),b.actualize&&(b=b.actualize(f.ownerDocument||F)),_(f,b),j(b))}b=q,A=K}T(f,A,O);var we=Se[f.nodeName];we&&we(f,v)}var M=t,I=M.nodeType,U=n.nodeType;if(!w){if(I===V)U===V?J(t,n)||(p(t),M=Ze(t,Qe(n.nodeName,n.namespaceURI))):M=n;else if(I===Le||I===Te){if(U===I)return M.nodeValue!==n.nodeValue&&(M.nodeValue=n.nodeValue),M;M=n}}if(M===n)p(t);else{if(n.isSameNode&&n.isSameNode(M))return;if(E(M,n,w),m)for(var H=0,B=m.length;H<B;H++){var R=y[m[H]];R&&C(R,R.parentNode,!1)}}return!w&&M!==t&&t.parentNode&&(M.actualize&&(M=M.actualize(t.ownerDocument||F)),t.parentNode.replaceChild(M,t)),M}}var nt=tt(Ve),ke=nt;var fe=["text","textarea","number","email","password","search","tel","url","date","time","datetime-local","color","range"];var G=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=`${fe.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?fe.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 xe(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 _e(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 Re(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=`
1
+ "use strict";var LiveTemplateClient=(()=>{var fe=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var $e=Object.getOwnPropertyNames;var Be=Object.prototype.hasOwnProperty;var Pe=(o,e)=>{for(var t in e)fe(o,t,{get:e[t],enumerable:!0})},Ke=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of $e(e))!Be.call(o,r)&&r!==t&&fe(o,r,{get:()=>e[r],enumerable:!(n=We(e,r))||n.enumerable});return o};var Ve=o=>Ke(fe({},"__esModule",{value:!0}),o);var ft={};Pe(ft,{LiveTemplateClient:()=>pe,checkLvtConfirm:()=>Q,compareHTML:()=>De,extractLvtData:()=>Re,loadAndApplyUpdate:()=>Oe,setupReactiveAttributeListeners:()=>ie});var Se=11;function je(o,e){var t=e.attributes,n,r,s,a,i;if(!(e.nodeType===Se||o.nodeType===Se)){for(var l=t.length-1;l>=0;l--)n=t[l],r=n.name,s=n.namespaceURI,a=n.value,s?(r=n.localName||r,i=o.getAttributeNS(s,r),i!==a&&(n.prefix==="xmlns"&&(r=n.name),o.setAttributeNS(s,r,a))):(i=o.getAttribute(r),i!==a&&o.setAttribute(r,a));for(var c=o.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)||o.removeAttributeNS(s,r)):e.hasAttribute(r)||o.removeAttribute(r)}}var X,qe="http://www.w3.org/1999/xhtml",I=typeof document=="undefined"?void 0:document,ze=!!I&&"content"in I.createElement("template"),Ge=!!I&&I.createRange&&"createContextualFragment"in I.createRange();function Xe(o){var e=I.createElement("template");return e.innerHTML=o,e.content.childNodes[0]}function Je(o){X||(X=I.createRange(),X.selectNode(I.body));var e=X.createContextualFragment(o);return e.childNodes[0]}function Ye(o){var e=I.createElement("body");return e.innerHTML=o,e.childNodes[0]}function Qe(o){return o=o.trim(),ze?Xe(o):Ge?Je(o):Ye(o)}function J(o,e){var t=o.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 Ze(o,e){return!e||e===qe?I.createElement(o):I.createElementNS(e,o)}function et(o,e){for(var t=o.firstChild;t;){var n=t.nextSibling;e.appendChild(t),t=n}return e}function he(o,e,t){o[t]!==e[t]&&(o[t]=e[t],o[t]?o.setAttribute(t,""):o.removeAttribute(t))}var Te={OPTION:function(o,e){var t=o.parentNode;if(t){var n=t.nodeName.toUpperCase();n==="OPTGROUP"&&(t=t.parentNode,n=t&&t.nodeName.toUpperCase()),n==="SELECT"&&!t.hasAttribute("multiple")&&(o.hasAttribute("selected")&&!e.selected&&(o.setAttribute("selected","selected"),o.removeAttribute("selected")),t.selectedIndex=-1)}he(o,e,"selected")},INPUT:function(o,e){he(o,e,"checked"),he(o,e,"disabled"),o.value!==e.value&&(o.value=e.value),e.hasAttribute("value")||o.removeAttribute("value")},TEXTAREA:function(o,e){var t=e.value;o.value!==t&&(o.value=t);var n=o.firstChild;if(n){var r=n.nodeValue;if(r==t||!t&&r==o.placeholder)return;n.nodeValue=t}},SELECT:function(o,e){if(!e.hasAttribute("multiple")){for(var t=-1,n=0,r=o.firstChild,s,a;r;)if(a=r.nodeName&&r.nodeName.toUpperCase(),a==="OPTGROUP")s=r,r=s.firstChild,r||(r=s.nextSibling,s=null);else{if(a==="OPTION"){if(r.hasAttribute("selected")){t=n;break}n++}r=r.nextSibling,!r&&s&&(r=s.nextSibling,s=null)}o.selectedIndex=t}}},V=1,Me=11,Le=3,ke=8;function $(){}function tt(o){if(o)return o.getAttribute&&o.getAttribute("id")||o.id}function nt(o){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=I.createElement("html"),n.innerHTML=s}else n=Qe(n);else n.nodeType===Me&&(n=n.firstElementChild);var a=r.getNodeKey||tt,i=r.onBeforeNodeAdded||$,l=r.onNodeAdded||$,c=r.onBeforeElUpdated||$,d=r.onElUpdated||$,g=r.onBeforeNodeDiscarded||$,p=r.onNodeDiscarded||$,h=r.onBeforeElChildrenUpdated||$,S=r.skipFromChildren||$,C=r.addChild||function(f,v){return f.appendChild(v)},w=r.childrenOnly===!0,y=Object.create(null),m=[];function u(f){m.push(f)}function M(f,v){if(f.nodeType===V)for(var k=f.firstChild;k;){var b=void 0;v&&(b=a(k))?u(b):(p(k),k.firstChild&&M(k,v)),k=k.nextSibling}}function F(f,v,k){g(f)!==!1&&(v&&v.removeChild(f),p(f),M(f,k))}function N(f){if(f.nodeType===V||f.nodeType===Me)for(var v=f.firstChild;v;){var k=a(v);k&&(y[k]=v),N(v),v=v.nextSibling}}N(t);function q(f){l(f);for(var v=f.firstChild;v;){var k=v.nextSibling,b=a(v);if(b){var A=y[b];A&&J(v,A)?(v.parentNode.replaceChild(A,v),E(A,v)):q(v)}else q(v);v=k}}function L(f,v,k){for(;v;){var b=v.nextSibling;(k=a(v))?u(k):F(v,f,!0),v=b}}function E(f,v,k){var b=a(v);if(b&&delete y[b],!k){var A=c(f,v);if(A===!1||(A instanceof HTMLElement&&(f=A,N(f)),o(f,v),d(f),h(f,v)===!1))return}f.nodeName!=="TEXTAREA"?x(f,v):Te.TEXTAREA(f,v)}function x(f,v){var k=S(f,v),b=v.firstChild,A=f.firstChild,P,O,K,z,D;e:for(;b;){for(z=b.nextSibling,P=a(b);!k&&A;){if(K=A.nextSibling,b.isSameNode&&b.isSameNode(A)){b=z,A=K;continue e}O=a(A);var G=A.nodeType,W=void 0;if(G===b.nodeType&&(G===V?(P?P!==O&&((D=y[P])?K===D?W=!1:(f.insertBefore(D,A),O?u(O):F(A,f,!0),A=D,O=a(A)):W=!1):O&&(W=!1),W=W!==!1&&J(A,b),W&&E(A,b)):(G===Le||G==ke)&&(W=!0,A.nodeValue!==b.nodeValue&&(A.nodeValue=b.nodeValue))),W){b=z,A=K;continue e}O?u(O):F(A,f,!0),A=K}if(P&&(D=y[P])&&J(D,b))k||C(f,D),E(D,b);else{var ge=i(b);ge!==!1&&(ge&&(b=ge),b.actualize&&(b=b.actualize(f.ownerDocument||I)),C(f,b),q(b))}b=z,A=K}L(f,A,O);var Ae=Te[f.nodeName];Ae&&Ae(f,v)}var T=t,R=T.nodeType,U=n.nodeType;if(!w){if(R===V)U===V?J(t,n)||(p(t),T=et(t,Ze(n.nodeName,n.namespaceURI))):T=n;else if(R===Le||R===ke){if(U===R)return T.nodeValue!==n.nodeValue&&(T.nodeValue=n.nodeValue),T;T=n}}if(T===n)p(t);else{if(n.isSameNode&&n.isSameNode(T))return;if(E(T,n,w),m)for(var H=0,B=m.length;H<B;H++){var _=y[m[H]];_&&F(_,_.parentNode,!1)}}return!w&&T!==t&&t.parentNode&&(T.actualize&&(T=T.actualize(t.ownerDocument||I)),t.parentNode.replaceChild(T,t)),T}}var rt=nt(je),xe=rt;var me=["text","textarea","number","email","password","search","tel","url","date","time","datetime-local","color","range"];var Y=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=`${me.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=a=>{var l;let i=a.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=a=>{var l;let i=a.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,a;if(this.logger.debug("[Focus] restoreFocusedElement - lastFocusedElement:",(r=this.lastFocusedElement)==null?void 0:r.tagName,((s=this.lastFocusedElement)==null?void 0:s.id)||((a=this.lastFocusedElement)==null?void 0:a.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?me.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 Ce(o){o.querySelectorAll("[lvt-scroll]").forEach(t=>{let n=t,r=n.getAttribute("lvt-scroll"),s=n.getAttribute("lvt-scroll-behavior")||"auto",a=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<=a&&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 _e(o){o.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 a=t,i=a.style.backgroundColor,l=a.style.transition;a.style.transition=`background-color ${r}ms ease-out`,a.style.backgroundColor=s,setTimeout(()=>{a.style.backgroundColor=i,setTimeout(()=>{a.style.transition=l},r)},50)})}function Fe(o){if(o.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 he(a,e){let t=null;return function(...r){let s=this;t!==null&&clearTimeout(t),t=window.setTimeout(()=>{a.apply(s,r)},e)}}function me(a,e){let t=!1;return function(...r){let s=this;t||(a.apply(s,r),t=!0,setTimeout(()=>{t=!1},e))}}function Y(a){if(a.hasAttribute("lvt-confirm")){let e=a.getAttribute("lvt-confirm");if(e&&!confirm(e))return!1}return!0}function Ce(a){let e={},t=a.attributes;for(let n=0;n<t.length;n++){let r=t[n];if(r.name.startsWith("lvt-data-")){let s=r.name.substring(9);e[s]=r.value}}return 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","search","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 _,w;let d=this.context.getWrapperElement();if(!d)return;let g=c.target;if(s==="submit"&&(window.__lvtSubmitListenerTriggered=!0,window.__lvtSubmitEventTarget=(_=c.target)==null?void 0:_.tagName),this.logger.debug("Event listener triggered:",s,c.target),!g)return;let p=g,h=!1;for(;p;){if(p===d){h=!0;break}p=p.parentElement}if(s==="submit"&&(window.__lvtInWrapper=h,window.__lvtWrapperElement=d.getAttribute("data-lvt-id")),!h)return;let S=`lvt-${s}`;for(p=g;p&&p!==d.parentElement;){let y=p.getAttribute(S),m=p;if(!y&&s==="submit"&&p instanceof HTMLFormElement){let u=p.getAttribute("lvt-persist");u&&(y=`persist:${u}`,m=p)}if(!y&&s==="submit"&&p instanceof HTMLFormElement&&!p.hasAttribute("lvt-no-intercept")){let u=c.submitter;u instanceof HTMLButtonElement&&u.name?y=u.name:p.name?y=p.name:y="submit",m=p,u&&(p.__lvtSubmitter=u);let L=p.closest("dialog");L&&((w=p.getAttribute("method"))==null?void 0:w.toLowerCase())==="dialog"&&(p.__lvtCloseDialog=L)}if(!y&&(s==="change"||s==="input"||s==="search")&&((s==="input"||s==="search")&&p.hasAttribute("lvt-change")&&(y=p.getAttribute("lvt-change"),m=p),!y)){let u=p.closest("form");u&&u.hasAttribute("lvt-change")&&(y=u.getAttribute("lvt-change"),m=u)}if(y!=null&&m){if(s==="submit"&&(window.__lvtActionFound=y,window.__lvtActionElement=m.tagName),s==="submit"&&c.preventDefault(),(s==="keydown"||s==="keyup")&&m.hasAttribute("lvt-key")){let T=m.getAttribute("lvt-key");if(T&&c.key!==T){p=p.parentElement;continue}}let u=m,L=()=>{if(this.logger.debug("handleAction called",{action:y,eventType:s,targetElement:u}),!Y(u)){this.logger.debug("Action cancelled by user:",y);return}let T={action:y,data:{}};if(u instanceof HTMLFormElement){this.logger.debug("Processing form element");let E=new FormData(u),x=Array.from(u.querySelectorAll('input[type="checkbox"][name]')),M=new Set(x.map(R=>R.name));M.forEach(R=>{T.data[R]=!1});let I=new Set(Array.from(u.querySelectorAll('input[type="password"][name]')).map(R=>R.name)),U=u.__lvtSubmitter,H=(U==null?void 0:U.name)||"action";E.forEach((R,f)=>{f===H||f==="action"||f==="lvt-action"||(M.has(f)?(T.data[f]=!0,this.logger.debug("Converted checkbox",f,"to true")):I.has(f)?T.data[f]=R:T.data[f]=this.context.parseValue(R))});let B=u.__lvtSubmitter;B&&(B.value&&(T.data.value=this.context.parseValue(B.value)),Array.from(B.attributes).forEach(R=>{if(R.name.startsWith("data-")&&R.name!=="data-key"){let f=R.name.slice(5);T.data[f]=this.context.parseValue(R.value)}}),delete u.__lvtSubmitter),this.logger.debug("Form data collected:",T.data)}else if(s==="change"||s==="input"||s==="search"){if(u instanceof HTMLInputElement){let E=u.name||"value";T.data[E]=this.context.parseValue(u.value)}else if(u instanceof HTMLSelectElement){let E=u.name||"value";T.data[E]=this.context.parseValue(u.value)}else if(u instanceof HTMLTextAreaElement){let E=u.name||"value";T.data[E]=this.context.parseValue(u.value)}}if(Array.from(u.attributes).forEach(E=>{if(E.name.startsWith("lvt-data-")){let x=E.name.replace("lvt-data-","");T.data[x]=this.context.parseValue(E.value)}}),Array.from(u.attributes).forEach(E=>{if(E.name.startsWith("lvt-value-")){let x=E.name.replace("lvt-value-","");T.data[x]=this.context.parseValue(E.value)}}),s==="submit"&&u instanceof HTMLFormElement){let x=c.submitter,M=null;x&&x.hasAttribute("lvt-disable-with")&&(M=x.textContent,x.disabled=!0,x.textContent=x.getAttribute("lvt-disable-with"),this.logger.debug("Disabled submit button")),this.context.setActiveSubmission(u,x||null,M),u.querySelectorAll('input[type="file"][lvt-upload]').forEach(U=>{let H=U.getAttribute("lvt-upload");H&&(this.logger.debug("Triggering pending uploads for:",H),this.context.triggerPendingUploads(H))}),u.dispatchEvent(new CustomEvent("lvt:pending",{detail:T})),this.logger.debug("Emitted lvt:pending event")}if(this.logger.debug("About to send message:",T),this.logger.debug("WebSocket state:",this.context.getWebSocketReadyState()),this.context.send(T),this.logger.debug("send() called"),u instanceof HTMLFormElement){let E=u.__lvtCloseDialog;E&&(E.close(),delete u.__lvtCloseDialog)}},C=m.getAttribute("lvt-throttle"),N=m.getAttribute("lvt-debounce");if((C||N)&&s!=="search"){r.has(m)||r.set(m,new Map);let T=r.get(m),E=`${s}:${y}`,x=`__lvt_callback_${E}`,M=m;M[x]||(M[x]={current:L}),M[x].current=L;let I=T.get(E);if(!I){let U=()=>M[x].current();if(C){let H=parseInt(C,10);I=me(U,H)}else if(N){let H=parseInt(N,10);I=he(U,H)}I&&T.set(E,I)}I&&I()}else s==="submit"&&(window.__lvtBeforeHandleAction=!0),L(),s==="submit"&&(window.__lvtAfterHandleAction=!0);return}p=p.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 g=`lvt-window-${s}`;d.querySelectorAll(`[${g}]`).forEach(h=>{let S=h.getAttribute(g);if(!S)return;if((s==="keydown"||s==="keyup")&&h.hasAttribute("lvt-key")){let u=h.getAttribute("lvt-key");if(u&&c.key!==u)return}let _={action:S,data:{}};Array.from(h.attributes).forEach(u=>{if(u.name.startsWith("lvt-data-")){let L=u.name.replace("lvt-data-","");_.data[L]=this.context.parseValue(u.value)}}),Array.from(h.attributes).forEach(u=>{if(u.name.startsWith("lvt-value-")){let L=u.name.replace("lvt-value-","");_.data[L]=this.context.parseValue(u.value)}});let w=h.getAttribute("lvt-throttle"),y=h.getAttribute("lvt-debounce"),m=()=>this.context.send(_);if(w||y){r.has(h)||r.set(h,new Map);let u=r.get(h),L=`window-${s}:${S}`,C=u.get(L);if(!C){if(w){let N=parseInt(w,10);C=me(m,N)}else if(y){let N=parseInt(y,10);C=he(m,N)}C&&u.set(L,C)}C&&C()}else m()})};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 g=d.getAttribute("lvt-click-away");if(!g)return;let p={action:g,data:{}};Array.from(d.attributes).forEach(h=>{if(h.name.startsWith("lvt-data-")){let S=h.name.replace("lvt-data-","");p.data[S]=this.context.parseValue(h.value)}}),Array.from(d.attributes).forEach(h=>{if(h.name.startsWith("lvt-value-")){let S=h.name.replace("lvt-value-","");p.data[S]=this.context.parseValue(h.value)}}),this.context.send(p)}})};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=w=>{var L;let y=this.context.getWrapperElement();if(!y)return;let m=(L=w.target)==null?void 0:L.closest("[lvt-modal-open]");if(!m||!y.contains(m))return;let u=m.getAttribute("lvt-modal-open");u&&(w.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=w=>{var L;let y=(L=w.target)==null?void 0:L.closest("[lvt-modal-close]");if(!y)return;let m=y.getAttribute("lvt-modal-close");!m||!document.getElementById(m)||(w.preventDefault(),this.context.closeModal(m))};document[o]=l,document.addEventListener("click",l);let c=`__lvt_modal_backdrop_${t}`,d=document[c];d&&document.removeEventListener("click",d);let g=(w,y)=>{let m=w.getAttribute("data-modal-close-action");m?this.context.send({action:m,data:{}}):this.context.closeModal(y)},p=w=>{let y=w.target;if(!y.hasAttribute("data-modal-backdrop"))return;let m=y.getAttribute("data-modal-id");if(!m)return;let u=document.getElementById(m);u&&g(u,m)};document[c]=p,document.addEventListener("click",p);let h=`__lvt_modal_escape_${t}`,S=document[h];S&&document.removeEventListener("keydown",S);let _=w=>{if(w.key!=="Escape")return;let y=this.context.getWrapperElement();if(!y)return;let m=y.querySelectorAll('[role="dialog"]:not([hidden])');if(m.length>0){let u=m[m.length-1];u.id&&g(u,u.id)}};document[h]=_,document.addEventListener("keydown",_)}setupFocusTrapDelegation(){let e=this.context.getWrapperElement();if(!e)return;let n=`__lvt_focus_trap_${e.getAttribute("data-lvt-id")}`,r=document[n];r&&document.removeEventListener("keydown",r);let s=i=>{let l=["a[href]:not([disabled])","button:not([disabled])","textarea:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])",'[tabindex]:not([tabindex="-1"]):not([disabled])','[contenteditable="true"]'].join(", ");return Array.from(i.querySelectorAll(l)).filter(c=>{let d=c,g=window.getComputedStyle(d),p=g.display!=="none",h=g.visibility!=="hidden",S=d.offsetParent!==null||g.position==="fixed"||g.position==="absolute"||typeof process!="undefined"&&!1;return p&&h&&S})},o=i=>{if(i.key!=="Tab")return;let l=this.context.getWrapperElement();if(!l)return;let c=l.querySelectorAll("[lvt-focus-trap]"),d=null;if(c.forEach(S=>{S.contains(document.activeElement)&&(!d||S.contains(d))&&(d=S)}),d||c.forEach(S=>{let _=S,w=window.getComputedStyle(_);w.display!=="none"&&w.visibility!=="hidden"&&(d=S)}),!d)return;let g=s(d);if(g.length===0)return;let p=g[0],h=g[g.length-1];i.shiftKey?document.activeElement===p&&(i.preventDefault(),h.focus()):document.activeElement===h&&(i.preventDefault(),p.focus())};document[n]=o,document.addEventListener("keydown",o),this.logger.debug("Focus trap delegation set up")}setupAutofocusDelegation(){let e=this.context.getWrapperElement();if(!e)return;let n=`__lvt_autofocus_observer_${e.getAttribute("data-lvt-id")}`,r=e[n];r&&r.disconnect();let s=()=>{let i=this.context.getWrapperElement();if(!i)return;i.querySelectorAll("[lvt-autofocus]").forEach(c=>{let d=c,g=window.getComputedStyle(d),p=g.display!=="none",h=g.visibility!=="hidden",S=d.offsetParent!==null||g.position==="fixed"||g.position==="absolute"||d.tagName==="BODY"||typeof process!="undefined"&&!1,_=p&&h&&S,w=d.getAttribute("data-lvt-autofocused")==="true";_&&!w?(d.setAttribute("data-lvt-autofocused","true"),requestAnimationFrame(()=>{d.focus(),this.logger.debug("Autofocused element:",d.tagName,d.id||d.getAttribute("name"))})):!_&&w&&d.removeAttribute("data-lvt-autofocused")})};s();let o=new MutationObserver(i=>{let l=!1;i.forEach(c=>{c.type==="childList"&&c.addedNodes.length>0&&c.addedNodes.forEach(d=>{d instanceof Element&&(d.hasAttribute("lvt-autofocus")||d.querySelector("[lvt-autofocus]"))&&(l=!0)}),c.type==="attributes"&&(c.target.hasAttribute("lvt-autofocus")||c.attributeName==="hidden"||c.attributeName==="style"||c.attributeName==="class")&&(l=!0)}),l&&s()});o.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","style","class","lvt-autofocus"]}),e[n]=o,this.logger.debug("Autofocus delegation set up")}};var Z=class{constructor(e,t){this.context=e;this.logger=t;this.popstateListener=null}setup(e){let n=`__lvt_link_intercept_${e.getAttribute("data-lvt-id")}`,r=document[n];r&&document.removeEventListener("click",r);let s=o=>{var c;let i=(c=o.target)==null?void 0:c.closest("a[href]");if(!i)return;let l=this.context.getWrapperElement();!l||!l.contains(i)||this.shouldSkip(i)||(o.preventDefault(),this.navigate(i.href))};document.addEventListener("click",s),document[n]=s,this.popstateListener||(this.popstateListener=()=>{this.navigate(window.location.href,!1)},window.addEventListener("popstate",this.popstateListener))}shouldSkip(e){if(e.origin!==window.location.origin||e.target&&e.target!=="_self"||e.hasAttribute("download")||e.hasAttribute("lvt-no-intercept")||e.pathname===window.location.pathname&&e.hash)return!0;let t=e.protocol;return t!=="http:"&&t!=="https:"}async navigate(e,t=!0){try{let n=await fetch(e,{credentials:"include",headers:{Accept:"text/html"}});if(!n.ok){window.location.href=e;return}let r=await n.text();this.context.handleNavigationResponse(r),t&&window.history.pushState(null,"",e)}catch(n){window.location.href=e}}};var ee=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 te=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 ne=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 j(o,e){let t=null;return function(...r){let s=this;t!==null&&clearTimeout(t),t=window.setTimeout(()=>{o.apply(s,r)},e)}}function ve(o,e){let t=!1;return function(...r){let s=this;t||(o.apply(s,r),t=!0,setTimeout(()=>{t=!1},e))}}function Q(o){if(o.hasAttribute("lvt-confirm")){let e=o.getAttribute("lvt-confirm");if(e&&!confirm(e))return!1}return!0}function Re(o){let e={},t=o.attributes;for(let n=0;n<t.length;n++){let r=t[n];if(r.name.startsWith("lvt-data-")){let s=r.name.substring(9);e[s]=r.value}}return 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","search","keydown","keyup","focus","blur","mouseenter","mouseleave"],n=e.getAttribute("data-lvt-id"),r=this.context.getRateLimitedHandlers();t.forEach(s=>{let a=`__lvt_delegated_${s}_${n}`,i=document[a];i&&document.removeEventListener(s,i,!1);let l=c=>{var C,w;let d=this.context.getWrapperElement();if(!d)return;let g=c.target;if(s==="submit"&&(window.__lvtSubmitListenerTriggered=!0,window.__lvtSubmitEventTarget=(C=c.target)==null?void 0:C.tagName),this.logger.debug("Event listener triggered:",s,c.target),!g)return;let p=g,h=!1;for(;p;){if(p===d){h=!0;break}p=p.parentElement}if(s==="submit"&&(window.__lvtInWrapper=h,window.__lvtWrapperElement=d.getAttribute("data-lvt-id")),!h)return;let S=`lvt-${s}`;for(p=g;p&&p!==d.parentElement;){let y=p.getAttribute(S),m=p;if(!y&&s==="submit"&&p instanceof HTMLFormElement){let u=p.getAttribute("lvt-persist");u&&(y=`persist:${u}`,m=p)}if(!y&&s==="submit"&&p instanceof HTMLFormElement&&!p.hasAttribute("lvt-no-intercept")){let u=c.submitter;u instanceof HTMLButtonElement&&u.name?y=u.name:p.name?y=p.name:y="submit",m=p,u&&(p.__lvtSubmitter=u);let M=p.closest("dialog");M&&((w=p.getAttribute("method"))==null?void 0:w.toLowerCase())==="dialog"&&(p.__lvtCloseDialog=M)}if(!y&&(s==="change"||s==="input"||s==="search")&&((s==="input"||s==="search")&&p.hasAttribute("lvt-change")&&(y=p.getAttribute("lvt-change"),m=p),!y)){let u=p.closest("form");u&&u.hasAttribute("lvt-change")&&(y=u.getAttribute("lvt-change"),m=u)}if(y!=null&&m){if(s==="submit"&&(window.__lvtActionFound=y,window.__lvtActionElement=m.tagName),s==="submit"&&c.preventDefault(),(s==="keydown"||s==="keyup")&&m.hasAttribute("lvt-key")){let L=m.getAttribute("lvt-key");if(L&&c.key!==L){p=p.parentElement;continue}}let u=m,M=()=>{if(this.logger.debug("handleAction called",{action:y,eventType:s,targetElement:u}),!Q(u)){this.logger.debug("Action cancelled by user:",y);return}let L={action:y,data:{}};if(u instanceof HTMLFormElement){this.logger.debug("Processing form element");let E=new FormData(u),x=Array.from(u.querySelectorAll('input[type="checkbox"][name]')),T=new Set(x.map(_=>_.name));T.forEach(_=>{L.data[_]=!1});let R=new Set(Array.from(u.querySelectorAll('input[type="password"][name]')).map(_=>_.name)),U=u.__lvtSubmitter,H=(U==null?void 0:U.name)||"action";E.forEach((_,f)=>{f===H||f==="action"||f==="lvt-action"||(T.has(f)?(L.data[f]=!0,this.logger.debug("Converted checkbox",f,"to true")):R.has(f)?L.data[f]=_:L.data[f]=this.context.parseValue(_))});let B=u.__lvtSubmitter;B&&(B.value&&(L.data.value=this.context.parseValue(B.value)),Array.from(B.attributes).forEach(_=>{if(_.name.startsWith("data-")&&_.name!=="data-key"){let f=_.name.slice(5);L.data[f]=this.context.parseValue(_.value)}}),delete u.__lvtSubmitter),this.logger.debug("Form data collected:",L.data)}else if(s==="change"||s==="input"||s==="search"){if(u instanceof HTMLInputElement){let E=u.name||"value";L.data[E]=this.context.parseValue(u.value)}else if(u instanceof HTMLSelectElement){let E=u.name||"value";L.data[E]=this.context.parseValue(u.value)}else if(u instanceof HTMLTextAreaElement){let E=u.name||"value";L.data[E]=this.context.parseValue(u.value)}}if(Array.from(u.attributes).forEach(E=>{if(E.name.startsWith("lvt-data-")){let x=E.name.replace("lvt-data-","");L.data[x]=this.context.parseValue(E.value)}}),Array.from(u.attributes).forEach(E=>{if(E.name.startsWith("lvt-value-")){let x=E.name.replace("lvt-value-","");L.data[x]=this.context.parseValue(E.value)}}),s==="submit"&&u instanceof HTMLFormElement){let x=c.submitter,T=null;x&&x.hasAttribute("lvt-disable-with")&&(T=x.textContent,x.disabled=!0,x.textContent=x.getAttribute("lvt-disable-with"),this.logger.debug("Disabled submit button")),this.context.setActiveSubmission(u,x||null,T),u.querySelectorAll('input[type="file"][lvt-upload]').forEach(U=>{let H=U.getAttribute("lvt-upload");H&&(this.logger.debug("Triggering pending uploads for:",H),this.context.triggerPendingUploads(H))}),u.dispatchEvent(new CustomEvent("lvt:pending",{detail:L})),this.logger.debug("Emitted lvt:pending event")}if(this.logger.debug("About to send message:",L),this.logger.debug("WebSocket state:",this.context.getWebSocketReadyState()),this.context.send(L),this.logger.debug("send() called"),u instanceof HTMLFormElement){let E=u.__lvtCloseDialog;E&&(E.close(),delete u.__lvtCloseDialog)}},F=m.getAttribute("lvt-throttle"),N=m.getAttribute("lvt-debounce");if((F||N)&&s!=="search"){r.has(m)||r.set(m,new Map);let L=r.get(m),E=`${s}:${y}`,x=`__lvt_callback_${E}`,T=m;T[x]||(T[x]={current:M}),T[x].current=M;let R=L.get(E);if(!R){let U=()=>T[x].current();if(F){let H=parseInt(F,10);R=ve(U,H)}else if(N){let H=parseInt(N,10);R=j(U,H)}R&&L.set(E,R)}R&&R()}else s==="submit"&&(window.__lvtBeforeHandleAction=!0),M(),s==="submit"&&(window.__lvtAfterHandleAction=!0);return}p=p.parentElement}};document[a]=l,document.addEventListener(s,l,!1),this.logger.debug("Registered event listener:",s,"with key:",a)})}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 a=`__lvt_window_${s}_${n}`,i=window[a];i&&window.removeEventListener(s,i);let l=c=>{let d=this.context.getWrapperElement();if(!d)return;let g=`lvt-window-${s}`;d.querySelectorAll(`[${g}]`).forEach(h=>{let S=h.getAttribute(g);if(!S)return;if((s==="keydown"||s==="keyup")&&h.hasAttribute("lvt-key")){let u=h.getAttribute("lvt-key");if(u&&c.key!==u)return}let C={action:S,data:{}};Array.from(h.attributes).forEach(u=>{if(u.name.startsWith("lvt-data-")){let M=u.name.replace("lvt-data-","");C.data[M]=this.context.parseValue(u.value)}}),Array.from(h.attributes).forEach(u=>{if(u.name.startsWith("lvt-value-")){let M=u.name.replace("lvt-value-","");C.data[M]=this.context.parseValue(u.value)}});let w=h.getAttribute("lvt-throttle"),y=h.getAttribute("lvt-debounce"),m=()=>this.context.send(C);if(w||y){r.has(h)||r.set(h,new Map);let u=r.get(h),M=`window-${s}:${S}`,F=u.get(M);if(!F){if(w){let N=parseInt(w,10);F=ve(m,N)}else if(y){let N=parseInt(y,10);F=j(m,N)}F&&u.set(M,F)}F&&F()}else m()})};window[a]=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=a=>{let i=this.context.getWrapperElement();if(!i)return;let l=a.target;i.querySelectorAll("[lvt-click-away]").forEach(d=>{if(!d.contains(l)){let g=d.getAttribute("lvt-click-away");if(!g)return;let p={action:g,data:{}};Array.from(d.attributes).forEach(h=>{if(h.name.startsWith("lvt-data-")){let S=h.name.replace("lvt-data-","");p.data[S]=this.context.parseValue(h.value)}}),Array.from(d.attributes).forEach(h=>{if(h.name.startsWith("lvt-value-")){let S=h.name.replace("lvt-value-","");p.data[S]=this.context.parseValue(h.value)}}),this.context.send(p)}})};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=w=>{var M;let y=this.context.getWrapperElement();if(!y)return;let m=(M=w.target)==null?void 0:M.closest("[lvt-modal-open]");if(!m||!y.contains(m))return;let u=m.getAttribute("lvt-modal-open");u&&(w.preventDefault(),this.context.openModal(u))};document[n]=s,document.addEventListener("click",s);let a=`__lvt_modal_close_${t}`,i=document[a];i&&document.removeEventListener("click",i);let l=w=>{var M;let y=(M=w.target)==null?void 0:M.closest("[lvt-modal-close]");if(!y)return;let m=y.getAttribute("lvt-modal-close");!m||!document.getElementById(m)||(w.preventDefault(),this.context.closeModal(m))};document[a]=l,document.addEventListener("click",l);let c=`__lvt_modal_backdrop_${t}`,d=document[c];d&&document.removeEventListener("click",d);let g=(w,y)=>{let m=w.getAttribute("data-modal-close-action");m?this.context.send({action:m,data:{}}):this.context.closeModal(y)},p=w=>{let y=w.target;if(!y.hasAttribute("data-modal-backdrop"))return;let m=y.getAttribute("data-modal-id");if(!m)return;let u=document.getElementById(m);u&&g(u,m)};document[c]=p,document.addEventListener("click",p);let h=`__lvt_modal_escape_${t}`,S=document[h];S&&document.removeEventListener("keydown",S);let C=w=>{if(w.key!=="Escape")return;let y=this.context.getWrapperElement();if(!y)return;let m=y.querySelectorAll('[role="dialog"]:not([hidden])');if(m.length>0){let u=m[m.length-1];u.id&&g(u,u.id)}};document[h]=C,document.addEventListener("keydown",C)}setupFocusTrapDelegation(){let e=this.context.getWrapperElement();if(!e)return;let n=`__lvt_focus_trap_${e.getAttribute("data-lvt-id")}`,r=document[n];r&&document.removeEventListener("keydown",r);let s=i=>{let l=["a[href]:not([disabled])","button:not([disabled])","textarea:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])",'[tabindex]:not([tabindex="-1"]):not([disabled])','[contenteditable="true"]'].join(", ");return Array.from(i.querySelectorAll(l)).filter(c=>{let d=c,g=window.getComputedStyle(d),p=g.display!=="none",h=g.visibility!=="hidden",S=d.offsetParent!==null||g.position==="fixed"||g.position==="absolute"||typeof process!="undefined"&&!1;return p&&h&&S})},a=i=>{if(i.key!=="Tab")return;let l=this.context.getWrapperElement();if(!l)return;let c=l.querySelectorAll("[lvt-focus-trap]"),d=null;if(c.forEach(S=>{S.contains(document.activeElement)&&(!d||S.contains(d))&&(d=S)}),d||c.forEach(S=>{let C=S,w=window.getComputedStyle(C);w.display!=="none"&&w.visibility!=="hidden"&&(d=S)}),!d)return;let g=s(d);if(g.length===0)return;let p=g[0],h=g[g.length-1];i.shiftKey?document.activeElement===p&&(i.preventDefault(),h.focus()):document.activeElement===h&&(i.preventDefault(),p.focus())};document[n]=a,document.addEventListener("keydown",a),this.logger.debug("Focus trap delegation set up")}setupAutofocusDelegation(){let e=this.context.getWrapperElement();if(!e)return;let n=`__lvt_autofocus_observer_${e.getAttribute("data-lvt-id")}`,r=e[n];r&&r.disconnect();let s=()=>{let i=this.context.getWrapperElement();if(!i)return;i.querySelectorAll("[lvt-autofocus]").forEach(c=>{let d=c,g=window.getComputedStyle(d),p=g.display!=="none",h=g.visibility!=="hidden",S=d.offsetParent!==null||g.position==="fixed"||g.position==="absolute"||d.tagName==="BODY"||typeof process!="undefined"&&!1,C=p&&h&&S,w=d.getAttribute("data-lvt-autofocused")==="true";C&&!w?(d.setAttribute("data-lvt-autofocused","true"),requestAnimationFrame(()=>{d.focus(),this.logger.debug("Autofocused element:",d.tagName,d.id||d.getAttribute("name"))})):!C&&w&&d.removeAttribute("data-lvt-autofocused")})};s();let a=new MutationObserver(i=>{let l=!1;i.forEach(c=>{c.type==="childList"&&c.addedNodes.length>0&&c.addedNodes.forEach(d=>{d instanceof Element&&(d.hasAttribute("lvt-autofocus")||d.querySelector("[lvt-autofocus]"))&&(l=!0)}),c.type==="attributes"&&(c.target.hasAttribute("lvt-autofocus")||c.attributeName==="hidden"||c.attributeName==="style"||c.attributeName==="class")&&(l=!0)}),l&&s()});a.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","style","class","lvt-autofocus"]}),e[n]=a,this.logger.debug("Autofocus delegation set up")}};var ee=class{constructor(e,t){this.context=e;this.logger=t;this.popstateListener=null}setup(e){let n=`__lvt_link_intercept_${e.getAttribute("data-lvt-id")}`,r=document[n];r&&document.removeEventListener("click",r);let s=a=>{var c;let i=(c=a.target)==null?void 0:c.closest("a[href]");if(!i)return;let l=this.context.getWrapperElement();!l||!l.contains(i)||this.shouldSkip(i)||(a.preventDefault(),this.navigate(i.href))};document.addEventListener("click",s),document[n]=s,this.popstateListener||(this.popstateListener=()=>{this.navigate(window.location.href,!1)},window.addEventListener("popstate",this.popstateListener))}shouldSkip(e){if(e.origin!==window.location.origin||e.target&&e.target!=="_self"||e.hasAttribute("download")||e.hasAttribute("lvt-no-intercept")||e.pathname===window.location.pathname&&e.hash)return!0;let t=e.protocol;return t!=="http:"&&t!=="https:"}async navigate(e,t=!0){try{let n=await fetch(e,{credentials:"include",headers:{Accept:"text/html"}});if(!n.ok){window.location.href=e;return}let r=await n.text();this.context.handleNavigationResponse(r),t&&window.history.pushState(null,"",e)}catch(n){window.location.href=e}}};var te=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 ne=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 re=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 re=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 Ie=["pending","success","error","done"];var rt={reset:"reset",disable:"disable",enable:"enable",addclass:"addClass",removeclass:"removeClass",toggleclass:"toggleClass",setattr:"setAttr",toggleattr:"toggleAttr"};function st(a,e){let t=a.toLowerCase().match(/^lvt-(\w+)-on:(.+)$/);if(!t)return null;let n=t[1],r=rt[n];if(!r)return null;let o=t[2].split(":"),i=o[o.length-1];if(!Ie.includes(i))return null;let l=i,c=o.length>1?o.slice(0,-1).join(":"):void 0;return{action:r,lifecycle:l,actionName:c||void 0,param:e||void 0}}function it(a,e,t){switch(e){case"reset":a instanceof HTMLFormElement&&a.reset();break;case"disable":"disabled"in a&&(a.disabled=!0);break;case"enable":"disabled"in a&&(a.disabled=!1);break;case"addClass":if(t){let n=t.split(/\s+/).filter(Boolean);a.classList.add(...n)}break;case"removeClass":if(t){let n=t.split(/\s+/).filter(Boolean);a.classList.remove(...n)}break;case"toggleClass":t&&t.split(/\s+/).filter(Boolean).forEach(r=>a.classList.toggle(r));break;case"setAttr":if(t){let n=t.indexOf(":");if(n>0){let r=t.substring(0,n),s=t.substring(n+1);a.setAttribute(r,s)}}break;case"toggleAttr":t&&a.toggleAttribute(t);break}}function ot(a,e,t){return a.lifecycle!==e?!1:a.actionName?a.actionName===t:!0}function at(a,e){document.querySelectorAll("*").forEach(n=>{Array.from(n.attributes).forEach(r=>{if(!r.name.startsWith("lvt-")||!r.name.includes("-on:"))return;let s=st(r.name,r.value);s&&ot(s,a,e)&&it(n,s.action,s.param)})})}function se(){Ie.forEach(a=>{document.addEventListener(`lvt:${a}`,e=>{var r;let n=(r=e.detail)==null?void 0:r.action;at(a,n)},!0)})}function Fe(a){return typeof structuredClone=="function"?structuredClone(a):JSON.parse(JSON.stringify(a))}function lt(a){return a!=null&&typeof a=="object"&&Array.isArray(a.d)&&Array.isArray(a.s)}function ve(a,e=0){if(e>50||a==null||typeof a!="object"||Array.isArray(a))return!1;if(lt(a))return!0;for(let n of Object.keys(a))if(/^\d+$/.test(n)){let r=a[n];if(r!=null&&typeof r=="object"&&!Array.isArray(r)&&ve(r,e+1))return!0}return!1}function ct(a,e){if(!e.s||!Array.isArray(e.s))return!1;if(ve(a)&&!ve(e))return!0;for(let t of Object.keys(a))if(/^\d+$/.test(t)&&!(t in e))return!0;return!1}var ie=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"){let i=this.treeState[r];i&&typeof i=="object"&&!Array.isArray(i)&&Array.isArray(i.d)&&Array.isArray(i.s)?(this.treeState[r]=Fe(i),this.applyDifferentialOpsToRange(this.treeState[r],s,r)):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,r):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,n=""){var s;if(typeof t!="object"||t===null||Array.isArray(t)||typeof e!="object"||e===null||Array.isArray(e))return t;if(ct(e,t))return this.logger.debug(`[deepMerge] Structure transition at path ${n}, replacing instead of merging`),t;let r={...e};for(let[o,i]of Object.entries(t)){let l=n?`${n}.${o}`:o,c=Array.isArray(i)&&i.length>0&&Array.isArray(i[0])&&typeof i[0][0]=="string",d=r[o]&&typeof r[o]=="object"&&!Array.isArray(r[o])&&Array.isArray(r[o].d)&&Array.isArray(r[o].s);c&&d?(r[o]=Fe(r[o]),this.logger.debug(`[deepMerge] Applying diff ops at path ${l}`,{ops:i,rangeItems:(s=r[o].d)==null?void 0:s.length}),this.applyDifferentialOpsToRange(r[o],i,l)):typeof i=="object"&&i!==null&&!Array.isArray(i)&&typeof r[o]=="object"&&r[o]!==null&&!Array.isArray(r[o])?r[o]=this.deepMergeTreeNodes(r[o],i,l):r[o]=i}return r}applyDifferentialOpsToRange(e,t,n){if(!e||typeof e!="object"||!Array.isArray(e.d)||!Array.isArray(e.s)){this.logger.error(`[applyDiffOpsToRange] Invalid rangeStructure at path ${n}`,{rangeStructure:e});return}let r=e.d;this.rangeState[n]||(this.rangeState[n]={items:r,statics:e.s,staticsMap:e.sm}),e.m&&typeof e.m=="object"&&typeof e.m.idKey=="string"&&(this.rangeIdKeys[n]=e.m.idKey),this.logger.debug(`[applyDiffOpsToRange] path=${n}, idKey=${this.rangeIdKeys[n]}, items=${r.length}, ops=${t.length}`);for(let s of t){if(!Array.isArray(s)||s.length<2)continue;switch(s[0]){case"r":{let i=s[1],l=this.findItemIndexByKey(r,i,e.s,n);this.logger.debug(`[applyDiffOpsToRange] Remove: key=${i}, index=${l}, total=${r.length}`),l>=0?(r.splice(l,1),this.logger.debug(`[applyDiffOpsToRange] After removal: ${r.length} items`)):this.logger.debug(`[applyDiffOpsToRange] Remove failed: key ${i} not found`);break}case"u":{let i=this.findItemIndexByKey(r,s[1],e.s,n),l=s[2];i>=0&&l&&(r[i]=this.mergeRangeItem(r[i],l,n));break}case"a":{let i=Array.isArray(s[1])?s[1]:[s[1]];s[2]&&(e.s=s[2]),r.push(...i),s[3]&&typeof s[3]=="object"&&s[3].idKey&&(this.rangeIdKeys[n]=s[3].idKey);break}case"p":{let i=Array.isArray(s[1])?s[1]:[s[1]];s[2]&&(e.s=s[2]),r.unshift(...i);break}case"i":{let i=this.findItemIndexByKey(r,s[1],e.s,n);if(i>=0){let l=Array.isArray(s[2])?s[2]:[s[2]];r.splice(i+1,0,...l)}break}case"o":{let i=s[1],l=[],c=new Map;for(let d of r){let g=this.getItemKey(d,e.s,n);g&&c.set(g,d)}for(let d of i){let g=c.get(d);g&&l.push(g)}r.length=0,r.push(...l);break}default:break}}this.rangeState[n]={items:r,statics:e.s,staticsMap:e.sm}}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 o=n||t||"";return o&&(this.rangeState[o]={items:e.d,statics:e.s,staticsMap:e.sm},e.m&&typeof e.m=="object"&&typeof e.m.idKey=="string"&&(this.rangeIdKeys[o]=e.m.idKey)),this.renderRangeStructure(e,t,n)}if("s"in e&&Array.isArray(e.s))return this.reconstructFromTree(e,n||"");let r=Object.keys(e),s=r.filter(o=>/^\d+$/.test(o)).sort((o,i)=>parseInt(o)-parseInt(i));if(s.length>0&&s.length===r.length)return s.map(o=>{let i=n?`${n}.${o}`:o;return this.renderValue(e[o],o,i)}).join("")}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.debug("Skipping plain object value (not a tree node) - this is normal for state-only data"),""):String(e)}renderRangeStructure(e,t,n){let{d:r,s,sm:o}=e;if(!r||!Array.isArray(r))return"";if(r.length===0){if(e.else){let l="else",c=n?`${n}.else`:"else";return this.renderValue(e.else,l,c)}return""}let i=o&&typeof o=="object";return s&&Array.isArray(s)?r.map((l,c)=>{let d=s;i&&l._sk&&o[l._sk]&&(d=o[l._sk]);let g="";for(let p=0;p<d.length;p++)if(g+=d[p],p<d.length-1){let h=p.toString();if(l[h]!==void 0){let S=n?`${n}.${c}.${h}`:`${c}.${h}`;g+=this.renderValue(l[h],h,S)}}return g}).join(""):r.map((l,c)=>{let d=c.toString(),g=n?`${n}.${d}`:d;return this.renderValue(l,d,g)}).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]=this.mergeRangeItem(r[c],d,t||""));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=[],g=new Map;for(let p of r){let h=this.getItemKey(p,s,t);h&&g.set(h,p)}for(let p of c){let h=g.get(p);h&&d.push(h)}r.length=0,r.push(...d);break}default:break}}this.rangeState[t]={items:r,statics:n.statics,staticsMap:n.staticsMap},this.treeState[t]={d:r,s:n.statics,sm:n.staticsMap};let o=this.getCurrentRangeStructure(t);return o&&o.s?this.renderItemsWithStatics(r,o.s,o.sm,t):r.map(i=>this.renderValue(i)).join("")}getCurrentRangeStructure(e){if(this.rangeState[e])return{d:this.rangeState[e].items,s:this.rangeState[e].statics,sm:this.rangeState[e].staticsMap};let t=this.treeState[e];return t&&typeof t=="object"&&t.s?t:null}renderItemsWithStatics(e,t,n,r){let s=e.map((o,i)=>{let l=t;n&&typeof n=="object"&&o._sk&&n[o._sk]&&(l=n[o._sk]);let c="";for(let d=0;d<l.length;d++)if(c+=l[d],d<l.length-1){let g=d.toString();if(o[g]!==void 0){let p=r?`${r}.${i}.${g}`:`${i}.${g}`;c+=this.renderValue(o[g],g,p)}}return c}).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:",s.substring(0,200))),s}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(e._k&&typeof e._k=="string")return e._k;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)}mergeRangeItem(e,t,n){return this.deepMergeTreeNodes(e,t,`${n}.item`)}};var oe=class{constructor(e){this.modalManager=e;this.activeForm=null;this.activeButton=null;this.originalButtonText=null}setActiveSubmission(e,t,n){if(this.activeForm=e,this.activeButton=t,this.originalButtonText=n,e){e.setAttribute("aria-busy","true");let r=e.querySelector("fieldset");r&&(r.disabled=!0)}}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(){if(this.activeForm){this.activeForm.removeAttribute("aria-busy");let e=this.activeForm.querySelector("fieldset");e&&(e.disabled=!1)}this.activeButton&&this.originalButtonText!==null&&(this.activeButton.disabled=!1,this.activeButton.textContent=this.originalButtonText),this.activeForm=null,this.activeButton=null,this.originalButtonText=null}};var ye=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,g;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=(g=this.options.maxReconnectDelay)!=null?g:16e3,r=t*Math.pow(2,this.reconnectAttempts-1),s=Math.random()*1e3,o=Math.min(r+s,n);this.reconnectTimer=window.setTimeout(()=>{var p,h;(h=(p=this.options).onReconnectAttempt)==null||h.call(p,this.reconnectAttempts,o),this.connect()},o)}clearReconnectTimer(){this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}},ae=class{constructor(e){this.config=e;this.transport=null}async connect(){let e=this.getLiveUrl();return await dt(e,this.config.logger)?(this.transport=new ye({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 ut(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||`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}${e}`}getLiveUrl(){return this.config.options.liveUrl||window.location.pathname+window.location.search}};async function dt(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 ut(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 le=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 ce=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 le)}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 He={silent:0,error:1,warn:2,info:3,debug:4},Ne="LiveTemplate",be=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 He[e]<=He[this.state.level]}formatPrefix(){return this.scope.length===0?`[${Ne}]`:`[${Ne}:${this.scope.join(":")}]`}};function Ee(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 be(e,t,(r=a.sink)!=null?r:console)}async function Ue(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 Oe(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(`
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 se=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 Ie=["pending","success","error","done"];var st={reset:"reset",disable:"disable",enable:"enable",addclass:"addClass",removeclass:"removeClass",toggleclass:"toggleClass",setattr:"setAttr",toggleattr:"toggleAttr"};function it(o,e){let t=o.toLowerCase().match(/^lvt-(\w+)-on:(.+)$/);if(!t)return null;let n=t[1],r=st[n];if(!r)return null;let a=t[2].split(":"),i=a[a.length-1];if(!Ie.includes(i))return null;let l=i,c=a.length>1?a.slice(0,-1).join(":"):void 0;return{action:r,lifecycle:l,actionName:c||void 0,param:e||void 0}}function at(o,e,t){switch(e){case"reset":o instanceof HTMLFormElement&&o.reset();break;case"disable":"disabled"in o&&(o.disabled=!0);break;case"enable":"disabled"in o&&(o.disabled=!1);break;case"addClass":if(t){let n=t.split(/\s+/).filter(Boolean);o.classList.add(...n)}break;case"removeClass":if(t){let n=t.split(/\s+/).filter(Boolean);o.classList.remove(...n)}break;case"toggleClass":t&&t.split(/\s+/).filter(Boolean).forEach(r=>o.classList.toggle(r));break;case"setAttr":if(t){let n=t.indexOf(":");if(n>0){let r=t.substring(0,n),s=t.substring(n+1);o.setAttribute(r,s)}}break;case"toggleAttr":t&&o.toggleAttribute(t);break}}function ot(o,e,t){return o.lifecycle!==e?!1:o.actionName?o.actionName===t:!0}function lt(o,e){document.querySelectorAll("*").forEach(n=>{Array.from(n.attributes).forEach(r=>{if(!r.name.startsWith("lvt-")||!r.name.includes("-on:"))return;let s=it(r.name,r.value);s&&ot(s,o,e)&&at(n,s.action,s.param)})})}function ie(){Ie.forEach(o=>{document.addEventListener(`lvt:${o}`,e=>{var r;let n=(r=e.detail)==null?void 0:r.action;lt(o,n)},!0)})}function He(o){return typeof structuredClone=="function"?structuredClone(o):JSON.parse(JSON.stringify(o))}function ct(o){return o!=null&&typeof o=="object"&&Array.isArray(o.d)&&Array.isArray(o.s)}function ye(o,e=0){if(e>50||o==null||typeof o!="object"||Array.isArray(o))return!1;if(ct(o))return!0;for(let n of Object.keys(o))if(/^\d+$/.test(n)){let r=o[n];if(r!=null&&typeof r=="object"&&!Array.isArray(r)&&ye(r,e+1))return!0}return!1}function dt(o,e){if(!e.s||!Array.isArray(e.s))return!1;if(ye(o)&&!ye(e))return!0;for(let t of Object.keys(o))if(/^\d+$/.test(t)&&!(t in e))return!0;return!1}var ae=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"){let i=this.treeState[r];i&&typeof i=="object"&&!Array.isArray(i)&&Array.isArray(i.d)&&Array.isArray(i.s)?(this.treeState[r]=He(i),this.applyDifferentialOpsToRange(this.treeState[r],s,r)):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,r):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,n=""){var s;if(typeof t!="object"||t===null||Array.isArray(t)||typeof e!="object"||e===null||Array.isArray(e))return t;if(dt(e,t))return this.logger.debug(`[deepMerge] Structure transition at path ${n}, replacing instead of merging`),t;let r={...e};for(let[a,i]of Object.entries(t)){let l=n?`${n}.${a}`:a,c=Array.isArray(i)&&i.length>0&&Array.isArray(i[0])&&typeof i[0][0]=="string",d=r[a]&&typeof r[a]=="object"&&!Array.isArray(r[a])&&Array.isArray(r[a].d)&&Array.isArray(r[a].s);c&&d?(r[a]=He(r[a]),this.logger.debug(`[deepMerge] Applying diff ops at path ${l}`,{ops:i,rangeItems:(s=r[a].d)==null?void 0:s.length}),this.applyDifferentialOpsToRange(r[a],i,l)):typeof i=="object"&&i!==null&&!Array.isArray(i)&&typeof r[a]=="object"&&r[a]!==null&&!Array.isArray(r[a])?r[a]=this.deepMergeTreeNodes(r[a],i,l):r[a]=i}return r}applyDifferentialOpsToRange(e,t,n){if(!e||typeof e!="object"||!Array.isArray(e.d)||!Array.isArray(e.s)){this.logger.error(`[applyDiffOpsToRange] Invalid rangeStructure at path ${n}`,{rangeStructure:e});return}let r=e.d;this.rangeState[n]||(this.rangeState[n]={items:r,statics:e.s,staticsMap:e.sm}),e.m&&typeof e.m=="object"&&typeof e.m.idKey=="string"&&(this.rangeIdKeys[n]=e.m.idKey),this.logger.debug(`[applyDiffOpsToRange] path=${n}, idKey=${this.rangeIdKeys[n]}, items=${r.length}, ops=${t.length}`);for(let s of t){if(!Array.isArray(s)||s.length<2)continue;switch(s[0]){case"r":{let i=s[1],l=this.findItemIndexByKey(r,i,e.s,n);this.logger.debug(`[applyDiffOpsToRange] Remove: key=${i}, index=${l}, total=${r.length}`),l>=0?(r.splice(l,1),this.logger.debug(`[applyDiffOpsToRange] After removal: ${r.length} items`)):this.logger.debug(`[applyDiffOpsToRange] Remove failed: key ${i} not found`);break}case"u":{let i=this.findItemIndexByKey(r,s[1],e.s,n),l=s[2];i>=0&&l&&(r[i]=this.mergeRangeItem(r[i],l,n));break}case"a":{let i=Array.isArray(s[1])?s[1]:[s[1]];s[2]&&(e.s=s[2]),r.push(...i),s[3]&&typeof s[3]=="object"&&s[3].idKey&&(this.rangeIdKeys[n]=s[3].idKey);break}case"p":{let i=Array.isArray(s[1])?s[1]:[s[1]];s[2]&&(e.s=s[2]),r.unshift(...i);break}case"i":{let i=this.findItemIndexByKey(r,s[1],e.s,n);if(i>=0){let l=Array.isArray(s[2])?s[2]:[s[2]];r.splice(i+1,0,...l)}break}case"o":{let i=s[1],l=[],c=new Map;for(let d of r){let g=this.getItemKey(d,e.s,n);g&&c.set(g,d)}for(let d of i){let g=c.get(d);g&&l.push(g)}r.length=0,r.push(...l);break}default:break}}this.rangeState[n]={items:r,statics:e.s,staticsMap:e.sm}}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 a=r.toString();if(e[a]!==void 0){let i=t?`${t}.${a}`:a;n+=this.renderValue(e[a],a,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 a=n||t||"";return a&&(this.rangeState[a]={items:e.d,statics:e.s,staticsMap:e.sm},e.m&&typeof e.m=="object"&&typeof e.m.idKey=="string"&&(this.rangeIdKeys[a]=e.m.idKey)),this.renderRangeStructure(e,t,n)}if("s"in e&&Array.isArray(e.s))return this.reconstructFromTree(e,n||"");let r=Object.keys(e),s=r.filter(a=>/^\d+$/.test(a)).sort((a,i)=>parseInt(a)-parseInt(i));if(s.length>0&&s.length===r.length)return s.map(a=>{let i=n?`${n}.${a}`:a;return this.renderValue(e[a],a,i)}).join("")}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 a=s.toString(),i=n?`${n}.${a}`:a;return typeof r=="object"&&r&&r.s?this.reconstructFromTree(r,i):this.renderValue(r,a,i)}).join(""):typeof e=="object"?(this.logger.debug("Skipping plain object value (not a tree node) - this is normal for state-only data"),""):String(e)}renderRangeStructure(e,t,n){let{d:r,s,sm:a}=e;if(!r||!Array.isArray(r))return"";if(r.length===0){if(e.else){let l="else",c=n?`${n}.else`:"else";return this.renderValue(e.else,l,c)}return""}let i=a&&typeof a=="object";return s&&Array.isArray(s)?r.map((l,c)=>{let d=s;i&&l._sk&&a[l._sk]&&(d=a[l._sk]);let g="";for(let p=0;p<d.length;p++)if(g+=d[p],p<d.length-1){let h=p.toString();if(l[h]!==void 0){let S=n?`${n}.${c}.${h}`:`${c}.${h}`;g+=this.renderValue(l[h],h,S)}}return g}).join(""):r.map((l,c)=>{let d=c.toString(),g=n?`${n}.${d}`:d;return this.renderValue(l,d,g)}).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]=this.mergeRangeItem(r[c],d,t||""));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=[],g=new Map;for(let p of r){let h=this.getItemKey(p,s,t);h&&g.set(h,p)}for(let p of c){let h=g.get(p);h&&d.push(h)}r.length=0,r.push(...d);break}default:break}}this.rangeState[t]={items:r,statics:n.statics,staticsMap:n.staticsMap},this.treeState[t]={d:r,s:n.statics,sm:n.staticsMap};let a=this.getCurrentRangeStructure(t);return a&&a.s?this.renderItemsWithStatics(r,a.s,a.sm,t):r.map(i=>this.renderValue(i)).join("")}getCurrentRangeStructure(e){if(this.rangeState[e])return{d:this.rangeState[e].items,s:this.rangeState[e].statics,sm:this.rangeState[e].staticsMap};let t=this.treeState[e];return t&&typeof t=="object"&&t.s?t:null}renderItemsWithStatics(e,t,n,r){let s=e.map((a,i)=>{let l=t;n&&typeof n=="object"&&a._sk&&n[a._sk]&&(l=n[a._sk]);let c="";for(let d=0;d<l.length;d++)if(c+=l[d],d<l.length-1){let g=d.toString();if(a[g]!==void 0){let p=r?`${r}.${i}.${g}`:`${i}.${g}`;c+=this.renderValue(a[g],g,p)}}return c}).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:",s.substring(0,200))),s}addItemsToRange(e,t,n,r,s){if(n&&(r.statics=n),!t)return;let a=Array.isArray(t)?t:[t];s?e.unshift(...a):e.push(...a)}getItemKey(e,t,n){if(e._k&&typeof e._k=="string")return e._k;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)}mergeRangeItem(e,t,n){return this.deepMergeTreeNodes(e,t,`${n}.item`)}};var oe=class{constructor(e){this.modalManager=e;this.activeForm=null;this.activeButton=null;this.originalButtonText=null}setActiveSubmission(e,t,n){if(this.activeForm=e,this.activeButton=t,this.originalButtonText=n,e){e.setAttribute("aria-busy","true");let r=e.querySelector("fieldset");r&&(r.disabled=!0)}}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(){if(this.activeForm){this.activeForm.removeAttribute("aria-busy");let e=this.activeForm.querySelector("fieldset");e&&(e.disabled=!1)}this.activeButton&&this.originalButtonText!==null&&(this.activeButton.disabled=!1,this.activeButton.textContent=this.originalButtonText),this.activeForm=null,this.activeButton=null,this.originalButtonText=null}};var le=class{constructor(e,t){this.context=e;this.logger=t;this.boundFields=new Map;this.enabled=!1;this.wiredElements=new Set;this.elementCleanups=new Map}setCapabilities(e){this.enabled=e.includes("change"),this.logger.debug("Capabilities received, change auto-wiring:",this.enabled?"enabled":"disabled")}analyzeStatics(e){let t=this.boundFields.size;this.walkTree(e),this.boundFields.size>t&&this.logger.debug(`Detected ${this.boundFields.size} bound field(s):`,Array.from(this.boundFields.keys()))}wireElements(){if(!this.enabled||this.boundFields.size===0)return;let e=this.context.getWrapperElement();if(e){for(let t of this.elementCleanups.keys())t.isConnected||(this.elementCleanups.get(t)(),this.elementCleanups.delete(t),this.wiredElements.delete(t));for(let[t,n]of this.boundFields){let r=this.escapeCSSSelector(t),s=e.querySelectorAll(`[name="${r}"]`);for(let a of s){if(this.wiredElements.has(a)||a.hasAttribute("lvt-input")||a.hasAttribute("lvt-change"))continue;let i=a.closest("form");i&&(i.hasAttribute("lvt-change")||i.hasAttribute("lvt-no-intercept"))||a instanceof HTMLInputElement&&(a.type==="hidden"||a.type==="submit"||a.type==="button")||a instanceof HTMLButtonElement||(this.attachListener(a,t,n),this.wiredElements.add(a))}}}}teardown(){for(let e of this.elementCleanups.values())e();this.elementCleanups.clear(),this.wiredElements.clear(),this.boundFields.clear(),this.enabled=!1}getBoundFields(){return this.boundFields}isEnabled(){return this.enabled}walkTree(e){if(!(!e||typeof e!="object"||Array.isArray(e))){e.s&&Array.isArray(e.s)&&this.analyzeStaticsArray(e.s);for(let t of Object.keys(e))if(/^\d+$/.test(t)){let n=e[t];n&&typeof n=="object"&&!Array.isArray(n)&&this.walkTree(n)}if(e.d&&Array.isArray(e.d))for(let t of e.d)t&&typeof t=="object"&&!Array.isArray(t)&&this.walkTree(t)}}analyzeStaticsArray(e){for(let t=0;t<e.length-1;t++){let n=e[t],r=e[t+1],s=this.detectBinding(n,r);s&&!this.boundFields.has(s.fieldName)&&this.boundFields.set(s.fieldName,s.bindingType)}}detectBinding(e,t){let n=this.detectValueBinding(e);return n?{fieldName:n,bindingType:"value"}:(n=this.detectTextareaBinding(e,t),n?{fieldName:n,bindingType:"content"}:(n=this.detectAttributeBinding(e,t),n?{fieldName:n,bindingType:"attribute"}:null))}escapeCSSSelector(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}extractUnclosedTag(e){let t=e.lastIndexOf("<"),n=e.lastIndexOf(">");return t===-1||t<=n?null:e.substring(t)}extractNameFromTag(e){let t=e.match(/\sname="([^"]+)"/);return t?t[1]:null}detectValueBinding(e){if(!e.endsWith('value="'))return null;let t=this.extractUnclosedTag(e);return t?this.extractNameFromTag(t):null}detectTextareaBinding(e,t){if(!t.startsWith("</textarea"))return null;let n=e.match(/<textarea[^>]*\sname="([^"]+)"[^>]*>$/);return n?n[1]:null}detectAttributeBinding(e,t){if(!e.endsWith(" ")||!/^[a-zA-Z>/\s]/.test(t))return null;let n=this.extractUnclosedTag(e);if(!n||!/^<input\s/i.test(n))return null;let r=n.match(/\stype="([^"]+)"/i);if(!r)return null;let s=r[1].toLowerCase();return s!=="checkbox"&&s!=="radio"?null:this.extractNameFromTag(n)}attachListener(e,t,n){let r=e.getAttribute("lvt-debounce"),s=r?parseInt(r,10):NaN,a=Number.isNaN(s)||s<0?300:s,l=j(()=>{if(!this.enabled)return;let d=n==="attribute"&&e.type==="checkbox"?e.checked:e.value;this.context.send({action:"change",data:{[t]:d}})},a),c=n==="attribute"||e instanceof HTMLSelectElement?"change":"input";e.addEventListener(c,l),this.elementCleanups.set(e,()=>{e.removeEventListener(c,l)}),this.logger.debug(`Auto-wired ${c} listener on [name="${t}"] (debounce: ${a}ms)`)}};var be=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,g;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=(g=this.options.maxReconnectDelay)!=null?g:16e3,r=t*Math.pow(2,this.reconnectAttempts-1),s=Math.random()*1e3,a=Math.min(r+s,n);this.reconnectTimer=window.setTimeout(()=>{var p,h;(h=(p=this.options).onReconnectAttempt)==null||h.call(p,this.reconnectAttempts,a),this.connect()},a)}clearReconnectTimer(){this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}},ce=class{constructor(e){this.config=e;this.transport=null}async connect(){let e=this.getLiveUrl();return await pt(e,this.config.logger)?(this.transport=new be({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,a;(a=(s=this.config).onReconnectAttempt)==null||a.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 gt(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||`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}${e}`}getLiveUrl(){return this.config.options.liveUrl||window.location.pathname+window.location.search}};async function pt(o,e){try{let n=(await fetch(o,{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 gt(o,e){try{let t=await fetch(o,{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 de=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 a=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 a}catch(s){throw e.error=s instanceof Error?s.message:String(s),s}}};var ue=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 de)}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 a=i=>{let l=i.target.files;!l||l.length===0||this.startUpload(r,Array.from(l))};n.addEventListener("change",a),this.inputHandlers.set(n,a)})}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 a=[];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),a.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 a=Math.min(r+this.chunkSize,t.size),i=t.slice(r,a),l=await this.fileToBase64(i),c={action:"upload_chunk",entry_id:n,chunk_base64:l,offset:r,total:t.size};this.sendMessage(c),r=a,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 a=s instanceof Error?s.message:String(s);e.error=a,this.onError&&this.onError(e,a),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 a=r.result.split(",")[1];t(a)},r.onerror=n,r.readAsDataURL(e)})}};var Ne={silent:0,error:1,warn:2,info:3,debug:4},Ue="LiveTemplate",Ee=class o{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 o(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 Ne[e]<=Ne[this.state.level]}formatPrefix(){return this.scope.length===0?`[${Ue}]`:`[${Ue}:${this.scope.join(":")}]`}};function we(o={}){var n,r;let e={level:(n=o.level)!=null?n:"info"},t=Array.isArray(o.scope)?o.scope:o.scope?[o.scope]:[];return new Ee(e,t,(r=o.sink)!=null?r:console)}async function Oe(o,e){try{let t=globalThis==null?void 0:globalThis.require;if(typeof t=="function"){let s=t("fs"),a=JSON.parse(s.readFileSync(e,"utf8"));return o.applyUpdate(a)}let r=await(await fetch(e)).json();return o.applyUpdate(r)}catch(t){throw new Error(`Failed to load update from ${e}: ${t}`)}}function De(o,e){let t=[],n=c=>c.replace(/\s+/g," ").replace(/>\s+</g,"><").trim(),r=n(o),s=n(e);if(r===s)return{match:!0,differences:[]};let a=r.split(`
42
42
  `),i=s.split(`
43
- `),l=Math.max(o.length,i.length);for(let c=0;c<l;c++){let d=o[c]||"",g=i[c]||"";d!==g&&(t.push(`Line ${c+1}:`),t.push(` Expected: ${d}`),t.push(` Actual: ${g}`))}return{match:!1,differences:t}}var de=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:Ee({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+window.location.search,...s},this.treeRenderer=new ie(this.logger.child("TreeRenderer")),this.focusManager=new G(this.logger.child("FocusManager")),this.modalManager=new te(this.logger.child("ModalManager")),this.formLifecycleManager=new oe(this.modalManager),this.loadingIndicator=new ne,this.formDisabler=new re,this.uploadHandler=new ce(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.linkInterceptor=new Z({getWrapperElement:()=>this.wrapperElement,handleNavigationResponse:l=>this.handleNavigationResponse(l)},this.logger.child("LinkInterceptor")),this.observerManager=new ee({getWrapperElement:()=>this.wrapperElement,send:l=>this.send(l)},this.logger.child("ObserverManager")),this.webSocketManager=new ae({options:this.options,logger:this.logger.child("Transport"),onConnected:()=>{var l,c,d;this.ws=this.webSocketManager.getSocket(),this.logger.info("WebSocket connected"),this.clearFlashQueryParams(),(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=Ee({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.eventDelegator.setupFocusTrapDelegation(),this.eventDelegator.setupAutofocusDelegation(),this.linkInterceptor.setup(this.wrapperElement),se(),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)}clearFlashQueryParams(){let e=new URL(window.location.href),t=["error","success"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&(this.logger.debug("Clearing flash query params from URL"),window.history.replaceState(null,"",e.toString()))}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)}}handleNavigationResponse(e){if(!this.wrapperElement)return;let n=new DOMParser().parseFromString(e,"text/html"),r=this.wrapperElement.getAttribute("data-lvt-id"),s=r?n.querySelector(`[data-lvt-id="${r}"]`):null;if(s)this.wrapperElement.replaceChildren(...Array.from(s.childNodes).map(o=>o.cloneNode(!0)));else{let o=n.querySelector("body");o&&this.wrapperElement.replaceChildren(...Array.from(o.childNodes).map(i=>i.cloneNode(!0)))}this.eventDelegator.setupEventDelegation(),this.linkInterceptor.setup(this.wrapperElement)}parseValue(e){let t=e.trim(),n=parseFloat(t);if(!isNaN(n)){if(Number.isInteger(n)&&Math.abs(n)>Number.MAX_SAFE_INTEGER)return t;if(t===n.toString())return n}return 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"))),ke(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(),xe(e),_e(e),Re(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"&&de.autoInit();return Ke(pt);})();
43
+ `),l=Math.max(a.length,i.length);for(let c=0;c<l;c++){let d=a[c]||"",g=i[c]||"";d!==g&&(t.push(`Line ${c+1}:`),t.push(` Expected: ${d}`),t.push(` Actual: ${g}`))}return{match:!1,differences:t}}var pe=class o{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,a=n!=null?n:r?"debug":"info",i=t!=null?t:we({level:a});t?n?t.setLevel(n):r&&t.setLevel("debug"):i.setLevel(a),this.logger=i.child("Client"),this.options={autoReconnect:!1,reconnectDelay:1e3,liveUrl:window.location.pathname+window.location.search,...s},this.treeRenderer=new ae(this.logger.child("TreeRenderer")),this.focusManager=new Y(this.logger.child("FocusManager")),this.modalManager=new ne(this.logger.child("ModalManager")),this.formLifecycleManager=new oe(this.modalManager),this.loadingIndicator=new re,this.formDisabler=new se,this.uploadHandler=new ue(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 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(),triggerPendingUploads:l=>this.uploadHandler.triggerPendingUploads(l)},this.logger.child("EventDelegator")),this.linkInterceptor=new ee({getWrapperElement:()=>this.wrapperElement,handleNavigationResponse:l=>this.handleNavigationResponse(l)},this.logger.child("LinkInterceptor")),this.observerManager=new te({getWrapperElement:()=>this.wrapperElement,send:l=>this.send(l)},this.logger.child("ObserverManager")),this.changeAutoWirer=new le({getWrapperElement:()=>this.wrapperElement,send:l=>this.send(l)},this.logger.child("ChangeAutoWirer")),this.webSocketManager=new ce({options:this.options,logger:this.logger.child("Transport"),onConnected:()=>{var l,c,d;this.ws=this.webSocketManager.getSocket(),this.logger.info("WebSocket connected"),this.clearFlashQueryParams(),(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=we({scope:"Client:autoInit"}),t=()=>{let n=document.querySelector("[data-lvt-id]");if(n){let r=new o;r.wrapperElement=n,n.getAttribute("data-lvt-loading")==="true"&&(r.loadingIndicator.show(),r.formDisabler.disable(r.wrapperElement)),r.connect().catch(a=>{e.error("Auto-initialization connect failed:",a)}),window.liveTemplateClient=r}};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",t):t()}handleWebSocketPayload(e,t){var r,s,a;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 i=n;try{this.handleUploadStartResponse(i)}catch(l){this.logger.error("Error handling upload start response:",l)}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&&((r=e.meta)!=null&&r.capabilities&&this.changeAutoWirer.setCapabilities(e.meta.capabilities),this.changeAutoWirer.analyzeStatics(e.tree),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:(s=e.meta)==null?void 0:s.action,success:(a=e.meta)==null?void 0:a.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.eventDelegator.setupFocusTrapDelegation(),this.eventDelegator.setupAutofocusDelegation(),this.linkInterceptor.setup(this.wrapperElement),ie(),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.changeAutoWirer.teardown(),this.formLifecycleManager.reset(),this.loadingIndicator.hide(),this.formDisabler.enable(this.wrapperElement)}clearFlashQueryParams(){let e=new URL(window.location.href),t=["error","success"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&(this.logger.debug("Clearing flash query params from URL"),window.history.replaceState(null,"",e.toString()))}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)}}handleNavigationResponse(e){if(!this.wrapperElement)return;let n=new DOMParser().parseFromString(e,"text/html"),r=this.wrapperElement.getAttribute("data-lvt-id"),s=r?n.querySelector(`[data-lvt-id="${r}"]`):null;if(s)this.wrapperElement.replaceChildren(...Array.from(s.childNodes).map(a=>a.cloneNode(!0)));else{let a=n.querySelector("body");a&&this.wrapperElement.replaceChildren(...Array.from(a.childNodes).map(i=>i.cloneNode(!0)))}this.eventDelegator.setupEventDelegation(),this.linkInterceptor.setup(this.wrapperElement)}parseValue(e){let t=e.trim(),n=parseFloat(t);if(!isNaN(n)){if(Number.isInteger(n)&&Math.abs(n)>Number.MAX_SAFE_INTEGER)return t;if(t===n.toString())return n}return 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 a=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"))),a.innerHTML=r.html,this.logger.isDebugEnabled()&&(this.logger.debug("[updateDOM] tempWrapper.innerHTML (first 500 chars):",a.innerHTML.substring(0,500)),this.logger.debug("[updateDOM] tempWrapper has <table>:",a.innerHTML.includes("<table>")),this.logger.debug("[updateDOM] tempWrapper has <tbody>:",a.innerHTML.includes("<tbody>")),this.logger.debug("[updateDOM] tempWrapper has <tr>:",a.innerHTML.includes("<tr"))),xe(e,a,{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(),Ce(e),_e(e),Fe(e),this.uploadHandler.initializeFileInputs(e),this.changeAutoWirer.wireElements(),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.changeAutoWirer.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"&&pe.autoInit();return Ve(ft);})();
44
44
  //# sourceMappingURL=livetemplate-client.browser.js.map