haori 0.18.1 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/haori.cjs.js CHANGED
@@ -1,21 +1,21 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const G=class G{static isEnabled(){return G.devMode}static enable(){G.devMode=!0}static disable(){G.devMode=!1}static set(t){G.devMode=t}};G.devMode=!1;let H=G;const ct="embedded";function Et(g){return g==="embedded"||g==="demo"}function xt(g){return g===null?null:Et(g)?g:ct}const L=class L{static get runtime(){return L._runtime}static setRuntime(t){L._runtime=Et(t)?t:ct}static detect(){try{const t=document.currentScript||document.querySelector('script[src*="haori"]');if(t instanceof HTMLScriptElement){const r=t.getAttribute("data-prefix")||L._prefix;L._prefix=r.endsWith("-")?r:r+"-";const i=xt(t.getAttribute("data-runtime"));i!==null&&(L._runtime=i)}if(t instanceof HTMLScriptElement&&t.hasAttribute(`${L._prefix}dev`)){H.set(!0);return}const e=window.location.hostname;if(e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="::1"||e.endsWith(".local")){H.set(!0);return}H.set(!1)}catch{}}static get prefix(){return L._prefix}};L._prefix="data-",L._runtime=ct;let l=L;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",l.detect):l.detect();class m{static info(t,...e){H.isEnabled()&&console.log&&console.log(t,...e)}static warn(t,...e){H.isEnabled()&&console.warn&&console.warn(t,...e)}static error(t,...e){console.error(t,...e)}}const kt="yyyy/MM/dd HH:mm",Pt="en-US",vt=1e4;function q(g){return String(g).padStart(2,"0")}function At(g,t=kt){if(g==null||g==="")return"";const e=g instanceof Date?g:new Date(g);if(Number.isNaN(e.getTime()))return"";const r={yyyy:String(e.getFullYear()).padStart(4,"0"),yy:q(e.getFullYear()%100),MM:q(e.getMonth()+1),M:String(e.getMonth()+1),dd:q(e.getDate()),d:String(e.getDate()),HH:q(e.getHours()),H:String(e.getHours()),mm:q(e.getMinutes()),ss:q(e.getSeconds())};return t.replace(/'([^']*)'|yyyy|yy|MM|dd|HH|mm|ss|M|d|H/g,(i,n)=>n!==void 0?n===""?"'":n:r[i])}function St(g,t){if(g==null)return"";let e;if(typeof g=="number")e=g;else{const i=String(g).trim();if(i==="")return"";e=Number(i)}if(!Number.isFinite(e))return"";const r={};if(t!==void 0&&Number.isFinite(t)){const i=Math.max(0,Math.trunc(t));r.minimumFractionDigits=i,r.maximumFractionDigits=i}return new Intl.NumberFormat(Pt,r).format(e)}function Tt(g,t,e){let r,i,n;if(t===void 0?(r=0,i=g,n=1):(r=g,i=t,n=e===void 0?1:e),!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(n)||n===0)return[];r=Math.trunc(r),i=Math.trunc(i),n=Math.trunc(n);const s=[];if(n>0)for(let a=r;a<i&&s.length<vt;a+=n)s.push(a);else for(let a=r;a>i&&s.length<vt;a+=n)s.push(a);return s}function wt(g,t,e={}){const r=Math.trunc(Number(g));if(!Number.isFinite(r)||r<=0)return[];const i=Math.min(Math.max(Math.trunc(Number(t))||0,0),r-1),n=Math.max(0,Math.trunc(e.window??2)),s=Math.max(0,Math.trunc(e.boundary??1)),a=new Set;for(let d=0;d<s&&d<r;d+=1)a.add(d);for(let d=Math.max(0,r-s);d<r;d+=1)a.add(d);for(let d=Math.max(0,i-n);d<=Math.min(r-1,i+n);d+=1)a.add(d);const o=Array.from(a).sort((d,p)=>d-p),u=[];let c=null;for(const d of o){if(c!==null&&d-c>1)if(d-c===2){const p=c+1;u.push({page:p,label:p+1,active:p===i,ellipsis:!1})}else u.push({page:null,label:"…",active:!1,ellipsis:!0});u.push({page:d,label:d+1,active:d===i,ellipsis:!1}),c=d}return u}const It=/^(\d{4})-(\d{1,2})$/,Ct=1200;function tt(g,t){const e=Number(g);return Number.isFinite(e)?Math.trunc(e):t}function at(g,t){if(typeof g!="string")return"";const e=It.exec(g.trim());if(!e)return"";const r=Number(e[1]),i=Number(e[2]);if(i<1||i>12)return"";const n=Number.isFinite(t)?Math.trunc(t):0,s=r*12+(i-1)+n,a=Math.floor(s/12),o=s-a*12+1;return`${String(a).padStart(4,"0")}-${q(o)}`}function Bt(g){if(typeof g=="string"&&g.trim()!=="")return at(g,0);const t=new Date;return`${String(t.getFullYear()).padStart(4,"0")}-${q(t.getMonth()+1)}`}function Dt(g,t){const e=Math.trunc(Number(g));if(!Number.isFinite(e)||e<0)return[];const r=Bt(t);if(r==="")return[];const i=Math.min(e,Ct),n=[];for(let s=0;s<=i;s+=1){const a=at(r,-s);n.push({targetMonth:a,label:a.replace(/-/g,"/")})}return n}function Rt(g,t){const e={start:0,end:0,total:0,empty:!0};if(!g||typeof g!="object")return e;const r=g,i=tt(r.totalElements??r.totalCount,0);if(i<=0)return e;const n=Math.max(0,tt(r.number,0)),s=Math.max(0,tt(r.size,0)),a=n*s,o=Math.min(a+1,i);let u;if(t!==void 0&&Number.isFinite(t))u=Math.max(0,Math.trunc(t));else{const d=tt(r.numberOfElements,NaN);u=Number.isFinite(d)?d:Math.min(s,i-a)}const c=Math.min(a+u,i);return{start:o,end:Math.max(c,o),total:i,empty:!1}}function Ft(g,t,e){if(!Array.isArray(g)||g.length===0)return null;const r=String(e),i=g.find(n=>n!=null&&String(n[t])===r);return i===void 0?null:i}function Nt(g,t){if(!Array.isArray(g))return 0;let e=0;for(const r of g){const i=t==null?r:r?.[t];if(i==null||i==="")continue;const n=typeof i=="number"?i:Number(i);Number.isNaN(n)||(e+=n)}return e}const $t=Object.freeze({date:At,number:St,pages:wt,range:Tt,monthAdd:at,monthRange:Dt,pageSummary:Rt,findBy:Ft,sum:Nt}),B=class B{static getForbiddenBindingValues(){const t=globalThis,e=[t,t.window,t.document,t.navigator,t.history,t.localStorage,t.sessionStorage,t.fetch,t.Function,t.setTimeout,t.setInterval,t.requestAnimationFrame,t.alert,t.confirm,t.prompt];return t.window?.location&&e.push(t.window.location),e.filter(r=>r!=null)}static getForbiddenBindingValueSet(){return new Set(this.getForbiddenBindingValues())}static scheduleForbiddenBindingValueCacheReset(){this.forbiddenBindingValueCacheResetScheduled||(this.forbiddenBindingValueCacheResetScheduled=!0,queueMicrotask(()=>{this.forbiddenBindingValueCache=new WeakMap,this.forbiddenBindingValueCacheResetScheduled=!1}))}static buildAssignments(t){const e=new Set(t);return this.FORBIDDEN_NAMES.filter(r=>!e.has(r)).map(r=>`const ${r} = undefined`).join(`;
2
- `)}static detectForbiddenIdentifiers(t){return this.FORBIDDEN_NAMES.filter(e=>new RegExp(`(^|[^\\w$.])${e}(?![\\w$])`).test(t))}static evaluate(t,e={}){return this.evaluateDetailed(t,e).value}static evaluateDetailed(t,e={}){if(this.scheduleForbiddenBindingValueCacheReset(),t.trim()==="")return m.warn("[Haori]",t,"Expression is empty"),{value:null,unresolvedReference:!1};if(this.containsDangerousPatterns(t)){const o=this.detectDisallowedKeywords(t);if(o.length>0){const u=o.some(c=>c==="function"||c==="return")?" Statement keywords are not allowed in expressions; use an arrow function such as `x => ({key: value})` instead of `function(x){ return {key: value}; }`.":" These are statement keywords and cannot be used in expressions.";m.warn("[Haori]",t,"Expression uses disallowed keyword(s): "+o.join(", ")+"."+u)}else m.warn("[Haori]",t,"Expression contains dangerous patterns");return{value:null,unresolvedReference:!1}}if(this.containsForbiddenKeys(e))return m.warn("[Haori]",e,"Binded values contain forbidden keys"),{value:null,unresolvedReference:!1};const r=this.getForbiddenBindingValueSet();if(this.containsForbiddenBindingValues(e,new WeakSet,r))return m.warn("[Haori]",e,"Binded values contain forbidden values"),{value:null,unresolvedReference:!1};const i=t.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g,""),n=this.BUILTIN_REFERENCE_PATTERN.test(i);n&&this.BUILTIN_NAMESPACE in e&&m.warn("[Haori]",`Binding key "${this.BUILTIN_NAMESPACE}" is reserved for built-in helpers; the bound value is ignored in expressions.`);const s=n?{...e,[this.BUILTIN_NAMESPACE]:this.BUILTIN_HELPERS}:{...e},a=this.canAttemptMissingIdentifierRecovery(t);for(let o=0;o<=this.MAX_IDENTIFIER_RECOVERY_COUNT;o+=1){const u=this.prepareEvaluator(t,s);if(u.compileFailed||u.evaluator===null)return{value:null,unresolvedReference:!1};try{const c=[],d=this.wrapBoundValues(s);return u.bindKeys.forEach(p=>{c.push(d[p])}),{value:this.withBlockedPropertyAccess(()=>u.evaluator(...c)),unresolvedReference:!1}}catch(c){if(a&&c instanceof ReferenceError){const p=this.extractMissingIdentifier(c);if(p!==null&&this.canRecoverMissingIdentifier(p,s)){s[p]=void 0;continue}}const d=this.detectForbiddenIdentifiers(t);return d.length>0&&m.warn("[Haori]","Expression references blocked identifier(s): "+d.join(", ")+". These are blocked in expressions and evaluate to undefined (often the cause of this error). Use spread {...a, ...b} instead of Object.assign.",t),m.error("[Haori]","Expression evaluation error:",t,c),c instanceof ReferenceError?{value:void 0,unresolvedReference:!0}:{value:null,unresolvedReference:!1}}}return m.error("[Haori]","Failed to recover missing identifiers:",t,s),{value:void 0,unresolvedReference:!0}}static prepareEvaluator(t,e){const r=Object.keys(e).filter(o=>!this.FORBIDDEN_BINDING_NAMES.has(o)).sort(),i=`${t}:${r.join(",")}`;let n=this.EXPRESSION_CACHE.get(i)||null;if(n!==null)return{bindKeys:r,evaluator:n,compileFailed:!1};const s=this.buildAssignments(r),a=s?`"use strict";
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const G=class G{static isEnabled(){return G.devMode}static enable(){G.devMode=!0}static disable(){G.devMode=!1}static set(t){G.devMode=t}};G.devMode=!1;let H=G;const ct="embedded";function Et(p){return p==="embedded"||p==="demo"}function xt(p){return p===null?null:Et(p)?p:ct}const L=class L{static get runtime(){return L._runtime}static setRuntime(t){L._runtime=Et(t)?t:ct}static detect(){try{const t=document.currentScript||document.querySelector('script[src*="haori"]');if(t instanceof HTMLScriptElement){const r=t.getAttribute("data-prefix")||L._prefix;L._prefix=r.endsWith("-")?r:r+"-";const i=xt(t.getAttribute("data-runtime"));i!==null&&(L._runtime=i)}if(t instanceof HTMLScriptElement&&t.hasAttribute(`${L._prefix}dev`)){H.set(!0);return}const e=window.location.hostname;if(e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="::1"||e.endsWith(".local")){H.set(!0);return}H.set(!1)}catch{}}static get prefix(){return L._prefix}};L._prefix="data-",L._runtime=ct;let l=L;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",l.detect):l.detect();class m{static info(t,...e){H.isEnabled()&&console.log&&console.log(t,...e)}static warn(t,...e){H.isEnabled()&&console.warn&&console.warn(t,...e)}static error(t,...e){console.error(t,...e)}}const kt="yyyy/MM/dd HH:mm",Pt="en-US",vt=1e4;function q(p){return String(p).padStart(2,"0")}function At(p,t=kt){if(p==null||p==="")return"";const e=p instanceof Date?p:new Date(p);if(Number.isNaN(e.getTime()))return"";const r={yyyy:String(e.getFullYear()).padStart(4,"0"),yy:q(e.getFullYear()%100),MM:q(e.getMonth()+1),M:String(e.getMonth()+1),dd:q(e.getDate()),d:String(e.getDate()),HH:q(e.getHours()),H:String(e.getHours()),mm:q(e.getMinutes()),ss:q(e.getSeconds())};return t.replace(/'([^']*)'|yyyy|yy|MM|dd|HH|mm|ss|M|d|H/g,(i,n)=>n!==void 0?n===""?"'":n:r[i])}function St(p,t){if(p==null)return"";let e;if(typeof p=="number")e=p;else{const i=String(p).trim();if(i==="")return"";e=Number(i)}if(!Number.isFinite(e))return"";const r={};if(t!==void 0&&Number.isFinite(t)){const i=Math.max(0,Math.trunc(t));r.minimumFractionDigits=i,r.maximumFractionDigits=i}return new Intl.NumberFormat(Pt,r).format(e)}function Tt(p,t,e){let r,i,n;if(t===void 0?(r=0,i=p,n=1):(r=p,i=t,n=e===void 0?1:e),!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(n)||n===0)return[];r=Math.trunc(r),i=Math.trunc(i),n=Math.trunc(n);const s=[];if(n>0)for(let a=r;a<i&&s.length<vt;a+=n)s.push(a);else for(let a=r;a>i&&s.length<vt;a+=n)s.push(a);return s}function wt(p,t,e={}){const r=Math.trunc(Number(p));if(!Number.isFinite(r)||r<=0)return[];const i=Math.min(Math.max(Math.trunc(Number(t))||0,0),r-1),n=Math.max(0,Math.trunc(e.window??2)),s=Math.max(0,Math.trunc(e.boundary??1)),a=new Set;for(let d=0;d<s&&d<r;d+=1)a.add(d);for(let d=Math.max(0,r-s);d<r;d+=1)a.add(d);for(let d=Math.max(0,i-n);d<=Math.min(r-1,i+n);d+=1)a.add(d);const o=Array.from(a).sort((d,g)=>d-g),u=[];let c=null;for(const d of o){if(c!==null&&d-c>1)if(d-c===2){const g=c+1;u.push({page:g,label:g+1,active:g===i,ellipsis:!1})}else u.push({page:null,label:"…",active:!1,ellipsis:!0});u.push({page:d,label:d+1,active:d===i,ellipsis:!1}),c=d}return u}const It=/^(\d{4})-(\d{1,2})$/,Ct=1200;function tt(p,t){const e=Number(p);return Number.isFinite(e)?Math.trunc(e):t}function at(p,t){if(typeof p!="string")return"";const e=It.exec(p.trim());if(!e)return"";const r=Number(e[1]),i=Number(e[2]);if(i<1||i>12)return"";const n=Number.isFinite(t)?Math.trunc(t):0,s=r*12+(i-1)+n,a=Math.floor(s/12),o=s-a*12+1;return`${String(a).padStart(4,"0")}-${q(o)}`}function Bt(p){if(typeof p=="string"&&p.trim()!=="")return at(p,0);const t=new Date;return`${String(t.getFullYear()).padStart(4,"0")}-${q(t.getMonth()+1)}`}function Dt(p,t){const e=Math.trunc(Number(p));if(!Number.isFinite(e)||e<0)return[];const r=Bt(t);if(r==="")return[];const i=Math.min(e,Ct),n=[];for(let s=0;s<=i;s+=1){const a=at(r,-s);n.push({targetMonth:a,label:a.replace(/-/g,"/")})}return n}function Rt(p,t){const e={start:0,end:0,total:0,empty:!0};if(!p||typeof p!="object")return e;const r=p,i=tt(r.totalElements??r.totalCount,0);if(i<=0)return e;const n=Math.max(0,tt(r.number,0)),s=Math.max(0,tt(r.size,0)),a=n*s,o=Math.min(a+1,i);let u;if(t!==void 0&&Number.isFinite(t))u=Math.max(0,Math.trunc(t));else{const d=tt(r.numberOfElements,NaN);u=Number.isFinite(d)?d:Math.min(s,i-a)}const c=Math.min(a+u,i);return{start:o,end:Math.max(c,o),total:i,empty:!1}}function Nt(p,t,e){if(!Array.isArray(p)||p.length===0)return null;const r=String(e),i=p.find(n=>n!=null&&String(n[t])===r);return i===void 0?null:i}function Ft(p,t){if(!Array.isArray(p))return 0;let e=0;for(const r of p){const i=t==null?r:r?.[t];if(i==null||i==="")continue;const n=typeof i=="number"?i:Number(i);Number.isNaN(n)||(e+=n)}return e}const $t=Object.freeze({date:At,number:St,pages:wt,range:Tt,monthAdd:at,monthRange:Dt,pageSummary:Rt,findBy:Nt,sum:Ft}),B=class B{static getForbiddenBindingValues(){const t=globalThis,e=[t,t.window,t.document,t.navigator,t.history,t.localStorage,t.sessionStorage,t.fetch,t.Function,t.setTimeout,t.setInterval,t.requestAnimationFrame,t.alert,t.confirm,t.prompt];return t.window?.location&&e.push(t.window.location),e.filter(r=>r!=null)}static getForbiddenBindingValueSet(){return new Set(this.getForbiddenBindingValues())}static scheduleForbiddenBindingValueCacheReset(){this.forbiddenBindingValueCacheResetScheduled||(this.forbiddenBindingValueCacheResetScheduled=!0,queueMicrotask(()=>{this.forbiddenBindingValueCache=new WeakMap,this.forbiddenBindingValueCacheResetScheduled=!1}))}static buildAssignments(t){const e=new Set(t);return this.FORBIDDEN_NAMES.filter(r=>!e.has(r)).map(r=>`const ${r} = undefined`).join(`;
2
+ `)}static detectForbiddenIdentifiers(t){return this.FORBIDDEN_NAMES.filter(e=>new RegExp(`(^|[^\\w$.])${e}(?![\\w$])`).test(t))}static evaluate(t,e={}){return this.evaluateDetailed(t,e).value}static evaluateDetailed(t,e={}){if(this.scheduleForbiddenBindingValueCacheReset(),t.trim()==="")return m.warn("[Haori]",t,"Expression is empty"),{value:null,unresolvedReference:!1};if(this.containsDangerousPatterns(t)){const o=this.detectDisallowedKeywords(t);if(o.length>0){const u=o.some(c=>c==="function"||c==="return")?" Statement keywords are not allowed in expressions; use an arrow function such as `x => ({key: value})` instead of `function(x){ return {key: value}; }`.":" These are statement keywords and cannot be used in expressions.";m.warn("[Haori]",t,"Expression uses disallowed keyword(s): "+o.join(", ")+"."+u)}else m.warn("[Haori]",t,"Expression contains dangerous patterns");return{value:null,unresolvedReference:!1}}if(this.containsForbiddenKeys(e))return m.warn("[Haori]",e,"Binded values contain forbidden keys"),{value:null,unresolvedReference:!1};const r=this.getForbiddenBindingValueSet();if(this.containsForbiddenBindingValues(e,new WeakSet,r))return m.warn("[Haori]",e,"Binded values contain forbidden values"),{value:null,unresolvedReference:!1};const i=t.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g,""),n=this.BUILTIN_REFERENCE_PATTERN.test(i);n&&this.BUILTIN_NAMESPACE in e&&m.warn("[Haori]",`Binding key "${this.BUILTIN_NAMESPACE}" is reserved for built-in helpers; the bound value is ignored in expressions.`);const s=n?{...e,[this.BUILTIN_NAMESPACE]:this.BUILTIN_HELPERS}:{...e},a=this.canAttemptMissingIdentifierRecovery(t);for(let o=0;o<=this.MAX_IDENTIFIER_RECOVERY_COUNT;o+=1){const u=this.prepareEvaluator(t,s);if(u.compileFailed||u.evaluator===null)return{value:null,unresolvedReference:!1};try{const c=[],d=this.wrapBoundValues(s);return u.bindKeys.forEach(g=>{c.push(d[g])}),{value:this.withBlockedPropertyAccess(()=>u.evaluator(...c)),unresolvedReference:!1}}catch(c){if(a&&c instanceof ReferenceError){const g=this.extractMissingIdentifier(c);if(g!==null&&this.canRecoverMissingIdentifier(g,s)){s[g]=void 0;continue}}const d=this.detectForbiddenIdentifiers(t);return d.length>0&&m.warn("[Haori]","Expression references blocked identifier(s): "+d.join(", ")+". These are blocked in expressions and evaluate to undefined (often the cause of this error). Use spread {...a, ...b} instead of Object.assign.",t),m.error("[Haori]","Expression evaluation error:",t,c),c instanceof ReferenceError?{value:void 0,unresolvedReference:!0}:{value:null,unresolvedReference:!1}}}return m.error("[Haori]","Failed to recover missing identifiers:",t,s),{value:void 0,unresolvedReference:!0}}static prepareEvaluator(t,e){const r=Object.keys(e).filter(o=>!this.FORBIDDEN_BINDING_NAMES.has(o)).sort(),i=`${t}:${r.join(",")}`;let n=this.EXPRESSION_CACHE.get(i)||null;if(n!==null)return{bindKeys:r,evaluator:n,compileFailed:!1};const s=this.buildAssignments(r),a=s?`"use strict";
3
3
  ${s};
4
4
  return (${t});`:`"use strict";
5
5
  return (${t});`;try{return n=new Function(...r,a),this.EXPRESSION_CACHE.set(i,n),{bindKeys:r,evaluator:n,compileFailed:!1}}catch(o){return m.error("[Haori]","Failed to compile expression:",t,o),{bindKeys:r,evaluator:null,compileFailed:!0}}}static extractMissingIdentifier(t){return String(t.message||"").match(/^([A-Za-z_$][A-Za-z0-9_$]*) is not defined$/)?.[1]||null}static canRecoverMissingIdentifier(t,e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?e[t]===void 0&&!(t in e):!1}static canAttemptMissingIdentifierRecovery(t){return t.includes("?.")||t.includes("??")||t.includes("||")||t.includes("&&")}static containsDangerousPatterns(t){return this.hasAllowedSyntax(t)?[/\beval\s*\(/,/\barguments\s*\[/,/\barguments\s*\./].some(r=>r.test(t)):!0}static detectDisallowedKeywords(t){const e=[];return this.DISALLOWED_KEYWORDS.forEach(r=>{new RegExp(`(^|[^\\w$.])${r}(?![\\w$])`).test(t)&&e.push(r)}),e}static hasAllowedSyntax(t){const e=this.tokenizeExpression(t);if(e===null||e.length===0)return!1;const r=[];let i=null;for(let n=0;n<e.length;n++){const s=e[n],a=e[n+1]||null,o=r[r.length-1]||null,u=e[n-2]||null,c=e[n-3]||null;if(this.startsObjectKey(o,i,u,c)&&(s.value==="["||s.type==="identifier"&&this.FORBIDDEN_PROPERTY_NAMES.has(s.value)||s.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(s.value)))||s.type==="identifier"&&(this.DISALLOWED_KEYWORDS.has(s.value)||this.STRICT_FORBIDDEN_NAMES.includes(s.value)||(i?.value==="."||i?.value==="?.")&&this.FORBIDDEN_PROPERTY_NAMES.has(s.value))||o==="member"&&s.value!=="]"&&s.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(s.value))||s.value==="."&&a?.type!=="identifier"||s.value==="?."&&a?.type!=="identifier"&&a?.value!=="["&&a?.value!=="(")return!1;switch(s.value){case"(":r.push("paren");break;case")":{if(r.pop()!=="paren")return!1;break}case"[":{const d=this.startsMemberAccess(i)?"member":"array";r.push(d);break}case"{":r.push("object");break;case"]":{if(r.pop()===void 0)return!1;break}case"}":{if(r.pop()!=="object")return!1;break}}i=s}return r.length===0}static tokenizeExpression(t){const e=[],r=["===","!==","...","?.","&&","||",">=","<=","==","!=","=>"],i=new Set(["(",")","{","}","[","]",".",",","?",":","+","-","*","/","%","!",">","<"]);let n=0;for(;n<t.length;){const s=t[n];if(/\s/.test(s)){n+=1;continue}if(s==="/"&&(t[n+1]==="/"||t[n+1]==="*"))return null;if(s==='"'||s==="'"){const o=this.readStringToken(t,n);if(o===null)return null;e.push(o.token),n=o.nextIndex;continue}const a=r.find(o=>t.startsWith(o,n));if(a){e.push({type:"operator",value:a,position:n}),n+=a.length;continue}if(/[0-9]/.test(s)){const o=this.readNumberToken(t,n);e.push(o.token),n=o.nextIndex;continue}if(/[A-Za-z_$]/.test(s)){const o=this.readIdentifierToken(t,n);e.push(o.token),n=o.nextIndex;continue}if(i.has(s)){e.push({type:"operator",value:s,position:n}),n+=1;continue}return null}return e}static readStringToken(t,e){const r=t[e];let i=e+1;for(;i<t.length;){const n=t[i];if(n==="\\"){i+=2;continue}if(n===r)return{token:{type:"string",value:t.slice(e,i+1),position:e},nextIndex:i+1};i+=1}return null}static readNumberToken(t,e){let r=e;for(;r<t.length&&/[0-9_]/.test(t[r]);)r+=1;if(t[r]===".")for(r+=1;r<t.length&&/[0-9_]/.test(t[r]);)r+=1;return{token:{type:"number",value:t.slice(e,r),position:e},nextIndex:r}}static readIdentifierToken(t,e){let r=e;for(;r<t.length&&/[A-Za-z0-9_$]/.test(t[r]);)r+=1;return{token:{type:"identifier",value:t.slice(e,r),position:e},nextIndex:r}}static startsMemberAccess(t){return t===null?!1:t.type==="identifier"||t.type==="number"?!0:t.value===")"||t.value==="]"||t.value==="?."}static startsObjectKey(t,e,r,i){return t!=="object"?!1:e?.value==="{"||e?.value===","||e?.type==="identifier"&&this.OBJECT_PROPERTY_MODIFIERS.has(e.value)&&(r?.value==="{"||r?.value===",")?!0:e?.value!=="*"?!1:r?.value==="{"||r?.value===","?!0:r?.type==="identifier"&&r.value==="async"&&(i?.value==="{"||i?.value===",")}static decodeStringLiteral(t){return t.slice(1,-1).replace(/\\u\{([0-9a-fA-F]+)\}/g,(e,r)=>String.fromCodePoint(parseInt(r,16))).replace(/\\u([0-9a-fA-F]{4})/g,(e,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\x([0-9a-fA-F]{2})/g,(e,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\(["'\\bfnrtv0])/g,(e,r)=>{switch(r){case"b":return"\b";case"f":return"\f";case"n":return`
6
- `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return r}})}static wrapBoundValues(t){const e=new WeakMap,r={};return Object.entries(t).forEach(([i,n])=>{r[i]=this.wrapBoundValue(n,e)}),r}static wrapBoundValue(t,e){if(!this.shouldWrapValue(t))return t;const r=t,i=e.get(r);if(i!==void 0)return i;const n=new Proxy(r,{get:(s,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const u=Reflect.get(s,a,o);return typeof a=="symbol"?u:this.wrapBoundValue(u,e)},has:(s,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(s,a),getOwnPropertyDescriptor:(s,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(s,a)},apply:(s,a,o)=>{const u=Reflect.apply(s,a,o);return this.isIteratorLike(u)?u:this.wrapBoundValue(u,e)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),e)});return e.set(r,n),n}static shouldWrapValue(t){if(typeof t=="function")return!0;if(t===null||typeof t!="object")return!1;if(Array.isArray(t))return!0;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}static withBlockedPropertyAccess(t){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:n})=>{Object.defineProperty(i,n,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return t()}finally{r.forEach(({target:i,property:n,descriptor:s})=>{s!==void 0&&Object.defineProperty(i,n,s)})}}static isIteratorLike(t){return t===null||typeof t!="object"?!1:typeof t.next=="function"}static containsForbiddenKeys(t){if(!t||typeof t!="object")return!1;for(const e of Object.keys(t))if(this.FORBIDDEN_BINDING_NAMES.has(e))return!0;return!1}static containsForbiddenBindingValues(t,e=new WeakSet,r=this.getForbiddenBindingValueSet()){if(!t||typeof t!="object")return!1;const i=this.forbiddenBindingValueCache.get(t);if(i!==void 0)return i;if(e.has(t))return!1;if(e.add(t),r.has(t))return this.forbiddenBindingValueCache.set(t,!0),!0;for(const n of Object.values(t)){if(typeof n=="function"){if(r.has(n))return this.forbiddenBindingValueCache.set(t,!0),!0;continue}if(this.containsForbiddenBindingValues(n,e,r))return this.forbiddenBindingValueCache.set(t,!0),!0}return this.forbiddenBindingValueCache.set(t,!1),!1}};B.MAX_IDENTIFIER_RECOVERY_COUNT=8,B.BUILTIN_NAMESPACE="haori",B.BUILTIN_HELPERS={...$t},B.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,B.forbiddenBindingValueCache=new WeakMap,B.forbiddenBindingValueCacheResetScheduled=!1,B.FORBIDDEN_NAMES=["window","self","globalThis","frames","parent","top","Function","setTimeout","setInterval","requestAnimationFrame","alert","confirm","prompt","fetch","XMLHttpRequest","Reflect","constructor","__proto__","prototype","Object","document","location","navigator","localStorage","sessionStorage","IndexedDB","history"],B.STRICT_FORBIDDEN_NAMES=["eval","arguments"],B.REBINDABLE_FORBIDDEN_NAMES=new Set(["location"]),B.FORBIDDEN_BINDING_NAMES=new Set([...B.FORBIDDEN_NAMES.filter(t=>!B.REBINDABLE_FORBIDDEN_NAMES.has(t)),"constructor","__proto__","prototype",...B.STRICT_FORBIDDEN_NAMES]),B.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),B.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),B.DISALLOWED_KEYWORDS=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","finally","for","function","if","import","in","instanceof","let","new","return","switch","this","throw","try","typeof","var","void","while","with","yield"]),B.EXPRESSION_CACHE=new Map;let z=B;class dt{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(t,e=!1){let r,i;const n=new Promise((a,o)=>{r=a,i=o}),s={task:t,timestamp:performance.now(),promise:n,resolve:r,reject:i};return e?this.queue.unshift(s):this.queue.push(s),this.scheduleProcessing(),n}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const t=performance.now();for(;this.queue.length>0;){const e=this.queue.shift();if(!e)return;try{const r=await e.task();e.resolve(r)}catch(r){e.reject(r),m.error("[Haori]",`Task ${e.timestamp} failed:`,r)}if(performance.now()-t>this.MAX_BUDGET)break}}catch(t){m.error("[Haori]","Error processing queue:",t)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const t=this.queue.map(e=>e.promise);t.length>0&&await Promise.allSettled(t)}async waitForIdle(t=1e3){let e=0,r=0;for(;e<2&&r<t;)this.processing||this.queue.length>0?(await this.wait(),e=0):e+=1,await dt.nextTick(),r+=1}static nextTick(){return new Promise(t=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>t()):setTimeout(t,0)})}}const gt=class gt{static enqueue(t,e=!1){return this.ASYNC_QUEUE.enqueue(t,e)}static wait(){return this.ASYNC_QUEUE.wait()}static waitForIdle(t=1e3){return this.ASYNC_QUEUE.waitForIdle(t)}};gt.ASYNC_QUEUE=new dt;let M=gt;const F=class F{static reset(){F.ELEMENT_STORES.clear(),F.ensureGlobalAccess()}static snapshot(){return F.ensureGlobalAccess(),[...F.ELEMENT_STORES.entries()].map(([t,e])=>({elementId:t,tagName:e.tagName,attributes:[...e.attributes.entries()].map(([r,i])=>({name:r,template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:F.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls),texts:[...e.texts.entries()].map(([r,i])=>({childIndex:Number(r),template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:F.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls)})).sort((t,e)=>{const r=t.attributes.reduce((n,s)=>n+s.calls,0)+t.texts.reduce((n,s)=>n+s.calls,0);return e.attributes.reduce((n,s)=>n+s.calls,0)+e.texts.reduce((n,s)=>n+s.calls,0)-r})}static record(t,e,r){if(!H.isEnabled()||!t||e.length===0)return;F.ensureGlobalAccess();const i=F.getOrCreateElementStore(t.element);if(t.kind==="attribute"){const s=F.getOrCreateCounter(i.attributes,t.rawName,t.template);F.updateCounter(s,e,r);return}const n=F.getOrCreateCounter(i.texts,String(t.childIndex),t.template);F.updateCounter(n,e,r)}static ensureGlobalAccess(){if(!H.isEnabled())return;const t=globalThis;t[F.GLOBAL_KEY]===void 0&&(t[F.GLOBAL_KEY]={reset:()=>F.reset(),snapshot:()=>F.snapshot()})}static getOrCreateElementStore(t){const e=F.createElementId(t),r=F.ELEMENT_STORES.get(e);if(r)return r;const i={tagName:t.tagName.toLowerCase(),attributes:new Map,texts:new Map};return F.ELEMENT_STORES.set(e,i),i}static getOrCreateCounter(t,e,r){const i=t.get(e);if(i)return i;const n={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return t.set(e,n),n}static getOrCreatePlaceholder(t,e){const r=t.get(e);if(r)return r;const i={calls:0,totalDurationMs:0,maxDurationMs:0};return t.set(e,i),i}static updateCounter(t,e,r){t.calls+=1,t.totalDurationMs+=r,t.maxDurationMs=Math.max(t.maxDurationMs,r),e.forEach(i=>{const n=F.getOrCreatePlaceholder(t.placeholders,i.expression);n.calls+=1,n.totalDurationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs)})}static sortPlaceholders(t){return[...t.entries()].map(([e,r])=>({expression:e,calls:r.calls,totalDurationMs:r.totalDurationMs,maxDurationMs:r.maxDurationMs})).sort((e,r)=>r.calls!==e.calls?r.calls-e.calls:r.totalDurationMs-e.totalDurationMs)}static now(){return globalThis.performance?.now()??Date.now()}static measure(t){const e=F.now();return{value:t(),durationMs:F.now()-e}}static createElementId(t){const e=[];let r=t;for(;r;){let i=r.tagName.toLowerCase();const n=r.getAttribute("id")||"";if(n.trim()!==""){i+=`#${n.trim()}`,e.unshift(i);break}const s=r.getAttribute(`${l.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${l.prefix}derive-name="${s.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),e.unshift(i),r=a}return e.join(" > ")}};F.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",F.ELEMENT_STORES=new Map;let et=F;const Y=class Y{constructor(t){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=t,Y.FRAGMENT_CACHE.set(t,this)}static get(t){if(t==null)return null;if(Y.FRAGMENT_CACHE.has(t))return Y.FRAGMENT_CACHE.get(t);let e;switch(t.nodeType){case Node.ELEMENT_NODE:e=new k(t);break;case Node.TEXT_NODE:e=new U(t);break;case Node.COMMENT_NODE:e=new ft(t);break;default:return m.warn("[Haori]","Unsupported node type:",t.nodeType),null}return e}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const t=this.parent,e=t.skipMutationNodes;return M.enqueue(()=>{t.skipMutationNodes=!0,this.target.parentNode===t.getTarget()&&t.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{t.skipMutationNodes=e})}else{const t=this.target.parentNode;if(t)return M.enqueue(()=>{this.target.parentNode===t&&t.removeChild(this.target),this.mounted=!1});this.mounted=!1}return Promise.resolve()}mount(){if(this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const t=this.parent,e=t.skipMutationNodes;return M.enqueue(()=>{t.skipMutationNodes=!0,this.target.parentNode!==t.getTarget()&&t.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{t.skipMutationNodes=e})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(t){this.mounted=t}remove(t=!0){return this.parent&&this.parent.removeChild(this),Y.FRAGMENT_CACHE.delete(this.target),t?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(t){this.parent=t}};Y.FRAGMENT_CACHE=new WeakMap;let w=Y;const W=class W extends w{constructor(t){super(t),this.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],this.children=[],this.attributeMap=new Map,this.bindingData=null,this.bindingWorkChain=Promise.resolve(),this.bindingWorkActive=0,this.initialBindAttribute=null,this.derivedBindingData=null,this.bindingDataCache=null,this.descendantBindingDataCache=null,this.visible=!0,this.display=null,this.displayPriority=null,this.template=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.skipMutationAttributes=!1,this.skipChangeValue=!1,this.selfWrittenBind=new Map,this.syncValue(),this.initialBindAttribute=t.getAttribute(`${l.prefix}bind`),t.getAttributeNames().forEach(e=>{const r=t.getAttribute(e);if(r!==null&&!this.attributeMap.has(e)){const i=new rt(e,r);this.attributeMap.set(e,i)}}),t.childNodes.forEach(e=>{const r=w.get(e);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(t=>t instanceof W)}pushChild(t){this.children.push(t),t.setParent(this)}removeChild(t){const e=this.children.indexOf(t);if(e<0){m.warn("[Haori]","Child fragment not found.",t);return}this.children.splice(e,1),t.setParent(null)}clone(){const t=new W(this.target.cloneNode(!1));return this.attributeMap.forEach((e,r)=>{t.attributeMap.set(r,e)}),this.children.forEach(e=>{const r=e.clone();t.getTarget().appendChild(r.getTarget()),t.pushChild(r)}),t.mounted=!1,t.bindingData=this.bindingData,t.derivedBindingData=this.derivedBindingData,t.clearBindingDataCache(),t.visible=!0,t.display=this.display,t.displayPriority=this.displayPriority,t.template=this.template,t.renderSignature=this.renderSignature,t.eachInputSignature=this.eachInputSignature,t.deriveSubtreeSignature=null,t.deriveInputSignature=null,t.freshInitializationSkippable=this.freshInitializationSkippable,t.normalizeClonedVisibilityState(),t}normalizeClonedVisibilityState(){(this.visible===!1||this.getTarget().style.display==="none"||this.getTarget().hasAttribute(`${l.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${l.prefix}if-false`)),this.children.forEach(t=>{t instanceof W&&t.normalizeClonedVisibilityState()})}remove(t=!0){const e=[];return this.children.forEach(r=>{e.push(r.remove(!1))}),this.children.length=0,this.attributeMap.clear(),this.bindingData=null,this.bindingDataCache=null,this.derivedBindingData=null,this.descendantBindingDataCache=null,this.template&&(e.push(this.template.remove(!1)),this.template=null),this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,e.push(super.remove(t)),Promise.all(e).then(()=>{})}getTarget(){return this.target}getBindingData(){return this.bindingDataCache?this.bindingDataCache:(this.bindingDataCache={},this.parent&&Object.assign(this.bindingDataCache,this.parent.getDescendantBindingData()),this.bindingData&&Object.assign(this.bindingDataCache,this.bindingData),this.bindingDataCache)}getDescendantBindingData(){return this.descendantBindingDataCache?this.descendantBindingDataCache:(this.descendantBindingDataCache={...this.getBindingData()},this.derivedBindingData&&Object.assign(this.descendantBindingDataCache,this.derivedBindingData),this.descendantBindingDataCache)}getRawBindingData(){return this.bindingData}recordSelfWrittenBind(t){this.selfWrittenBind.size>64&&this.selfWrittenBind.clear(),this.selfWrittenBind.set(t,(this.selfWrittenBind.get(t)??0)+1)}consumeSelfWrittenBind(t){const e=this.selfWrittenBind.get(t);return e===void 0?!1:(e<=1?this.selfWrittenBind.delete(t):this.selfWrittenBind.set(t,e-1),!0)}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(t){this.bindingData=t,this.clearBindingDataCache()}isExecutingBindingWork(){return this.bindingWorkActive>0}markBindingWorkStart(){this.bindingWorkActive++}markBindingWorkEnd(){this.bindingWorkActive>0&&this.bindingWorkActive--}enqueueBindingWork(t){const e=this.bindingWorkChain.then(t,t);return this.bindingWorkChain=e.then(()=>{},()=>{}),e}getInitialBindAttribute(){return this.initialBindAttribute}setDerivedBindingData(t){this.derivedBindingData=t,this.clearBindingDataCache()}setParent(t){this.parent!==t&&(this.parent=t,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(t=>{t instanceof W&&t.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(t){this.template=t}setListKey(t){this.listKey=t}getListKey(){return this.listKey}getRenderSignature(){return this.renderSignature}setRenderSignature(t){this.renderSignature=t}getEachInputSignature(){return this.eachInputSignature}setEachInputSignature(t){this.eachInputSignature=t}getDeriveSubtreeSignature(){return this.deriveSubtreeSignature}setDeriveSubtreeSignature(t){this.deriveSubtreeSignature=t}getDeriveInputSignature(){return this.deriveInputSignature}setDeriveInputSignature(t){this.deriveInputSignature=t}isFreshInitializationSkippable(){return this.freshInitializationSkippable}setFreshInitializationSkippable(t){this.freshInitializationSkippable=t}setValue(t){return this.applyValue(t,!0)}syncBindingValue(t){return this.applyValue(t,!1)}applyValue(t,e){if(this.skipChangeValue||this.value===t)return Promise.resolve();const r=this.getTarget();if(r instanceof HTMLInputElement&&(r.type==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),n=r.type==="checkbox"&&i==="true";let s;return n?s=t===!0||t==="true":i==="false"?s=t===!1:Array.isArray(t)?s=t.map(String).includes(String(i)):s=i===String(t),n?this.value=s:s?Array.isArray(t)?this.value=String(i):this.value=t:this.value=null,r.checked===s?Promise.resolve():(this.skipChangeValue=!0,M.enqueue(()=>{r.checked=s,e&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else if(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement){const i=Array.isArray(t)?t.join(","):t;return this.value=this.normalizeValueForElement(r,i),this.skipChangeValue=!0,M.enqueue(()=>{r.value=i===null?"":String(i),e&&((r instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(r.type)||r instanceof HTMLTextAreaElement)&&r.dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0})))}).finally(()=>{this.skipChangeValue=!1})}else return m.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve()}getValue(){return this.value}clearValue(){this.value=null}normalizeValueForElement(t,e){if(t instanceof HTMLInputElement&&t.type==="number"){if(e===null||e==="")return null;const r=typeof e=="number"?e:Number(e);return Number.isNaN(r)?null:r}return e}syncValue(){const t=this.getTarget();if(t instanceof HTMLInputElement)if(t.type==="checkbox"||t.type==="radio"){const e=t.type==="checkbox"&&t.value==="true";if(t.checked){const r=t.value;e?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=t.value;e?this.value=!1:r==="false"?this.value=!0:this.value=null}}else this.value=this.normalizeValueForElement(t,t.value);else t instanceof HTMLTextAreaElement?this.value=t.value:t instanceof HTMLSelectElement&&(this.value=t.value)}setAttribute(t,e,r=!1){return this.setAttributeInternal(t,t,e,!0,r)}setAliasedAttribute(t,e,r,i=!1){return this.setAttributeInternal(t,e,r,!1,i)}removeAliasedAttribute(t,e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(t),this.skipMutationAttributes=!0;const r=this.getTarget();return M.enqueue(()=>{r.removeAttribute(t),e!==t&&r.removeAttribute(e)}).finally(()=>{this.skipMutationAttributes=!1})}setAttributeInternal(t,e,r,i,n=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return t===e?this.removeAttribute(t):this.removeAliasedAttribute(t,e);const s=new rt(t,r);if(n){const ot=this.attributeMap.get(t);if(ot&&(ot.isEvaluate||ot.isForceEvaluation())&&!s.isEvaluate&&!s.isForceEvaluation())return this.skipMutationAttributes=!0,M.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(t,s);const a=this.getTarget(),o=s.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:t,template:r}),u=s.isEvaluate||s.isRawEvaluate,c=t===e&&W.BOOLEAN_ATTRIBUTES.has(e.toLowerCase()),d=s.isSingleExpression(),p=K.joinEvaluateResults(o.results),y=o.results.length===1?o.results[0]:p,T=!s.isForceEvaluation()&&(e!==t||c||d?o.hasUnresolvedReference||y===null||y===void 0||y===!1:u&&p===""),P=s.isForceEvaluation()?r:d?y:p,A=i&&s.isEvaluate&&e==="value"&&(a instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(a.type)||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement),v=a.getRootNode(),b=A&&a===v.activeElement,S=T||P===null||P===!1?null:String(P),x=t!==e&&a.getAttribute(t)!==r,I=S===null?a.hasAttribute(e):a.getAttribute(e)!==S,$=A&&!b&&S!==null&&a.value!==S,V=e==="checked"&&a instanceof HTMLInputElement&&(a.type==="checkbox"||a.type==="radio"),C=e==="selected"&&a instanceof HTMLOptionElement,Z=v.activeElement,pt=Z!==null&&(V&&a===Z||C&&a.closest("select")===Z),_=S!==null,mt=V&&!pt&&a.checked!==_,bt=C&&!pt&&a.selected!==_;return!x&&!I&&!$&&!mt&&!bt?(A&&!b&&S!==null&&(this.value=this.normalizeValueForElement(a,S)),Promise.resolve()):(this.skipMutationAttributes=!0,M.enqueue(()=>{x&&a.setAttribute(t,r),S===null?a.removeAttribute(e):(I&&(a.setAttribute(e,S),e===`${l.prefix}bind`&&this.recordSelfWrittenBind(S)),A&&!b&&(this.value=this.normalizeValueForElement(a,S),$&&(a.value=S))),mt&&(a.checked=_),bt&&(a.selected=_)}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(t),this.skipMutationAttributes=!0;const e=this.getTarget();return M.enqueue(()=>{e.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}getAttribute(t){return this.getAttributeEvaluation(t)?.value??null}getAttributeEvaluation(t){const e=this.attributeMap.get(t);if(e===void 0)return null;const r=e.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:this.getTarget(),rawName:t,template:e.getValue()});return r.results.length===1?{value:r.results[0],hasUnresolvedReference:r.hasUnresolvedReference}:{value:K.joinEvaluateResults(r.results),hasUnresolvedReference:r.hasUnresolvedReference}}getRawAttribute(t){const e=this.attributeMap.get(t);return e===void 0?null:e.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(t){return this.attributeMap.has(t)}resolveInsertionPointFromDom(t,e){const r=t.getTarget();if(r.parentNode!==this.target)return null;const i=e?r.nextSibling:r;let n=e?r.nextSibling:r;for(;n!==null;){const s=w.get(n);if(s!==null){const a=this.children.indexOf(s);if(a!==-1)return{index:a,referenceNode:i}}n=n.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(t,e,r){if(this.skipMutationNodes)return Promise.resolve();if(t===this)return m.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let n=this.parent;for(;n;)i.add(n),n=n.getParent();if(i.has(t))return m.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=t.getParent()===this;let a=-1,o=-1;s&&(a=this.children.indexOf(t),e!==null&&(o=this.children.indexOf(e)));const u=t.getParent();u!==null&&u.removeChild(t);let c=r===void 0?e?.getTarget()||null:r;if(e===null)this.children.push(t);else{let p;if(s?a!==-1&&a<o?p=o-1:p=o:p=this.children.indexOf(e),p===-1){const y=this.resolveInsertionPointFromDom(e,!1);y===null?(m.warn("[Haori]","Reference child not found in children.",e),this.children.push(t)):(this.children.splice(y.index,0,t),c=y.referenceNode)}else this.children.splice(p,0,t)}t.setParent(this),t.setMounted(this.mounted);const d=this.skipMutationNodes;return this.skipMutationNodes=!0,M.enqueue(()=>{this.target.insertBefore(t.getTarget(),c)}).finally(()=>{this.skipMutationNodes=d})}insertAfter(t,e){if(e==null)return this.insertBefore(t,null);const r=this.children.indexOf(e);if(r===-1){const i=this.resolveInsertionPointFromDom(e,!0);return i===null?(m.warn("[Haori]","Reference child not found in children.",e),this.insertBefore(t,null)):this.insertBefore(t,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(t,this.children[r+1]||null)}getPrevious(){const t=this.getParent();if(t===null)return null;const e=t.getChildElementFragments(),r=e.indexOf(this);return r<=0?null:e[r-1]}getNext(){const t=this.getParent();if(t===null)return null;const e=t.getChildElementFragments(),r=e.indexOf(this);return r<0||r+1>=e.length?null:e[r+1]}isVisible(){return this.visible}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const t=this.getTarget();return this.display=t.style.getPropertyValue("display"),this.displayPriority=t.style.getPropertyPriority("display"),t.style.setProperty("display","none","important"),t.setAttribute(`${l.prefix}if-false`,""),Promise.resolve()}show(){if(this.visible)return Promise.resolve();const t=this.getTarget();return this.display===null||this.display===""?t.style.removeProperty("display"):t.style.setProperty("display",this.display,this.displayPriority??""),this.display=null,this.displayPriority=null,t.removeAttribute(`${l.prefix}if-false`),this.visible=!0,Promise.resolve()}closestByAttribute(t){if(this.hasAttribute(t))return this;const e=this.getParent();return e===null?null:e.closestByAttribute(t)}};W.BOOLEAN_ATTRIBUTES=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","hidden","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]);let k=W;class U extends w{constructor(t){super(t),this.skipMutation=!1,this.renderedText=null,this.text=t.textContent||"",this.contents=new K(this.text)}clone(){const t=new U(this.target.cloneNode(!0));return t.mounted=!1,t.text=this.text,t.contents=this.contents,t.renderedText=this.renderedText,t}getTarget(){return this.target}hasDynamicContent(){return this.contents.isEvaluate||this.contents.isRawEvaluate}setContent(t){return this.skipMutation||this.text===t?Promise.resolve():(this.text=t,this.contents=new K(t),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):M.enqueue(()=>{this.skipMutation=!0;let t=this.text;this.contents.isRawEvaluate?t=this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})[0]:this.contents.isEvaluate&&(t=K.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})));const e=this.contents.isRawEvaluate?this.parent.getTarget().innerHTML:this.target.textContent||"";this.renderedText===t&&e===t||(this.contents.isRawEvaluate?this.parent.getTarget().innerHTML=t:this.target.textContent=t,this.renderedText=t)}).finally(()=>{this.skipMutation=!1})}}class ft extends w{constructor(t){super(t),this.skipMutation=!1,this.text=t.textContent||""}clone(){const t=new ft(this.target.cloneNode(!0));return t.mounted=!1,t.text=this.text,t}getTarget(){return this.target}setContent(t){return this.skipMutation||this.text===t?Promise.resolve():(this.text=t,M.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const nt=class nt{constructor(t){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=t;const e=[...t.matchAll(nt.PLACEHOLDER_REGEX)];let r=0,i=!1,n=!1;for(const s of e){s.index>r&&this.contents.push({text:t.slice(r,s.index),type:0});const a={text:s[1]??s[2],type:s[1]?2:1};i=!0,n=n||a.type===2,this.contents.push(a),r=s.index+s[0].length}r<t.length&&this.contents.push({text:t.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=n,this.checkRawExpressions()}static joinEvaluateResults(t){return t===null||t.length===0?"":t.map(e=>e==null||e===!1||Number.isNaN(e)?"":typeof e!="string"?String(e):e).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let t=0;t<this.contents.length;t++)this.contents[t].type===2&&this.contents.length>1&&(m.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[t].type=1)}evaluate(t,e){return this.evaluateDetailed(t,e).results}evaluateDetailed(t,e){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(t,e,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(t,e,r,i){const n=[],s=[];let a=0,o=!1;return this.contents.forEach(u=>{try{if(r(u)){const c=et.measure(()=>z.evaluateDetailed(u.text,t)),d=c.value;a+=c.durationMs,s.push({expression:u.text,durationMs:c.durationMs}),o=o||d.unresolvedReference,n.push(d.value)}else n.push(u.text)}catch(c){m.error("[Haori]",`Error evaluating ${i} expression: ${u.text}`,c),s.push({expression:u.text,durationMs:0}),n.push("")}}),et.record(e,s,a),{results:n,hasUnresolvedReference:o}}};nt.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let K=nt;const st=class st extends K{constructor(t,e){super(e),this.forceEvaluation=st.FORCE_EVALUATION_ATTRIBUTES.includes(t)}isForceEvaluation(){return this.forceEvaluation}evaluate(t,e){return this.evaluateDetailed(t,e).results}evaluateDetailed(t,e){if(!this.isEvaluate&&!this.forceEvaluation)return{results:this.contents.map(i=>i.text),hasUnresolvedReference:!1};const r=this.evaluateWithProfile(t,e,i=>this.forceEvaluation&&i.type===0||i.type===1||i.type===2,"attribute");return this.forceEvaluation&&r.results.length>1?(m.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};st.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let rt=st;class J{static get runtime(){return l.runtime}static setRuntime(t){l.setRuntime(t)}static waitForRenders(){return M.waitForIdle()}static dialog(t){return M.enqueue(()=>{window.alert(t)},!0)}static async toast(t,e="info"){const r=document.createElement("div");r.className=`haori-toast haori-toast-${e}`,r.textContent=t,r.setAttribute("popover","manual"),r.setAttribute("role","status"),r.setAttribute("aria-live",e==="error"?"assertive":"polite"),document.body.appendChild(r),r.showPopover(),setTimeout(()=>{try{r.hidePopover()}finally{r.remove()}},3e3)}static confirm(t){return M.enqueue(()=>window.confirm(t),!0)}static openDialog(t){return M.enqueue(()=>{t instanceof HTMLDialogElement?t.showModal():m.error("[Haori]","Element is not a dialog: ",t)},!0)}static closeDialog(t){return M.enqueue(()=>{t instanceof HTMLDialogElement?t.close():m.error("[Haori]","Element is not a dialog: ",t)},!0)}static addErrorMessage(t,e){return J.addMessage(t,e,"error")}static addMessage(t,e,r){return M.enqueue(()=>{const i=t instanceof HTMLFormElement?t:t.parentElement??t;i.setAttribute("data-message",e),r!==void 0?i.setAttribute("data-message-level",r):i.removeAttribute("data-message-level")},!0)}static clearMessages(t){return M.enqueue(()=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level"),t.querySelectorAll("[data-message]").forEach(e=>{e.removeAttribute("data-message"),e.removeAttribute("data-message-level")})},!0)}static date(t,e){return At(t,e)}static number(t,e){return St(t,e)}static range(t,e,r){return Tt(t,e,r)}static pages(t,e,r){return wt(t,e,r)}static monthAdd(t,e){return at(t,e)}static monthRange(t,e){return Dt(t,e)}static pageSummary(t,e){return Rt(t,e)}static findBy(t,e,r){return Ft(t,e,r)}static sum(t,e){return Nt(t,e)}}const Ot=["addErrorMessage","clearMessages"];function yt(){const t=globalThis.window?.Haori;return Ot.every(r=>typeof t?.[r]=="function")?t:J}class E{static getValues(t){const e={};return E.getPartValues(t,e)}static getPartValues(t,e){const r=t.getAttribute("name"),i=t.getAttribute(`${l.prefix}form-object`),n=t.getAttribute(`${l.prefix}form-list`);if(r){if(n)Array.isArray(e[String(r)])?e[String(r)].push(t.getValue()):e[String(r)]=[t.getValue()];else if(E.isGroupedCheckable(t)){const s=t.getValue(),a=String(r);s===null?a in e||(e[a]=null):e[a]===null||e[a]===void 0?e[a]=s:Array.isArray(e[a])?e[a].push(s):e[a]=[e[a],s]}else e[String(r)]=t.getValue();i&&m.warn("Haori",`Element cannot have both ${l.prefix}form-object and name attributes.`);for(const s of t.getChildElementFragments())E.getPartValues(s,e)}else if(i){const s={};for(const a of t.getChildElementFragments())E.getPartValues(a,s);Object.keys(s).length>0&&(e[String(i)]=s),n&&m.warn("Haori",`Element cannot have both ${l.prefix}form-list and ${l.prefix}form-object attributes.`)}else if(n){const s=[];for(const a of t.getChildElementFragments()){const o={};E.getPartValues(a,o),Object.keys(o).length>0&&s.push(o)}s.length>0&&(e[String(n)]=s)}else for(const s of t.getChildElementFragments())E.getPartValues(s,e);return e}static setValues(t,e,r=!1){return E.setPartValues(t,e,null,r,!0)}static syncValues(t,e,r=!1){return E.setPartValues(t,e,null,r,!1)}static isGroupedCheckable(t){const e=t.getTarget();return e instanceof HTMLInputElement?e.type==="radio"?!0:e.type!=="checkbox"?!1:e.value!=="true"&&e.value!=="false":!1}static applyFragmentValue(t,e,r){return r?t.setValue(e):t.syncBindingValue(e)}static setPartValues(t,e,r=null,i=!1,n=!0){const s=[],a=t.getAttribute("name"),o=t.getAttribute(`${l.prefix}form-object`),u=t.getAttribute(`${l.prefix}form-list`),c=t.getAttribute(`${l.prefix}form-detach`);if(a){if(!c||i){const d=e[String(a)];u&&Array.isArray(d)&&r!==null?s.push(E.applyFragmentValue(t,d[r]??null,n)):typeof d>"u"||(Array.isArray(d)&&E.isGroupedCheckable(t)||typeof d=="string"||typeof d=="number"||typeof d=="boolean"||d===null?s.push(E.applyFragmentValue(t,d,n)):s.push(E.applyFragmentValue(t,String(d),n)))}}else if(o){const d=e[String(o)];if(d&&typeof d=="object")for(const p of t.getChildElementFragments())s.push(E.setPartValues(p,d,null,i,n))}else if(u){const d=e[String(u)];if(Array.isArray(d)){const p=t.getChildElementFragments();for(let y=0;y<p.length;y++){const T=p[y];d.length>y?s.push(E.setPartValues(T,d[y],y,i,n)):s.push(E.setPartValues(T,{},y,i,n))}}}else for(const d of t.getChildElementFragments())s.push(E.setPartValues(d,e,null,i,n));return Promise.all(s).then(()=>{})}static async reset(t){E.clearValues(t),await Promise.all([E.clearMessages(t),E.clearEachClones(t)]),await M.enqueue(()=>{const r=t.getTarget();if(r instanceof HTMLFormElement)r.reset();else{r.querySelectorAll("form").forEach(n=>n.reset());const i=r.parentElement;if(i){const n=r.nextElementSibling,s=document.createElement("form");s.appendChild(r),s.reset(),i.insertBefore(r,n)}}});const e=E.collectBindingTargetForms(t);for(const r of e){const i=E.getInitialBindingData(r);i&&await N.setBindingData(r.getTarget(),i)}E.syncValuesFromDom(t);for(const r of e){const i=E.getInitialBindingData(r);if(r.getRawBindingData()===null&&i===null)continue;const n=E.getValues(r),s=r.getAttribute(`${l.prefix}form-arg`),a={...i||{}};s?a[String(s)]=n:Object.assign(a,n),await N.setBindingData(r.getTarget(),a)}await N.evaluateAll(t)}static getInitialBindingData(t){const e=t.getInitialBindAttribute();return e===null?null:N.parseDataBind(e)}static syncValuesFromDom(t){const e=t.getTarget();(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&t.syncValue();for(const r of t.getChildElementFragments())E.syncValuesFromDom(r)}static collectBindingTargetForms(t){const e=t.getTarget(),r=[];e instanceof HTMLFormElement?r.push(e):r.push(...Array.from(e.querySelectorAll("form")));const i=[];for(const n of r){const s=w.get(n);s instanceof k&&i.push(s)}return i}static clearEachClones(t){const e=[],r=n=>{if(n.hasAttribute(`${l.prefix}each`))for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${l.prefix}each-before`),o=s.hasAttribute(`${l.prefix}each-after`);!a&&!o&&e.push(s.remove())}},i=n=>{r(n);for(const s of n.getChildElementFragments())i(s)};r(t);for(const n of t.getChildElementFragments())i(n);return Promise.all(e).then(()=>{})}static clearValues(t){t.clearValue();for(const e of t.getChildElementFragments())E.clearValues(e)}static clearMessages(t){return yt().clearMessages(t.getTarget())}static addErrorMessage(t,e,r){return E.addMessage(t,e,r,"error")}static addMessage(t,e,r,i){const n=[],s=yt(),a=s.addMessage,o=c=>typeof a=="function"?a.call(s,c,r,i):s.addErrorMessage(c,r),u=E.findFragmentsByKey(t,e);return u.forEach(c=>{n.push(o(c.getTarget()))}),u.length===0&&n.push(o(t.getTarget())),Promise.all(n).then(()=>{})}static findFragmentsByKey(t,e){return E.findFragmentByKeyParts(t,e.split("."))}static findFragmentByKeyParts(t,e){const r=[],i=e[0];if(e.length==1&&t.getAttribute("name")===i&&r.push(t),t.hasAttribute(`${l.prefix}form-object`))e.length>1&&t.getAttribute(`${l.prefix}form-object`)===i&&t.getChildElementFragments().forEach(s=>{r.push(...E.findFragmentByKeyParts(s,e.slice(1)))});else if(t.hasAttribute(`${l.prefix}form-list`)){if(e.length>1){const n=t.getAttribute(`${l.prefix}form-list`),s=i.lastIndexOf("["),a=i.lastIndexOf("]");if(s!==-1&&a!==-1&&s<a){const o=i.substring(0,s);if(n===o){const u=i.substring(s+1,a),c=Number(u);if(isNaN(c))m.error("Haori",`Invalid index: ${i}`);else{const d=t.getChildElementFragments().filter(p=>p.hasAttribute(`${l.prefix}row`));c<d.length&&r.push(...E.findFragmentByKeyParts(d[c],e.slice(1)))}}}}}else t.getChildElementFragments().forEach(n=>{r.push(...E.findFragmentByKeyParts(n,e))});return r}static getFormFragment(t){const e=t.getTarget();if(e instanceof HTMLFormElement||e instanceof HTMLElement&&e.hasAttribute(`${l.prefix}form`))return t;const r=t.getParent();return r?this.getFormFragment(r):null}}class R{static dispatch(t,e,r,i){const n=new CustomEvent(`haori:${e}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return t.dispatchEvent(n)}static ready(t){R.dispatch(document,"ready",{version:t})}static render(t){R.dispatch(t,"render",{target:t})}static importStart(t,e){R.dispatch(t,"importstart",{url:e,startedAt:performance.now()})}static importEnd(t,e,r,i){R.dispatch(t,"importend",{url:e,bytes:r,durationMs:performance.now()-i})}static importError(t,e,r){R.dispatch(t,"importerror",{url:e,error:r})}static bindChange(t,e,r,i="other"){const n=[],s=new Set(Object.keys(e||{})),a=new Set(Object.keys(r)),o=new Set([...s,...a]);for(const u of o){const c=e?.[u],d=r[u];c!==d&&n.push(u)}R.dispatch(t,"bindchange",{previous:e||{},next:r,changedKeys:n,reason:i})}static bindComplete(t,e=null,r="other"){R.dispatch(t,"bindcomplete",{bindArg:e,reason:r})}static eachUpdate(t,e,r,i){R.dispatch(t,"eachupdate",{added:e,removed:r,order:i,total:i.length})}static rowAdd(t,e,r,i){R.dispatch(t,"rowadd",{key:e,index:r,item:i})}static rowRemove(t,e,r){R.dispatch(t,"rowremove",{key:e,index:r})}static rowMove(t,e,r,i){R.dispatch(t,"rowmove",{key:e,from:r,to:i})}static show(t){R.dispatch(t,"show",{visible:!0})}static hide(t){R.dispatch(t,"hide",{visible:!1})}static fetchStart(t,e,r,i,n){R.dispatch(t,"fetchstart",{url:e,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(t,e,r,i){R.dispatch(t,"fetchend",{url:e,status:r,durationMs:performance.now()-i})}static fetchError(t,e,r,i,n){R.dispatch(t,"fetcherror",{url:e,status:i,error:r,durationMs:n?performance.now()-n:void 0})}}const Ht={401:"unauthorized-redirect",403:"forbidden-redirect"};function Lt(g,t){return g.replace(/\{\{([\s\S]+?)\}\}/g,(e,r)=>{try{const i=z.evaluate(String(r).trim(),t);return i==null?"":String(i)}catch{return""}})}function Ut(g,t){const e=g.getAttribute(t);if(e===null||e==="")return null;if(!e.includes("{{"))return e;const r=w.get(g),i=r instanceof k?r.getBindingData():{},n=Lt(e,i);return n===""?null:n}function Mt(g){const t=Ht[g];if(t===void 0||typeof document>"u")return!1;const e=`${l.prefix}${t}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=Ut(i,e);if(n!==null){try{if(new URL(n,window.location.href).href===window.location.href)return!1}catch{}return window.location.href=n,!0}}return!1}const Vt=["addErrorMessage","closeDialog","confirm","dialog","openDialog","toast"],jt="__haoriHistoryState__",lt="data-haori-click-lock";function ut(){const t=globalThis.window?.Haori;return Vt.every(r=>typeof t?.[r]=="function")?t:J}const qt=new Set(["GET","HEAD","OPTIONS"]);function Wt(g){return qt.has(g.toUpperCase())}function zt(g,t){for(const[e,r]of Object.entries(t))r!==void 0&&(r===null?g.append(e,""):Array.isArray(r)?r.forEach(i=>{g.append(e,String(i))}):typeof r=="object"||typeof r=="function"?g.append(e,JSON.stringify(r)):g.append(e,String(r)))}function Kt(g,t){const e=new URL(g,window.location.href),r=new URLSearchParams(e.search);return zt(r,t),e.search=r.toString(),e.toString()}function Gt(g){return g==null?null:typeof g=="string"?g:g instanceof URLSearchParams?g.toString():g instanceof FormData?Array.from(g.entries()).map(([t,e])=>e instanceof File?[t,{type:"file",name:e.name,size:e.size,mimeType:e.type}]:[t,String(e)]):String(g)}function Yt(g,t){const e=new Headers(t.headers||void 0),r=Array.from(e.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:g,method:String(t.method||"GET").toUpperCase(),headers:r,body:Gt(t.body||null)})}const f=class f{constructor(t,e=null,r=null){this.reentrantBind=!1,f.isElementFragment(t)?(this.options=f.buildOptions(t,e),this.eventType=e):(this.options=t,this.eventType=null),this.domEvent=r}static attrName(t,e,r=!1){return t?`${l.prefix}${t}-${e}`:r?`${l.prefix}fetch-${e}`:`${l.prefix}${e}`}static resolveDataParamString(t,e){return f.resolveDataParamStringDetailed(t,e).value}static resolveDataParamStringDetailed(t,e){let r=!1;return{value:t.replace(f.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=z.evaluateDetailed(s??a??"",e);return r=r||o.unresolvedReference,o.value===null||o.value===void 0||Number.isNaN(o.value)?"":typeof o.value=="object"?encodeURIComponent(JSON.stringify(o.value)):encodeURIComponent(String(o.value))}),hasUnresolvedReference:r}}static isJsonStringContext(t,e){let r=!1,i=!1;for(let n=0;n<e;n+=1){const s=t[n];if(i){i=!1;continue}if(s==="\\"){i=!0;continue}s==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(t){if(t===void 0||Number.isNaN(t))return"null";try{return JSON.stringify(t)??JSON.stringify(String(t))}catch{return JSON.stringify(String(t))}}static stringifyJsonTemplateStringContent(t){if(t==null||Number.isNaN(t))return"";const e=typeof t=="object"?f.stringifyJsonTemplateValue(t):String(t);return JSON.stringify(e).slice(1,-1)}static resolveDataJsonString(t,e){return f.resolveDataJsonStringDetailed(t,e).value}static resolveDataJsonStringDetailed(t,e){let r=!1;return{value:t.replace(f.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const u=z.evaluateDetailed(s??a??"",e);return r=r||u.unresolvedReference,f.isJsonStringContext(t,o)?f.stringifyJsonTemplateStringContent(u.value):f.stringifyJsonTemplateValue(u.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(t,e){return f.resolveDataAttributeDetailed(t,e).value}static resolveDataAttributeDetailed(t,e){const r=t.getRawAttribute(e),i=t.getAttributeEvaluation(e),n=i?.value??null,s=i?.hasUnresolvedReference??!1;if(n&&typeof n=="object"&&!Array.isArray(n))return{value:n,hasUnresolvedReference:s};if(typeof n!="string"||r===null)return{value:null,hasUnresolvedReference:s};const a=r.trim();if(f.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:N.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const u=f.resolveDataJsonStringDetailed(r,t.getBindingData());return{value:N.parseDataBind(u.value),hasUnresolvedReference:s||u.hasUnresolvedReference}}const o=f.resolveDataParamStringDetailed(r,t.getBindingData());return{value:N.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(t,e){const r={targetFragment:t};if(e){if(t.hasAttribute(f.attrName(e,"validate"))&&(r.valid=!0),t.hasAttribute(f.attrName(e,"confirm"))&&(r.confirmMessage=t.getAttribute(f.attrName(e,"confirm")).replace(/\\n/g,`
6
+ `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return r}})}static wrapBoundValues(t){const e=new WeakMap,r={};return Object.entries(t).forEach(([i,n])=>{r[i]=this.wrapBoundValue(n,e)}),r}static wrapBoundValue(t,e){if(!this.shouldWrapValue(t))return t;const r=t,i=e.get(r);if(i!==void 0)return i;const n=new Proxy(r,{get:(s,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const u=Reflect.get(s,a,o);return typeof a=="symbol"?u:this.wrapBoundValue(u,e)},has:(s,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(s,a),getOwnPropertyDescriptor:(s,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(s,a)},apply:(s,a,o)=>{const u=Reflect.apply(s,a,o);return this.isIteratorLike(u)?u:this.wrapBoundValue(u,e)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),e)});return e.set(r,n),n}static shouldWrapValue(t){if(typeof t=="function")return!0;if(t===null||typeof t!="object")return!1;if(Array.isArray(t))return!0;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}static withBlockedPropertyAccess(t){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:n})=>{Object.defineProperty(i,n,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return t()}finally{r.forEach(({target:i,property:n,descriptor:s})=>{s!==void 0&&Object.defineProperty(i,n,s)})}}static isIteratorLike(t){return t===null||typeof t!="object"?!1:typeof t.next=="function"}static containsForbiddenKeys(t){if(!t||typeof t!="object")return!1;for(const e of Object.keys(t))if(this.FORBIDDEN_BINDING_NAMES.has(e))return!0;return!1}static containsForbiddenBindingValues(t,e=new WeakSet,r=this.getForbiddenBindingValueSet()){if(!t||typeof t!="object")return!1;const i=this.forbiddenBindingValueCache.get(t);if(i!==void 0)return i;if(e.has(t))return!1;if(e.add(t),r.has(t))return this.forbiddenBindingValueCache.set(t,!0),!0;for(const n of Object.values(t)){if(typeof n=="function"){if(r.has(n))return this.forbiddenBindingValueCache.set(t,!0),!0;continue}if(this.containsForbiddenBindingValues(n,e,r))return this.forbiddenBindingValueCache.set(t,!0),!0}return this.forbiddenBindingValueCache.set(t,!1),!1}};B.MAX_IDENTIFIER_RECOVERY_COUNT=8,B.BUILTIN_NAMESPACE="haori",B.BUILTIN_HELPERS={...$t},B.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,B.forbiddenBindingValueCache=new WeakMap,B.forbiddenBindingValueCacheResetScheduled=!1,B.FORBIDDEN_NAMES=["window","self","globalThis","frames","parent","top","Function","setTimeout","setInterval","requestAnimationFrame","alert","confirm","prompt","fetch","XMLHttpRequest","Reflect","constructor","__proto__","prototype","Object","document","location","navigator","localStorage","sessionStorage","IndexedDB","history"],B.STRICT_FORBIDDEN_NAMES=["eval","arguments"],B.REBINDABLE_FORBIDDEN_NAMES=new Set(["location"]),B.FORBIDDEN_BINDING_NAMES=new Set([...B.FORBIDDEN_NAMES.filter(t=>!B.REBINDABLE_FORBIDDEN_NAMES.has(t)),"constructor","__proto__","prototype",...B.STRICT_FORBIDDEN_NAMES]),B.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),B.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),B.DISALLOWED_KEYWORDS=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","finally","for","function","if","import","in","instanceof","let","new","return","switch","this","throw","try","typeof","var","void","while","with","yield"]),B.EXPRESSION_CACHE=new Map;let z=B;class dt{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(t,e=!1){let r,i;const n=new Promise((a,o)=>{r=a,i=o}),s={task:t,timestamp:performance.now(),promise:n,resolve:r,reject:i};return e?this.queue.unshift(s):this.queue.push(s),this.scheduleProcessing(),n}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const t=performance.now();for(;this.queue.length>0;){const e=this.queue.shift();if(!e)return;try{const r=await e.task();e.resolve(r)}catch(r){e.reject(r),m.error("[Haori]",`Task ${e.timestamp} failed:`,r)}if(performance.now()-t>this.MAX_BUDGET)break}}catch(t){m.error("[Haori]","Error processing queue:",t)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const t=this.queue.map(e=>e.promise);t.length>0&&await Promise.allSettled(t)}async waitForIdle(t=1e3){let e=0,r=0;for(;e<2&&r<t;)this.processing||this.queue.length>0?(await this.wait(),e=0):e+=1,await dt.nextTick(),r+=1}static nextTick(){return new Promise(t=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>t()):setTimeout(t,0)})}}const pt=class pt{static enqueue(t,e=!1){return this.ASYNC_QUEUE.enqueue(t,e)}static wait(){return this.ASYNC_QUEUE.wait()}static waitForIdle(t=1e3){return this.ASYNC_QUEUE.waitForIdle(t)}};pt.ASYNC_QUEUE=new dt;let M=pt;const N=class N{static reset(){N.ELEMENT_STORES.clear(),N.ensureGlobalAccess()}static snapshot(){return N.ensureGlobalAccess(),[...N.ELEMENT_STORES.entries()].map(([t,e])=>({elementId:t,tagName:e.tagName,attributes:[...e.attributes.entries()].map(([r,i])=>({name:r,template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:N.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls),texts:[...e.texts.entries()].map(([r,i])=>({childIndex:Number(r),template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:N.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls)})).sort((t,e)=>{const r=t.attributes.reduce((n,s)=>n+s.calls,0)+t.texts.reduce((n,s)=>n+s.calls,0);return e.attributes.reduce((n,s)=>n+s.calls,0)+e.texts.reduce((n,s)=>n+s.calls,0)-r})}static record(t,e,r){if(!H.isEnabled()||!t||e.length===0)return;N.ensureGlobalAccess();const i=N.getOrCreateElementStore(t.element);if(t.kind==="attribute"){const s=N.getOrCreateCounter(i.attributes,t.rawName,t.template);N.updateCounter(s,e,r);return}const n=N.getOrCreateCounter(i.texts,String(t.childIndex),t.template);N.updateCounter(n,e,r)}static ensureGlobalAccess(){if(!H.isEnabled())return;const t=globalThis;t[N.GLOBAL_KEY]===void 0&&(t[N.GLOBAL_KEY]={reset:()=>N.reset(),snapshot:()=>N.snapshot()})}static getOrCreateElementStore(t){const e=N.createElementId(t),r=N.ELEMENT_STORES.get(e);if(r)return r;const i={tagName:t.tagName.toLowerCase(),attributes:new Map,texts:new Map};return N.ELEMENT_STORES.set(e,i),i}static getOrCreateCounter(t,e,r){const i=t.get(e);if(i)return i;const n={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return t.set(e,n),n}static getOrCreatePlaceholder(t,e){const r=t.get(e);if(r)return r;const i={calls:0,totalDurationMs:0,maxDurationMs:0};return t.set(e,i),i}static updateCounter(t,e,r){t.calls+=1,t.totalDurationMs+=r,t.maxDurationMs=Math.max(t.maxDurationMs,r),e.forEach(i=>{const n=N.getOrCreatePlaceholder(t.placeholders,i.expression);n.calls+=1,n.totalDurationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs)})}static sortPlaceholders(t){return[...t.entries()].map(([e,r])=>({expression:e,calls:r.calls,totalDurationMs:r.totalDurationMs,maxDurationMs:r.maxDurationMs})).sort((e,r)=>r.calls!==e.calls?r.calls-e.calls:r.totalDurationMs-e.totalDurationMs)}static now(){return globalThis.performance?.now()??Date.now()}static measure(t){const e=N.now();return{value:t(),durationMs:N.now()-e}}static createElementId(t){const e=[];let r=t;for(;r;){let i=r.tagName.toLowerCase();const n=r.getAttribute("id")||"";if(n.trim()!==""){i+=`#${n.trim()}`,e.unshift(i);break}const s=r.getAttribute(`${l.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${l.prefix}derive-name="${s.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),e.unshift(i),r=a}return e.join(" > ")}};N.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",N.ELEMENT_STORES=new Map;let et=N;const Y=class Y{constructor(t){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=t,Y.FRAGMENT_CACHE.set(t,this)}static get(t){if(t==null)return null;if(Y.FRAGMENT_CACHE.has(t))return Y.FRAGMENT_CACHE.get(t);let e;switch(t.nodeType){case Node.ELEMENT_NODE:e=new k(t);break;case Node.TEXT_NODE:e=new U(t);break;case Node.COMMENT_NODE:e=new ft(t);break;default:return m.warn("[Haori]","Unsupported node type:",t.nodeType),null}return e}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const t=this.parent,e=t.skipMutationNodes;return M.enqueue(()=>{t.skipMutationNodes=!0,this.target.parentNode===t.getTarget()&&t.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{t.skipMutationNodes=e})}else{const t=this.target.parentNode;if(t)return M.enqueue(()=>{this.target.parentNode===t&&t.removeChild(this.target),this.mounted=!1});this.mounted=!1}return Promise.resolve()}mount(){if(this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const t=this.parent,e=t.skipMutationNodes;return M.enqueue(()=>{t.skipMutationNodes=!0,this.target.parentNode!==t.getTarget()&&t.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{t.skipMutationNodes=e})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(t){this.mounted=t}remove(t=!0){return this.parent&&this.parent.removeChild(this),Y.FRAGMENT_CACHE.delete(this.target),t?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(t){this.parent=t}};Y.FRAGMENT_CACHE=new WeakMap;let w=Y;const W=class W extends w{constructor(t){super(t),this.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],this.children=[],this.attributeMap=new Map,this.bindingData=null,this.bindingWorkChain=Promise.resolve(),this.bindingWorkActive=0,this.initialBindAttribute=null,this.derivedBindingData=null,this.bindingDataCache=null,this.descendantBindingDataCache=null,this.visible=!0,this.display=null,this.displayPriority=null,this.template=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.skipMutationAttributes=!1,this.skipChangeValue=!1,this.selfWrittenBind=new Map,this.syncValue(),this.initialBindAttribute=t.getAttribute(`${l.prefix}bind`),t.getAttributeNames().forEach(e=>{const r=t.getAttribute(e);if(r!==null&&!this.attributeMap.has(e)){const i=new rt(e,r);this.attributeMap.set(e,i)}}),t.childNodes.forEach(e=>{const r=w.get(e);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(t=>t instanceof W)}pushChild(t){this.children.push(t),t.setParent(this)}removeChild(t){const e=this.children.indexOf(t);if(e<0){m.warn("[Haori]","Child fragment not found.",t);return}this.children.splice(e,1),t.setParent(null)}clone(){const t=new W(this.target.cloneNode(!1));return this.attributeMap.forEach((e,r)=>{t.attributeMap.set(r,e)}),this.children.forEach(e=>{const r=e.clone();t.getTarget().appendChild(r.getTarget()),t.pushChild(r)}),t.mounted=!1,t.bindingData=this.bindingData,t.derivedBindingData=this.derivedBindingData,t.clearBindingDataCache(),t.visible=!0,t.display=this.display,t.displayPriority=this.displayPriority,t.template=this.template,t.renderSignature=this.renderSignature,t.eachInputSignature=this.eachInputSignature,t.deriveSubtreeSignature=null,t.deriveInputSignature=null,t.freshInitializationSkippable=this.freshInitializationSkippable,t.normalizeClonedVisibilityState(),t}normalizeClonedVisibilityState(){(this.visible===!1||this.getTarget().style.display==="none"||this.getTarget().hasAttribute(`${l.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${l.prefix}if-false`)),this.children.forEach(t=>{t instanceof W&&t.normalizeClonedVisibilityState()})}remove(t=!0){const e=[];return this.children.forEach(r=>{e.push(r.remove(!1))}),this.children.length=0,this.attributeMap.clear(),this.bindingData=null,this.bindingDataCache=null,this.derivedBindingData=null,this.descendantBindingDataCache=null,this.template&&(e.push(this.template.remove(!1)),this.template=null),this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,e.push(super.remove(t)),Promise.all(e).then(()=>{})}getTarget(){return this.target}getBindingData(){return this.bindingDataCache?this.bindingDataCache:(this.bindingDataCache={},this.parent&&Object.assign(this.bindingDataCache,this.parent.getDescendantBindingData()),this.bindingData&&Object.assign(this.bindingDataCache,this.bindingData),this.bindingDataCache)}getDescendantBindingData(){return this.descendantBindingDataCache?this.descendantBindingDataCache:(this.descendantBindingDataCache={...this.getBindingData()},this.derivedBindingData&&Object.assign(this.descendantBindingDataCache,this.derivedBindingData),this.descendantBindingDataCache)}getRawBindingData(){return this.bindingData}recordSelfWrittenBind(t){this.selfWrittenBind.size>64&&this.selfWrittenBind.clear(),this.selfWrittenBind.set(t,(this.selfWrittenBind.get(t)??0)+1)}consumeSelfWrittenBind(t){const e=this.selfWrittenBind.get(t);return e===void 0?!1:(e<=1?this.selfWrittenBind.delete(t):this.selfWrittenBind.set(t,e-1),!0)}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(t){this.bindingData=t,this.clearBindingDataCache()}isExecutingBindingWork(){return this.bindingWorkActive>0}markBindingWorkStart(){this.bindingWorkActive++}markBindingWorkEnd(){this.bindingWorkActive>0&&this.bindingWorkActive--}enqueueBindingWork(t){const e=this.bindingWorkChain.then(t,t);return this.bindingWorkChain=e.then(()=>{},()=>{}),e}getInitialBindAttribute(){return this.initialBindAttribute}setDerivedBindingData(t){this.derivedBindingData=t,this.clearBindingDataCache()}setParent(t){this.parent!==t&&(this.parent=t,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(t=>{t instanceof W&&t.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(t){this.template=t}setListKey(t){this.listKey=t}getListKey(){return this.listKey}getRenderSignature(){return this.renderSignature}setRenderSignature(t){this.renderSignature=t}getEachInputSignature(){return this.eachInputSignature}setEachInputSignature(t){this.eachInputSignature=t}getDeriveSubtreeSignature(){return this.deriveSubtreeSignature}setDeriveSubtreeSignature(t){this.deriveSubtreeSignature=t}getDeriveInputSignature(){return this.deriveInputSignature}setDeriveInputSignature(t){this.deriveInputSignature=t}isFreshInitializationSkippable(){return this.freshInitializationSkippable}setFreshInitializationSkippable(t){this.freshInitializationSkippable=t}setValue(t){return this.applyValue(t,!0)}syncBindingValue(t){return this.applyValue(t,!1)}applyValue(t,e){if(this.skipChangeValue||this.value===t)return Promise.resolve();const r=this.getTarget();if(r instanceof HTMLInputElement&&(r.type==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),n=r.type==="checkbox"&&i==="true";let s;return n?s=t===!0||t==="true":i==="false"?s=t===!1:Array.isArray(t)?s=t.map(String).includes(String(i)):s=i===String(t),n?this.value=s:s?Array.isArray(t)?this.value=String(i):this.value=t:this.value=null,r.checked===s?Promise.resolve():(this.skipChangeValue=!0,M.enqueue(()=>{r.checked=s,e&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else if(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement){const i=Array.isArray(t)?t.join(","):t;return this.value=this.normalizeValueForElement(r,i),this.skipChangeValue=!0,M.enqueue(()=>{r.value=i===null?"":String(i),e&&((r instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(r.type)||r instanceof HTMLTextAreaElement)&&r.dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0})))}).finally(()=>{this.skipChangeValue=!1})}else return m.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve()}getValue(){return this.value}clearValue(){this.value=null}normalizeValueForElement(t,e){if(t instanceof HTMLInputElement&&t.type==="number"){if(e===null||e==="")return null;const r=typeof e=="number"?e:Number(e);return Number.isNaN(r)?null:r}return e}syncValue(){const t=this.getTarget();if(t instanceof HTMLInputElement)if(t.type==="checkbox"||t.type==="radio"){const e=t.type==="checkbox"&&t.value==="true";if(t.checked){const r=t.value;e?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=t.value;e?this.value=!1:r==="false"?this.value=!0:this.value=null}}else this.value=this.normalizeValueForElement(t,t.value);else t instanceof HTMLTextAreaElement?this.value=t.value:t instanceof HTMLSelectElement&&(this.value=t.value)}setAttribute(t,e,r=!1){return this.setAttributeInternal(t,t,e,!0,r)}setAliasedAttribute(t,e,r,i=!1){return this.setAttributeInternal(t,e,r,!1,i)}removeAliasedAttribute(t,e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(t),this.skipMutationAttributes=!0;const r=this.getTarget();return M.enqueue(()=>{r.removeAttribute(t),e!==t&&r.removeAttribute(e)}).finally(()=>{this.skipMutationAttributes=!1})}setAttributeInternal(t,e,r,i,n=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return t===e?this.removeAttribute(t):this.removeAliasedAttribute(t,e);const s=new rt(t,r);if(n){const ot=this.attributeMap.get(t);if(ot&&(ot.isEvaluate||ot.isForceEvaluation())&&!s.isEvaluate&&!s.isForceEvaluation())return this.skipMutationAttributes=!0,M.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(t,s);const a=this.getTarget(),o=s.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:t,template:r}),u=s.isEvaluate||s.isRawEvaluate,c=t===e&&W.BOOLEAN_ATTRIBUTES.has(e.toLowerCase()),d=s.isSingleExpression(),g=K.joinEvaluateResults(o.results),y=o.results.length===1?o.results[0]:g,T=!s.isForceEvaluation()&&(e!==t||c||d?o.hasUnresolvedReference||y===null||y===void 0||y===!1:u&&g===""),P=s.isForceEvaluation()?r:d?y:g,A=i&&s.isEvaluate&&e==="value"&&(a instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(a.type)||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement),v=a.getRootNode(),b=A&&a===v.activeElement,S=T||P===null||P===!1?null:String(P),x=t!==e&&a.getAttribute(t)!==r,I=S===null?a.hasAttribute(e):a.getAttribute(e)!==S,$=A&&!b&&S!==null&&a.value!==S,V=e==="checked"&&a instanceof HTMLInputElement&&(a.type==="checkbox"||a.type==="radio"),C=e==="selected"&&a instanceof HTMLOptionElement,Z=v.activeElement,gt=Z!==null&&(V&&a===Z||C&&a.closest("select")===Z),_=S!==null,mt=V&&!gt&&a.checked!==_,bt=C&&!gt&&a.selected!==_;return!x&&!I&&!$&&!mt&&!bt?(A&&!b&&S!==null&&(this.value=this.normalizeValueForElement(a,S)),Promise.resolve()):(this.skipMutationAttributes=!0,M.enqueue(()=>{x&&a.setAttribute(t,r),S===null?a.removeAttribute(e):(I&&(a.setAttribute(e,S),e===`${l.prefix}bind`&&this.recordSelfWrittenBind(S)),A&&!b&&(this.value=this.normalizeValueForElement(a,S),$&&(a.value=S))),mt&&(a.checked=_),bt&&(a.selected=_)}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(t),this.skipMutationAttributes=!0;const e=this.getTarget();return M.enqueue(()=>{e.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}getAttribute(t){return this.getAttributeEvaluation(t)?.value??null}getAttributeEvaluation(t){const e=this.attributeMap.get(t);if(e===void 0)return null;const r=e.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:this.getTarget(),rawName:t,template:e.getValue()});return r.results.length===1?{value:r.results[0],hasUnresolvedReference:r.hasUnresolvedReference}:{value:K.joinEvaluateResults(r.results),hasUnresolvedReference:r.hasUnresolvedReference}}getRawAttribute(t){const e=this.attributeMap.get(t);return e===void 0?null:e.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(t){return this.attributeMap.has(t)}resolveInsertionPointFromDom(t,e){const r=t.getTarget();if(r.parentNode!==this.target)return null;const i=e?r.nextSibling:r;let n=e?r.nextSibling:r;for(;n!==null;){const s=w.get(n);if(s!==null){const a=this.children.indexOf(s);if(a!==-1)return{index:a,referenceNode:i}}n=n.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(t,e,r){if(this.skipMutationNodes)return Promise.resolve();if(t===this)return m.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let n=this.parent;for(;n;)i.add(n),n=n.getParent();if(i.has(t))return m.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=t.getParent()===this;let a=-1,o=-1;s&&(a=this.children.indexOf(t),e!==null&&(o=this.children.indexOf(e)));const u=t.getParent();u!==null&&u.removeChild(t);let c=r===void 0?e?.getTarget()||null:r;if(e===null)this.children.push(t);else{let g;if(s?a!==-1&&a<o?g=o-1:g=o:g=this.children.indexOf(e),g===-1){const y=this.resolveInsertionPointFromDom(e,!1);y===null?(m.warn("[Haori]","Reference child not found in children.",e),this.children.push(t)):(this.children.splice(y.index,0,t),c=y.referenceNode)}else this.children.splice(g,0,t)}t.setParent(this),t.setMounted(this.mounted);const d=this.skipMutationNodes;return this.skipMutationNodes=!0,M.enqueue(()=>{this.target.insertBefore(t.getTarget(),c)}).finally(()=>{this.skipMutationNodes=d})}insertAfter(t,e){if(e==null)return this.insertBefore(t,null);const r=this.children.indexOf(e);if(r===-1){const i=this.resolveInsertionPointFromDom(e,!0);return i===null?(m.warn("[Haori]","Reference child not found in children.",e),this.insertBefore(t,null)):this.insertBefore(t,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(t,this.children[r+1]||null)}getPrevious(){const t=this.getParent();if(t===null)return null;const e=t.getChildElementFragments(),r=e.indexOf(this);return r<=0?null:e[r-1]}getNext(){const t=this.getParent();if(t===null)return null;const e=t.getChildElementFragments(),r=e.indexOf(this);return r<0||r+1>=e.length?null:e[r+1]}isVisible(){return this.visible}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const t=this.getTarget();return this.display=t.style.getPropertyValue("display"),this.displayPriority=t.style.getPropertyPriority("display"),t.style.setProperty("display","none","important"),t.setAttribute(`${l.prefix}if-false`,""),Promise.resolve()}show(){if(this.visible)return Promise.resolve();const t=this.getTarget();return this.display===null||this.display===""?t.style.removeProperty("display"):t.style.setProperty("display",this.display,this.displayPriority??""),this.display=null,this.displayPriority=null,t.removeAttribute(`${l.prefix}if-false`),this.visible=!0,Promise.resolve()}closestByAttribute(t){if(this.hasAttribute(t))return this;const e=this.getParent();return e===null?null:e.closestByAttribute(t)}};W.BOOLEAN_ATTRIBUTES=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","hidden","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]);let k=W;class U extends w{constructor(t){super(t),this.skipMutation=!1,this.renderedText=null,this.text=t.textContent||"",this.contents=new K(this.text)}clone(){const t=new U(this.target.cloneNode(!0));return t.mounted=!1,t.text=this.text,t.contents=this.contents,t.renderedText=this.renderedText,t}getTarget(){return this.target}hasDynamicContent(){return this.contents.isEvaluate||this.contents.isRawEvaluate}setContent(t){return this.skipMutation||this.text===t?Promise.resolve():(this.text=t,this.contents=new K(t),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):M.enqueue(()=>{this.skipMutation=!0;let t=this.text;this.contents.isRawEvaluate?t=this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})[0]:this.contents.isEvaluate&&(t=K.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})));const e=this.contents.isRawEvaluate?this.parent.getTarget().innerHTML:this.target.textContent||"";this.renderedText===t&&e===t||(this.contents.isRawEvaluate?this.parent.getTarget().innerHTML=t:this.target.textContent=t,this.renderedText=t)}).finally(()=>{this.skipMutation=!1})}}class ft extends w{constructor(t){super(t),this.skipMutation=!1,this.text=t.textContent||""}clone(){const t=new ft(this.target.cloneNode(!0));return t.mounted=!1,t.text=this.text,t}getTarget(){return this.target}setContent(t){return this.skipMutation||this.text===t?Promise.resolve():(this.text=t,M.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const nt=class nt{constructor(t){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=t;const e=[...t.matchAll(nt.PLACEHOLDER_REGEX)];let r=0,i=!1,n=!1;for(const s of e){s.index>r&&this.contents.push({text:t.slice(r,s.index),type:0});const a={text:s[1]??s[2],type:s[1]?2:1};i=!0,n=n||a.type===2,this.contents.push(a),r=s.index+s[0].length}r<t.length&&this.contents.push({text:t.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=n,this.checkRawExpressions()}static joinEvaluateResults(t){return t===null||t.length===0?"":t.map(e=>e==null||e===!1||Number.isNaN(e)?"":typeof e!="string"?String(e):e).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let t=0;t<this.contents.length;t++)this.contents[t].type===2&&this.contents.length>1&&(m.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[t].type=1)}evaluate(t,e){return this.evaluateDetailed(t,e).results}evaluateDetailed(t,e){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(t,e,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(t,e,r,i){const n=[],s=[];let a=0,o=!1;return this.contents.forEach(u=>{try{if(r(u)){const c=et.measure(()=>z.evaluateDetailed(u.text,t)),d=c.value;a+=c.durationMs,s.push({expression:u.text,durationMs:c.durationMs}),o=o||d.unresolvedReference,n.push(d.value)}else n.push(u.text)}catch(c){m.error("[Haori]",`Error evaluating ${i} expression: ${u.text}`,c),s.push({expression:u.text,durationMs:0}),n.push("")}}),et.record(e,s,a),{results:n,hasUnresolvedReference:o}}};nt.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let K=nt;const st=class st extends K{constructor(t,e){super(e),this.forceEvaluation=st.FORCE_EVALUATION_ATTRIBUTES.includes(t)}isForceEvaluation(){return this.forceEvaluation}evaluate(t,e){return this.evaluateDetailed(t,e).results}evaluateDetailed(t,e){if(!this.isEvaluate&&!this.forceEvaluation)return{results:this.contents.map(i=>i.text),hasUnresolvedReference:!1};const r=this.evaluateWithProfile(t,e,i=>this.forceEvaluation&&i.type===0||i.type===1||i.type===2,"attribute");return this.forceEvaluation&&r.results.length>1?(m.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};st.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let rt=st;class J{static get runtime(){return l.runtime}static setRuntime(t){l.setRuntime(t)}static waitForRenders(){return M.waitForIdle()}static dialog(t){return M.enqueue(()=>{window.alert(t)},!0)}static async toast(t,e="info"){const r=document.createElement("div");r.className=`haori-toast haori-toast-${e}`,r.textContent=t,r.setAttribute("popover","manual"),r.setAttribute("role","status"),r.setAttribute("aria-live",e==="error"?"assertive":"polite"),document.body.appendChild(r),r.showPopover(),setTimeout(()=>{try{r.hidePopover()}finally{r.remove()}},3e3)}static confirm(t){return M.enqueue(()=>window.confirm(t),!0)}static openDialog(t){return M.enqueue(()=>{t instanceof HTMLDialogElement?t.showModal():m.error("[Haori]","Element is not a dialog: ",t)},!0)}static closeDialog(t){return M.enqueue(()=>{t instanceof HTMLDialogElement?t.close():m.error("[Haori]","Element is not a dialog: ",t)},!0)}static addErrorMessage(t,e){return J.addMessage(t,e,"error")}static addMessage(t,e,r){return M.enqueue(()=>{const i=t instanceof HTMLFormElement?t:t.parentElement??t;i.setAttribute("data-message",e),r!==void 0?i.setAttribute("data-message-level",r):i.removeAttribute("data-message-level")},!0)}static clearMessages(t){return M.enqueue(()=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level"),t.querySelectorAll("[data-message]").forEach(e=>{e.removeAttribute("data-message"),e.removeAttribute("data-message-level")})},!0)}static date(t,e){return At(t,e)}static number(t,e){return St(t,e)}static range(t,e,r){return Tt(t,e,r)}static pages(t,e,r){return wt(t,e,r)}static monthAdd(t,e){return at(t,e)}static monthRange(t,e){return Dt(t,e)}static pageSummary(t,e){return Rt(t,e)}static findBy(t,e,r){return Nt(t,e,r)}static sum(t,e){return Ft(t,e)}}const Ot=["addErrorMessage","clearMessages"];function yt(){const t=globalThis.window?.Haori;return Ot.every(r=>typeof t?.[r]=="function")?t:J}class E{static getValues(t){const e={};return E.getPartValues(t,e)}static getPartValues(t,e){const r=t.getAttribute("name"),i=t.getAttribute(`${l.prefix}form-object`),n=t.getAttribute(`${l.prefix}form-list`);if(r){if(n)Array.isArray(e[String(r)])?e[String(r)].push(t.getValue()):e[String(r)]=[t.getValue()];else if(E.isGroupedCheckable(t)){const s=t.getValue(),a=String(r);s===null?a in e||(e[a]=null):e[a]===null||e[a]===void 0?e[a]=s:Array.isArray(e[a])?e[a].push(s):e[a]=[e[a],s]}else e[String(r)]=t.getValue();i&&m.warn("Haori",`Element cannot have both ${l.prefix}form-object and name attributes.`);for(const s of t.getChildElementFragments())E.getPartValues(s,e)}else if(i){const s={};for(const a of t.getChildElementFragments())E.getPartValues(a,s);Object.keys(s).length>0&&(e[String(i)]=s),n&&m.warn("Haori",`Element cannot have both ${l.prefix}form-list and ${l.prefix}form-object attributes.`)}else if(n){const s=[];for(const a of t.getChildElementFragments()){const o={};E.getPartValues(a,o),Object.keys(o).length>0&&s.push(o)}s.length>0&&(e[String(n)]=s)}else for(const s of t.getChildElementFragments())E.getPartValues(s,e);return e}static setValues(t,e,r=!1){return E.setPartValues(t,e,null,r,!0)}static syncValues(t,e,r=!1){return E.setPartValues(t,e,null,r,!1)}static isGroupedCheckable(t){const e=t.getTarget();return e instanceof HTMLInputElement?e.type==="radio"?!0:e.type!=="checkbox"?!1:e.value!=="true"&&e.value!=="false":!1}static applyFragmentValue(t,e,r){return r?t.setValue(e):t.syncBindingValue(e)}static setPartValues(t,e,r=null,i=!1,n=!0){const s=[],a=t.getAttribute("name"),o=t.getAttribute(`${l.prefix}form-object`),u=t.getAttribute(`${l.prefix}form-list`),c=t.getAttribute(`${l.prefix}form-detach`);if(a){if(!c||i){const d=e[String(a)];u&&Array.isArray(d)&&r!==null?s.push(E.applyFragmentValue(t,d[r]??null,n)):typeof d>"u"||(Array.isArray(d)&&E.isGroupedCheckable(t)||typeof d=="string"||typeof d=="number"||typeof d=="boolean"||d===null?s.push(E.applyFragmentValue(t,d,n)):s.push(E.applyFragmentValue(t,String(d),n)))}}else if(o){const d=e[String(o)];if(d&&typeof d=="object")for(const g of t.getChildElementFragments())s.push(E.setPartValues(g,d,null,i,n))}else if(u){const d=e[String(u)];if(Array.isArray(d)){const g=t.getChildElementFragments();for(let y=0;y<g.length;y++){const T=g[y];d.length>y?s.push(E.setPartValues(T,d[y],y,i,n)):s.push(E.setPartValues(T,{},y,i,n))}}}else for(const d of t.getChildElementFragments())s.push(E.setPartValues(d,e,null,i,n));return Promise.all(s).then(()=>{})}static async reset(t){E.clearValues(t),await Promise.all([E.clearMessages(t),E.clearEachClones(t)]),await M.enqueue(()=>{const r=t.getTarget();if(r instanceof HTMLFormElement)r.reset();else{r.querySelectorAll("form").forEach(n=>n.reset());const i=r.parentElement;if(i){const n=r.nextElementSibling,s=document.createElement("form");s.appendChild(r),s.reset(),i.insertBefore(r,n)}}});const e=E.collectBindingTargetForms(t);for(const r of e){const i=E.getInitialBindingData(r);i&&await F.setBindingData(r.getTarget(),i)}E.syncValuesFromDom(t);for(const r of e){const i=E.getInitialBindingData(r);if(r.getRawBindingData()===null&&i===null)continue;const n=E.getValues(r),s=r.getAttribute(`${l.prefix}form-arg`),a={...i||{}};s?a[String(s)]=n:Object.assign(a,n),await F.setBindingData(r.getTarget(),a)}await F.evaluateAll(t)}static getInitialBindingData(t){const e=t.getInitialBindAttribute();return e===null?null:F.parseDataBind(e)}static syncValuesFromDom(t){const e=t.getTarget();(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&t.syncValue();for(const r of t.getChildElementFragments())E.syncValuesFromDom(r)}static collectBindingTargetForms(t){const e=t.getTarget(),r=[];e instanceof HTMLFormElement?r.push(e):r.push(...Array.from(e.querySelectorAll("form")));const i=[];for(const n of r){const s=w.get(n);s instanceof k&&i.push(s)}return i}static clearEachClones(t){const e=[],r=n=>{if(n.hasAttribute(`${l.prefix}each`))for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${l.prefix}each-before`),o=s.hasAttribute(`${l.prefix}each-after`);!a&&!o&&e.push(s.remove())}},i=n=>{r(n);for(const s of n.getChildElementFragments())i(s)};r(t);for(const n of t.getChildElementFragments())i(n);return Promise.all(e).then(()=>{})}static clearValues(t){t.clearValue();for(const e of t.getChildElementFragments())E.clearValues(e)}static clearMessages(t){return yt().clearMessages(t.getTarget())}static addErrorMessage(t,e,r){return E.addMessage(t,e,r,"error")}static addMessage(t,e,r,i){const n=[],s=yt(),a=s.addMessage,o=c=>typeof a=="function"?a.call(s,c,r,i):s.addErrorMessage(c,r),u=E.findFragmentsByKey(t,e);return u.forEach(c=>{n.push(o(c.getTarget()))}),u.length===0&&n.push(o(t.getTarget())),Promise.all(n).then(()=>{})}static findFragmentsByKey(t,e){return E.findFragmentByKeyParts(t,e.split("."))}static findFragmentByKeyParts(t,e){const r=[],i=e[0];if(e.length==1&&t.getAttribute("name")===i&&r.push(t),t.hasAttribute(`${l.prefix}form-object`))e.length>1&&t.getAttribute(`${l.prefix}form-object`)===i&&t.getChildElementFragments().forEach(s=>{r.push(...E.findFragmentByKeyParts(s,e.slice(1)))});else if(t.hasAttribute(`${l.prefix}form-list`)){if(e.length>1){const n=t.getAttribute(`${l.prefix}form-list`),s=i.lastIndexOf("["),a=i.lastIndexOf("]");if(s!==-1&&a!==-1&&s<a){const o=i.substring(0,s);if(n===o){const u=i.substring(s+1,a),c=Number(u);if(isNaN(c))m.error("Haori",`Invalid index: ${i}`);else{const d=t.getChildElementFragments().filter(g=>g.hasAttribute(`${l.prefix}row`));c<d.length&&r.push(...E.findFragmentByKeyParts(d[c],e.slice(1)))}}}}}else t.getChildElementFragments().forEach(n=>{r.push(...E.findFragmentByKeyParts(n,e))});return r}static getFormFragment(t){const e=t.getTarget();if(e instanceof HTMLFormElement||e instanceof HTMLElement&&e.hasAttribute(`${l.prefix}form`))return t;const r=t.getParent();return r?this.getFormFragment(r):null}}class R{static dispatch(t,e,r,i){const n=new CustomEvent(`haori:${e}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return t.dispatchEvent(n)}static ready(t){R.dispatch(document,"ready",{version:t})}static render(t){R.dispatch(t,"render",{target:t})}static importStart(t,e){R.dispatch(t,"importstart",{url:e,startedAt:performance.now()})}static importEnd(t,e,r,i){R.dispatch(t,"importend",{url:e,bytes:r,durationMs:performance.now()-i})}static importError(t,e,r){R.dispatch(t,"importerror",{url:e,error:r})}static bindChange(t,e,r,i="other"){const n=[],s=new Set(Object.keys(e||{})),a=new Set(Object.keys(r)),o=new Set([...s,...a]);for(const u of o){const c=e?.[u],d=r[u];c!==d&&n.push(u)}R.dispatch(t,"bindchange",{previous:e||{},next:r,changedKeys:n,reason:i})}static bindComplete(t,e=null,r="other"){R.dispatch(t,"bindcomplete",{bindArg:e,reason:r})}static eachUpdate(t,e,r,i){R.dispatch(t,"eachupdate",{added:e,removed:r,order:i,total:i.length})}static rowAdd(t,e,r,i){R.dispatch(t,"rowadd",{key:e,index:r,item:i})}static rowRemove(t,e,r){R.dispatch(t,"rowremove",{key:e,index:r})}static rowMove(t,e,r,i){R.dispatch(t,"rowmove",{key:e,from:r,to:i})}static show(t){R.dispatch(t,"show",{visible:!0})}static hide(t){R.dispatch(t,"hide",{visible:!1})}static fetchStart(t,e,r,i,n){R.dispatch(t,"fetchstart",{url:e,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(t,e,r,i){R.dispatch(t,"fetchend",{url:e,status:r,durationMs:performance.now()-i})}static fetchError(t,e,r,i,n){R.dispatch(t,"fetcherror",{url:e,status:i,error:r,durationMs:n?performance.now()-n:void 0})}}const Ht={401:"unauthorized-redirect",403:"forbidden-redirect"};function Lt(p,t){return p.replace(/\{\{([\s\S]+?)\}\}/g,(e,r)=>{try{const i=z.evaluate(String(r).trim(),t);return i==null?"":String(i)}catch{return""}})}function Ut(p,t){const e=p.getAttribute(t);if(e===null||e==="")return null;if(!e.includes("{{"))return e;const r=w.get(p),i=r instanceof k?r.getBindingData():{},n=Lt(e,i);return n===""?null:n}function Vt(p,t,e){const r=p.getAttribute(`${t}-return-param`);if(r===null||r==="")return e;try{if(new URL(e,window.location.href).searchParams.has(r))return e}catch{return e}const i=window.location.pathname+window.location.search+window.location.hash,n=`${encodeURIComponent(r)}=${encodeURIComponent(i)}`,s=e.indexOf("#"),a=s>=0?e.slice(s):"",o=s>=0?e.slice(0,s):e,u=o.includes("?")?"&":"?";return`${o}${u}${n}${a}`}function Mt(p){const t=Ht[p];if(t===void 0||typeof document>"u")return!1;const e=`${l.prefix}${t}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=Ut(i,e);if(n===null)continue;const s=Vt(i,e,n);try{if(new URL(s,window.location.href).href===window.location.href)return!1}catch{}return window.location.href=s,!0}return!1}const jt=["addErrorMessage","closeDialog","confirm","dialog","openDialog","toast"],qt="__haoriHistoryState__",lt="data-haori-click-lock";function ut(){const t=globalThis.window?.Haori;return jt.every(r=>typeof t?.[r]=="function")?t:J}const Wt=new Set(["GET","HEAD","OPTIONS"]);function zt(p){return Wt.has(p.toUpperCase())}function Kt(p,t){for(const[e,r]of Object.entries(t))r!==void 0&&(r===null?p.append(e,""):Array.isArray(r)?r.forEach(i=>{p.append(e,String(i))}):typeof r=="object"||typeof r=="function"?p.append(e,JSON.stringify(r)):p.append(e,String(r)))}function Gt(p,t){const e=new URL(p,window.location.href),r=new URLSearchParams(e.search);return Kt(r,t),e.search=r.toString(),e.toString()}function Yt(p){return p==null?null:typeof p=="string"?p:p instanceof URLSearchParams?p.toString():p instanceof FormData?Array.from(p.entries()).map(([t,e])=>e instanceof File?[t,{type:"file",name:e.name,size:e.size,mimeType:e.type}]:[t,String(e)]):String(p)}function Jt(p,t){const e=new Headers(t.headers||void 0),r=Array.from(e.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:p,method:String(t.method||"GET").toUpperCase(),headers:r,body:Yt(t.body||null)})}const f=class f{constructor(t,e=null,r=null){this.reentrantBind=!1,f.isElementFragment(t)?(this.options=f.buildOptions(t,e),this.eventType=e):(this.options=t,this.eventType=null),this.domEvent=r}static attrName(t,e,r=!1){return t?`${l.prefix}${t}-${e}`:r?`${l.prefix}fetch-${e}`:`${l.prefix}${e}`}static resolveDataParamString(t,e){return f.resolveDataParamStringDetailed(t,e).value}static resolveDataParamStringDetailed(t,e){let r=!1;return{value:t.replace(f.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=z.evaluateDetailed(s??a??"",e);return r=r||o.unresolvedReference,o.value===null||o.value===void 0||Number.isNaN(o.value)?"":typeof o.value=="object"?encodeURIComponent(JSON.stringify(o.value)):encodeURIComponent(String(o.value))}),hasUnresolvedReference:r}}static isJsonStringContext(t,e){let r=!1,i=!1;for(let n=0;n<e;n+=1){const s=t[n];if(i){i=!1;continue}if(s==="\\"){i=!0;continue}s==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(t){if(t===void 0||Number.isNaN(t))return"null";try{return JSON.stringify(t)??JSON.stringify(String(t))}catch{return JSON.stringify(String(t))}}static stringifyJsonTemplateStringContent(t){if(t==null||Number.isNaN(t))return"";const e=typeof t=="object"?f.stringifyJsonTemplateValue(t):String(t);return JSON.stringify(e).slice(1,-1)}static resolveDataJsonString(t,e){return f.resolveDataJsonStringDetailed(t,e).value}static resolveDataJsonStringDetailed(t,e){let r=!1;return{value:t.replace(f.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const u=z.evaluateDetailed(s??a??"",e);return r=r||u.unresolvedReference,f.isJsonStringContext(t,o)?f.stringifyJsonTemplateStringContent(u.value):f.stringifyJsonTemplateValue(u.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(t,e){return f.resolveDataAttributeDetailed(t,e).value}static resolveDataAttributeDetailed(t,e){const r=t.getRawAttribute(e),i=t.getAttributeEvaluation(e),n=i?.value??null,s=i?.hasUnresolvedReference??!1;if(n&&typeof n=="object"&&!Array.isArray(n))return{value:n,hasUnresolvedReference:s};if(typeof n!="string"||r===null)return{value:null,hasUnresolvedReference:s};const a=r.trim();if(f.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:F.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const u=f.resolveDataJsonStringDetailed(r,t.getBindingData());return{value:F.parseDataBind(u.value),hasUnresolvedReference:s||u.hasUnresolvedReference}}const o=f.resolveDataParamStringDetailed(r,t.getBindingData());return{value:F.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(t,e){const r={targetFragment:t};if(e){if(t.hasAttribute(f.attrName(e,"validate"))&&(r.valid=!0),t.hasAttribute(f.attrName(e,"confirm"))&&(r.confirmMessage=t.getAttribute(f.attrName(e,"confirm")).replace(/\\n/g,`
7
7
  `)),t.hasAttribute(f.attrName(e,"data"))&&(r.dataAttrName=f.attrName(e,"data")),t.hasAttribute(f.attrName(e,"form"))){const v=t.getRawAttribute(f.attrName(e,"form"));if(v){const b=document.body.querySelector(v);b!==null?r.formFragment=E.getFormFragment(w.get(b)):m.error("Haori",`Form element not found: ${v} (${f.attrName(e,"form")})`)}else r.formFragment=E.getFormFragment(t)}else(e==="change"||e==="input")&&(r.formFragment=E.getFormFragment(t));if(t.hasAttribute(`${l.prefix}${e}-before-run`)){const v=t.getRawAttribute(`${l.prefix}${e}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
8
8
  "use strict";
9
9
  ${v}
10
10
  `)}catch(b){m.error("Haori",`Invalid before script: ${b}`)}}const A=f.attrName(e,"run");if(t.hasAttribute(A)){const v=String(t.getAttribute(A)??"");try{r.runScript=new Function("event",`
11
11
  "use strict";
12
12
  ${v}
13
- `)}catch(b){m.error("Haori",`Invalid run script: ${b}`)}}}const i=f.attrName(e,"fetch"),n=t.hasAttribute(i);if(n){const A=t.getAttributeEvaluation(i);A&&(r.fetchHasUnresolvedReference=A.hasUnresolvedReference,r.fetchUrl=A.hasUnresolvedReference?null:A.value)}const s={};if(e){const A=f.attrName(e,"fetch-method");if(t.hasAttribute(A)){const v=t.getAttributeEvaluation(A);v?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:s.method=v?.value}}else{const A=f.attrName(null,"method",!0);if(t.hasAttribute(A)){const v=t.getAttributeEvaluation(A);v?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:s.method=v?.value}}if(e){const A=f.attrName(e,"fetch-headers");if(t.hasAttribute(A)){const v=t.getRawAttribute(A);try{s.headers=N.parseDataBind(v)}catch(b){m.error("Haori",`Invalid fetch headers: ${b}`)}}}else{const A=f.attrName(null,"headers",!0);if(t.hasAttribute(A)){const v=t.getRawAttribute(A);try{s.headers=N.parseDataBind(v)}catch(b){m.error("Haori",`Invalid fetch headers: ${b}`)}}}if(e){const A=f.attrName(e,"fetch-content-type");if(t.hasAttribute(A)){const v=t.getAttributeEvaluation(A);v?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),s.headers={...s.headers,"Content-Type":v?.value}}else if(s.method&&s.method!=="GET"&&s.method!=="HEAD"&&s.method!=="OPTIONS"){let v=!1;s.headers&&typeof s.headers=="object"&&(v="Content-Type"in s.headers),v||(s.headers={...s.headers,"Content-Type":"application/json"})}else s.method&&(s.method==="GET"||s.method==="HEAD"||s.method==="OPTIONS")&&(s.headers={...s.headers,"Content-Type":"application/x-www-form-urlencoded"})}else{const A=f.attrName(null,"content-type",!0);if(t.hasAttribute(A)){const v=t.getAttributeEvaluation(A);v?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),s.headers={...s.headers,"Content-Type":v?.value}}else if(s.method&&s.method!=="GET"&&s.method!=="HEAD"&&s.method!=="OPTIONS"){let v=!1;s.headers&&typeof s.headers=="object"&&(v="Content-Type"in s.headers),v||(s.headers={...s.headers,"Content-Type":"application/json"})}else s.method&&(s.method==="GET"||s.method==="HEAD"||s.method==="OPTIONS")&&(s.headers={...s.headers,"Content-Type":"application/x-www-form-urlencoded"})}Object.keys(s).length>0&&(r.fetchOptions=s);const a=e?f.attrName(e,"bind"):f.attrName(null,"bind",!0);if(t.hasAttribute(a)){const A=t.getRawAttribute(a);if(A){const v=document.body.querySelectorAll(A);v.length>0?(r.bindFragments=[],v.forEach(b=>{const S=w.get(b);S&&r.bindFragments.push(S)})):m.error("Haori",`Bind element not found: ${A} (${a})`)}}const o=f.attrName(e,"bind-arg"),u=f.attrName(null,"arg",!0),c=f.attrName(null,"bind-arg",!0);e?t.hasAttribute(o)&&(r.bindArg=t.getRawAttribute(o)):t.hasAttribute(u)?r.bindArg=t.getRawAttribute(u):t.hasAttribute(c)&&(r.bindArg=t.getRawAttribute(c));const d=e?f.attrName(e,"bind-params"):f.attrName(null,"bind-params",!0);if(t.hasAttribute(d)){const A=t.getRawAttribute(d);r.bindParams=A.split("&").map(v=>v.trim())}const p=e?f.attrName(e,"bind-append"):f.attrName(null,"bind-append",!0);if(t.hasAttribute(p)){const A=t.getRawAttribute(p);r.bindAppendParams=A.split("&").map(v=>v.trim()).filter(Boolean)}const y=e?f.attrName(e,"bind-merge"):f.attrName(null,"bind-merge",!0);t.hasAttribute(y)&&(r.bindMerge=!0);const T=e?f.attrName(e,"bind-transform"):f.attrName(null,"bind-transform",!0);t.hasAttribute(T)&&(r.bindTransform=t.getRawAttribute(T));const P=e?f.attrName(e,"copy-params"):null;if(P&&t.hasAttribute(P)){const A=t.getRawAttribute(P);r.copyParams=A.split("&").map(v=>v.trim()).filter(Boolean)}if(e){if(t.hasAttribute(f.attrName(e,"adjust"))){const b=t.getRawAttribute(f.attrName(e,"adjust"));if(b){const S=document.body.querySelectorAll(b);S.length>0?(r.adjustFragments=[],S.forEach(x=>{const I=w.get(x);I&&r.adjustFragments.push(I)})):m.error("Haori",`Adjust element not found: ${b} (${f.attrName(e,"adjust")})`)}if(t.hasAttribute(f.attrName(e,"adjust-value"))){const S=t.getRawAttribute(f.attrName(e,"adjust-value")),x=Number(S);isNaN(x)||(r.adjustValue=x)}}if(t.hasAttribute(f.attrName(e,"row-add"))&&(r.rowAdd=!0),t.hasAttribute(f.attrName(e,"row-remove"))&&(r.rowRemove=!0),t.hasAttribute(f.attrName(e,"row-prev"))&&(r.rowMovePrev=!0),t.hasAttribute(f.attrName(e,"row-next"))&&(r.rowMoveNext=!0),t.hasAttribute(`${l.prefix}${e}-after-run`)){const b=t.getRawAttribute(`${l.prefix}${e}-after-run`);try{r.afterCallback=new Function("response",`
13
+ `)}catch(b){m.error("Haori",`Invalid run script: ${b}`)}}}const i=f.attrName(e,"fetch"),n=t.hasAttribute(i);if(n){const A=t.getAttributeEvaluation(i);A&&(r.fetchHasUnresolvedReference=A.hasUnresolvedReference,r.fetchUrl=A.hasUnresolvedReference?null:A.value)}const s={};if(e){const A=f.attrName(e,"fetch-method");if(t.hasAttribute(A)){const v=t.getAttributeEvaluation(A);v?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:s.method=v?.value}}else{const A=f.attrName(null,"method",!0);if(t.hasAttribute(A)){const v=t.getAttributeEvaluation(A);v?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:s.method=v?.value}}if(e){const A=f.attrName(e,"fetch-headers");if(t.hasAttribute(A)){const v=t.getRawAttribute(A);try{s.headers=F.parseDataBind(v)}catch(b){m.error("Haori",`Invalid fetch headers: ${b}`)}}}else{const A=f.attrName(null,"headers",!0);if(t.hasAttribute(A)){const v=t.getRawAttribute(A);try{s.headers=F.parseDataBind(v)}catch(b){m.error("Haori",`Invalid fetch headers: ${b}`)}}}if(e){const A=f.attrName(e,"fetch-content-type");if(t.hasAttribute(A)){const v=t.getAttributeEvaluation(A);v?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),s.headers={...s.headers,"Content-Type":v?.value}}else if(s.method&&s.method!=="GET"&&s.method!=="HEAD"&&s.method!=="OPTIONS"){let v=!1;s.headers&&typeof s.headers=="object"&&(v="Content-Type"in s.headers),v||(s.headers={...s.headers,"Content-Type":"application/json"})}else s.method&&(s.method==="GET"||s.method==="HEAD"||s.method==="OPTIONS")&&(s.headers={...s.headers,"Content-Type":"application/x-www-form-urlencoded"})}else{const A=f.attrName(null,"content-type",!0);if(t.hasAttribute(A)){const v=t.getAttributeEvaluation(A);v?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),s.headers={...s.headers,"Content-Type":v?.value}}else if(s.method&&s.method!=="GET"&&s.method!=="HEAD"&&s.method!=="OPTIONS"){let v=!1;s.headers&&typeof s.headers=="object"&&(v="Content-Type"in s.headers),v||(s.headers={...s.headers,"Content-Type":"application/json"})}else s.method&&(s.method==="GET"||s.method==="HEAD"||s.method==="OPTIONS")&&(s.headers={...s.headers,"Content-Type":"application/x-www-form-urlencoded"})}Object.keys(s).length>0&&(r.fetchOptions=s);const a=e?f.attrName(e,"bind"):f.attrName(null,"bind",!0);if(t.hasAttribute(a)){const A=t.getRawAttribute(a);if(A){const v=document.body.querySelectorAll(A);v.length>0?(r.bindFragments=[],v.forEach(b=>{const S=w.get(b);S&&r.bindFragments.push(S)})):m.error("Haori",`Bind element not found: ${A} (${a})`)}}const o=f.attrName(e,"bind-arg"),u=f.attrName(null,"arg",!0),c=f.attrName(null,"bind-arg",!0);e?t.hasAttribute(o)&&(r.bindArg=t.getRawAttribute(o)):t.hasAttribute(u)?r.bindArg=t.getRawAttribute(u):t.hasAttribute(c)&&(r.bindArg=t.getRawAttribute(c));const d=e?f.attrName(e,"bind-params"):f.attrName(null,"bind-params",!0);if(t.hasAttribute(d)){const A=t.getRawAttribute(d);r.bindParams=A.split("&").map(v=>v.trim())}const g=e?f.attrName(e,"bind-append"):f.attrName(null,"bind-append",!0);if(t.hasAttribute(g)){const A=t.getRawAttribute(g);r.bindAppendParams=A.split("&").map(v=>v.trim()).filter(Boolean)}const y=e?f.attrName(e,"bind-merge"):f.attrName(null,"bind-merge",!0);t.hasAttribute(y)&&(r.bindMerge=!0);const T=e?f.attrName(e,"bind-transform"):f.attrName(null,"bind-transform",!0);t.hasAttribute(T)&&(r.bindTransform=t.getRawAttribute(T));const P=e?f.attrName(e,"copy-params"):null;if(P&&t.hasAttribute(P)){const A=t.getRawAttribute(P);r.copyParams=A.split("&").map(v=>v.trim()).filter(Boolean)}if(e){if(t.hasAttribute(f.attrName(e,"adjust"))){const b=t.getRawAttribute(f.attrName(e,"adjust"));if(b){const S=document.body.querySelectorAll(b);S.length>0?(r.adjustFragments=[],S.forEach(x=>{const I=w.get(x);I&&r.adjustFragments.push(I)})):m.error("Haori",`Adjust element not found: ${b} (${f.attrName(e,"adjust")})`)}if(t.hasAttribute(f.attrName(e,"adjust-value"))){const S=t.getRawAttribute(f.attrName(e,"adjust-value")),x=Number(S);isNaN(x)||(r.adjustValue=x)}}if(t.hasAttribute(f.attrName(e,"row-add"))&&(r.rowAdd=!0),t.hasAttribute(f.attrName(e,"row-remove"))&&(r.rowRemove=!0),t.hasAttribute(f.attrName(e,"row-prev"))&&(r.rowMovePrev=!0),t.hasAttribute(f.attrName(e,"row-next"))&&(r.rowMoveNext=!0),t.hasAttribute(`${l.prefix}${e}-after-run`)){const b=t.getRawAttribute(`${l.prefix}${e}-after-run`);try{r.afterCallback=new Function("response",`
14
14
  "use strict";
15
15
  ${b}
16
16
  `)}catch(S){m.error("Haori",`Invalid after script: ${S}`)}}if(t.hasAttribute(f.attrName(e,"dialog"))&&(r.dialogMessage=t.getAttribute(f.attrName(e,"dialog")).replace(/\\n/g,`
17
- `)),t.hasAttribute(f.attrName(e,"toast"))){r.toastMessage=t.getAttribute(f.attrName(e,"toast"));const b=t.getRawAttribute(f.attrName(e,"toast-level")),x=["info","warning","error","success"].includes(b);r.toastLevel=x?b:null}if(t.hasAttribute(f.attrName(e,"redirect"))&&(r.redirectUrl=t.getAttribute(f.attrName(e,"redirect"))),t.hasAttribute(f.attrName(e,"scroll-error"))&&(r.scrollOnError=!0),t.hasAttribute(f.attrName(e,"scroll"))&&(r.scrollTarget=t.getAttribute(f.attrName(e,"scroll"))),t.hasAttribute(f.attrName(e,"history"))&&(r.historyUrl=t.getAttribute(f.attrName(e,"history"))),t.hasAttribute(f.attrName(e,"history-data"))&&(r.historyDataAttrName=f.attrName(e,"history-data")),t.hasAttribute(f.attrName(e,"history-form"))){const b=t.getRawAttribute(f.attrName(e,"history-form"));if(b){const S=document.body.querySelector(b);S!==null?r.historyFormFragment=E.getFormFragment(w.get(S)):m.error("Haori",`Form element not found: ${b} (${f.attrName(e,"history-form")})`)}else r.historyFormFragment=E.getFormFragment(t)}["reset-before","reset","refetch","click","copy","open","close"].forEach(b=>{const S=f.attrName(e,b);if(!t.hasAttribute(S))return;const x=t.getRawAttribute(S),I=[];if(x?(document.body.querySelectorAll(x).forEach(V=>{const C=w.get(V);C&&I.push(C)}),I.length===0&&m.error("Haori",`Element not found: ${x} (${S})`)):I.push(t),I.length>0)switch(b){case"reset-before":r.resetBeforeFragments=I;break;case"reset":r.resetFragments=I;break;case"refetch":r.refetchFragments=I;break;case"click":r.clickFragments=I;break;case"copy":r.copyFragments=I;break;case"open":r.openFragments=I;break;case"close":r.closeFragments=I;break}});const v=f.attrName(e,"copy-source");if(t.hasAttribute(v)){const b=t.getRawAttribute(v);if(b){const S=document.body.querySelector(b);if(S!==null){const x=w.get(S);x?r.copySourceFragment=x:m.error("Haori",`Element is not managed by Haori: ${b} (${v})`)}else m.error("Haori",`Element not found: ${b} (${v})`)}else r.copySourceFragment=t}}if(!e&&(t.hasAttribute(f.attrName(null,"data",!0))&&(r.dataAttrName=f.attrName(null,"data",!0)),t.hasAttribute(f.attrName(null,"form",!0)))){const A=t.getRawAttribute(f.attrName(null,"form",!0));if(A){const v=document.body.querySelector(A);v!==null?r.formFragment=E.getFormFragment(w.get(v)):m.error("Haori",`Form element not found: ${A} (${f.attrName(null,"fetch-form",!0)})`)}else r.formFragment=E.getFormFragment(t)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[t],r.defaultSelfBind=!0),r}static isElementFragment(t){if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.getTarget=="function"&&typeof e.getChildElementFragments=="function"}static resolveAutoFetchSignature(t){return new f(t,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}markReentrantBind(){this.reentrantBind=!0}runWithResult(){return this.execute()}async execute(){const t=this.acquireExecutionLock();if(t===!1)return!1;try{if(Object.keys(this.options).length===0||this.options.formFragment&&this.validate(this.options.formFragment)===!1)return!1;if(this.options.runScript){const c=this.options.targetFragment?.getTarget()??null;try{this.options.runScript.call(c,this.domEvent)===!1&&this.domEvent&&this.domEvent.preventDefault()}catch(d){m.error("Haori",`Run script execution error: ${d}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(c=>E.reset(c))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let n=r.url,s=r.options;if(this.options.beforeCallback){const c=this.options.beforeCallback(n||null,s||null);if(c!=null){if(c===!1||typeof c=="object"&&c.stop)return!1;typeof c=="object"&&(n="fetchUrl"in c?c.fetchUrl:n,s="fetchOptions"in c?c.fetchOptions:s)}}const a=Object.keys(i).length>0;if(n){const c={...s||{}},d=r.requestedMethod,p=r.effectiveMethod,y=r.transportMode==="query-get",T=r.queryString;if(y&&m.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:d,effectiveMethod:p,transportMode:"query-get",url:n,payload:a?i:void 0,queryString:T}),this.options.targetFragment&&n){const P=performance.now(),A={runtime:l.runtime,requestedMethod:d,effectiveMethod:p,transportMode:y?"query-get":"http",...y?{queryString:T}:{}};return R.fetchStart(this.options.targetFragment.getTarget(),n,c,a?i:void 0,A),fetch(n,c).then(v=>this.handleFetchResult(v,n||void 0,P)).catch(v=>{throw n&&R.fetchError(this.options.targetFragment.getTarget(),n,v),v})}return fetch(n,c).then(P=>this.handleFetchResult(P,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const c=this.options.formFragment,d=c.getTarget(),p=new Set;t&&t.appliedDisabledAttribute&&this.options.targetFragment&&p.add(this.options.targetFragment);const y=c.getBindingData();Object.assign(y,i),await N.setBindingData(d,y,p)}const o=a?i:{},u=new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(u)}finally{this.releaseExecutionLock(t)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const e=this.options.targetFragment.getTarget();if(f.RUNNING_CLICK_TARGETS.has(e)||e.matches(":disabled")||e.hasAttribute("disabled")||e.hasAttribute(lt))return!1;const r=e.hasAttribute(`${l.prefix}click-no-disabled`);return f.RUNNING_CLICK_TARGETS.add(e),e.setAttribute(lt,""),r||e.setAttribute("disabled",""),{target:e,appliedDisabledAttribute:!r}}releaseExecutionLock(t){t&&(f.RUNNING_CLICK_TARGETS.delete(t.target),t.target.removeAttribute(lt),t.appliedDisabledAttribute&&t.target.removeAttribute("disabled"))}async handleFetchResult(t,e,r){const i=ut();if(!t.ok)return Mt(t.status)||(this.options.targetFragment&&e&&R.fetchError(this.options.targetFragment.getTarget(),e,new Error(`${t.status} ${t.statusText}`),t.status,r),await this.handleFetchError(t)),!1;if(this.options.targetFragment&&e&&r&&R.fetchEnd(this.options.targetFragment.getTarget(),e,t.status,r),this.options.afterCallback){const a=this.options.afterCallback(t);if(a!=null){if(a===!1||typeof a=="object"&&a.stop)return!1;typeof a=="object"&&"response"in a&&(t="response"in a?a.response:t)}}const n=[];n.push(this.bindResult(t)),n.push(this.adjust()),n.push(this.addRow()),n.push(this.removeRow()),n.push(this.movePrevRow()),n.push(this.moveNextRow()),await Promise.all(n),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(a=>E.reset(a))),await this.copy();const s=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{s.push(new f(a,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const a of this.options.clickFragments){await N.evaluateAll(a);const o=a.getTarget();typeof o.click=="function"?o.click():o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}return this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.push(i.openDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.push(i.closeDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(s),this.options.dialogMessage&&await i.dialog(this.options.dialogMessage),this.options.toastMessage&&await i.toast(this.options.toastMessage,this.options.toastLevel??"info"),this.pushHistory(),this.options.scrollTarget&&document.querySelector(this.options.scrollTarget)?.scrollIntoView({behavior:"smooth",block:"nearest"}),this.options.redirectUrl&&(window.location.href=this.options.redirectUrl),!0}pushHistory(){const t=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,e=this.resolveHistoryDataValues(),r=this.resolveHistoryFormValues(),i=e!=null,n=r!=null;if(!(!t&&!i&&!n))try{const s=t?this.options.historyUrl:window.location.pathname,a=new URL(s,window.location.href);if(a.origin!==window.location.origin){const u="history.pushState: cross-origin URL is not allowed: "+a.toString();m.error("Haori",u);return}const o=u=>{for(const[c,d]of Object.entries(u))d!=null&&(Array.isArray(d)?d.forEach(p=>a.searchParams.append(c,String(p))):typeof d=="object"?a.searchParams.set(c,JSON.stringify(d)):a.searchParams.set(c,String(d)))};i&&o(e),n&&o(r),history.pushState({[jt]:!0},"",a.toString())}catch(s){m.error("Haori",`history.pushState failed: ${s}`)}}async handleFetchError(t){let e=null;this.options.formFragment?e=this.options.formFragment:this.options.targetFragment&&(e=E.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=async s=>{const a=e?e.getTarget():document.body;await ut().addErrorMessage(a,s)},i=()=>{if(!this.options.scrollOnError)return;const s=e?e.getTarget():document.body;(s.getAttribute("data-message-level")==="error"?s:s.parentElement?.getAttribute("data-message-level")==="error"?s.parentElement:s.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((t.headers.get("Content-Type")||"").includes("application/json"))try{const s=await t.json(),a=[];if(Array.isArray(s)){const o=new Map,u=[];for(const c of s)if(c&&typeof c=="object"&&!Array.isArray(c)){const d=c.key,p=c.message,y=typeof d=="string"&&d.length>0?d:null,T=typeof p=="string"?p:p!=null?String(p):"";if(T.length===0)continue;if(y!==null){const P=o.get(y)??[];P.push(T),o.set(y,P)}else u.push(T)}else typeof c=="string"&&c.length>0&&u.push(c);for(const[c,d]of o)a.push({key:c,message:d.join(`
17
+ `)),t.hasAttribute(f.attrName(e,"toast"))){r.toastMessage=t.getAttribute(f.attrName(e,"toast"));const b=t.getRawAttribute(f.attrName(e,"toast-level")),x=["info","warning","error","success"].includes(b);r.toastLevel=x?b:null}if(t.hasAttribute(f.attrName(e,"redirect"))&&(r.redirectUrl=t.getAttribute(f.attrName(e,"redirect"))),t.hasAttribute(f.attrName(e,"scroll-error"))&&(r.scrollOnError=!0),t.hasAttribute(f.attrName(e,"scroll"))&&(r.scrollTarget=t.getAttribute(f.attrName(e,"scroll"))),t.hasAttribute(f.attrName(e,"history"))&&(r.historyUrl=t.getAttribute(f.attrName(e,"history"))),t.hasAttribute(f.attrName(e,"history-data"))&&(r.historyDataAttrName=f.attrName(e,"history-data")),t.hasAttribute(f.attrName(e,"history-form"))){const b=t.getRawAttribute(f.attrName(e,"history-form"));if(b){const S=document.body.querySelector(b);S!==null?r.historyFormFragment=E.getFormFragment(w.get(S)):m.error("Haori",`Form element not found: ${b} (${f.attrName(e,"history-form")})`)}else r.historyFormFragment=E.getFormFragment(t)}["reset-before","reset","refetch","click","copy","open","close"].forEach(b=>{const S=f.attrName(e,b);if(!t.hasAttribute(S))return;const x=t.getRawAttribute(S),I=[];if(x?(document.body.querySelectorAll(x).forEach(V=>{const C=w.get(V);C&&I.push(C)}),I.length===0&&m.error("Haori",`Element not found: ${x} (${S})`)):I.push(t),I.length>0)switch(b){case"reset-before":r.resetBeforeFragments=I;break;case"reset":r.resetFragments=I;break;case"refetch":r.refetchFragments=I;break;case"click":r.clickFragments=I;break;case"copy":r.copyFragments=I;break;case"open":r.openFragments=I;break;case"close":r.closeFragments=I;break}});const v=f.attrName(e,"copy-source");if(t.hasAttribute(v)){const b=t.getRawAttribute(v);if(b){const S=document.body.querySelector(b);if(S!==null){const x=w.get(S);x?r.copySourceFragment=x:m.error("Haori",`Element is not managed by Haori: ${b} (${v})`)}else m.error("Haori",`Element not found: ${b} (${v})`)}else r.copySourceFragment=t}}if(!e&&(t.hasAttribute(f.attrName(null,"data",!0))&&(r.dataAttrName=f.attrName(null,"data",!0)),t.hasAttribute(f.attrName(null,"form",!0)))){const A=t.getRawAttribute(f.attrName(null,"form",!0));if(A){const v=document.body.querySelector(A);v!==null?r.formFragment=E.getFormFragment(w.get(v)):m.error("Haori",`Form element not found: ${A} (${f.attrName(null,"fetch-form",!0)})`)}else r.formFragment=E.getFormFragment(t)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[t],r.defaultSelfBind=!0),r}static isElementFragment(t){if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.getTarget=="function"&&typeof e.getChildElementFragments=="function"}static resolveAutoFetchSignature(t){return new f(t,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}markReentrantBind(){this.reentrantBind=!0}runWithResult(){return this.execute()}async execute(){const t=this.acquireExecutionLock();if(t===!1)return!1;try{if(Object.keys(this.options).length===0||this.options.formFragment&&this.validate(this.options.formFragment)===!1)return!1;if(this.options.runScript){const c=this.options.targetFragment?.getTarget()??null;try{this.options.runScript.call(c,this.domEvent)===!1&&this.domEvent&&this.domEvent.preventDefault()}catch(d){m.error("Haori",`Run script execution error: ${d}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(c=>E.reset(c))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let n=r.url,s=r.options;if(this.options.beforeCallback){const c=this.options.beforeCallback(n||null,s||null);if(c!=null){if(c===!1||typeof c=="object"&&c.stop)return!1;typeof c=="object"&&(n="fetchUrl"in c?c.fetchUrl:n,s="fetchOptions"in c?c.fetchOptions:s)}}const a=Object.keys(i).length>0;if(n){const c={...s||{}},d=r.requestedMethod,g=r.effectiveMethod,y=r.transportMode==="query-get",T=r.queryString;if(y&&m.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:d,effectiveMethod:g,transportMode:"query-get",url:n,payload:a?i:void 0,queryString:T}),this.options.targetFragment&&n){const P=performance.now(),A={runtime:l.runtime,requestedMethod:d,effectiveMethod:g,transportMode:y?"query-get":"http",...y?{queryString:T}:{}};return R.fetchStart(this.options.targetFragment.getTarget(),n,c,a?i:void 0,A),fetch(n,c).then(v=>this.handleFetchResult(v,n||void 0,P)).catch(v=>{throw n&&R.fetchError(this.options.targetFragment.getTarget(),n,v),v})}return fetch(n,c).then(P=>this.handleFetchResult(P,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const c=this.options.formFragment,d=c.getTarget(),g=new Set;t&&t.appliedDisabledAttribute&&this.options.targetFragment&&g.add(this.options.targetFragment);const y=c.getBindingData();Object.assign(y,i),await F.setBindingData(d,y,g)}const o=a?i:{},u=new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(u)}finally{this.releaseExecutionLock(t)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const e=this.options.targetFragment.getTarget();if(f.RUNNING_CLICK_TARGETS.has(e)||e.matches(":disabled")||e.hasAttribute("disabled")||e.hasAttribute(lt))return!1;const r=e.hasAttribute(`${l.prefix}click-no-disabled`);return f.RUNNING_CLICK_TARGETS.add(e),e.setAttribute(lt,""),r||e.setAttribute("disabled",""),{target:e,appliedDisabledAttribute:!r}}releaseExecutionLock(t){t&&(f.RUNNING_CLICK_TARGETS.delete(t.target),t.target.removeAttribute(lt),t.appliedDisabledAttribute&&t.target.removeAttribute("disabled"))}async handleFetchResult(t,e,r){const i=ut();if(!t.ok)return Mt(t.status)||(this.options.targetFragment&&e&&R.fetchError(this.options.targetFragment.getTarget(),e,new Error(`${t.status} ${t.statusText}`),t.status,r),await this.handleFetchError(t)),!1;if(this.options.targetFragment&&e&&r&&R.fetchEnd(this.options.targetFragment.getTarget(),e,t.status,r),this.options.afterCallback){const a=this.options.afterCallback(t);if(a!=null){if(a===!1||typeof a=="object"&&a.stop)return!1;typeof a=="object"&&"response"in a&&(t="response"in a?a.response:t)}}const n=[];n.push(this.bindResult(t)),n.push(this.adjust()),n.push(this.addRow()),n.push(this.removeRow()),n.push(this.movePrevRow()),n.push(this.moveNextRow()),await Promise.all(n),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(a=>E.reset(a))),await this.copy();const s=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{s.push(new f(a,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const a of this.options.clickFragments){await F.evaluateAll(a);const o=a.getTarget();typeof o.click=="function"?o.click():o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}return this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.push(i.openDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.push(i.closeDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(s),this.options.dialogMessage&&await i.dialog(this.options.dialogMessage),this.options.toastMessage&&await i.toast(this.options.toastMessage,this.options.toastLevel??"info"),this.pushHistory(),this.options.scrollTarget&&document.querySelector(this.options.scrollTarget)?.scrollIntoView({behavior:"smooth",block:"nearest"}),this.options.redirectUrl&&(window.location.href=this.options.redirectUrl),!0}pushHistory(){const t=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,e=this.resolveHistoryDataValues(),r=this.resolveHistoryFormValues(),i=e!=null,n=r!=null;if(!(!t&&!i&&!n))try{const s=t?this.options.historyUrl:window.location.pathname,a=new URL(s,window.location.href);if(a.origin!==window.location.origin){const u="history.pushState: cross-origin URL is not allowed: "+a.toString();m.error("Haori",u);return}const o=u=>{for(const[c,d]of Object.entries(u))d!=null&&(Array.isArray(d)?d.forEach(g=>a.searchParams.append(c,String(g))):typeof d=="object"?a.searchParams.set(c,JSON.stringify(d)):a.searchParams.set(c,String(d)))};i&&o(e),n&&o(r),history.pushState({[qt]:!0},"",a.toString())}catch(s){m.error("Haori",`history.pushState failed: ${s}`)}}async handleFetchError(t){let e=null;this.options.formFragment?e=this.options.formFragment:this.options.targetFragment&&(e=E.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=async s=>{const a=e?e.getTarget():document.body;await ut().addErrorMessage(a,s)},i=()=>{if(!this.options.scrollOnError)return;const s=e?e.getTarget():document.body;(s.getAttribute("data-message-level")==="error"?s:s.parentElement?.getAttribute("data-message-level")==="error"?s.parentElement:s.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((t.headers.get("Content-Type")||"").includes("application/json"))try{const s=await t.json(),a=[];if(Array.isArray(s)){const o=new Map,u=[];for(const c of s)if(c&&typeof c=="object"&&!Array.isArray(c)){const d=c.key,g=c.message,y=typeof d=="string"&&d.length>0?d:null,T=typeof g=="string"?g:g!=null?String(g):"";if(T.length===0)continue;if(y!==null){const P=o.get(y)??[];P.push(T),o.set(y,P)}else u.push(T)}else typeof c=="string"&&c.length>0&&u.push(c);for(const[c,d]of o)a.push({key:c,message:d.join(`
18
18
  `)});for(const c of u)a.push({message:c})}else if(s&&typeof s=="object"){if(typeof s.message=="string"&&a.push({message:s.message}),Array.isArray(s.messages))for(const o of s.messages)typeof o=="string"&&a.push({message:o});if(s.errors&&typeof s.errors=="object")for(const[o,u]of Object.entries(s.errors))Array.isArray(u)?a.push({key:o,message:u.join(`
19
19
  `)}):typeof u=="string"?a.push({key:o,message:u}):u!=null&&a.push({key:o,message:String(u)});if(a.length===0)for(const[o,u]of Object.entries(s))o==="message"||o==="messages"||o==="errors"||(Array.isArray(u)?a.push({key:o,message:u.join(`
20
- `)}):typeof u=="string"&&a.push({key:o,message:u}))}if(a.length===0)return await r(`${t.status} ${t.statusText}`),i(),!1;for(const o of a)o.key&&e?await E.addErrorMessage(e,o.key,o.message):await r(o.message);return i(),!1}catch{}try{const s=await t.text();s&&s.trim().length>0?await r(s.trim()):await r(`${t.status} ${t.statusText}`)}catch{await r(`${t.status} ${t.statusText}`)}return i(),!1}validate(t){if(this.options.valid!==!0)return!0;const e=this.findFirstInvalid(t);return e===null?!0:(e.reportValidity(),e.focus(),this.options.scrollOnError&&e.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(t){let e=null;for(const r of t.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(e=i)}return this.checkOne(t)?e:t.getTarget()}checkOne(t){const e=t.getTarget();return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?e.checkValidity():!0}confirm(){const t=this.options.confirmMessage;return t==null?Promise.resolve(!0):ut().confirm(t)}bindResult(t){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const e=t.headers.get("Content-Type")?.includes("application/json");return t.text().then(r=>{if(r==="")return;let i=e?JSON.parse(r):r;if(this.options.bindTransform)try{i=z.evaluate(this.options.bindTransform,{response:i})}catch(s){m.error("Haori",`Invalid bind-transform: ${s}`)}if(this.options.bindParams){const s={};this.options.bindParams.forEach(a=>{i&&typeof i=="object"&&a in i&&(s[a]=i[a])}),i=s}const n=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const a={...s.getRawBindingData()??{}},o=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const u=a[o],c=u&&typeof u=="object"&&!Array.isArray(u)?u:{};a[o]=this.mergeAppendBindingData(s,i,c)}else a[o]=i;n.push(N.setBindingData(s.getTarget(),a,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});else if(typeof i=="string"){if(this.options.defaultSelfBind){m.warn("Haori","string data is not bound because no bind target was specified.");return}return m.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(s=>{const a=this.mergeAppendBindingData(s,i),o=this.options.bindMerge?{...s.getRawBindingData()??{},...a}:a;n.push(N.setBindingData(s.getTarget(),o,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});return Promise.all(n).then(()=>{const s=this.options.bindArg??null;this.options.bindFragments.forEach(a=>{R.bindComplete(a.getTarget(),s)})})})}mergeAppendBindingData(t,e,r=t.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return e;const i={...e},n=r;for(const s of this.options.bindAppendParams){const a=i[s],o=n[s];Array.isArray(o)&&Array.isArray(a)&&(i[s]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const t=this.resolveCopySourceData(),e=this.pickCopyData(t),r=this.options.copyFragments.map(i=>{const n={...i.getBindingData(),...e};return N.setBindingData(i.getTarget(),n)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?E.getValues(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?E.getValues(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const t={};let e=!1;if(this.options.formFragment&&Object.assign(t,E.getValues(this.options.formFragment)),this.options.data&&typeof this.options.data=="object"&&Object.assign(t,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const r=f.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);e=e||r.hasUnresolvedReference,r.value&&Object.assign(t,r.value)}return{payload:t,hasUnresolvedReference:e}}resolveFetchSignature(){const t=this.prepareFetchRequest();return{signature:t.signature,hasUnresolvedReference:t.hasUnresolvedReference}}prepareFetchRequest(){const t=this.buildPayloadResolution(),e=t.payload,r=!!this.options.fetchHasUnresolvedReference||t.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:e,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const n={...this.options.fetchOptions||{}},s=new Headers(n.headers||void 0),a=(n.method||"GET").toUpperCase(),o=l.runtime==="demo"&&!Wt(a),u=o?"GET":a;if(n.method=u,u==="GET"||u==="HEAD"||u==="OPTIONS")Object.keys(e).length>0&&(i=Kt(i,e));else if(Object.keys(e).length>0){const d=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(d)){s.delete("Content-Type");const p=new FormData;for(const[y,T]of Object.entries(e))T==null?p.append(y,""):T instanceof Blob?p.append(y,T):Array.isArray(T)?T.forEach(P=>p.append(y,String(P))):typeof T=="object"?p.append(y,JSON.stringify(T)):p.append(y,String(T));n.body=p}else if(/application\/x-www-form-urlencoded/i.test(d)){const p=new URLSearchParams;for(const[y,T]of Object.entries(e))T!==void 0&&(T===null?p.append(y,""):Array.isArray(T)?T.forEach(P=>p.append(y,String(P))):typeof T=="object"?p.append(y,JSON.stringify(T)):p.append(y,String(T)));n.body=p}else s.set("Content-Type","application/json"),n.body=JSON.stringify(e)}n.headers=s;let c;return o&&(c=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,options:n,payload:e,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:u,queryString:c,transportMode:o?"query-get":"http",signature:Yt(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=f.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?E.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?f.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return E.getValues(this.options.historyFormFragment)}pickCopyData(t){if(!this.options.copyParams||this.options.copyParams.length===0)return t;const e=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}e.add(a)}});const i={};return(e.size>0?Array.from(e):Object.keys(t)).forEach(s=>{s in t&&(r.has(s)||(i[s]=t[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const t=this.options.adjustValue??0,e=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=t,e.push(r.setValue(String(n)))}return Promise.all(e).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return m.error("Haori","Target fragment is not specified for row operation."),null;const t=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return t||(m.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=[],r=t.clone();return e.push(t.getParent().insertAfter(r,t)),e.push(N.evaluateAll(r)),e.push(E.reset(r)),Promise.all(e).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getParent();return e&&e.getChildElementFragments().filter(i=>!i.hasAttribute(`${l.prefix}each-before`)&&!i.hasAttribute(`${l.prefix}each-after`)).length<=1?Promise.resolve():t.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getPrevious();if(!e)return Promise.resolve();const r=t.getParent();return r?r.insertBefore(t,e):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getNext();if(!e)return Promise.resolve();const r=t.getParent();return r?r.insertAfter(t,e):Promise.resolve()}};f.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,f.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,f.RUNNING_CLICK_TARGETS=new WeakSet;let j=f;class Jt{static readParams(){const t={},e=window.location.search;return new URLSearchParams(e).forEach((i,n)=>{t[n]=i}),t}}class Xt{static async load(t,e){let r;try{r=await fetch(t,e)}catch(n){throw m.error("[Haori]","Failed to fetch import source:",t,n),new Error(`Failed to fetch: ${t}`)}if(!r.ok){Mt(r.status);const n=`${r.status} ${r.statusText}`;throw m.error("[Haori]","Import HTTP error:",t,n),new Error(`Failed to load ${t}: ${n}`)}let i;try{i=await r.text()}catch(n){throw m.error("[Haori]","Failed to read response text:",t,n),new Error(`Failed to read response from: ${t}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(m.warn("[Haori]","No body found in imported document:",t),i)}catch(n){return m.error("[Haori]","Failed to parse imported HTML:",t,n),i}}}const h=class h{static isDeferredAttributeName(t){return h.DEFERRED_ATTRIBUTE_SUFFIXES.some(e=>t===`${l.prefix}${e}`)}static isEvaluateAllExcludedAttributeName(t){return h.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(e=>t===`${l.prefix}${e}`)}static shouldReevaluateAttribute(t,e){return e!==null&&!h.isEvaluateAllExcludedAttributeName(t)&&h.ATTRIBUTE_PLACEHOLDER_REGEX.test(e)}static getAliasedAttributeName(t){const e=`${l.prefix}${h.ATTRIBUTE_ALIAS_SUFFIX}`;return!t.startsWith(e)||t.length<=e.length?null:t.slice(e.length)}static isAliasedAttributeReflection(t,e){const r=w.get(t);return r instanceof k?r.hasAttribute(`${l.prefix}${h.ATTRIBUTE_ALIAS_SUFFIX}${e}`):!1}static reevaluateInterpolatedAttributes(t){let e=Promise.resolve();for(const r of t.getAttributeNames()){const i=t.getRawAttribute(r);h.shouldReevaluateAttribute(r,i)&&(e=e.then(()=>h.setAttribute(t.getTarget(),r,i)))}return e.then(()=>{})}static reevaluateChildren(t){const e=[];return t.getChildren().forEach(r=>{r instanceof k?e.push(h.evaluateAll(r)):r instanceof U&&e.push(h.evaluateText(r))}),Promise.all(e).then(()=>{})}static getReactiveFetchState(t){const e=h.REACTIVE_FETCH_STATES.get(t);if(e)return e;const r={lastSignature:null,running:!1,rerunRequested:!1};return h.REACTIVE_FETCH_STATES.set(t,r),r}static getReactiveImportState(t){const e=h.REACTIVE_IMPORT_STATES.get(t);if(e)return e;const r={lastUrl:null,running:!1,rerunRequested:!1};return h.REACTIVE_IMPORT_STATES.set(t,r),r}static reevaluateReactiveSpecialAttributes(t,e=new Set){if(e.has(t))return Promise.resolve();const r=[];return t.hasAttribute(`${l.prefix}fetch`)&&r.push(h.executeManagedFetch(t)),t.hasAttribute(`${l.prefix}import`)&&r.push(h.executeManagedImport(t)),t.getChildren().forEach(i=>{i instanceof k&&r.push(h.reevaluateReactiveSpecialAttributes(i,e))}),Promise.all(r).then(()=>{})}static executeManagedFetch(t){const e=t.getTarget(),r=h.getReactiveFetchState(e),i=j.resolveAutoFetchSignature(t);if(r.running)return(i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve();if(i.hasUnresolvedReference||i.signature===null)return r.lastSignature=null,Promise.resolve();if(r.lastSignature===i.signature)return Promise.resolve();r.lastSignature=i.signature,r.running=!0;const n=new j(t,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,h.executeManagedFetch(t)})}static executeManagedImport(t){const e=t.getTarget(),r=h.getReactiveImportState(e),i=t.getAttributeEvaluation(`${l.prefix}import`),n=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return n!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(n===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===n)return Promise.resolve();r.lastUrl=n,r.running=!0;const s=performance.now();return e.setAttribute(`${l.prefix}importing`,""),R.importStart(e,n),Xt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return M.enqueue(()=>{e.innerHTML=a}).then(()=>{if(e.removeAttribute(`${l.prefix}importing`),R.importEnd(e,n,o,s),!document.body.hasAttribute("data-haori-ready")){const u=[];return e.childNodes.forEach(c=>{const d=w.get(c);d instanceof k?u.push(h.scan(d.getTarget())):d instanceof U&&u.push(h.evaluateText(d))}),Promise.all(u).then(()=>{})}})}).catch(a=>{e.removeAttribute(`${l.prefix}importing`),R.importError(e,n,a),m.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,h.executeManagedImport(t)})}static scan(t){const e=w.get(t);return e?h.initializeElementFragment(e,!1):Promise.resolve()}static initializeFreshEachRow(t){return h.initializeElementFragment(t,!0).then(()=>{h.needsScheduledEvaluateAll(t)&&h.scheduleEvaluateAll(t)})}static initializeElementFragment(t,e){return h.syncMountedState(t),e&&t.isFreshInitializationSkippable()?Promise.resolve():h.initializeElementAttributes(t).then(()=>{if(h.shouldSkipChildInitialization(t,e)){h.refreshDerivedSubtreeSignature(t);return}const r=[];return t.getChildren().forEach(i=>{i instanceof k?r.push(h.initializeElementFragment(i,e)):i instanceof U&&r.push(h.evaluateText(i))}),Promise.all(r).then(()=>{h.refreshDerivedSubtreeSignature(t)})})}static syncMountedState(t){if(t.getParent()?.isMounted()){t.setMounted(!0);return}const r=t.getTarget();if(r.parentNode&&document.body.contains(r)){t.setMounted(!0);return}t.setMounted(!1)}static initializeElementAttributes(t){let e=Promise.resolve();const r=new Set;for(const i of h.PRIORITY_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;t.hasAttribute(n)&&(e=e.then(()=>h.setAttribute(t.getTarget(),n,t.getRawAttribute(n))),r.add(n))}for(const i of t.getAttributeNames()){if(r.has(i)||h.isDeferredAttributeName(i))continue;const n=t.getRawAttribute(i);n!==null&&(e=e.then(()=>h.setAttribute(t.getTarget(),i,n)))}for(const i of h.DEFERRED_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;t.hasAttribute(n)&&(e=e.then(()=>h.setAttribute(t.getTarget(),n,t.getRawAttribute(n))),r.add(n))}return e.then(()=>{})}static shouldSkipChildInitialization(t,e){const r=t.getAttribute(`${l.prefix}if`);return t.hasAttribute(`${l.prefix}if`)&&h.isHiddenIfCondition(r)?!0:e&&t.hasAttribute(`${l.prefix}each`)}static setAttribute(t,e,r,i=!1){const n=w.get(t),s=h.getAliasedAttributeName(e);if(s!==null)return r===null?n.removeAliasedAttribute(e,s):n.setAliasedAttribute(e,s,r,i);const a=[];let o=null,u=null;switch(e){case`${l.prefix}bind`:{if(r===null)n.clearBindingDataCache(),n.setBindingData({});else{if(i&&n instanceof k&&n.consumeSelfWrittenBind(r))break;n.setBindingData(h.parseDataBind(r))}break}case`${l.prefix}derive`:u=h.createDeriveInputSignature(n,r,n.getRawAttribute(`${l.prefix}derive-name`)),o=h.evaluateDerive(n,r,n.getRawAttribute(`${l.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${l.prefix}derive-name`:u=h.createDeriveInputSignature(n,n.getRawAttribute(`${l.prefix}derive`),r),o=h.evaluateDerive(n,n.getRawAttribute(`${l.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${l.prefix}if`:a.push(h.evaluateIf(n));break;case`${l.prefix}each`:a.push(h.evaluateEach(n));break;case`${l.prefix}fetch`:a.push(h.executeManagedFetch(n));break;case`${l.prefix}import`:typeof r=="string"&&a.push(h.executeManagedImport(n));break;case`${l.prefix}url-param`:{const c=n.getAttribute(`${l.prefix}url-arg`),d=Jt.readParams();if(c===null)a.push(h.setBindingData(t,d,new Set,!0));else{const p=n.getRawBindingData()||{};p[String(c)]=d,a.push(h.setBindingData(t,p,new Set,!0))}break}}return r===null?a.push(n.removeAttribute(e)):a.push(n.setAttribute(e,r,i)),Promise.all(a).then(()=>{if(o!==null)return n.setDeriveInputSignature(u),o.then(c=>{if(c)return h.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(t,e,r=new Set,i=!1){const n=w.get(t),s=n.getRawBindingData();n.setBindingData(e),R.bindChange(t,s,e,"manual");const a=()=>{n.markBindingWorkStart();const o=n.getRawBindingData()??e;let u=n.setAttribute(`${l.prefix}bind`,JSON.stringify(o));if(t.tagName==="FORM"){const c=n.getAttribute(`${l.prefix}form-arg`),d=c&&o[String(c)]&&typeof o[String(c)]=="object"&&!Array.isArray(o[String(c)])?o[String(c)]:c?{}:o;u=u.then(()=>E.syncValues(n,d))}return u=u.then(()=>h.evaluateAll(n,r)),u=u.then(()=>h.reevaluateReactiveSpecialAttributes(n,r)),u.then(()=>n.markBindingWorkEnd(),c=>{throw n.markBindingWorkEnd(),c})};return i?a():n.enqueueBindingWork(a)}static getBindingData(t,e={}){const r=w.get(t);return r instanceof k?e.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(t){const e=w.get(t);if(!e)return{resolved:{},sources:{}};const r=e.getBindingData(),i={},n=u=>{const c=u.getTarget();return c.id?`#${c.id}`:c.tagName.toLowerCase()},s=(u,c,d,p)=>{if(u)for(const y of Object.keys(u))y in i||(i[y]={value:u[y],source:n(c),kind:d,depth:p})};let a=e,o=0;for(;a;)a!==e&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return H.isEnabled()&&m.info("[Haori]","scope dump for",t,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(t){if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(t)}catch(e){return m.error("[Haori]","Invalid JSON in data-bind:",e),{}}else{const e=new URLSearchParams(t),r={};for(const[i,n]of e.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(t,e){const r=w.get(t);if(r.isSkipMutationNodes())return;const i=w.get(e.nextSibling),n=w.get(e);n&&(r.insertBefore(n,i),n instanceof k?h.scan(n.getTarget()):n instanceof U&&h.evaluateText(n))}static removeNode(t){const e=w.get(t);if(e){const r=e.getParent();if(r&&r.isSkipMutationNodes())return;e.remove()}}static changeText(t,e){const r=w.get(t);r&&r.setContent(e)}static changeValue(t,e){const r=w.get(t);if(r.getValue()===e)return Promise.resolve();const i=[];i.push(r.setValue(e));const n=h.getFormFragment(r);if(n){const s=E.getValues(n),a=n.getAttribute(`${l.prefix}form-arg`);let o;a?(o=n.getRawBindingData(),o||(o={}),o[String(a)]=s):o=s,i.push(h.setBindingData(n.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(t){if(t.getTarget()instanceof HTMLFormElement)return t;const e=t.getParent();return e?h.getFormFragment(e):null}static evaluateAll(t,e=new Set){if(e.has(t))return Promise.resolve();let r=h.reevaluateInterpolatedAttributes(t);const i=t.hasAttribute(`${l.prefix}derive`),n=t.hasAttribute(`${l.prefix}if`),s=t.hasAttribute(`${l.prefix}each`),a=t.getRawAttribute(`${l.prefix}derive`),o=t.getRawAttribute(`${l.prefix}derive-name`);let u=!1,c=!1,d=null;if(!i&&t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),!i&&t.getDeriveInputSignature()!==null&&t.setDeriveInputSignature(null),i){const p=h.createDeriveInputSignature(t,a,o);p===null?(t.getDeriveInputSignature()!==null&&t.setDeriveInputSignature(null),r=r.then(()=>h.evaluateDerive(t,a,o).then(()=>{}))):t.getDeriveInputSignature()!==p&&(r=r.then(()=>h.evaluateDerive(t,a,o).then(()=>{t.setDeriveInputSignature(p)})))}return n&&(r=r.then(()=>h.evaluateIf(t))),s?(t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),r.then(()=>h.evaluateEach(t))):n?(t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!h.canSkipStableDerivedSubtree(t)){t.setDeriveSubtreeSignature(null),h.logDerivedSubtreeProfileSnapshot(t,"skip-ineligible");return}d=h.createDescendantBindingSignature(t,"evaluateAll"),c=!0,u=t.getDeriveSubtreeSignature()!==null&&t.getDeriveSubtreeSignature()===d,h.logDerivedSubtreeProfileSnapshot(t,u?"skip-hit":"skip-miss")})),r.then(()=>{if(u)return;const p=[];return t.getChildren().forEach(y=>{if(y instanceof k){if(h.canSkipUnchangedNestedEach(y))return;p.push(h.evaluateAll(y,e))}else y instanceof U&&p.push(h.evaluateText(y))}),Promise.all(p).then(()=>{})}).then(()=>{c&&d!==null&&t.setDeriveSubtreeSignature(d)}))}static evaluateDerive(t,e=t.getRawAttribute(`${l.prefix}derive`),r=t.getRawAttribute(`${l.prefix}derive-name`)){const i=t.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!e||n==="")return i===null?Promise.resolve(!1):(t.setDerivedBindingData(null),Promise.resolve(!0));const s=z.evaluateDetailed(e,t.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(t.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return h.createBindingSignature(i)===h.createBindingSignature(a)?Promise.resolve(!1):(t.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(t){return t.evaluate()}static isHiddenIfCondition(t){return!t}static logFalsyIfDiagnostics(t){const e=t.getRawAttribute(`${l.prefix}if`);if(typeof e!="string"||e.indexOf("{{")>=0)return;const{sources:r}=h.dumpScope(t.getTarget()),i=new Set,n=e.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const u=e.indexOf(o,s);s=u+o.length,!(u>0&&e[u-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),m.info("[Haori]","data-if is falsy (hidden):",e,"— referenced scope:",a)}static evaluateIf(t){const e=[],r=t.getAttribute(`${l.prefix}if`);if(h.isHiddenIfCondition(r))H.isEnabled()&&h.logFalsyIfDiagnostics(t),e.push(t.hide().then(()=>{R.hide(t.getTarget())}));else{const i=t.isVisible(),n=[];t.getChildren().forEach(s=>{s instanceof k?n.push(s.isMounted()?h.evaluateAll(s):h.scan(s.getTarget())):s instanceof U&&n.push(h.evaluateText(s))}),e.push(t.show().then(()=>{R.show(t.getTarget()),i||h.triggerLoadOnShow(t)})),e.push(Promise.all(n).then(()=>{}))}return Promise.all(e).then(()=>{})}static triggerLoadOnShow(t){const e=`${l.prefix}load-`;t.getTarget().getAttributeNames().some(i=>i.startsWith(e))&&new j(t,"load").run().catch(i=>{m.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(t){let e=h.EACH_UPDATE_STATES.get(t);return e||(e={running:!1,rerunRequested:!1,settled:null},h.EACH_UPDATE_STATES.set(t,e)),e}static evaluateEach(t){if(!t.isVisible()||!t.isMounted())return Promise.resolve();const e=h.getEachUpdateState(t);return e.running?(e.rerunRequested=!0,e.settled??Promise.resolve()):h.runEachUpdateLoop(t,e)}static runEachUpdateLoop(t,e){e.running=!0,t.getTarget().removeAttribute(`${l.prefix}each-done`);const r=(async()=>{try{do e.rerunRequested=!1,await h.performEachUpdate(t);while(e.rerunRequested);t.getTarget().setAttribute(`${l.prefix}each-done`,"")}finally{e.running=!1,e.settled=null}})();return e.settled=r,r}static performEachUpdate(t){const e=h.resolveEachItems(t);if(e===null)return Promise.reject(new Error("Invalid each attribute."));let r=t.getTemplate();const i=t.getAttribute(`${l.prefix}each-key`),n=h.createBindingSignature({key:i?String(i):null,items:e});if(r===null){let s=!1;if(t.getChildren().forEach(a=>{if(!s&&a instanceof k){if(a.hasAttribute(`${l.prefix}each-before`)||a.hasAttribute(`${l.prefix}each-after`))return;r=a.clone(),h.markFreshInitializationSkippable(r),t.setTemplate(r),s=!0,t.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=t.getTarget();Array.from(a.children).filter(u=>!u.hasAttribute(`${l.prefix}each-before`)&&!u.hasAttribute(`${l.prefix}each-after`)).forEach(u=>{if(!s){const d=w.get(u);d instanceof k&&(r=d.clone(),h.markFreshInitializationSkippable(r),t.setTemplate(r),s=!0)}const c=w.get(u);c instanceof k&&t.getChildren().includes(c)&&(t.removeChild(c),c.setMounted(!1)),u.parentNode&&u.parentNode.removeChild(u)})}return this.updateDiff(t,e).then(()=>{t.setEachInputSignature(n)})}return t.getEachInputSignature()===n?Promise.resolve():this.updateDiff(t,e).then(()=>{t.setEachInputSignature(n)})}static resolveEachItems(t){const e=t.getAttributeEvaluation(`${l.prefix}each`),r=e?.value;return e?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(m.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(t){if(!t.hasAttribute(`${l.prefix}each`)||t.getEachInputSignature()===null)return!1;const e=t.getParent();if(e?.closestByAttribute(`${l.prefix}derive`)||e?.closestByAttribute(`${l.prefix}derive-name`)||e?.closestByAttribute(`${l.prefix}if`)||e?.closestByAttribute(`${l.prefix}fetch`)||e?.closestByAttribute(`${l.prefix}import`)||h.hasNonEachDynamicElementState(t))return!1;const r=h.resolveEachItems(t);if(r===null)return!1;const i=t.getAttribute(`${l.prefix}each-key`),n=h.createBindingSignature({key:i?String(i):null,items:r});return t.getEachInputSignature()===n}static canSkipStableDerivedSubtree(t){return!t.hasAttribute(`${l.prefix}derive`)||t.hasAttribute(`${l.prefix}if`)||t.hasAttribute(`${l.prefix}each`)||t.hasAttribute(`${l.prefix}fetch`)||t.hasAttribute(`${l.prefix}import`)?!1:!h.hasDisallowedDerivedSubtreeDescendant(t)}static hasDisallowedDerivedSubtreeDescendant(t){return t.getChildren().some(e=>e instanceof k?e.hasAttribute(`${l.prefix}derive`)||e.hasAttribute(`${l.prefix}derive-name`)||e.hasAttribute(`${l.prefix}fetch`)||e.hasAttribute(`${l.prefix}import`)?!0:h.hasDisallowedDerivedSubtreeDescendant(e):!1)}static createDescendantBindingSignature(t,e){return h.recordDerivedSubtreeSignatureComputation(t,e),h.createBindingSignature(t.getDescendantBindingData())}static createDeriveInputSignature(t,e,r){const i=typeof r=="string"?r.trim():"";return!e||i===""?null:h.createBindingSignature({expression:e,name:i,scope:t.getBindingData()})}static refreshDerivedSubtreeSignature(t){if(!h.canSkipStableDerivedSubtree(t)){t.setDeriveSubtreeSignature(null),h.logDerivedSubtreeProfileSnapshot(t,"skip-ineligible");return}t.setDeriveSubtreeSignature(h.createDescendantBindingSignature(t,"refresh")),h.logDerivedSubtreeProfileSnapshot(t,"refresh")}static getOrCreateDerivedSubtreeProfile(t){if(!H.isEnabled()||!t.hasAttribute(`${l.prefix}derive`))return null;const e=h.DERIVE_SUBTREE_PROFILES.get(t);if(e)return e;const r={hostId:h.createDerivedSubtreeHostId(t),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return h.DERIVE_SUBTREE_PROFILES.set(t,r),r}static createDerivedSubtreeHostId(t){const e=[];let r=t;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();if(i.id.trim()!==""){n+=`#${i.id.trim()}`,e.unshift(n);break}const s=r.getRawAttribute(`${l.prefix}derive-name`);typeof s=="string"&&s.trim()!==""&&(n+=`[${l.prefix}derive-name="${s.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(u=>u instanceof k).findIndex(u=>u===r);n+=`:nth-child(${o+1})`}e.unshift(n),r=a}return e.join(" > ")}static recordDerivedSubtreeSignatureComputation(t,e){const r=h.getOrCreateDerivedSubtreeProfile(t);if(r!==null){if(r.signatureComputeTotal+=1,e==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(t,e){const r=h.getOrCreateDerivedSubtreeProfile(t);r!==null&&(e==="skip-hit"?r.skipHitCount+=1:e==="skip-miss"?r.skipMissCount+=1:e==="skip-ineligible"&&(r.skipIneligibleCount+=1),m.info("[Haori][derive-profile]",{reason:e,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(t){const e=new Set([`${l.prefix}each`,`${l.prefix}each-key`,`${l.prefix}each-arg`,`${l.prefix}each-index`]);return t.getAttributeNames().some(i=>{if(e.has(i))return!1;if(i.startsWith(`${l.prefix}attr-`)||i.startsWith(l.prefix))return!0;const n=t.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:t.getChildren().some(i=>i instanceof U&&i.hasDynamicContent())}static markFreshInitializationSkippable(t){const e=t.getAttributeNames().some(n=>h.isFreshInitializationDynamicAttribute(t,n)),r=t.getChildren().some(n=>n instanceof k?!h.markFreshInitializationSkippable(n):n instanceof U?n.hasDynamicContent():!1),i=!e&&!r;return t.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(t,e){if(e.startsWith(`${l.prefix}attr-`)||e.startsWith(l.prefix))return!0;const r=t.getRawAttribute(e);return typeof r=="string"&&r.includes("{{")}static updateDiff(t,e){const r=t.getTemplate();if(r===null)return m.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=t.getAttribute(`${l.prefix}each-index`);i&&(i=String(i));const n=t.getAttribute(`${l.prefix}each-key`),s=t.getAttribute(`${l.prefix}each-arg`),a=new Map,o=[];e.forEach((b,S)=>{const x=h.createListKey(b,n?String(n):null,S);o.push(x),a.set(x,{item:b,itemIndex:S})});const u=new Set(o),c=[];let d=t.getChildren().filter(b=>b instanceof k).filter(b=>!b.hasAttribute(`${l.prefix}each-before`)&&!b.hasAttribute(`${l.prefix}each-after`));const p=d.map(b=>b.getListKey());d=d.filter(b=>u.has(String(b.getListKey()))?!0:(c.push(b.remove()),!1));const y=d.map(b=>b.getListKey()),T=new Map;d.forEach(b=>{const S=b.getListKey();S!==null&&!T.has(S)&&T.set(S,b)});const P=t.getChildElementFragments().slice(),A=P.filter(b=>b.hasAttribute(`${l.prefix}each-before`)).length;let v=Promise.resolve();return o.forEach((b,S)=>{const{item:x,itemIndex:I}=a.get(b);let $;const V=T.get(b);if(V)$=V,v=v.then(()=>h.updateRowFragment($,x,i,I,s?String(s):null,b).then(C=>{if(C)return h.evaluateAll($)}));else{$=r.clone();const C=A+S;v=v.then(()=>h.updateRowFragment($,x,i,I,s?String(s):null,b).then(()=>{const Z=P[C]??null;return t.insertBefore($,Z).then(()=>{P.splice(C,0,$)}).then(()=>h.initializeFreshEachRow($))}))}}),Promise.all(c).then(()=>v).then(()=>{const b=o.filter(C=>C!==null),S=y.filter(C=>C!==null),x=new Set(S),I=b.filter(C=>!x.has(C)),V=p.filter(C=>C!==null).filter(C=>!u.has(C));R.eachUpdate(t.getTarget(),I,V,b)})}static createListKey(t,e,r){let i;if(typeof t=="object"&&t!==null)if(e){const n=t[e];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(t);return i}static updateRowFragment(t,e,r,i,n,s){let a=e;if(typeof e=="object"&&e!==null)a={...e},r&&(a[r]=i),n&&(a={[n]:a});else if(n)a={[n]:e},r&&(a[r]=i);else return m.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${e}`),Promise.resolve(!1);const o=a,u=h.createBindingSignature({listKey:s,bindingData:o});return t.getListKey()===s&&t.getRenderSignature()===u?Promise.resolve(!1):(t.setListKey(s),t.setRenderSignature(u),t.setBindingData(o),t.setAttribute(`${l.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(t){const e=[t];for(;e.length>0;){const r=e.pop();if(r.getChildElementFragments().forEach(i=>{e.push(i)}),r!==t&&!r.isMounted()&&h.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(t){return["fetch","import"].some(e=>t.hasAttribute(`${l.prefix}${e}`))}static createBindingSignature(t,e=new WeakMap,r={value:0}){if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);if(typeof t=="function")return`[Function:${t.name||"anonymous"}]`;if(typeof t=="symbol")return t.toString();if(t instanceof Date)return`[Date:${t.toISOString()}]`;if(Array.isArray(t)){if(e.has(t))return`[Circular:${e.get(t)}]`;const i=`array-${r.value}`;return r.value+=1,e.set(t,i),`[${t.map(n=>h.createBindingSignature(n,e,r)).join(",")}]`}if(typeof t=="object"){if(e.has(t))return`[Circular:${e.get(t)}]`;const i=`object-${r.value}`;r.value+=1,e.set(t,i);const n=t;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${h.createBindingSignature(n[s],e,r)}`).join(",")}}`}return String(t)}static scheduleEvaluateAll(t){setTimeout(()=>{h.evaluateAll(t)},100)}};h.ATTRIBUTE_ALIAS_SUFFIX="attr-",h.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],h.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],h.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],h.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,h.REACTIVE_FETCH_STATES=new WeakMap,h.REACTIVE_IMPORT_STATES=new WeakMap,h.DERIVE_SUBTREE_PROFILES=new WeakMap,h.EACH_UPDATE_STATES=new WeakMap;let N=h;const Q=class Q{constructor(t=document){this.customEventHandlers=new Map,this.onClick=e=>this.delegate(e,"click"),this.onChange=e=>this.delegate(e,"change"),this.onInput=e=>this.delegate(e,"input"),this.onLoadCapture=e=>this.delegate(e,"load"),this.onWindowLoad=()=>{const e=document.documentElement,r=w.get(e);r&&new j(r,"load").run()},this.onPopstate=e=>{const r=e.state;!r||r[Q.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=t}start(){this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),this.root.addEventListener("input",this.onInput),this.root.addEventListener("load",this.onLoadCapture,!0),window.addEventListener("load",this.onWindowLoad,{once:!0}),window.addEventListener("popstate",this.onPopstate),this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations()}stop(){this.root.removeEventListener("click",this.onClick),this.root.removeEventListener("change",this.onChange),this.root.removeEventListener("input",this.onInput),this.root.removeEventListener("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad),window.removeEventListener("popstate",this.onPopstate);for(const[t,e]of this.customEventHandlers)window.removeEventListener(t,e,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${l.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(e=>this.subscribeCustomEvent(e.getAttribute(this.onAttributeName)))}subscribeCustomEvent(t){if(t===null||t==="")return;if(Q.BUILTIN_EVENT_NAMES.has(t)){m.warn("[Haori]",`data-on="${t}" は組み込みイベントです。data-${t}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(t))return;const e=r=>this.runCustomEventProcedures(t,r);this.customEventHandlers.set(t,e),window.addEventListener(t,e,!0)}runCustomEventProcedures(t,e){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==t)return;const n=w.get(i);n instanceof k&&new j(n,"on",e).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const t=this.root instanceof Document?this.root:this.root.ownerDocument??document,e=this.root instanceof Document?t.body:this.root;e&&(this.customEventObserver=new MutationObserver(r=>{for(const i of r)i.addedNodes.forEach(n=>{n instanceof HTMLElement&&(n.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(n.getAttribute(this.onAttributeName)),n.querySelectorAll(`[${this.onAttributeName}]`).forEach(s=>this.subscribeCustomEvent(s.getAttribute(this.onAttributeName))))})}),this.customEventObserver.observe(e,{childList:!0,subtree:!0}))}delegate(t,e){const r=this.getElementFromTarget(t.target,e);if(!r)return;if(e==="input"){const s=`${l.prefix}input-`;if(!r.getAttributeNames().some(o=>o.startsWith(s)))return}r.hasAttribute(`${l.prefix}${e}-prevent`)&&t.preventDefault();const i=w.get(r);if(!i)return;(e==="change"||e==="input")&&i instanceof k&&i.syncValue();const n=()=>{new j(i,e,t).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})};if(e==="click"&&r.hasAttribute(`${l.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}getElementFromTarget(t,e){if(!t)return null;if(t instanceof HTMLElement)return e==="click"?this.findClickableElement(t):t;if(t instanceof Node){const r=t.parentElement;return r?e==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(t){const e=`${l.prefix}click-`,r=`${l.prefix}click-passive`;let i=t;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(e)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};Q.HISTORY_STATE_KEY="__haoriHistoryState__",Q.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let ht=Q;const D=class D{static isHtmlElement(t){if(!(t instanceof Element))return!1;const e=t.ownerDocument?.defaultView?.HTMLElement;return typeof e<"u"&&t instanceof e}static syncTree(t){(t instanceof Element||t instanceof DocumentFragment)&&(D.isHtmlElement(t)&&D.syncElement(t),t.querySelectorAll("*").forEach(e=>{D.syncElement(e)}))}static syncElement(t){const e=D.registrations.get(t),r=w.get(t);if(!r||!D.shouldObserve(r)){e&&(e.observer.disconnect(),D.registrations.delete(t));return}if(typeof IntersectionObserver>"u")return;const i=D.resolveRoot(r),n=D.resolveRootMargin(r),s=D.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(e&&e.observer.root===i&&e.observer.rootMargin===n&&D.sameThreshold(e.observer.thresholds,s)&&e.once===a){e.fragment=r;return}e&&(e.observer.disconnect(),D.registrations.delete(t));const o=new IntersectionObserver(u=>{const c=D.registrations.get(t);c&&u.forEach(d=>{!d.isIntersecting||c.running||D.isDisabled(c.fragment)||(c.running=!0,new j(c.fragment,"intersect").runWithResult().then(p=>{p&&c.once&&(c.observer.disconnect(),D.registrations.delete(t))}).catch(p=>{m.error("[Haori]","Intersect procedure execution error:",p)}).finally(()=>{const p=D.registrations.get(t);p&&(p.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(t),D.registrations.set(t,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(t){if(D.isHtmlElement(t)){const e=D.registrations.get(t);e&&(e.observer.disconnect(),D.registrations.delete(t))}(t instanceof Element||t instanceof DocumentFragment)&&t.querySelectorAll("*").forEach(e=>{const r=D.registrations.get(e);r&&(r.observer.disconnect(),D.registrations.delete(e))})}static disconnectAll(){D.registrations.forEach(t=>{t.observer.disconnect()}),D.registrations.clear()}static shouldObserve(t){return t.getAttributeNames().some(e=>{if(!e.startsWith(`${l.prefix}intersect-`))return!1;const r=e.slice(`${l.prefix}intersect-`.length);return!D.CONFIG_KEYS.has(r)})}static resolveRoot(t){const e=`${l.prefix}intersect-root`;if(!t.hasAttribute(e))return null;const r=t.getAttribute(e);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return D.isHtmlElement(i)?i:(m.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(t){const e=`${l.prefix}intersect-root-margin`,r=t.getAttribute(e);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(t){const e=`${l.prefix}intersect-threshold`,r=t.getAttribute(e),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(t){const e=`${l.prefix}intersect-disabled`,r=t.getAttribute(e);if(r===null||r===!1)return!1;if(typeof r=="boolean")return r;const i=String(r).trim().toLowerCase();return i!==""&&i!=="false"&&i!=="0"}static sameThreshold(t,e){return t.length===1&&t[0]===e}};D.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),D.registrations=new Map;let X=D;const O=class O{static disconnectMutationObservers(){O._mutationObservers.forEach(t=>{t.disconnect()}),O._mutationObservers.length=0}static async init(){if(O._initialized)return;O._initialized=!0,O.disconnectMutationObservers();const t=await Promise.allSettled([N.scan(document.head),N.scan(document.body)]),[e,r]=t;e.status!=="fulfilled"&&m.error("[Haori]","Failed to build head fragment:",e.reason),r.status!=="fulfilled"&&m.error("[Haori]","Failed to build body fragment:",r.reason),await M.wait(),document.body.setAttribute("data-haori-ready",""),O.observe(document.head),O.observe(document.body),new ht().start(),X.syncTree(document.body)}static observe(t){const e=new MutationObserver(async r=>{for(const i of r)try{switch(i.type){case"attributes":{const n=i.target;if(i.attributeName&&n.hasAttribute("data-haori-click-lock")&&(i.attributeName==="disabled"||i.attributeName==="data-haori-click-lock")||i.attributeName&&N.isAliasedAttributeReflection(n,i.attributeName))break;N.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),X.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{X.cleanupTree(n),N.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(N.addNode(n.parentElement,n),X.syncTree(n))});break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?N.changeText(i.target,i.target.textContent):m.warn("[Haori]","Unsupported character data type:",i.target);break}default:m.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){m.error("[Haori]","Error processing mutation:",n)}});e.observe(t,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),O._mutationObservers.push(e)}};O._initialized=!1,O._mutationObservers=[];let it=O;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",it.init):it.init();const Qt=()=>J.waitForRenders(),Zt="0.18.0";exports.Core=N;exports.Env=l;exports.Form=E;exports.Fragment=w;exports.Haori=J;exports.Log=m;exports.Queue=M;exports.default=J;exports.version=Zt;exports.waitForRenders=Qt;
20
+ `)}):typeof u=="string"&&a.push({key:o,message:u}))}if(a.length===0)return await r(`${t.status} ${t.statusText}`),i(),!1;for(const o of a)o.key&&e?await E.addErrorMessage(e,o.key,o.message):await r(o.message);return i(),!1}catch{}try{const s=await t.text();s&&s.trim().length>0?await r(s.trim()):await r(`${t.status} ${t.statusText}`)}catch{await r(`${t.status} ${t.statusText}`)}return i(),!1}validate(t){if(this.options.valid!==!0)return!0;const e=this.findFirstInvalid(t);return e===null?!0:(e.reportValidity(),e.focus(),this.options.scrollOnError&&e.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(t){let e=null;for(const r of t.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(e=i)}return this.checkOne(t)?e:t.getTarget()}checkOne(t){const e=t.getTarget();return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?e.checkValidity():!0}confirm(){const t=this.options.confirmMessage;return t==null?Promise.resolve(!0):ut().confirm(t)}bindResult(t){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const e=t.headers.get("Content-Type")?.includes("application/json");return t.text().then(r=>{if(r==="")return;let i=e?JSON.parse(r):r;if(this.options.bindTransform)try{i=z.evaluate(this.options.bindTransform,{response:i})}catch(s){m.error("Haori",`Invalid bind-transform: ${s}`)}if(this.options.bindParams){const s={};this.options.bindParams.forEach(a=>{i&&typeof i=="object"&&a in i&&(s[a]=i[a])}),i=s}const n=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const a={...s.getRawBindingData()??{}},o=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const u=a[o],c=u&&typeof u=="object"&&!Array.isArray(u)?u:{};a[o]=this.mergeAppendBindingData(s,i,c)}else a[o]=i;n.push(F.setBindingData(s.getTarget(),a,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});else if(typeof i=="string"){if(this.options.defaultSelfBind){m.warn("Haori","string data is not bound because no bind target was specified.");return}return m.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(s=>{const a=this.mergeAppendBindingData(s,i),o=this.options.bindMerge?{...s.getRawBindingData()??{},...a}:a;n.push(F.setBindingData(s.getTarget(),o,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});return Promise.all(n).then(()=>{const s=this.options.bindArg??null;this.options.bindFragments.forEach(a=>{R.bindComplete(a.getTarget(),s)})})})}mergeAppendBindingData(t,e,r=t.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return e;const i={...e},n=r;for(const s of this.options.bindAppendParams){const a=i[s],o=n[s];Array.isArray(o)&&Array.isArray(a)&&(i[s]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const t=this.resolveCopySourceData(),e=this.pickCopyData(t),r=this.options.copyFragments.map(i=>{const n={...i.getBindingData(),...e};return F.setBindingData(i.getTarget(),n)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?E.getValues(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?E.getValues(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const t={};let e=!1;if(this.options.formFragment&&Object.assign(t,E.getValues(this.options.formFragment)),this.options.data&&typeof this.options.data=="object"&&Object.assign(t,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const r=f.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);e=e||r.hasUnresolvedReference,r.value&&Object.assign(t,r.value)}return{payload:t,hasUnresolvedReference:e}}resolveFetchSignature(){const t=this.prepareFetchRequest();return{signature:t.signature,hasUnresolvedReference:t.hasUnresolvedReference}}prepareFetchRequest(){const t=this.buildPayloadResolution(),e=t.payload,r=!!this.options.fetchHasUnresolvedReference||t.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:e,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const n={...this.options.fetchOptions||{}},s=new Headers(n.headers||void 0),a=(n.method||"GET").toUpperCase(),o=l.runtime==="demo"&&!zt(a),u=o?"GET":a;if(n.method=u,u==="GET"||u==="HEAD"||u==="OPTIONS")Object.keys(e).length>0&&(i=Gt(i,e));else if(Object.keys(e).length>0){const d=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(d)){s.delete("Content-Type");const g=new FormData;for(const[y,T]of Object.entries(e))T==null?g.append(y,""):T instanceof Blob?g.append(y,T):Array.isArray(T)?T.forEach(P=>g.append(y,String(P))):typeof T=="object"?g.append(y,JSON.stringify(T)):g.append(y,String(T));n.body=g}else if(/application\/x-www-form-urlencoded/i.test(d)){const g=new URLSearchParams;for(const[y,T]of Object.entries(e))T!==void 0&&(T===null?g.append(y,""):Array.isArray(T)?T.forEach(P=>g.append(y,String(P))):typeof T=="object"?g.append(y,JSON.stringify(T)):g.append(y,String(T)));n.body=g}else s.set("Content-Type","application/json"),n.body=JSON.stringify(e)}n.headers=s;let c;return o&&(c=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,options:n,payload:e,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:u,queryString:c,transportMode:o?"query-get":"http",signature:Jt(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=f.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?E.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?f.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return E.getValues(this.options.historyFormFragment)}pickCopyData(t){if(!this.options.copyParams||this.options.copyParams.length===0)return t;const e=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}e.add(a)}});const i={};return(e.size>0?Array.from(e):Object.keys(t)).forEach(s=>{s in t&&(r.has(s)||(i[s]=t[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const t=this.options.adjustValue??0,e=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=t,e.push(r.setValue(String(n)))}return Promise.all(e).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return m.error("Haori","Target fragment is not specified for row operation."),null;const t=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return t||(m.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=[],r=t.clone();return e.push(t.getParent().insertAfter(r,t)),e.push(F.evaluateAll(r)),e.push(E.reset(r)),Promise.all(e).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getParent();return e&&e.getChildElementFragments().filter(i=>!i.hasAttribute(`${l.prefix}each-before`)&&!i.hasAttribute(`${l.prefix}each-after`)).length<=1?Promise.resolve():t.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getPrevious();if(!e)return Promise.resolve();const r=t.getParent();return r?r.insertBefore(t,e):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getNext();if(!e)return Promise.resolve();const r=t.getParent();return r?r.insertAfter(t,e):Promise.resolve()}};f.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,f.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,f.RUNNING_CLICK_TARGETS=new WeakSet;let j=f;class Xt{static readParams(){const t={},e=window.location.search;return new URLSearchParams(e).forEach((i,n)=>{t[n]=i}),t}}class Qt{static async load(t,e){let r;try{r=await fetch(t,e)}catch(n){throw m.error("[Haori]","Failed to fetch import source:",t,n),new Error(`Failed to fetch: ${t}`)}if(!r.ok){Mt(r.status);const n=`${r.status} ${r.statusText}`;throw m.error("[Haori]","Import HTTP error:",t,n),new Error(`Failed to load ${t}: ${n}`)}let i;try{i=await r.text()}catch(n){throw m.error("[Haori]","Failed to read response text:",t,n),new Error(`Failed to read response from: ${t}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(m.warn("[Haori]","No body found in imported document:",t),i)}catch(n){return m.error("[Haori]","Failed to parse imported HTML:",t,n),i}}}const h=class h{static isDeferredAttributeName(t){return h.DEFERRED_ATTRIBUTE_SUFFIXES.some(e=>t===`${l.prefix}${e}`)}static isEvaluateAllExcludedAttributeName(t){return h.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(e=>t===`${l.prefix}${e}`)}static shouldReevaluateAttribute(t,e){return e!==null&&!h.isEvaluateAllExcludedAttributeName(t)&&h.ATTRIBUTE_PLACEHOLDER_REGEX.test(e)}static getAliasedAttributeName(t){const e=`${l.prefix}${h.ATTRIBUTE_ALIAS_SUFFIX}`;return!t.startsWith(e)||t.length<=e.length?null:t.slice(e.length)}static isAliasedAttributeReflection(t,e){const r=w.get(t);return r instanceof k?r.hasAttribute(`${l.prefix}${h.ATTRIBUTE_ALIAS_SUFFIX}${e}`):!1}static reevaluateInterpolatedAttributes(t){let e=Promise.resolve();for(const r of t.getAttributeNames()){const i=t.getRawAttribute(r);h.shouldReevaluateAttribute(r,i)&&(e=e.then(()=>h.setAttribute(t.getTarget(),r,i)))}return e.then(()=>{})}static reevaluateChildren(t){const e=[];return t.getChildren().forEach(r=>{r instanceof k?e.push(h.evaluateAll(r)):r instanceof U&&e.push(h.evaluateText(r))}),Promise.all(e).then(()=>{})}static getReactiveFetchState(t){const e=h.REACTIVE_FETCH_STATES.get(t);if(e)return e;const r={lastSignature:null,running:!1,rerunRequested:!1};return h.REACTIVE_FETCH_STATES.set(t,r),r}static getReactiveImportState(t){const e=h.REACTIVE_IMPORT_STATES.get(t);if(e)return e;const r={lastUrl:null,running:!1,rerunRequested:!1};return h.REACTIVE_IMPORT_STATES.set(t,r),r}static reevaluateReactiveSpecialAttributes(t,e=new Set){if(e.has(t))return Promise.resolve();const r=[];return t.hasAttribute(`${l.prefix}fetch`)&&r.push(h.executeManagedFetch(t)),t.hasAttribute(`${l.prefix}import`)&&r.push(h.executeManagedImport(t)),t.getChildren().forEach(i=>{i instanceof k&&r.push(h.reevaluateReactiveSpecialAttributes(i,e))}),Promise.all(r).then(()=>{})}static executeManagedFetch(t){const e=t.getTarget(),r=h.getReactiveFetchState(e),i=j.resolveAutoFetchSignature(t);if(r.running)return(i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve();if(i.hasUnresolvedReference||i.signature===null)return r.lastSignature=null,Promise.resolve();if(r.lastSignature===i.signature)return Promise.resolve();r.lastSignature=i.signature,r.running=!0;const n=new j(t,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,h.executeManagedFetch(t)})}static executeManagedImport(t){const e=t.getTarget(),r=h.getReactiveImportState(e),i=t.getAttributeEvaluation(`${l.prefix}import`),n=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return n!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(n===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===n)return Promise.resolve();r.lastUrl=n,r.running=!0;const s=performance.now();return e.setAttribute(`${l.prefix}importing`,""),R.importStart(e,n),Qt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return M.enqueue(()=>{e.innerHTML=a}).then(()=>{if(e.removeAttribute(`${l.prefix}importing`),R.importEnd(e,n,o,s),!document.body.hasAttribute("data-haori-ready")){const u=[];return e.childNodes.forEach(c=>{const d=w.get(c);d instanceof k?u.push(h.scan(d.getTarget())):d instanceof U&&u.push(h.evaluateText(d))}),Promise.all(u).then(()=>{})}})}).catch(a=>{e.removeAttribute(`${l.prefix}importing`),R.importError(e,n,a),m.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,h.executeManagedImport(t)})}static scan(t){const e=w.get(t);return e?h.initializeElementFragment(e,!1):Promise.resolve()}static initializeFreshEachRow(t){return h.initializeElementFragment(t,!0).then(()=>{h.needsScheduledEvaluateAll(t)&&h.scheduleEvaluateAll(t)})}static initializeElementFragment(t,e){return h.syncMountedState(t),e&&t.isFreshInitializationSkippable()?Promise.resolve():h.initializeElementAttributes(t).then(()=>{if(h.shouldSkipChildInitialization(t,e)){h.refreshDerivedSubtreeSignature(t);return}const r=[];return t.getChildren().forEach(i=>{i instanceof k?r.push(h.initializeElementFragment(i,e)):i instanceof U&&r.push(h.evaluateText(i))}),Promise.all(r).then(()=>{h.refreshDerivedSubtreeSignature(t)})})}static syncMountedState(t){if(t.getParent()?.isMounted()){t.setMounted(!0);return}const r=t.getTarget();if(r.parentNode&&document.body.contains(r)){t.setMounted(!0);return}t.setMounted(!1)}static initializeElementAttributes(t){let e=Promise.resolve();const r=new Set;for(const i of h.PRIORITY_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;t.hasAttribute(n)&&(e=e.then(()=>h.setAttribute(t.getTarget(),n,t.getRawAttribute(n))),r.add(n))}for(const i of t.getAttributeNames()){if(r.has(i)||h.isDeferredAttributeName(i))continue;const n=t.getRawAttribute(i);n!==null&&(e=e.then(()=>h.setAttribute(t.getTarget(),i,n)))}for(const i of h.DEFERRED_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;t.hasAttribute(n)&&(e=e.then(()=>h.setAttribute(t.getTarget(),n,t.getRawAttribute(n))),r.add(n))}return e.then(()=>{})}static shouldSkipChildInitialization(t,e){const r=t.getAttribute(`${l.prefix}if`);return t.hasAttribute(`${l.prefix}if`)&&h.isHiddenIfCondition(r)?!0:e&&t.hasAttribute(`${l.prefix}each`)}static setAttribute(t,e,r,i=!1){const n=w.get(t),s=h.getAliasedAttributeName(e);if(s!==null)return r===null?n.removeAliasedAttribute(e,s):n.setAliasedAttribute(e,s,r,i);const a=[];let o=null,u=null;switch(e){case`${l.prefix}bind`:{if(r===null)n.clearBindingDataCache(),n.setBindingData({});else{if(i&&n instanceof k&&n.consumeSelfWrittenBind(r))break;n.setBindingData(h.parseDataBind(r))}break}case`${l.prefix}derive`:u=h.createDeriveInputSignature(n,r,n.getRawAttribute(`${l.prefix}derive-name`)),o=h.evaluateDerive(n,r,n.getRawAttribute(`${l.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${l.prefix}derive-name`:u=h.createDeriveInputSignature(n,n.getRawAttribute(`${l.prefix}derive`),r),o=h.evaluateDerive(n,n.getRawAttribute(`${l.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${l.prefix}if`:a.push(h.evaluateIf(n));break;case`${l.prefix}each`:a.push(h.evaluateEach(n));break;case`${l.prefix}fetch`:a.push(h.executeManagedFetch(n));break;case`${l.prefix}import`:typeof r=="string"&&a.push(h.executeManagedImport(n));break;case`${l.prefix}url-param`:{const c=n.getAttribute(`${l.prefix}url-arg`),d=Xt.readParams();if(c===null)a.push(h.setBindingData(t,d,new Set,!0));else{const g=n.getRawBindingData()||{};g[String(c)]=d,a.push(h.setBindingData(t,g,new Set,!0))}break}}return r===null?a.push(n.removeAttribute(e)):a.push(n.setAttribute(e,r,i)),Promise.all(a).then(()=>{if(o!==null)return n.setDeriveInputSignature(u),o.then(c=>{if(c)return h.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(t,e,r=new Set,i=!1){const n=w.get(t),s=n.getRawBindingData();n.setBindingData(e),R.bindChange(t,s,e,"manual");const a=()=>{n.markBindingWorkStart();const o=n.getRawBindingData()??e;let u=n.setAttribute(`${l.prefix}bind`,JSON.stringify(o));if(t.tagName==="FORM"){const c=n.getAttribute(`${l.prefix}form-arg`),d=c&&o[String(c)]&&typeof o[String(c)]=="object"&&!Array.isArray(o[String(c)])?o[String(c)]:c?{}:o;u=u.then(()=>E.syncValues(n,d))}return u=u.then(()=>h.evaluateAll(n,r)),u=u.then(()=>h.reevaluateReactiveSpecialAttributes(n,r)),u.then(()=>n.markBindingWorkEnd(),c=>{throw n.markBindingWorkEnd(),c})};return i?a():n.enqueueBindingWork(a)}static getBindingData(t,e={}){const r=w.get(t);return r instanceof k?e.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(t){const e=w.get(t);if(!e)return{resolved:{},sources:{}};const r=e.getBindingData(),i={},n=u=>{const c=u.getTarget();return c.id?`#${c.id}`:c.tagName.toLowerCase()},s=(u,c,d,g)=>{if(u)for(const y of Object.keys(u))y in i||(i[y]={value:u[y],source:n(c),kind:d,depth:g})};let a=e,o=0;for(;a;)a!==e&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return H.isEnabled()&&m.info("[Haori]","scope dump for",t,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(t){if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(t)}catch(e){return m.error("[Haori]","Invalid JSON in data-bind:",e),{}}else{const e=new URLSearchParams(t),r={};for(const[i,n]of e.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(t,e){const r=w.get(t);if(r.isSkipMutationNodes())return;const i=w.get(e.nextSibling),n=w.get(e);n&&(r.insertBefore(n,i),n instanceof k?h.scan(n.getTarget()):n instanceof U&&h.evaluateText(n))}static removeNode(t){const e=w.get(t);if(e){const r=e.getParent();if(r&&r.isSkipMutationNodes())return;e.remove()}}static changeText(t,e){const r=w.get(t);r&&r.setContent(e)}static changeValue(t,e){const r=w.get(t);if(r.getValue()===e)return Promise.resolve();const i=[];i.push(r.setValue(e));const n=h.getFormFragment(r);if(n){const s=E.getValues(n),a=n.getAttribute(`${l.prefix}form-arg`);let o;a?(o=n.getRawBindingData(),o||(o={}),o[String(a)]=s):o=s,i.push(h.setBindingData(n.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(t){if(t.getTarget()instanceof HTMLFormElement)return t;const e=t.getParent();return e?h.getFormFragment(e):null}static evaluateAll(t,e=new Set){if(e.has(t))return Promise.resolve();let r=h.reevaluateInterpolatedAttributes(t);const i=t.hasAttribute(`${l.prefix}derive`),n=t.hasAttribute(`${l.prefix}if`),s=t.hasAttribute(`${l.prefix}each`),a=t.getRawAttribute(`${l.prefix}derive`),o=t.getRawAttribute(`${l.prefix}derive-name`);let u=!1,c=!1,d=null;if(!i&&t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),!i&&t.getDeriveInputSignature()!==null&&t.setDeriveInputSignature(null),i){const g=h.createDeriveInputSignature(t,a,o);g===null?(t.getDeriveInputSignature()!==null&&t.setDeriveInputSignature(null),r=r.then(()=>h.evaluateDerive(t,a,o).then(()=>{}))):t.getDeriveInputSignature()!==g&&(r=r.then(()=>h.evaluateDerive(t,a,o).then(()=>{t.setDeriveInputSignature(g)})))}return n&&(r=r.then(()=>h.evaluateIf(t))),s?(t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),r.then(()=>h.evaluateEach(t))):n?(t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!h.canSkipStableDerivedSubtree(t)){t.setDeriveSubtreeSignature(null),h.logDerivedSubtreeProfileSnapshot(t,"skip-ineligible");return}d=h.createDescendantBindingSignature(t,"evaluateAll"),c=!0,u=t.getDeriveSubtreeSignature()!==null&&t.getDeriveSubtreeSignature()===d,h.logDerivedSubtreeProfileSnapshot(t,u?"skip-hit":"skip-miss")})),r.then(()=>{if(u)return;const g=[];return t.getChildren().forEach(y=>{if(y instanceof k){if(h.canSkipUnchangedNestedEach(y))return;g.push(h.evaluateAll(y,e))}else y instanceof U&&g.push(h.evaluateText(y))}),Promise.all(g).then(()=>{})}).then(()=>{c&&d!==null&&t.setDeriveSubtreeSignature(d)}))}static evaluateDerive(t,e=t.getRawAttribute(`${l.prefix}derive`),r=t.getRawAttribute(`${l.prefix}derive-name`)){const i=t.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!e||n==="")return i===null?Promise.resolve(!1):(t.setDerivedBindingData(null),Promise.resolve(!0));const s=z.evaluateDetailed(e,t.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(t.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return h.createBindingSignature(i)===h.createBindingSignature(a)?Promise.resolve(!1):(t.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(t){return t.evaluate()}static isHiddenIfCondition(t){return!t}static logFalsyIfDiagnostics(t){const e=t.getRawAttribute(`${l.prefix}if`);if(typeof e!="string"||e.indexOf("{{")>=0)return;const{sources:r}=h.dumpScope(t.getTarget()),i=new Set,n=e.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const u=e.indexOf(o,s);s=u+o.length,!(u>0&&e[u-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),m.info("[Haori]","data-if is falsy (hidden):",e,"— referenced scope:",a)}static evaluateIf(t){const e=[],r=t.getAttribute(`${l.prefix}if`);if(h.isHiddenIfCondition(r))H.isEnabled()&&h.logFalsyIfDiagnostics(t),e.push(t.hide().then(()=>{R.hide(t.getTarget())}));else{const i=t.isVisible(),n=[];t.getChildren().forEach(s=>{s instanceof k?n.push(s.isMounted()?h.evaluateAll(s):h.scan(s.getTarget())):s instanceof U&&n.push(h.evaluateText(s))}),e.push(t.show().then(()=>{R.show(t.getTarget()),i||h.triggerLoadOnShow(t)})),e.push(Promise.all(n).then(()=>{}))}return Promise.all(e).then(()=>{})}static triggerLoadOnShow(t){const e=`${l.prefix}load-`;t.getTarget().getAttributeNames().some(i=>i.startsWith(e))&&new j(t,"load").run().catch(i=>{m.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(t){let e=h.EACH_UPDATE_STATES.get(t);return e||(e={running:!1,rerunRequested:!1,settled:null},h.EACH_UPDATE_STATES.set(t,e)),e}static evaluateEach(t){if(!t.isVisible()||!t.isMounted())return Promise.resolve();const e=h.getEachUpdateState(t);return e.running?(e.rerunRequested=!0,e.settled??Promise.resolve()):h.runEachUpdateLoop(t,e)}static runEachUpdateLoop(t,e){e.running=!0,t.getTarget().removeAttribute(`${l.prefix}each-done`);const r=(async()=>{try{do e.rerunRequested=!1,await h.performEachUpdate(t);while(e.rerunRequested);t.getTarget().setAttribute(`${l.prefix}each-done`,"")}finally{e.running=!1,e.settled=null}})();return e.settled=r,r}static performEachUpdate(t){const e=h.resolveEachItems(t);if(e===null)return Promise.reject(new Error("Invalid each attribute."));let r=t.getTemplate();const i=t.getAttribute(`${l.prefix}each-key`),n=h.createBindingSignature({key:i?String(i):null,items:e});if(r===null){let s=!1;if(t.getChildren().forEach(a=>{if(!s&&a instanceof k){if(a.hasAttribute(`${l.prefix}each-before`)||a.hasAttribute(`${l.prefix}each-after`))return;r=a.clone(),h.markFreshInitializationSkippable(r),t.setTemplate(r),s=!0,t.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=t.getTarget();Array.from(a.children).filter(u=>!u.hasAttribute(`${l.prefix}each-before`)&&!u.hasAttribute(`${l.prefix}each-after`)).forEach(u=>{if(!s){const d=w.get(u);d instanceof k&&(r=d.clone(),h.markFreshInitializationSkippable(r),t.setTemplate(r),s=!0)}const c=w.get(u);c instanceof k&&t.getChildren().includes(c)&&(t.removeChild(c),c.setMounted(!1)),u.parentNode&&u.parentNode.removeChild(u)})}return this.updateDiff(t,e).then(()=>{t.setEachInputSignature(n)})}return t.getEachInputSignature()===n?Promise.resolve():this.updateDiff(t,e).then(()=>{t.setEachInputSignature(n)})}static resolveEachItems(t){const e=t.getAttributeEvaluation(`${l.prefix}each`),r=e?.value;return e?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(m.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(t){if(!t.hasAttribute(`${l.prefix}each`)||t.getEachInputSignature()===null)return!1;const e=t.getParent();if(e?.closestByAttribute(`${l.prefix}derive`)||e?.closestByAttribute(`${l.prefix}derive-name`)||e?.closestByAttribute(`${l.prefix}if`)||e?.closestByAttribute(`${l.prefix}fetch`)||e?.closestByAttribute(`${l.prefix}import`)||h.hasNonEachDynamicElementState(t))return!1;const r=h.resolveEachItems(t);if(r===null)return!1;const i=t.getAttribute(`${l.prefix}each-key`),n=h.createBindingSignature({key:i?String(i):null,items:r});return t.getEachInputSignature()===n}static canSkipStableDerivedSubtree(t){return!t.hasAttribute(`${l.prefix}derive`)||t.hasAttribute(`${l.prefix}if`)||t.hasAttribute(`${l.prefix}each`)||t.hasAttribute(`${l.prefix}fetch`)||t.hasAttribute(`${l.prefix}import`)?!1:!h.hasDisallowedDerivedSubtreeDescendant(t)}static hasDisallowedDerivedSubtreeDescendant(t){return t.getChildren().some(e=>e instanceof k?e.hasAttribute(`${l.prefix}derive`)||e.hasAttribute(`${l.prefix}derive-name`)||e.hasAttribute(`${l.prefix}fetch`)||e.hasAttribute(`${l.prefix}import`)?!0:h.hasDisallowedDerivedSubtreeDescendant(e):!1)}static createDescendantBindingSignature(t,e){return h.recordDerivedSubtreeSignatureComputation(t,e),h.createBindingSignature(t.getDescendantBindingData())}static createDeriveInputSignature(t,e,r){const i=typeof r=="string"?r.trim():"";return!e||i===""?null:h.createBindingSignature({expression:e,name:i,scope:t.getBindingData()})}static refreshDerivedSubtreeSignature(t){if(!h.canSkipStableDerivedSubtree(t)){t.setDeriveSubtreeSignature(null),h.logDerivedSubtreeProfileSnapshot(t,"skip-ineligible");return}t.setDeriveSubtreeSignature(h.createDescendantBindingSignature(t,"refresh")),h.logDerivedSubtreeProfileSnapshot(t,"refresh")}static getOrCreateDerivedSubtreeProfile(t){if(!H.isEnabled()||!t.hasAttribute(`${l.prefix}derive`))return null;const e=h.DERIVE_SUBTREE_PROFILES.get(t);if(e)return e;const r={hostId:h.createDerivedSubtreeHostId(t),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return h.DERIVE_SUBTREE_PROFILES.set(t,r),r}static createDerivedSubtreeHostId(t){const e=[];let r=t;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();if(i.id.trim()!==""){n+=`#${i.id.trim()}`,e.unshift(n);break}const s=r.getRawAttribute(`${l.prefix}derive-name`);typeof s=="string"&&s.trim()!==""&&(n+=`[${l.prefix}derive-name="${s.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(u=>u instanceof k).findIndex(u=>u===r);n+=`:nth-child(${o+1})`}e.unshift(n),r=a}return e.join(" > ")}static recordDerivedSubtreeSignatureComputation(t,e){const r=h.getOrCreateDerivedSubtreeProfile(t);if(r!==null){if(r.signatureComputeTotal+=1,e==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(t,e){const r=h.getOrCreateDerivedSubtreeProfile(t);r!==null&&(e==="skip-hit"?r.skipHitCount+=1:e==="skip-miss"?r.skipMissCount+=1:e==="skip-ineligible"&&(r.skipIneligibleCount+=1),m.info("[Haori][derive-profile]",{reason:e,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(t){const e=new Set([`${l.prefix}each`,`${l.prefix}each-key`,`${l.prefix}each-arg`,`${l.prefix}each-index`]);return t.getAttributeNames().some(i=>{if(e.has(i))return!1;if(i.startsWith(`${l.prefix}attr-`)||i.startsWith(l.prefix))return!0;const n=t.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:t.getChildren().some(i=>i instanceof U&&i.hasDynamicContent())}static markFreshInitializationSkippable(t){const e=t.getAttributeNames().some(n=>h.isFreshInitializationDynamicAttribute(t,n)),r=t.getChildren().some(n=>n instanceof k?!h.markFreshInitializationSkippable(n):n instanceof U?n.hasDynamicContent():!1),i=!e&&!r;return t.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(t,e){if(e.startsWith(`${l.prefix}attr-`)||e.startsWith(l.prefix))return!0;const r=t.getRawAttribute(e);return typeof r=="string"&&r.includes("{{")}static updateDiff(t,e){const r=t.getTemplate();if(r===null)return m.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=t.getAttribute(`${l.prefix}each-index`);i&&(i=String(i));const n=t.getAttribute(`${l.prefix}each-key`),s=t.getAttribute(`${l.prefix}each-arg`),a=new Map,o=[];e.forEach((b,S)=>{const x=h.createListKey(b,n?String(n):null,S);o.push(x),a.set(x,{item:b,itemIndex:S})});const u=new Set(o),c=[];let d=t.getChildren().filter(b=>b instanceof k).filter(b=>!b.hasAttribute(`${l.prefix}each-before`)&&!b.hasAttribute(`${l.prefix}each-after`));const g=d.map(b=>b.getListKey());d=d.filter(b=>u.has(String(b.getListKey()))?!0:(c.push(b.remove()),!1));const y=d.map(b=>b.getListKey()),T=new Map;d.forEach(b=>{const S=b.getListKey();S!==null&&!T.has(S)&&T.set(S,b)});const P=t.getChildElementFragments().slice(),A=P.filter(b=>b.hasAttribute(`${l.prefix}each-before`)).length;let v=Promise.resolve();return o.forEach((b,S)=>{const{item:x,itemIndex:I}=a.get(b);let $;const V=T.get(b);if(V)$=V,v=v.then(()=>h.updateRowFragment($,x,i,I,s?String(s):null,b).then(C=>{if(C)return h.evaluateAll($)}));else{$=r.clone();const C=A+S;v=v.then(()=>h.updateRowFragment($,x,i,I,s?String(s):null,b).then(()=>{const Z=P[C]??null;return t.insertBefore($,Z).then(()=>{P.splice(C,0,$)}).then(()=>h.initializeFreshEachRow($))}))}}),Promise.all(c).then(()=>v).then(()=>{const b=o.filter(C=>C!==null),S=y.filter(C=>C!==null),x=new Set(S),I=b.filter(C=>!x.has(C)),V=g.filter(C=>C!==null).filter(C=>!u.has(C));R.eachUpdate(t.getTarget(),I,V,b)})}static createListKey(t,e,r){let i;if(typeof t=="object"&&t!==null)if(e){const n=t[e];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(t);return i}static updateRowFragment(t,e,r,i,n,s){let a=e;if(typeof e=="object"&&e!==null)a={...e},r&&(a[r]=i),n&&(a={[n]:a});else if(n)a={[n]:e},r&&(a[r]=i);else return m.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${e}`),Promise.resolve(!1);const o=a,u=h.createBindingSignature({listKey:s,bindingData:o});return t.getListKey()===s&&t.getRenderSignature()===u?Promise.resolve(!1):(t.setListKey(s),t.setRenderSignature(u),t.setBindingData(o),t.setAttribute(`${l.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(t){const e=[t];for(;e.length>0;){const r=e.pop();if(r.getChildElementFragments().forEach(i=>{e.push(i)}),r!==t&&!r.isMounted()&&h.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(t){return["fetch","import"].some(e=>t.hasAttribute(`${l.prefix}${e}`))}static createBindingSignature(t,e=new WeakMap,r={value:0}){if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);if(typeof t=="function")return`[Function:${t.name||"anonymous"}]`;if(typeof t=="symbol")return t.toString();if(t instanceof Date)return`[Date:${t.toISOString()}]`;if(Array.isArray(t)){if(e.has(t))return`[Circular:${e.get(t)}]`;const i=`array-${r.value}`;return r.value+=1,e.set(t,i),`[${t.map(n=>h.createBindingSignature(n,e,r)).join(",")}]`}if(typeof t=="object"){if(e.has(t))return`[Circular:${e.get(t)}]`;const i=`object-${r.value}`;r.value+=1,e.set(t,i);const n=t;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${h.createBindingSignature(n[s],e,r)}`).join(",")}}`}return String(t)}static scheduleEvaluateAll(t){setTimeout(()=>{h.evaluateAll(t)},100)}};h.ATTRIBUTE_ALIAS_SUFFIX="attr-",h.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],h.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],h.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],h.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,h.REACTIVE_FETCH_STATES=new WeakMap,h.REACTIVE_IMPORT_STATES=new WeakMap,h.DERIVE_SUBTREE_PROFILES=new WeakMap,h.EACH_UPDATE_STATES=new WeakMap;let F=h;const Q=class Q{constructor(t=document){this.customEventHandlers=new Map,this.onClick=e=>this.delegate(e,"click"),this.onChange=e=>this.delegate(e,"change"),this.onInput=e=>this.delegate(e,"input"),this.onLoadCapture=e=>this.delegate(e,"load"),this.onWindowLoad=()=>{const e=document.documentElement,r=w.get(e);r&&new j(r,"load").run()},this.onPopstate=e=>{const r=e.state;!r||r[Q.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=t}start(){this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),this.root.addEventListener("input",this.onInput),this.root.addEventListener("load",this.onLoadCapture,!0),window.addEventListener("load",this.onWindowLoad,{once:!0}),window.addEventListener("popstate",this.onPopstate),this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations()}stop(){this.root.removeEventListener("click",this.onClick),this.root.removeEventListener("change",this.onChange),this.root.removeEventListener("input",this.onInput),this.root.removeEventListener("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad),window.removeEventListener("popstate",this.onPopstate);for(const[t,e]of this.customEventHandlers)window.removeEventListener(t,e,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${l.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(e=>this.subscribeCustomEvent(e.getAttribute(this.onAttributeName)))}subscribeCustomEvent(t){if(t===null||t==="")return;if(Q.BUILTIN_EVENT_NAMES.has(t)){m.warn("[Haori]",`data-on="${t}" は組み込みイベントです。data-${t}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(t))return;const e=r=>this.runCustomEventProcedures(t,r);this.customEventHandlers.set(t,e),window.addEventListener(t,e,!0)}runCustomEventProcedures(t,e){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==t)return;const n=w.get(i);n instanceof k&&new j(n,"on",e).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const t=this.root instanceof Document?this.root:this.root.ownerDocument??document,e=this.root instanceof Document?t.body:this.root;e&&(this.customEventObserver=new MutationObserver(r=>{for(const i of r)i.addedNodes.forEach(n=>{n instanceof HTMLElement&&(n.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(n.getAttribute(this.onAttributeName)),n.querySelectorAll(`[${this.onAttributeName}]`).forEach(s=>this.subscribeCustomEvent(s.getAttribute(this.onAttributeName))))})}),this.customEventObserver.observe(e,{childList:!0,subtree:!0}))}delegate(t,e){const r=this.getElementFromTarget(t.target,e);if(!r)return;if(e==="input"){const s=`${l.prefix}input-`;if(!r.getAttributeNames().some(o=>o.startsWith(s)))return}r.hasAttribute(`${l.prefix}${e}-prevent`)&&t.preventDefault();const i=w.get(r);if(!i)return;(e==="change"||e==="input")&&i instanceof k&&i.syncValue();const n=()=>{new j(i,e,t).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})};if(e==="click"&&r.hasAttribute(`${l.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}getElementFromTarget(t,e){if(!t)return null;if(t instanceof HTMLElement)return e==="click"?this.findClickableElement(t):t;if(t instanceof Node){const r=t.parentElement;return r?e==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(t){const e=`${l.prefix}click-`,r=`${l.prefix}click-passive`;let i=t;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(e)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};Q.HISTORY_STATE_KEY="__haoriHistoryState__",Q.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let ht=Q;const D=class D{static isHtmlElement(t){if(!(t instanceof Element))return!1;const e=t.ownerDocument?.defaultView?.HTMLElement;return typeof e<"u"&&t instanceof e}static syncTree(t){(t instanceof Element||t instanceof DocumentFragment)&&(D.isHtmlElement(t)&&D.syncElement(t),t.querySelectorAll("*").forEach(e=>{D.syncElement(e)}))}static syncElement(t){const e=D.registrations.get(t),r=w.get(t);if(!r||!D.shouldObserve(r)){e&&(e.observer.disconnect(),D.registrations.delete(t));return}if(typeof IntersectionObserver>"u")return;const i=D.resolveRoot(r),n=D.resolveRootMargin(r),s=D.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(e&&e.observer.root===i&&e.observer.rootMargin===n&&D.sameThreshold(e.observer.thresholds,s)&&e.once===a){e.fragment=r;return}e&&(e.observer.disconnect(),D.registrations.delete(t));const o=new IntersectionObserver(u=>{const c=D.registrations.get(t);c&&u.forEach(d=>{!d.isIntersecting||c.running||D.isDisabled(c.fragment)||(c.running=!0,new j(c.fragment,"intersect").runWithResult().then(g=>{g&&c.once&&(c.observer.disconnect(),D.registrations.delete(t))}).catch(g=>{m.error("[Haori]","Intersect procedure execution error:",g)}).finally(()=>{const g=D.registrations.get(t);g&&(g.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(t),D.registrations.set(t,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(t){if(D.isHtmlElement(t)){const e=D.registrations.get(t);e&&(e.observer.disconnect(),D.registrations.delete(t))}(t instanceof Element||t instanceof DocumentFragment)&&t.querySelectorAll("*").forEach(e=>{const r=D.registrations.get(e);r&&(r.observer.disconnect(),D.registrations.delete(e))})}static disconnectAll(){D.registrations.forEach(t=>{t.observer.disconnect()}),D.registrations.clear()}static shouldObserve(t){return t.getAttributeNames().some(e=>{if(!e.startsWith(`${l.prefix}intersect-`))return!1;const r=e.slice(`${l.prefix}intersect-`.length);return!D.CONFIG_KEYS.has(r)})}static resolveRoot(t){const e=`${l.prefix}intersect-root`;if(!t.hasAttribute(e))return null;const r=t.getAttribute(e);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return D.isHtmlElement(i)?i:(m.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(t){const e=`${l.prefix}intersect-root-margin`,r=t.getAttribute(e);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(t){const e=`${l.prefix}intersect-threshold`,r=t.getAttribute(e),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(t){const e=`${l.prefix}intersect-disabled`,r=t.getAttribute(e);if(r===null||r===!1)return!1;if(typeof r=="boolean")return r;const i=String(r).trim().toLowerCase();return i!==""&&i!=="false"&&i!=="0"}static sameThreshold(t,e){return t.length===1&&t[0]===e}};D.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),D.registrations=new Map;let X=D;const O=class O{static disconnectMutationObservers(){O._mutationObservers.forEach(t=>{t.disconnect()}),O._mutationObservers.length=0}static async init(){if(O._initialized)return;O._initialized=!0,O.disconnectMutationObservers();const t=await Promise.allSettled([F.scan(document.head),F.scan(document.body)]),[e,r]=t;e.status!=="fulfilled"&&m.error("[Haori]","Failed to build head fragment:",e.reason),r.status!=="fulfilled"&&m.error("[Haori]","Failed to build body fragment:",r.reason),await M.wait(),document.body.setAttribute("data-haori-ready",""),O.observe(document.head),O.observe(document.body),new ht().start(),X.syncTree(document.body)}static observe(t){const e=new MutationObserver(async r=>{for(const i of r)try{switch(i.type){case"attributes":{const n=i.target;if(i.attributeName&&n.hasAttribute("data-haori-click-lock")&&(i.attributeName==="disabled"||i.attributeName==="data-haori-click-lock")||i.attributeName&&F.isAliasedAttributeReflection(n,i.attributeName))break;F.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),X.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{X.cleanupTree(n),F.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(F.addNode(n.parentElement,n),X.syncTree(n))});break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?F.changeText(i.target,i.target.textContent):m.warn("[Haori]","Unsupported character data type:",i.target);break}default:m.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){m.error("[Haori]","Error processing mutation:",n)}});e.observe(t,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),O._mutationObservers.push(e)}};O._initialized=!1,O._mutationObservers=[];let it=O;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",it.init):it.init();const Zt=()=>J.waitForRenders(),_t="0.19.0";exports.Core=F;exports.Env=l;exports.Form=E;exports.Fragment=w;exports.Haori=J;exports.Log=m;exports.Queue=M;exports.default=J;exports.version=_t;exports.waitForRenders=Zt;
21
21
  //# sourceMappingURL=haori.cjs.js.map