haori 0.22.1 → 0.22.3
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/README.ja.md +1 -1
- package/README.md +1 -1
- package/dist/haori.cjs.js +4 -4
- package/dist/haori.es.js +99 -81
- package/dist/haori.iife.js +6 -6
- package/dist/index.d.ts +9 -0
- package/package.json +1 -1
package/dist/haori.cjs.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const X=class X{static isEnabled(){return X.devMode}static enable(){X.devMode=!0}static disable(){X.devMode=!1}static set(e){X.devMode=e}};X.devMode=!1;let L=X;const de="embedded";function Se(f){return f==="embedded"||f==="demo"}function Oe(f){return f===null?null:Se(f)?f:de}const U=class U{static get runtime(){return U._runtime}static setRuntime(e){U._runtime=Se(e)?e:de}static detect(){try{const e=document.currentScript||document.querySelector('script[src*="haori"]');if(e instanceof HTMLScriptElement){const r=e.getAttribute("data-prefix")||U._prefix;U._prefix=r.endsWith("-")?r:r+"-";const i=Oe(e.getAttribute("data-runtime"));i!==null&&(U._runtime=i)}if(e instanceof HTMLScriptElement&&e.hasAttribute(`${U._prefix}dev`)){L.set(!0);return}const t=window.location.hostname;if(t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="::1"||t.endsWith(".local")){L.set(!0);return}L.set(!1)}catch{}}static get prefix(){return U._prefix}};U._prefix="data-",U._runtime=de;let c=U;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",c.detect):c.detect();class m{static info(e,...t){L.isEnabled()&&console.log&&console.log(e,...t)}static warn(e,...t){L.isEnabled()&&console.warn&&console.warn(e,...t)}static error(e,...t){console.error(e,...t)}}const He="yyyy/MM/dd HH:mm",Le="en-US",Ee=1e4;function K(f){return String(f).padStart(2,"0")}function we(f,e,t,r,i,n){return{yyyy:String(f).padStart(4,"0"),yy:K(f%100),MM:K(e),M:String(e),dd:K(t),d:String(t),HH:K(r),H:String(r),mm:K(i),ss:K(n)}}function Ue(f,e){let t;try{t=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(f)}catch{return null}const r={};for(const h of t)h.type!=="literal"&&(r[h.type]=h.value);const i=Number(r.year),n=Number(r.month),s=Number(r.day),a=Number(r.hour),o=Number(r.minute),l=Number(r.second);return!Number.isFinite(i)||!Number.isFinite(n)||!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(o)||!Number.isFinite(l)?null:we(i,n,s,a,o,l)}function Te(f,e=He,t){if(f==null||f==="")return"";const r=f instanceof Date?f:new Date(f);if(Number.isNaN(r.getTime()))return"";let i;if(typeof t=="string"&&t.trim()!==""){if(i=Ue(r,t.trim()),i===null)return""}else i=we(r.getFullYear(),r.getMonth()+1,r.getDate(),r.getHours(),r.getMinutes(),r.getSeconds());const n=i;return e.replace(/'([^']*)'|yyyy|yy|MM|dd|HH|mm|ss|M|d|H/g,(s,a)=>a!==void 0?a===""?"'":a:n[s])}function Re(f,e){if(f==null)return"";let t;if(typeof f=="number")t=f;else{const i=String(f).trim();if(i==="")return"";t=Number(i)}if(!Number.isFinite(t))return"";const r={};if(e!==void 0&&Number.isFinite(e)){const i=Math.max(0,Math.trunc(e));r.minimumFractionDigits=i,r.maximumFractionDigits=i}return new Intl.NumberFormat(Le,r).format(t)}function De(f,e,t){let r,i,n;if(e===void 0?(r=0,i=f,n=1):(r=f,i=e,n=t===void 0?1:t),!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<Ee;a+=n)s.push(a);else for(let a=r;a>i&&s.length<Ee;a+=n)s.push(a);return s}function Fe(f,e,t={}){const r=Math.trunc(Number(f));if(!Number.isFinite(r)||r<=0)return[];const i=Math.min(Math.max(Math.trunc(Number(e))||0,0),r-1),n=Math.max(0,Math.trunc(t.window??2)),s=Math.max(0,Math.trunc(t.boundary??1)),a=new Set;for(let u=0;u<s&&u<r;u+=1)a.add(u);for(let u=Math.max(0,r-s);u<r;u+=1)a.add(u);for(let u=Math.max(0,i-n);u<=Math.min(r-1,i+n);u+=1)a.add(u);const o=Array.from(a).sort((u,p)=>u-p),l=[];let h=null;for(const u of o){if(h!==null&&u-h>1)if(u-h===2){const p=h+1;l.push({page:p,label:p+1,active:p===i,ellipsis:!1})}else l.push({page:null,label:"…",active:!1,ellipsis:!0});l.push({page:u,label:u+1,active:u===i,ellipsis:!1}),h=u}return l}const Ve=/^(\d{4})-(\d{1,2})$/,je=1200;function re(f,e){const t=Number(f);return Number.isFinite(t)?Math.trunc(t):e}function ue(f,e){if(typeof f!="string")return"";const t=Ve.exec(f.trim());if(!t)return"";const r=Number(t[1]),i=Number(t[2]);if(i<1||i>12)return"";const n=Number.isFinite(e)?Math.trunc(e):0,s=r*12+(i-1)+n,a=Math.floor(s/12),o=s-a*12+1;return`${String(a).padStart(4,"0")}-${K(o)}`}function qe(f){if(typeof f=="string"&&f.trim()!=="")return ue(f,0);const e=new Date;return`${String(e.getFullYear()).padStart(4,"0")}-${K(e.getMonth()+1)}`}function Ne(f,e){const t=Math.trunc(Number(f));if(!Number.isFinite(t)||t<0)return[];const r=qe(e);if(r==="")return[];const i=Math.min(t,je),n=[];for(let s=0;s<=i;s+=1){const a=ue(r,-s);n.push({targetMonth:a,label:a.replace(/-/g,"/")})}return n}function Me(f,e){const t={start:0,end:0,total:0,empty:!0};if(!f||typeof f!="object")return t;const r=f,i=re(r.totalElements??r.totalCount,0);if(i<=0)return t;const n=Math.max(0,re(r.number,0)),s=Math.max(0,re(r.size,0)),a=n*s,o=Math.min(a+1,i);let l;if(e!==void 0&&Number.isFinite(e))l=Math.max(0,Math.trunc(e));else{const u=re(r.numberOfElements,NaN);l=Number.isFinite(u)?u:Math.min(s,i-a)}const h=Math.min(a+l,i);return{start:o,end:Math.max(h,o),total:i,empty:!1}}function xe(f,e,t){if(!Array.isArray(f)||f.length===0)return null;const r=String(t),i=f.find(n=>n!=null&&String(n[e])===r);return i===void 0?null:i}function Pe(f,e){if(!Array.isArray(f))return 0;let t=0;for(const r of f){const i=e==null?r:r?.[e];if(i==null||i==="")continue;const n=typeof i=="number"?i:Number(i);Number.isNaN(n)||(t+=n)}return t}function ke(f,e){return e==null||f==null?String(f):String(f[e])}function Ie(f,e){if(!Array.isArray(f))return[];const t=new Set,r=[];for(const i of f){const n=ke(i,e);t.has(n)||(t.add(n),r.push(i))}return r}function Ce(f,e){if(!Array.isArray(f))return[];const t=new Map,r=[];for(const i of f){const n=ke(i,e),s=t.get(n);if(s===void 0){const a=i==null?i:i[e];t.set(n,r.length),r.push({key:a,items:[i]})}else r[s].items.push(i)}return r}const We=Object.freeze({date:Te,number:Re,pages:Fe,range:De,monthAdd:ue,monthRange:Ne,pageSummary:Me,findBy:xe,sum:Pe,distinct:Ie,groupBy:Ce}),B=class B{static getForbiddenBindingValues(){const e=globalThis,t=[e,e.window,e.document,e.navigator,e.history,e.localStorage,e.sessionStorage,e.fetch,e.Function,e.setTimeout,e.setInterval,e.requestAnimationFrame,e.alert,e.confirm,e.prompt];return e.window?.location&&t.push(e.window.location),t.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 scheduleForbiddenKeyLogReset(){this.loggedForbiddenKeyResetScheduled||(this.loggedForbiddenKeyResetScheduled=!0,queueMicrotask(()=>{this.loggedForbiddenKeySignatures.clear(),this.loggedForbiddenKeyResetScheduled=!1}))}static buildAssignments(e){const t=new Set(e);return this.FORBIDDEN_NAMES.filter(r=>!t.has(r)).map(r=>`const ${r} = undefined`).join(`;
|
|
2
2
|
`)}static detectForbiddenIdentifiers(e){return this.FORBIDDEN_NAMES.filter(t=>new RegExp(`(^|[^\\w$.])${t}(?![\\w$])`).test(e))}static evaluate(e,t={}){return this.evaluateDetailed(e,t).value}static evaluateDetailed(e,t={}){if(this.scheduleForbiddenBindingValueCacheReset(),e.trim()==="")return m.warn("[Haori]",e,"Expression is empty"),{value:null,unresolvedReference:!1};if(this.containsDangerousPatterns(e)){const l=this.detectDisallowedKeywords(e);if(l.length>0){const h=l.some(u=>u==="function"||u==="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]",e,"Expression uses disallowed keyword(s): "+l.join(", ")+"."+h)}else m.warn("[Haori]",e,"Expression contains dangerous patterns");return{value:null,unresolvedReference:!1}}const r=this.collectForbiddenKeys(t);if(r.length>0){const l=r.join(",");this.loggedForbiddenKeySignatures.has(l)||(this.loggedForbiddenKeySignatures.add(l),this.scheduleForbiddenKeyLogReset(),m.error("[Haori]","Binding keys are reserved and ignored: "+r.join(", ")+". These collide with blocked global/prototype names and cannot be used as top-level binding keys; the remaining keys are still evaluated."))}const i=this.getForbiddenBindingValueSet();if(this.containsForbiddenBindingValues(t,new WeakSet,i))return m.warn("[Haori]",t,"Binded values contain forbidden values"),{value:null,unresolvedReference:!1};const n=e.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g,""),s=this.BUILTIN_REFERENCE_PATTERN.test(n);s&&this.BUILTIN_NAMESPACE in t&&m.warn("[Haori]",`Binding key "${this.BUILTIN_NAMESPACE}" is reserved for built-in helpers; the bound value is ignored in expressions.`);const a={};for(const l of Object.keys(t))this.FORBIDDEN_BINDING_NAMES.has(l)||(a[l]=t[l]);s&&(a[this.BUILTIN_NAMESPACE]=this.BUILTIN_HELPERS);const o=this.canAttemptMissingIdentifierRecovery(e);for(let l=0;l<=this.MAX_IDENTIFIER_RECOVERY_COUNT;l+=1){const h=this.prepareEvaluator(e,a);if(h.compileFailed||h.evaluator===null)return{value:null,unresolvedReference:!1};try{const u=[],p=this.wrapBoundValues(a);return h.bindKeys.forEach(v=>{u.push(p[v])}),{value:this.withBlockedPropertyAccess(()=>h.evaluator(...u)),unresolvedReference:!1}}catch(u){if(o&&u instanceof ReferenceError){const v=this.extractMissingIdentifier(u);if(v!==null&&this.canRecoverMissingIdentifier(v,a)){a[v]=void 0;continue}}const p=this.detectForbiddenIdentifiers(e);return p.length>0&&m.warn("[Haori]","Expression references blocked identifier(s): "+p.join(", ")+". These are blocked in expressions and evaluate to undefined (often the cause of this error). Use spread {...a, ...b} instead of Object.assign.",e),m.error("[Haori]","Expression evaluation error:",e,u),u instanceof ReferenceError?{value:void 0,unresolvedReference:!0}:{value:null,unresolvedReference:!1}}}return m.error("[Haori]","Failed to recover missing identifiers:",e,a),{value:void 0,unresolvedReference:!0}}static prepareEvaluator(e,t){const r=Object.keys(t).filter(o=>!this.FORBIDDEN_BINDING_NAMES.has(o)).sort(),i=`${e}:${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 (${e});`:`"use strict";
|
|
5
5
|
return (${e});`;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:",e,o),{bindKeys:r,evaluator:null,compileFailed:!0}}}static extractMissingIdentifier(e){return String(e.message||"").match(/^([A-Za-z_$][A-Za-z0-9_$]*) is not defined$/)?.[1]||null}static canRecoverMissingIdentifier(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?t[e]===void 0&&!(e in t):!1}static canAttemptMissingIdentifierRecovery(e){return e.includes("?.")||e.includes("??")||e.includes("||")||e.includes("&&")}static containsDangerousPatterns(e){return this.hasAllowedSyntax(e)?[/\beval\s*\(/,/\barguments\s*\[/,/\barguments\s*\./].some(r=>r.test(e)):!0}static detectDisallowedKeywords(e){const t=[];return this.DISALLOWED_KEYWORDS.forEach(r=>{new RegExp(`(^|[^\\w$.])${r}(?![\\w$])`).test(e)&&t.push(r)}),t}static hasAllowedSyntax(e){const t=this.tokenizeExpression(e);if(t===null||t.length===0)return!1;const r=[];let i=null;for(let n=0;n<t.length;n++){const s=t[n],a=t[n+1]||null,o=r[r.length-1]||null,l=t[n-2]||null,h=t[n-3]||null;if(this.startsObjectKey(o,i,l,h)&&(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 u=this.startsMemberAccess(i)?"member":"array";r.push(u);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(e){const t=[],r=["===","!==","...","?.","&&","||",">=","<=","==","!=","=>"],i=new Set(["(",")","{","}","[","]",".",",","?",":","+","-","*","/","%","!",">","<"]);let n=0;for(;n<e.length;){const s=e[n];if(/\s/.test(s)){n+=1;continue}if(s==="/"&&(e[n+1]==="/"||e[n+1]==="*"))return null;if(s==='"'||s==="'"){const o=this.readStringToken(e,n);if(o===null)return null;t.push(o.token),n=o.nextIndex;continue}const a=r.find(o=>e.startsWith(o,n));if(a){t.push({type:"operator",value:a,position:n}),n+=a.length;continue}if(/[0-9]/.test(s)){const o=this.readNumberToken(e,n);t.push(o.token),n=o.nextIndex;continue}if(/[A-Za-z_$]/.test(s)){const o=this.readIdentifierToken(e,n);t.push(o.token),n=o.nextIndex;continue}if(i.has(s)){t.push({type:"operator",value:s,position:n}),n+=1;continue}return null}return t}static readStringToken(e,t){const r=e[t];let i=t+1;for(;i<e.length;){const n=e[i];if(n==="\\"){i+=2;continue}if(n===r)return{token:{type:"string",value:e.slice(t,i+1),position:t},nextIndex:i+1};i+=1}return null}static readNumberToken(e,t){let r=t;for(;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;if(e[r]===".")for(r+=1;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;return{token:{type:"number",value:e.slice(t,r),position:t},nextIndex:r}}static readIdentifierToken(e,t){let r=t;for(;r<e.length&&/[A-Za-z0-9_$]/.test(e[r]);)r+=1;return{token:{type:"identifier",value:e.slice(t,r),position:t},nextIndex:r}}static startsMemberAccess(e){return e===null?!1:e.type==="identifier"||e.type==="number"?!0:e.value===")"||e.value==="]"||e.value==="?."}static startsObjectKey(e,t,r,i){return e!=="object"?!1:t?.value==="{"||t?.value===","||t?.type==="identifier"&&this.OBJECT_PROPERTY_MODIFIERS.has(t.value)&&(r?.value==="{"||r?.value===",")?!0:t?.value!=="*"?!1:r?.value==="{"||r?.value===","?!0:r?.type==="identifier"&&r.value==="async"&&(i?.value==="{"||i?.value===",")}static decodeStringLiteral(e){return e.slice(1,-1).replace(/\\u\{([0-9a-fA-F]+)\}/g,(t,r)=>String.fromCodePoint(parseInt(r,16))).replace(/\\u([0-9a-fA-F]{4})/g,(t,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\x([0-9a-fA-F]{2})/g,(t,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\(["'\\bfnrtv0])/g,(t,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(e){const t=new WeakMap,r={};return Object.entries(e).forEach(([i,n])=>{r[i]=this.wrapBoundValue(n,t)}),r}static wrapBoundValue(e,t){if(!this.shouldWrapValue(e))return e;const r=e,i=t.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 l=Reflect.get(s,a,o);return typeof a=="symbol"?l:this.wrapBoundValue(l,t)},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 l=Reflect.apply(s,a,o);return this.isIteratorLike(l)?l:this.wrapBoundValue(l,t)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),t)});return t.set(r,n),n}static shouldWrapValue(e){if(typeof e=="function")return!0;if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}static withBlockedPropertyAccess(e){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 e()}finally{r.forEach(({target:i,property:n,descriptor:s})=>{s!==void 0&&Object.defineProperty(i,n,s)})}}static isIteratorLike(e){return e===null||typeof e!="object"?!1:typeof e.next=="function"}static containsForbiddenKeys(e){return this.collectForbiddenKeys(e).length>0}static collectForbiddenKeys(e){return!e||typeof e!="object"?[]:Object.keys(e).filter(t=>this.FORBIDDEN_BINDING_NAMES.has(t))}static containsForbiddenBindingValues(e,t=new WeakSet,r=this.getForbiddenBindingValueSet()){if(!e||typeof e!="object")return!1;const i=this.forbiddenBindingValueCache.get(e);if(i!==void 0)return i;if(t.has(e))return!1;if(t.add(e),r.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const n of Object.values(e)){if(typeof n=="function"){if(r.has(n))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(n,t,r))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};B.MAX_IDENTIFIER_RECOVERY_COUNT=8,B.BUILTIN_NAMESPACE="haori",B.BUILTIN_HELPERS={...We},B.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,B.forbiddenBindingValueCache=new WeakMap,B.forbiddenBindingValueCacheResetScheduled=!1,B.loggedForbiddenKeySignatures=new Set,B.loggedForbiddenKeyResetScheduled=!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","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),B.FORBIDDEN_BINDING_NAMES=new Set([...B.FORBIDDEN_NAMES.filter(e=>!B.REBINDABLE_FORBIDDEN_NAMES.has(e)),"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 ge{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(e,t=!1){let r,i;const n=new Promise((a,o)=>{r=a,i=o}),s={task:e,timestamp:performance.now(),promise:n,resolve:r,reject:i};return t?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 e=performance.now();for(;this.queue.length>0;){const t=this.queue.shift();if(!t)return;try{const r=await t.task();t.resolve(r)}catch(r){t.reject(r),m.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){m.error("[Haori]","Error processing queue:",e)}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 e=this.queue.map(t=>t.promise);e.length>0&&await Promise.allSettled(e)}async waitForIdle(e=1e3){let t=0,r=0;for(;t<2&&r<e;)this.processing||this.queue.length>0?(await this.wait(),t=0):t+=1,await ge.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const me=class me{static enqueue(e,t=!1){return this.ASYNC_QUEUE.enqueue(e,t)}static wait(){return this.ASYNC_QUEUE.wait()}static waitForIdle(e=1e3){return this.ASYNC_QUEUE.waitForIdle(e)}};me.ASYNC_QUEUE=new ge;let P=me;const N=class N{static reset(){N.ELEMENT_STORES.clear(),N.ensureGlobalAccess()}static snapshot(){return N.ensureGlobalAccess(),[...N.ELEMENT_STORES.entries()].map(([e,t])=>({elementId:e,tagName:t.tagName,attributes:[...t.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:[...t.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((e,t)=>{const r=e.attributes.reduce((n,s)=>n+s.calls,0)+e.texts.reduce((n,s)=>n+s.calls,0);return t.attributes.reduce((n,s)=>n+s.calls,0)+t.texts.reduce((n,s)=>n+s.calls,0)-r})}static record(e,t,r){if(!L.isEnabled()||!e||t.length===0)return;N.ensureGlobalAccess();const i=N.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const s=N.getOrCreateCounter(i.attributes,e.rawName,e.template);N.updateCounter(s,t,r);return}const n=N.getOrCreateCounter(i.texts,String(e.childIndex),e.template);N.updateCounter(n,t,r)}static ensureGlobalAccess(){if(!L.isEnabled())return;const e=globalThis;e[N.GLOBAL_KEY]===void 0&&(e[N.GLOBAL_KEY]={reset:()=>N.reset(),snapshot:()=>N.snapshot()})}static getOrCreateElementStore(e){const t=N.createElementId(e),r=N.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return N.ELEMENT_STORES.set(t,i),i}static getOrCreateCounter(e,t,r){const i=e.get(t);if(i)return i;const n={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return e.set(t,n),n}static getOrCreatePlaceholder(e,t){const r=e.get(t);if(r)return r;const i={calls:0,totalDurationMs:0,maxDurationMs:0};return e.set(t,i),i}static updateCounter(e,t,r){e.calls+=1,e.totalDurationMs+=r,e.maxDurationMs=Math.max(e.maxDurationMs,r),t.forEach(i=>{const n=N.getOrCreatePlaceholder(e.placeholders,i.expression);n.calls+=1,n.totalDurationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs)})}static sortPlaceholders(e){return[...e.entries()].map(([t,r])=>({expression:t,calls:r.calls,totalDurationMs:r.totalDurationMs,maxDurationMs:r.maxDurationMs})).sort((t,r)=>r.calls!==t.calls?r.calls-t.calls:r.totalDurationMs-t.totalDurationMs)}static now(){return globalThis.performance?.now()??Date.now()}static measure(e){const t=N.now();return{value:e(),durationMs:N.now()-t}}static createElementId(e){const t=[];let r=e;for(;r;){let i=r.tagName.toLowerCase();const n=r.getAttribute("id")||"";if(n.trim()!==""){i+=`#${n.trim()}`,t.unshift(i);break}const s=r.getAttribute(`${c.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${c.prefix}derive-name="${s.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};N.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",N.ELEMENT_STORES=new Map;let ne=N;const X=class X{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,X.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(X.FRAGMENT_CACHE.has(e))return X.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new M(e);break;case Node.TEXT_NODE:t=new V(e);break;case Node.COMMENT_NODE:t=new pe(e);break;default:return m.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return P.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode===e.getTarget()&&e.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{e.skipMutationNodes=t})}else{const e=this.target.parentNode;if(e)return P.enqueue(()=>{this.target.parentNode===e&&e.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 e=this.parent,t=e.skipMutationNodes;return P.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode!==e.getTarget()&&e.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{e.skipMutationNodes=t})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(e){this.mounted=e}remove(e=!0){return this.parent&&this.parent.removeChild(this),X.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};X.FRAGMENT_CACHE=new WeakMap;let T=X;const K=class K extends T{constructor(e){super(e),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=e.getAttribute(`${c.prefix}bind`),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new se(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=T.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof K)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){m.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new K(this.target.cloneNode(!1));return this.attributeMap.forEach((t,r)=>{e.attributeMap.set(r,t)}),this.children.forEach(t=>{const r=t.clone();e.getTarget().appendChild(r.getTarget()),e.pushChild(r)}),e.mounted=!1,e.bindingData=this.bindingData,e.derivedBindingData=this.derivedBindingData,e.clearBindingDataCache(),e.visible=!0,e.display=this.display,e.displayPriority=this.displayPriority,e.template=this.template,e.renderSignature=this.renderSignature,e.eachInputSignature=this.eachInputSignature,e.deriveSubtreeSignature=null,e.deriveInputSignature=null,e.freshInitializationSkippable=this.freshInitializationSkippable,e.normalizeClonedVisibilityState(),e}normalizeClonedVisibilityState(){(this.visible===!1||this.getTarget().style.display==="none"||this.getTarget().hasAttribute(`${c.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${c.prefix}if-false`)),this.children.forEach(e=>{e instanceof K&&e.normalizeClonedVisibilityState()})}remove(e=!0){const t=[];return this.children.forEach(r=>{t.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&&(t.push(this.template.remove(!1)),this.template=null),this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,t.push(super.remove(e)),Promise.all(t).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(e){this.selfWrittenBind.size>64&&this.selfWrittenBind.clear(),this.selfWrittenBind.set(e,(this.selfWrittenBind.get(e)??0)+1)}consumeSelfWrittenBind(e){const t=this.selfWrittenBind.get(e);return t===void 0?!1:(t<=1?this.selfWrittenBind.delete(e):this.selfWrittenBind.set(e,t-1),!0)}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(e){this.bindingData=e,this.clearBindingDataCache()}isExecutingBindingWork(){return this.bindingWorkActive>0}markBindingWorkStart(){this.bindingWorkActive++}markBindingWorkEnd(){this.bindingWorkActive>0&&this.bindingWorkActive--}enqueueBindingWork(e){const t=this.bindingWorkChain.then(e,e);return this.bindingWorkChain=t.then(()=>{},()=>{}),t}getInitialBindAttribute(){return this.initialBindAttribute}setDerivedBindingData(e){this.derivedBindingData=e,this.clearBindingDataCache()}setParent(e){this.parent!==e&&(this.parent=e,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(e=>{e instanceof K&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e}setListKey(e){this.listKey=e}getListKey(){return this.listKey}getRenderSignature(){return this.renderSignature}setRenderSignature(e){this.renderSignature=e}getEachInputSignature(){return this.eachInputSignature}setEachInputSignature(e){this.eachInputSignature=e}getDeriveSubtreeSignature(){return this.deriveSubtreeSignature}setDeriveSubtreeSignature(e){this.deriveSubtreeSignature=e}getDeriveInputSignature(){return this.deriveInputSignature}setDeriveInputSignature(e){this.deriveInputSignature=e}isFreshInitializationSkippable(){return this.freshInitializationSkippable}setFreshInitializationSkippable(e){this.freshInitializationSkippable=e}setValue(e){return this.applyValue(e,!0)}syncBindingValue(e){return this.applyValue(e,!1)}applyValue(e,t){if(this.skipChangeValue||this.value===e)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=e===!0||e==="true":i==="false"?s=e===!1:Array.isArray(e)?s=e.map(String).includes(String(i)):s=i===String(e),n?this.value=s:s?Array.isArray(e)?this.value=String(i):this.value=e:this.value=null,r.checked===s?Promise.resolve():(this.skipChangeValue=!0,P.enqueue(()=>{r.checked=s,t&&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(e)?e.join(","):e;return this.value=this.normalizeValueForElement(r,i),this.skipChangeValue=!0,P.enqueue(()=>{r.value=i===null?"":String(i),t&&((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(e,t){if(e instanceof HTMLInputElement&&e.type==="number"){if(t===null||t==="")return null;const r=typeof t=="number"?t:Number(t);return Number.isNaN(r)?null:r}return t}syncValue(){const e=this.getTarget();if(e instanceof HTMLInputElement)if(e.type==="checkbox"||e.type==="radio"){const t=e.type==="checkbox"&&e.value==="true";if(e.checked){const r=e.value;t?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=e.value;t?this.value=!1:r==="false"?this.value=!0:this.value=null}}else this.value=this.normalizeValueForElement(e,e.value);else e instanceof HTMLTextAreaElement?this.value=e.value:e instanceof HTMLSelectElement&&(this.value=e.value)}setAttribute(e,t,r=!1){return this.setAttributeInternal(e,e,t,!0,r)}setAliasedAttribute(e,t,r,i=!1){return this.setAttributeInternal(e,t,r,!1,i)}removeAliasedAttribute(e,t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const r=this.getTarget();return P.enqueue(()=>{r.removeAttribute(e),t!==e&&r.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}setAttributeInternal(e,t,r,i,n=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const s=new se(e,r);if(n){const ce=this.attributeMap.get(e);if(ce&&(ce.isEvaluate||ce.isForceEvaluation())&&!s.isEvaluate&&!s.isForceEvaluation())return this.skipMutationAttributes=!0,P.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(e,s);const a=this.getTarget(),o=s.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:e,template:r}),l=s.isEvaluate||s.isRawEvaluate,h=e===t&&K.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),u=s.isSingleExpression(),p=G.joinEvaluateResults(o.results),v=o.results.length===1?o.results[0]:p,R=!s.isForceEvaluation()&&(t!==e||h||u?o.hasUnresolvedReference||v===null||v===void 0||v===!1:l&&p===""),I=s.isForceEvaluation()?r:u?v:p,A=i&&s.isEvaluate&&t==="value"&&(a instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(a.type)||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement),y=a.getRootNode(),b=A&&a===y.activeElement,S=R||I===null||I===!1?null:String(I),k=e!==t&&a.getAttribute(e)!==r,C=S===null?a.hasAttribute(t):a.getAttribute(t)!==S,O=A&&!b&&S!==null&&a.value!==S,j=t==="checked"&&a instanceof HTMLInputElement&&(a.type==="checkbox"||a.type==="radio"),$=t==="selected"&&a instanceof HTMLOptionElement,ee=y.activeElement,be=ee!==null&&(j&&a===ee||$&&a.closest("select")===ee),te=S!==null,ve=j&&!be&&a.checked!==te,ye=$&&!be&&a.selected!==te;return!k&&!C&&!O&&!ve&&!ye?(A&&!b&&S!==null&&(this.value=this.normalizeValueForElement(a,S)),Promise.resolve()):(this.skipMutationAttributes=!0,P.enqueue(()=>{k&&a.setAttribute(e,r),S===null?a.removeAttribute(t):(C&&(a.setAttribute(t,S),t===`${c.prefix}bind`&&this.recordSelfWrittenBind(S)),A&&!b&&(this.value=this.normalizeValueForElement(a,S),O&&(a.value=S))),ve&&(a.checked=te),ye&&(a.selected=te)}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const t=this.getTarget();return P.enqueue(()=>{t.removeAttribute(e)}).finally(()=>{this.skipMutationAttributes=!1})}getAttribute(e){return this.getAttributeEvaluation(e)?.value??null}getAttributeEvaluation(e){const t=this.attributeMap.get(e);if(t===void 0)return null;const r=t.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:this.getTarget(),rawName:e,template:t.getValue()});return r.results.length===1?{value:r.results[0],hasUnresolvedReference:r.hasUnresolvedReference}:{value:G.joinEvaluateResults(r.results),hasUnresolvedReference:r.hasUnresolvedReference}}getRawAttribute(e){const t=this.attributeMap.get(e);return t===void 0?null:t.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(e){return this.attributeMap.has(e)}resolveInsertionPointFromDom(e,t){const r=e.getTarget();if(r.parentNode!==this.target)return null;const i=t?r.nextSibling:r;let n=t?r.nextSibling:r;for(;n!==null;){const s=T.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(e,t,r){if(this.skipMutationNodes)return Promise.resolve();if(e===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(e))return m.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=e.getParent()===this;let a=-1,o=-1;s&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const l=e.getParent();l!==null&&l.removeChild(e);let h=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let p;if(s?a!==-1&&a<o?p=o-1:p=o:p=this.children.indexOf(t),p===-1){const v=this.resolveInsertionPointFromDom(t,!1);v===null?(m.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(v.index,0,e),h=v.referenceNode)}else this.children.splice(p,0,e)}e.setParent(this),e.setMounted(this.mounted);const u=this.skipMutationNodes;return this.skipMutationNodes=!0,P.enqueue(()=>{this.target.insertBefore(e.getTarget(),h)}).finally(()=>{this.skipMutationNodes=u})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(m.warn("[Haori]","Reference child not found in children.",t),this.insertBefore(e,null)):this.insertBefore(e,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(e,this.children[r+1]||null)}getPrevious(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<=0?null:t[r-1]}getNext(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<0||r+1>=t.length?null:t[r+1]}isVisible(){return this.visible}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const e=this.getTarget();return this.display=e.style.getPropertyValue("display"),this.displayPriority=e.style.getPropertyPriority("display"),e.style.setProperty("display","none","important"),e.setAttribute(`${c.prefix}if-false`,""),Promise.resolve()}show(){if(this.visible)return Promise.resolve();const e=this.getTarget();return this.display===null||this.display===""?e.style.removeProperty("display"):e.style.setProperty("display",this.display,this.displayPriority??""),this.display=null,this.displayPriority=null,e.removeAttribute(`${c.prefix}if-false`),this.visible=!0,Promise.resolve()}closestByAttribute(e){if(this.hasAttribute(e))return this;const t=this.getParent();return t===null?null:t.closestByAttribute(e)}};K.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 M=K;class V extends T{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new G(this.text)}clone(){const e=new V(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e.contents=this.contents,e.renderedText=this.renderedText,e}getTarget(){return this.target}hasDynamicContent(){return this.contents.isEvaluate||this.contents.isRawEvaluate}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new G(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):P.enqueue(()=>{this.skipMutation=!0;let e=this.text;this.contents.isRawEvaluate?e=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&&(e=G.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})));const t=this.contents.isRawEvaluate?this.parent.getTarget().innerHTML:this.target.textContent||"";this.renderedText===e&&t===e||(this.contents.isRawEvaluate?this.parent.getTarget().innerHTML=e:this.target.textContent=e,this.renderedText=e)}).finally(()=>{this.skipMutation=!1})}}class pe extends T{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new pe(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e}getTarget(){return this.target}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,P.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const oe=class oe{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(oe.PLACEHOLDER_REGEX)];let r=0,i=!1,n=!1;for(const s of t){s.index>r&&this.contents.push({text:e.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<e.length&&this.contents.push({text:e.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=n,this.checkRawExpressions()}static joinEvaluateResults(e){return e===null||e.length===0?"":e.map(t=>t==null||t===!1||Number.isNaN(t)?"":typeof t!="string"?String(t):t).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(m.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const n=[],s=[];let a=0,o=!1;return this.contents.forEach(l=>{try{if(r(l)){const h=ne.measure(()=>z.evaluateDetailed(l.text,e)),u=h.value;a+=h.durationMs,s.push({expression:l.text,durationMs:h.durationMs}),o=o||u.unresolvedReference,n.push(u.value)}else n.push(l.text)}catch(h){m.error("[Haori]",`Error evaluating ${i} expression: ${l.text}`,h),s.push({expression:l.text,durationMs:0}),n.push("")}}),ne.record(t,s,a),{results:n,hasUnresolvedReference:o}}};oe.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let G=oe;const le=class le extends G{constructor(e,t){super(t),this.forceEvaluation=le.FORCE_EVALUATION_ATTRIBUTES.includes(e)}isForceEvaluation(){return this.forceEvaluation}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){if(!this.isEvaluate&&!this.forceEvaluation)return{results:this.contents.map(i=>i.text),hasUnresolvedReference:!1};const r=this.evaluateWithProfile(e,t,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}};le.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let se=le;class Q{static get runtime(){return c.runtime}static setRuntime(e){c.setRuntime(e)}static waitForRenders(){return P.waitForIdle()}static dialog(e){return P.enqueue(()=>{window.alert(e)},!0)}static async toast(e,t="info"){const r=document.createElement("div");r.className=`haori-toast haori-toast-${t}`,r.textContent=e,r.setAttribute("popover","manual"),r.setAttribute("role","status"),r.setAttribute("aria-live",t==="error"?"assertive":"polite"),document.body.appendChild(r),r.showPopover(),setTimeout(()=>{try{r.hidePopover()}finally{r.remove()}},3e3)}static confirm(e){return P.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return P.enqueue(()=>{e instanceof HTMLDialogElement?e.showModal():m.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return P.enqueue(()=>{e instanceof HTMLDialogElement?e.close():m.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return Q.addMessage(e,t,"error")}static addMessage(e,t,r){return P.enqueue(()=>{const i=e instanceof HTMLFormElement?e:e.parentElement??e;i.setAttribute("data-message",t),r!==void 0?i.setAttribute("data-message-level",r):i.removeAttribute("data-message-level")},!0)}static clearMessages(e){return P.enqueue(()=>{e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})},!0)}static date(e,t,r){return Te(e,t,r)}static number(e,t){return Re(e,t)}static range(e,t,r){return De(e,t,r)}static pages(e,t,r){return Fe(e,t,r)}static monthAdd(e,t){return ue(e,t)}static monthRange(e,t){return Ne(e,t)}static pageSummary(e,t){return Me(e,t)}static findBy(e,t,r){return xe(e,t,r)}static sum(e,t){return Pe(e,t)}static distinct(e,t){return Ie(e,t)}static groupBy(e,t){return Ce(e,t)}}const Ke=["addErrorMessage","clearMessages"];function Ae(){const e=globalThis.window?.Haori;return Ke.every(r=>typeof e?.[r]=="function")?e:Q}class E{static getValues(e){const t={};return E.getPartValues(e,t)}static getPartValues(e,t){const r=e.getAttribute("name"),i=e.getAttribute(`${c.prefix}form-object`),n=e.getAttribute(`${c.prefix}form-list`);if(r){if(n)Array.isArray(t[String(r)])?t[String(r)].push(e.getValue()):t[String(r)]=[e.getValue()];else if(E.isGroupedCheckable(e)){const s=e.getValue(),a=String(r);s===null?a in t||(t[a]=null):t[a]===null||t[a]===void 0?t[a]=s:Array.isArray(t[a])?t[a].push(s):t[a]=[t[a],s]}else t[String(r)]=e.getValue();i&&m.warn("Haori",`Element cannot have both ${c.prefix}form-object and name attributes.`);for(const s of e.getChildElementFragments())E.getPartValues(s,t)}else if(i){const s={};for(const a of e.getChildElementFragments())E.getPartValues(a,s);Object.keys(s).length>0&&(t[String(i)]=s),n&&m.warn("Haori",`Element cannot have both ${c.prefix}form-list and ${c.prefix}form-object attributes.`)}else if(n){const s=[];for(const a of e.getChildElementFragments()){const o={};E.getPartValues(a,o),Object.keys(o).length>0&&s.push(o)}s.length>0&&(t[String(n)]=s)}else for(const s of e.getChildElementFragments())E.getPartValues(s,t);return t}static setValues(e,t,r=!1){return E.setPartValues(e,t,null,r,!0)}static syncValues(e,t,r=!1){return E.setPartValues(e,t,null,r,!1)}static isGroupedCheckable(e){const t=e.getTarget();return t instanceof HTMLInputElement?t.type==="radio"?!0:t.type!=="checkbox"?!1:t.value!=="true"&&t.value!=="false":!1}static applyFragmentValue(e,t,r){return r?e.setValue(t):e.syncBindingValue(t)}static setPartValues(e,t,r=null,i=!1,n=!0){const s=[],a=e.getAttribute("name"),o=e.getAttribute(`${c.prefix}form-object`),l=e.getAttribute(`${c.prefix}form-list`),h=e.getAttribute(`${c.prefix}form-detach`);if(a){if(!h||i){const u=t[String(a)];l&&Array.isArray(u)&&r!==null?s.push(E.applyFragmentValue(e,u[r]??null,n)):typeof u>"u"||(Array.isArray(u)&&E.isGroupedCheckable(e)||typeof u=="string"||typeof u=="number"||typeof u=="boolean"||u===null?s.push(E.applyFragmentValue(e,u,n)):s.push(E.applyFragmentValue(e,String(u),n)))}}else if(o){const u=t[String(o)];if(u&&typeof u=="object")for(const p of e.getChildElementFragments())s.push(E.setPartValues(p,u,null,i,n))}else if(l){const u=t[String(l)];if(Array.isArray(u)){const p=e.getChildElementFragments();for(let v=0;v<p.length;v++){const R=p[v];u.length>v?s.push(E.setPartValues(R,u[v],v,i,n)):s.push(E.setPartValues(R,{},v,i,n))}}}else for(const u of e.getChildElementFragments())s.push(E.setPartValues(u,t,null,i,n));return Promise.all(s).then(()=>{})}static async reset(e){E.clearValues(e),await Promise.all([E.clearMessages(e),E.clearEachClones(e)]),await P.enqueue(()=>{const r=e.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 t=E.collectBindingTargetForms(e);for(const r of t){const i=E.getInitialBindingData(r);i&&await x.setBindingData(r.getTarget(),i)}E.syncValuesFromDom(e);for(const r of t){const i=E.getInitialBindingData(r);if(r.getRawBindingData()===null&&i===null)continue;const n=E.getValues(r),s=r.getAttribute(`${c.prefix}form-arg`),a={...i||{}};s?a[String(s)]=n:Object.assign(a,n),await x.setBindingData(r.getTarget(),a)}await x.evaluateAll(e)}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:x.parseDataBind(t)}static syncValuesFromDom(e){const t=e.getTarget();(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&e.syncValue();for(const r of e.getChildElementFragments())E.syncValuesFromDom(r)}static collectBindingTargetForms(e){const t=e.getTarget(),r=[];t instanceof HTMLFormElement?r.push(t):r.push(...Array.from(t.querySelectorAll("form")));const i=[];for(const n of r){const s=T.get(n);s instanceof M&&i.push(s)}return i}static clearEachClones(e){const t=[],r=n=>{if(n.hasAttribute(`${c.prefix}each`))for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${c.prefix}each-before`),o=s.hasAttribute(`${c.prefix}each-after`);!a&&!o&&t.push(s.remove())}},i=n=>{r(n);for(const s of n.getChildElementFragments())i(s)};r(e);for(const n of e.getChildElementFragments())i(n);return Promise.all(t).then(()=>{})}static clearValues(e){e.clearValue();for(const t of e.getChildElementFragments())E.clearValues(t)}static clearMessages(e){return Ae().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return E.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=Ae(),a=s.addMessage,o=h=>typeof a=="function"?a.call(s,h,r,i):s.addErrorMessage(h,r),l=E.findFragmentsByKey(e,t);return l.forEach(h=>{n.push(o(h.getTarget()))}),l.length===0&&n.push(o(e.getTarget())),Promise.all(n).then(()=>{})}static findFragmentsByKey(e,t){return E.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&e.getAttribute("name")===i&&r.push(e),e.hasAttribute(`${c.prefix}form-object`))t.length>1&&e.getAttribute(`${c.prefix}form-object`)===i&&e.getChildElementFragments().forEach(s=>{r.push(...E.findFragmentByKeyParts(s,t.slice(1)))});else if(e.hasAttribute(`${c.prefix}form-list`)){if(t.length>1){const n=e.getAttribute(`${c.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 l=i.substring(s+1,a),h=Number(l);if(isNaN(h))m.error("Haori",`Invalid index: ${i}`);else{const u=e.getChildElementFragments().filter(p=>p.hasAttribute(`${c.prefix}row`));h<u.length&&r.push(...E.findFragmentByKeyParts(u[h],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(n=>{r.push(...E.findFragmentByKeyParts(n,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${c.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}}class F{static dispatch(e,t,r,i){const n=new CustomEvent(`haori:${t}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return e.dispatchEvent(n)}static ready(e){F.dispatch(document,"ready",{version:e})}static render(e){F.dispatch(e,"render",{target:e})}static importStart(e,t){F.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){F.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){F.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const n=[],s=new Set(Object.keys(t||{})),a=new Set(Object.keys(r)),o=new Set([...s,...a]);for(const l of o){const h=t?.[l],u=r[l];h!==u&&n.push(l)}F.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){F.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){F.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){F.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){F.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){F.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){F.dispatch(e,"show",{visible:!0})}static hide(e){F.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){F.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){F.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){F.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:n?performance.now()-n:void 0})}}const ze={401:"unauthorized-redirect",403:"forbidden-redirect"};function Ge(f,e){return f.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=z.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function Ye(f,e){const t=f.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=T.get(f),i=r instanceof M?r.getBindingData():{},n=Ge(t,i);return n===""?null:n}function Je(f,e,t){const r=f.getAttribute(`${e}-return-param`);if(r===null||r==="")return t;try{if(new URL(t,window.location.href).searchParams.has(r))return t}catch{return t}const i=window.location.pathname+window.location.search+window.location.hash,n=`${encodeURIComponent(r)}=${encodeURIComponent(i)}`,s=t.indexOf("#"),a=s>=0?t.slice(s):"",o=s>=0?t.slice(0,s):t,l=o.includes("?")?"&":"?";return`${o}${l}${n}${a}`}function Be(f){const e=ze[f];if(e===void 0||typeof document>"u")return!1;const t=`${c.prefix}${e}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=Ye(i,t);if(n===null)continue;const s=Je(i,t,n);try{if(new URL(s,window.location.href).href===window.location.href)return!1}catch{}return window.location.href=s,!0}return!1}class $e{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,n)=>{e[n]=i}),e}static isSafeLocalPath(e){const t=e.trim();if(t===""||t[0]!=="/"||t[1]==="/"||t[1]==="\\")return!1;try{return new URL(t,window.location.origin).origin===window.location.origin}catch{return!1}}}const Xe=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],Qe="__haoriHistoryState__",he="data-haori-click-lock";function ie(){const e=globalThis.window?.Haori;return Xe.every(r=>typeof e?.[r]=="function")?e:Q}const Ze=new Set(["GET","HEAD","OPTIONS"]);function _e(f){return Ze.has(f.toUpperCase())}function et(f,e){for(const[t,r]of Object.entries(e))r!==void 0&&(r===null?f.append(t,""):Array.isArray(r)?r.forEach(i=>{f.append(t,String(i))}):typeof r=="object"||typeof r=="function"?f.append(t,JSON.stringify(r)):f.append(t,String(r)))}function tt(f,e){const t=new URL(f,window.location.href),r=new URLSearchParams(t.search);return et(r,e),t.search=r.toString(),t.toString()}function rt(f){return f==null?null:typeof f=="string"?f:f instanceof URLSearchParams?f.toString():f instanceof FormData?Array.from(f.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(f)}function it(f,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:f,method:String(e.method||"GET").toUpperCase(),headers:r,body:rt(e.body||null)})}const g=class g{constructor(e,t=null,r=null){this.reentrantBind=!1,g.isElementFragment(e)?(this.options=g.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static attrName(e,t,r=!1){return e?`${c.prefix}${e}-${t}`:r?`${c.prefix}fetch-${t}`:`${c.prefix}${t}`}static resolveDataParamString(e,t){return g.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(g.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=z.evaluateDetailed(s??a??"",t);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(e,t){let r=!1,i=!1;for(let n=0;n<t;n+=1){const s=e[n];if(i){i=!1;continue}if(s==="\\"){i=!0;continue}s==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(e){if(e===void 0||Number.isNaN(e))return"null";try{return JSON.stringify(e)??JSON.stringify(String(e))}catch{return JSON.stringify(String(e))}}static stringifyJsonTemplateStringContent(e){if(e==null||Number.isNaN(e))return"";const t=typeof e=="object"?g.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return g.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(g.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const l=z.evaluateDetailed(s??a??"",t);return r=r||l.unresolvedReference,g.isJsonStringContext(e,o)?g.stringifyJsonTemplateStringContent(l.value):g.stringifyJsonTemplateValue(l.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return g.resolveDataAttributeDetailed(e,t).value}static resolveDataAttributeDetailed(e,t){const r=e.getRawAttribute(t),i=e.getAttributeEvaluation(t),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(g.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:x.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const l=g.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:x.parseDataBind(l.value),hasUnresolvedReference:s||l.hasUnresolvedReference}}const o=g.resolveDataParamStringDetailed(r,e.getBindingData());return{value:x.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e};if(t){if(e.hasAttribute(g.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(g.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(g.attrName(t,"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(e){const t=new WeakMap,r={};return Object.entries(e).forEach(([i,n])=>{r[i]=this.wrapBoundValue(n,t)}),r}static wrapBoundValue(e,t){if(!this.shouldWrapValue(e))return e;const r=e,i=t.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 l=Reflect.get(s,a,o);return typeof a=="symbol"?l:this.wrapBoundValue(l,t)},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 l=Reflect.apply(s,a,o);return this.isIteratorLike(l)?l:this.wrapBoundValue(l,t)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),t)});return t.set(r,n),n}static shouldWrapValue(e){if(typeof e=="function")return!0;if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}static withBlockedPropertyAccess(e){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 e()}finally{r.forEach(({target:i,property:n,descriptor:s})=>{s!==void 0&&Object.defineProperty(i,n,s)})}}static isIteratorLike(e){return e===null||typeof e!="object"?!1:typeof e.next=="function"}static containsForbiddenKeys(e){return this.collectForbiddenKeys(e).length>0}static collectForbiddenKeys(e){return!e||typeof e!="object"?[]:Object.keys(e).filter(t=>this.FORBIDDEN_BINDING_NAMES.has(t))}static containsForbiddenBindingValues(e,t=new WeakSet,r=this.getForbiddenBindingValueSet()){if(!e||typeof e!="object")return!1;const i=this.forbiddenBindingValueCache.get(e);if(i!==void 0)return i;if(t.has(e))return!1;if(t.add(e),r.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const n of Object.values(e)){if(typeof n=="function"){if(r.has(n))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(n,t,r))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};B.MAX_IDENTIFIER_RECOVERY_COUNT=8,B.BUILTIN_NAMESPACE="haori",B.BUILTIN_HELPERS={...We},B.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,B.forbiddenBindingValueCache=new WeakMap,B.forbiddenBindingValueCacheResetScheduled=!1,B.loggedForbiddenKeySignatures=new Set,B.loggedForbiddenKeyResetScheduled=!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","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),B.FORBIDDEN_BINDING_NAMES=new Set([...B.FORBIDDEN_NAMES.filter(e=>!B.REBINDABLE_FORBIDDEN_NAMES.has(e)),"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 G=B;class ge{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(e,t=!1){let r,i;const n=new Promise((a,o)=>{r=a,i=o}),s={task:e,timestamp:performance.now(),promise:n,resolve:r,reject:i};return t?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 e=performance.now();for(;this.queue.length>0;){const t=this.queue.shift();if(!t)return;try{const r=await t.task();t.resolve(r)}catch(r){t.reject(r),m.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){m.error("[Haori]","Error processing queue:",e)}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 e=this.queue.map(t=>t.promise);e.length>0&&await Promise.allSettled(e)}async waitForIdle(e=1e3){let t=0,r=0;for(;t<2&&r<e;)this.processing||this.queue.length>0?(await this.wait(),t=0):t+=1,await ge.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const me=class me{static enqueue(e,t=!1){return this.ASYNC_QUEUE.enqueue(e,t)}static wait(){return this.ASYNC_QUEUE.wait()}static waitForIdle(e=1e3){return this.ASYNC_QUEUE.waitForIdle(e)}};me.ASYNC_QUEUE=new ge;let P=me;const N=class N{static reset(){N.ELEMENT_STORES.clear(),N.ensureGlobalAccess()}static snapshot(){return N.ensureGlobalAccess(),[...N.ELEMENT_STORES.entries()].map(([e,t])=>({elementId:e,tagName:t.tagName,attributes:[...t.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:[...t.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((e,t)=>{const r=e.attributes.reduce((n,s)=>n+s.calls,0)+e.texts.reduce((n,s)=>n+s.calls,0);return t.attributes.reduce((n,s)=>n+s.calls,0)+t.texts.reduce((n,s)=>n+s.calls,0)-r})}static record(e,t,r){if(!L.isEnabled()||!e||t.length===0)return;N.ensureGlobalAccess();const i=N.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const s=N.getOrCreateCounter(i.attributes,e.rawName,e.template);N.updateCounter(s,t,r);return}const n=N.getOrCreateCounter(i.texts,String(e.childIndex),e.template);N.updateCounter(n,t,r)}static ensureGlobalAccess(){if(!L.isEnabled())return;const e=globalThis;e[N.GLOBAL_KEY]===void 0&&(e[N.GLOBAL_KEY]={reset:()=>N.reset(),snapshot:()=>N.snapshot()})}static getOrCreateElementStore(e){const t=N.createElementId(e),r=N.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return N.ELEMENT_STORES.set(t,i),i}static getOrCreateCounter(e,t,r){const i=e.get(t);if(i)return i;const n={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return e.set(t,n),n}static getOrCreatePlaceholder(e,t){const r=e.get(t);if(r)return r;const i={calls:0,totalDurationMs:0,maxDurationMs:0};return e.set(t,i),i}static updateCounter(e,t,r){e.calls+=1,e.totalDurationMs+=r,e.maxDurationMs=Math.max(e.maxDurationMs,r),t.forEach(i=>{const n=N.getOrCreatePlaceholder(e.placeholders,i.expression);n.calls+=1,n.totalDurationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs)})}static sortPlaceholders(e){return[...e.entries()].map(([t,r])=>({expression:t,calls:r.calls,totalDurationMs:r.totalDurationMs,maxDurationMs:r.maxDurationMs})).sort((t,r)=>r.calls!==t.calls?r.calls-t.calls:r.totalDurationMs-t.totalDurationMs)}static now(){return globalThis.performance?.now()??Date.now()}static measure(e){const t=N.now();return{value:e(),durationMs:N.now()-t}}static createElementId(e){const t=[];let r=e;for(;r;){let i=r.tagName.toLowerCase();const n=r.getAttribute("id")||"";if(n.trim()!==""){i+=`#${n.trim()}`,t.unshift(i);break}const s=r.getAttribute(`${c.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${c.prefix}derive-name="${s.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};N.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",N.ELEMENT_STORES=new Map;let ne=N;const Q=class Q{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,Q.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(Q.FRAGMENT_CACHE.has(e))return Q.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new M(e);break;case Node.TEXT_NODE:t=new V(e);break;case Node.COMMENT_NODE:t=new pe(e);break;default:return m.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return P.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode===e.getTarget()&&e.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{e.skipMutationNodes=t})}else{const e=this.target.parentNode;if(e)return P.enqueue(()=>{this.target.parentNode===e&&e.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 e=this.parent,t=e.skipMutationNodes;return P.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode!==e.getTarget()&&e.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{e.skipMutationNodes=t})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(e){this.mounted=e}remove(e=!0){return this.parent&&this.parent.removeChild(this),Q.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};Q.FRAGMENT_CACHE=new WeakMap;let T=Q;const z=class z extends T{constructor(e){super(e),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=e.getAttribute(`${c.prefix}bind`),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new se(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=T.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof z)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){m.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new z(this.target.cloneNode(!1));return this.attributeMap.forEach((t,r)=>{e.attributeMap.set(r,t)}),this.children.forEach(t=>{const r=t.clone();e.getTarget().appendChild(r.getTarget()),e.pushChild(r)}),e.mounted=!1,e.bindingData=this.bindingData,e.derivedBindingData=this.derivedBindingData,e.clearBindingDataCache(),e.visible=!0,e.display=this.display,e.displayPriority=this.displayPriority,e.template=this.template,e.renderSignature=this.renderSignature,e.eachInputSignature=this.eachInputSignature,e.deriveSubtreeSignature=null,e.deriveInputSignature=null,e.freshInitializationSkippable=this.freshInitializationSkippable,e.normalizeClonedVisibilityState(),e}normalizeClonedVisibilityState(){(this.visible===!1||this.getTarget().style.display==="none"||this.getTarget().hasAttribute(`${c.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${c.prefix}if-false`)),this.children.forEach(e=>{e instanceof z&&e.normalizeClonedVisibilityState()})}remove(e=!0){const t=[];return this.children.forEach(r=>{t.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&&(t.push(this.template.remove(!1)),this.template=null),this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,t.push(super.remove(e)),Promise.all(t).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(e){this.selfWrittenBind.size>64&&this.selfWrittenBind.clear(),this.selfWrittenBind.set(e,(this.selfWrittenBind.get(e)??0)+1)}consumeSelfWrittenBind(e){const t=this.selfWrittenBind.get(e);return t===void 0?!1:(t<=1?this.selfWrittenBind.delete(e):this.selfWrittenBind.set(e,t-1),!0)}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(e){this.bindingData=e,this.clearBindingDataCache()}isExecutingBindingWork(){return this.bindingWorkActive>0}markBindingWorkStart(){this.bindingWorkActive++}markBindingWorkEnd(){this.bindingWorkActive>0&&this.bindingWorkActive--}enqueueBindingWork(e){const t=this.bindingWorkChain.then(e,e);return this.bindingWorkChain=t.then(()=>{},()=>{}),t}getInitialBindAttribute(){return this.initialBindAttribute}setDerivedBindingData(e){this.derivedBindingData=e,this.clearBindingDataCache()}setParent(e){this.parent!==e&&(this.parent=e,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(e=>{e instanceof z&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e}setListKey(e){this.listKey=e}getListKey(){return this.listKey}getRenderSignature(){return this.renderSignature}setRenderSignature(e){this.renderSignature=e}getEachInputSignature(){return this.eachInputSignature}setEachInputSignature(e){this.eachInputSignature=e}getDeriveSubtreeSignature(){return this.deriveSubtreeSignature}setDeriveSubtreeSignature(e){this.deriveSubtreeSignature=e}getDeriveInputSignature(){return this.deriveInputSignature}setDeriveInputSignature(e){this.deriveInputSignature=e}isFreshInitializationSkippable(){return this.freshInitializationSkippable}setFreshInitializationSkippable(e){this.freshInitializationSkippable=e}setValue(e){return this.applyValue(e,!0)}syncBindingValue(e){return this.applyValue(e,!1)}applyValue(e,t){if(this.skipChangeValue||this.value===e)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=e===!0||e==="true":i==="false"?s=e===!1:Array.isArray(e)?s=e.map(String).includes(String(i)):s=i===String(e),n?this.value=s:s?Array.isArray(e)?this.value=String(i):this.value=e:this.value=null,r.checked===s?Promise.resolve():(this.skipChangeValue=!0,P.enqueue(()=>{r.checked=s,t&&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(e)?e.join(","):e;return this.value=this.normalizeValueForElement(r,i),this.skipChangeValue=!0,P.enqueue(()=>{r.value=i===null?"":String(i),t&&((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(e,t){if(e instanceof HTMLInputElement&&e.type==="number"){if(t===null||t==="")return null;const r=typeof t=="number"?t:Number(t);return Number.isNaN(r)?null:r}return t}syncValue(){const e=this.getTarget();if(e instanceof HTMLInputElement)if(e.type==="checkbox"||e.type==="radio"){const t=e.type==="checkbox"&&e.value==="true";if(e.checked){const r=e.value;t?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=e.value;t?this.value=!1:r==="false"?this.value=!0:this.value=null}}else this.value=this.normalizeValueForElement(e,e.value);else e instanceof HTMLTextAreaElement?this.value=e.value:e instanceof HTMLSelectElement&&(this.value=e.value)}setAttribute(e,t,r=!1){return this.setAttributeInternal(e,e,t,!0,r)}setAliasedAttribute(e,t,r,i=!1){return this.setAttributeInternal(e,t,r,!1,i)}removeAliasedAttribute(e,t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const r=this.getTarget();return P.enqueue(()=>{r.removeAttribute(e),t!==e&&r.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}setAttributeInternal(e,t,r,i,n=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const s=new se(e,r);if(n){const ce=this.attributeMap.get(e);if(ce&&(ce.isEvaluate||ce.isForceEvaluation())&&!s.isEvaluate&&!s.isForceEvaluation())return this.skipMutationAttributes=!0,P.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(e,s);const a=this.getTarget(),o=s.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:e,template:r}),l=s.isEvaluate||s.isRawEvaluate,h=e===t&&z.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),u=s.isSingleExpression(),p=Y.joinEvaluateResults(o.results),v=o.results.length===1?o.results[0]:p,R=!s.isForceEvaluation()&&(t!==e||h||u?o.hasUnresolvedReference||v===null||v===void 0||v===!1:l&&p===""),I=s.isForceEvaluation()?r:u?v:p,A=i&&s.isEvaluate&&t==="value"&&(a instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(a.type)||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement),y=a.getRootNode(),b=A&&a===y.activeElement,S=R||I===null||I===!1?null:String(I),k=e!==t&&a.getAttribute(e)!==r,C=S===null?a.hasAttribute(t):a.getAttribute(t)!==S,O=A&&!b&&S!==null&&a.value!==S,j=t==="checked"&&a instanceof HTMLInputElement&&(a.type==="checkbox"||a.type==="radio"),$=t==="selected"&&a instanceof HTMLOptionElement,ee=y.activeElement,be=ee!==null&&(j&&a===ee||$&&a.closest("select")===ee),te=S!==null,ve=j&&!be&&a.checked!==te,ye=$&&!be&&a.selected!==te;return!k&&!C&&!O&&!ve&&!ye?(A&&!b&&S!==null&&(this.value=this.normalizeValueForElement(a,S)),Promise.resolve()):(this.skipMutationAttributes=!0,P.enqueue(()=>{k&&a.setAttribute(e,r),S===null?a.removeAttribute(t):(C&&(a.setAttribute(t,S),t===`${c.prefix}bind`&&this.recordSelfWrittenBind(S)),A&&!b&&(this.value=this.normalizeValueForElement(a,S),O&&(a.value=S))),ve&&(a.checked=te),ye&&(a.selected=te)}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const t=this.getTarget();return P.enqueue(()=>{t.removeAttribute(e)}).finally(()=>{this.skipMutationAttributes=!1})}getAttribute(e){return this.getAttributeEvaluation(e)?.value??null}getAttributeEvaluation(e){const t=this.attributeMap.get(e);if(t===void 0)return null;const r=t.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:this.getTarget(),rawName:e,template:t.getValue()});return r.results.length===1?{value:r.results[0],hasUnresolvedReference:r.hasUnresolvedReference}:{value:Y.joinEvaluateResults(r.results),hasUnresolvedReference:r.hasUnresolvedReference}}getRawAttribute(e){const t=this.attributeMap.get(e);return t===void 0?null:t.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(e){return this.attributeMap.has(e)}resolveInsertionPointFromDom(e,t){const r=e.getTarget();if(r.parentNode!==this.target)return null;const i=t?r.nextSibling:r;let n=t?r.nextSibling:r;for(;n!==null;){const s=T.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(e,t,r){if(this.skipMutationNodes)return Promise.resolve();if(e===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(e))return m.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=e.getParent()===this;let a=-1,o=-1;s&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const l=e.getParent();l!==null&&l.removeChild(e);let h=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let p;if(s?a!==-1&&a<o?p=o-1:p=o:p=this.children.indexOf(t),p===-1){const v=this.resolveInsertionPointFromDom(t,!1);v===null?(m.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(v.index,0,e),h=v.referenceNode)}else this.children.splice(p,0,e)}e.setParent(this),e.setMounted(this.mounted);const u=this.skipMutationNodes;return this.skipMutationNodes=!0,P.enqueue(()=>{this.target.insertBefore(e.getTarget(),h)}).finally(()=>{this.skipMutationNodes=u})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(m.warn("[Haori]","Reference child not found in children.",t),this.insertBefore(e,null)):this.insertBefore(e,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(e,this.children[r+1]||null)}getPrevious(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<=0?null:t[r-1]}getNext(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<0||r+1>=t.length?null:t[r+1]}isVisible(){return this.visible}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const e=this.getTarget();return this.display=e.style.getPropertyValue("display"),this.displayPriority=e.style.getPropertyPriority("display"),e.style.setProperty("display","none","important"),e.setAttribute(`${c.prefix}if-false`,""),Promise.resolve()}show(){if(this.visible)return Promise.resolve();const e=this.getTarget();return this.display===null||this.display===""?e.style.removeProperty("display"):e.style.setProperty("display",this.display,this.displayPriority??""),this.display=null,this.displayPriority=null,e.removeAttribute(`${c.prefix}if-false`),this.visible=!0,Promise.resolve()}closestByAttribute(e){if(this.hasAttribute(e))return this;const t=this.getParent();return t===null?null:t.closestByAttribute(e)}};z.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 M=z;class V extends T{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new Y(this.text)}clone(){const e=new V(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e.contents=this.contents,e.renderedText=this.renderedText,e}getTarget(){return this.target}hasDynamicContent(){return this.contents.isEvaluate||this.contents.isRawEvaluate}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new Y(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):P.enqueue(()=>{this.skipMutation=!0;let e=this.text;this.contents.isRawEvaluate?e=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&&(e=Y.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})));const t=this.contents.isRawEvaluate?this.parent.getTarget().innerHTML:this.target.textContent||"";this.renderedText===e&&t===e||(this.contents.isRawEvaluate?this.parent.getTarget().innerHTML=e:this.target.textContent=e,this.renderedText=e)}).finally(()=>{this.skipMutation=!1})}}class pe extends T{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new pe(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e}getTarget(){return this.target}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,P.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const oe=class oe{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(oe.PLACEHOLDER_REGEX)];let r=0,i=!1,n=!1;for(const s of t){s.index>r&&this.contents.push({text:e.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<e.length&&this.contents.push({text:e.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=n,this.checkRawExpressions()}static joinEvaluateResults(e){return e===null||e.length===0?"":e.map(t=>t==null||t===!1||Number.isNaN(t)?"":typeof t!="string"?String(t):t).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(m.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const n=[],s=[];let a=0,o=!1;return this.contents.forEach(l=>{try{if(r(l)){const h=ne.measure(()=>G.evaluateDetailed(l.text,e)),u=h.value;a+=h.durationMs,s.push({expression:l.text,durationMs:h.durationMs}),o=o||u.unresolvedReference,n.push(u.value)}else n.push(l.text)}catch(h){m.error("[Haori]",`Error evaluating ${i} expression: ${l.text}`,h),s.push({expression:l.text,durationMs:0}),n.push("")}}),ne.record(t,s,a),{results:n,hasUnresolvedReference:o}}};oe.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let Y=oe;const le=class le extends Y{constructor(e,t){super(t),this.forceEvaluation=le.FORCE_EVALUATION_ATTRIBUTES.includes(e)}isForceEvaluation(){return this.forceEvaluation}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){if(!this.isEvaluate&&!this.forceEvaluation)return{results:this.contents.map(i=>i.text),hasUnresolvedReference:!1};const r=this.evaluateWithProfile(e,t,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}};le.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let se=le;class q{static get runtime(){return c.runtime}static setRuntime(e){c.setRuntime(e)}static waitForRenders(){return P.waitForIdle()}static dialog(e){return P.enqueue(()=>{window.alert(e)},!0)}static async toast(e,t="info"){const r=document.createElement("div");r.className=`haori-toast haori-toast-${t}`,r.textContent=e,r.setAttribute("popover","manual"),r.setAttribute("role","status"),r.setAttribute("aria-live",t==="error"?"assertive":"polite"),document.body.appendChild(r),r.showPopover(),setTimeout(()=>{try{r.hidePopover()}finally{r.remove()}},3e3)}static confirm(e){return P.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return P.enqueue(()=>{e instanceof HTMLDialogElement?(q.clearMessagesSync(e),e.showModal()):m.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return P.enqueue(()=>{e instanceof HTMLDialogElement?e.close():m.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return q.addMessage(e,t,"error")}static addMessage(e,t,r){return P.enqueue(()=>{const i=e instanceof HTMLFormElement?e:e.parentElement??e;i.setAttribute("data-message",t),r!==void 0?i.setAttribute("data-message-level",r):i.removeAttribute("data-message-level")},!0)}static clearMessages(e){return P.enqueue(()=>{q.clearMessagesSync(e)},!0)}static clearMessagesSync(e){e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})}static date(e,t,r){return Te(e,t,r)}static number(e,t){return Re(e,t)}static range(e,t,r){return De(e,t,r)}static pages(e,t,r){return Fe(e,t,r)}static monthAdd(e,t){return ue(e,t)}static monthRange(e,t){return Ne(e,t)}static pageSummary(e,t){return Me(e,t)}static findBy(e,t,r){return xe(e,t,r)}static sum(e,t){return Pe(e,t)}static distinct(e,t){return Ie(e,t)}static groupBy(e,t){return Ce(e,t)}}const Ke=["addErrorMessage","clearMessages"];function Ae(){const e=globalThis.window?.Haori;return Ke.every(r=>typeof e?.[r]=="function")?e:q}class E{static getValues(e){const t={};return E.getPartValues(e,t)}static getPartValues(e,t){const r=e.getAttribute("name"),i=e.getAttribute(`${c.prefix}form-object`),n=e.getAttribute(`${c.prefix}form-list`);if(r){if(n)Array.isArray(t[String(r)])?t[String(r)].push(e.getValue()):t[String(r)]=[e.getValue()];else if(E.isGroupedCheckable(e)){const s=e.getValue(),a=String(r);s===null?a in t||(t[a]=null):t[a]===null||t[a]===void 0?t[a]=s:Array.isArray(t[a])?t[a].push(s):t[a]=[t[a],s]}else t[String(r)]=e.getValue();i&&m.warn("Haori",`Element cannot have both ${c.prefix}form-object and name attributes.`);for(const s of e.getChildElementFragments())E.getPartValues(s,t)}else if(i){const s={};for(const a of e.getChildElementFragments())E.getPartValues(a,s);Object.keys(s).length>0&&(t[String(i)]=s),n&&m.warn("Haori",`Element cannot have both ${c.prefix}form-list and ${c.prefix}form-object attributes.`)}else if(n){const s=[];for(const a of e.getChildElementFragments()){const o={};E.getPartValues(a,o),Object.keys(o).length>0&&s.push(o)}s.length>0&&(t[String(n)]=s)}else for(const s of e.getChildElementFragments())E.getPartValues(s,t);return t}static setValues(e,t,r=!1){return E.setPartValues(e,t,null,r,!0)}static syncValues(e,t,r=!1){return E.setPartValues(e,t,null,r,!1)}static isGroupedCheckable(e){const t=e.getTarget();return t instanceof HTMLInputElement?t.type==="radio"?!0:t.type!=="checkbox"?!1:t.value!=="true"&&t.value!=="false":!1}static applyFragmentValue(e,t,r){return r?e.setValue(t):e.syncBindingValue(t)}static setPartValues(e,t,r=null,i=!1,n=!0){const s=[],a=e.getAttribute("name"),o=e.getAttribute(`${c.prefix}form-object`),l=e.getAttribute(`${c.prefix}form-list`),h=e.getAttribute(`${c.prefix}form-detach`);if(a){if(!h||i){const u=t[String(a)];l&&Array.isArray(u)&&r!==null?s.push(E.applyFragmentValue(e,u[r]??null,n)):typeof u>"u"||(Array.isArray(u)&&E.isGroupedCheckable(e)||typeof u=="string"||typeof u=="number"||typeof u=="boolean"||u===null?s.push(E.applyFragmentValue(e,u,n)):s.push(E.applyFragmentValue(e,String(u),n)))}}else if(o){const u=t[String(o)];if(u&&typeof u=="object")for(const p of e.getChildElementFragments())s.push(E.setPartValues(p,u,null,i,n))}else if(l){const u=t[String(l)];if(Array.isArray(u)){const p=e.getChildElementFragments();for(let v=0;v<p.length;v++){const R=p[v];u.length>v?s.push(E.setPartValues(R,u[v],v,i,n)):s.push(E.setPartValues(R,{},v,i,n))}}}else for(const u of e.getChildElementFragments())s.push(E.setPartValues(u,t,null,i,n));return Promise.all(s).then(()=>{})}static async reset(e){E.clearValues(e),await Promise.all([E.clearMessages(e),E.clearEachClones(e)]),await P.enqueue(()=>{const r=e.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 t=E.collectBindingTargetForms(e);for(const r of t){const i=E.getInitialBindingData(r);i&&await x.setBindingData(r.getTarget(),i)}E.syncValuesFromDom(e);for(const r of t){const i=E.getInitialBindingData(r);if(r.getRawBindingData()===null&&i===null)continue;const n=E.getValues(r),s=r.getAttribute(`${c.prefix}form-arg`),a={...i||{}};s?a[String(s)]=n:Object.assign(a,n),await x.setBindingData(r.getTarget(),a)}await x.evaluateAll(e)}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:x.parseDataBind(t)}static syncValuesFromDom(e){const t=e.getTarget();(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&e.syncValue();for(const r of e.getChildElementFragments())E.syncValuesFromDom(r)}static collectBindingTargetForms(e){const t=e.getTarget(),r=[];t instanceof HTMLFormElement?r.push(t):r.push(...Array.from(t.querySelectorAll("form")));const i=[];for(const n of r){const s=T.get(n);s instanceof M&&i.push(s)}return i}static clearEachClones(e){const t=[],r=n=>{if(n.hasAttribute(`${c.prefix}each`))for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${c.prefix}each-before`),o=s.hasAttribute(`${c.prefix}each-after`);!a&&!o&&t.push(s.remove())}},i=n=>{r(n);for(const s of n.getChildElementFragments())i(s)};r(e);for(const n of e.getChildElementFragments())i(n);return Promise.all(t).then(()=>{})}static clearValues(e){e.clearValue();for(const t of e.getChildElementFragments())E.clearValues(t)}static clearMessages(e){return Ae().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return E.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=Ae(),a=s.addMessage,o=h=>typeof a=="function"?a.call(s,h,r,i):s.addErrorMessage(h,r),l=E.findFragmentsByKey(e,t);return l.forEach(h=>{n.push(o(h.getTarget()))}),l.length===0&&n.push(o(e.getTarget())),Promise.all(n).then(()=>{})}static findFragmentsByKey(e,t){return E.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&e.getAttribute("name")===i&&r.push(e),e.hasAttribute(`${c.prefix}form-object`))t.length>1&&e.getAttribute(`${c.prefix}form-object`)===i&&e.getChildElementFragments().forEach(s=>{r.push(...E.findFragmentByKeyParts(s,t.slice(1)))});else if(e.hasAttribute(`${c.prefix}form-list`)){if(t.length>1){const n=e.getAttribute(`${c.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 l=i.substring(s+1,a),h=Number(l);if(isNaN(h))m.error("Haori",`Invalid index: ${i}`);else{const u=e.getChildElementFragments().filter(p=>p.hasAttribute(`${c.prefix}row`));h<u.length&&r.push(...E.findFragmentByKeyParts(u[h],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(n=>{r.push(...E.findFragmentByKeyParts(n,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${c.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}}class F{static dispatch(e,t,r,i){const n=new CustomEvent(`haori:${t}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return e.dispatchEvent(n)}static ready(e){F.dispatch(document,"ready",{version:e})}static render(e){F.dispatch(e,"render",{target:e})}static importStart(e,t){F.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){F.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){F.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const n=[],s=new Set(Object.keys(t||{})),a=new Set(Object.keys(r)),o=new Set([...s,...a]);for(const l of o){const h=t?.[l],u=r[l];h!==u&&n.push(l)}F.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){F.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){F.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){F.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){F.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){F.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){F.dispatch(e,"show",{visible:!0})}static hide(e){F.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){F.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){F.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){F.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:n?performance.now()-n:void 0})}}const ze={401:"unauthorized-redirect",403:"forbidden-redirect"};function Ge(f,e){return f.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=G.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function Ye(f,e){const t=f.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=T.get(f),i=r instanceof M?r.getBindingData():{},n=Ge(t,i);return n===""?null:n}function Je(f,e,t){const r=f.getAttribute(`${e}-return-param`);if(r===null||r==="")return t;try{if(new URL(t,window.location.href).searchParams.has(r))return t}catch{return t}const i=window.location.pathname+window.location.search+window.location.hash,n=`${encodeURIComponent(r)}=${encodeURIComponent(i)}`,s=t.indexOf("#"),a=s>=0?t.slice(s):"",o=s>=0?t.slice(0,s):t,l=o.includes("?")?"&":"?";return`${o}${l}${n}${a}`}function Be(f){const e=ze[f];if(e===void 0||typeof document>"u")return!1;const t=`${c.prefix}${e}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=Ye(i,t);if(n===null)continue;const s=Je(i,t,n);try{if(new URL(s,window.location.href).href===window.location.href)return!1}catch{}return window.location.href=s,!0}return!1}class $e{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,n)=>{e[n]=i}),e}static isSafeLocalPath(e){const t=e.trim();if(t===""||t[0]!=="/"||t[1]==="/"||t[1]==="\\")return!1;try{return new URL(t,window.location.origin).origin===window.location.origin}catch{return!1}}}const Xe=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],Qe="__haoriHistoryState__",he="data-haori-click-lock";function ie(){const e=globalThis.window?.Haori;return Xe.every(r=>typeof e?.[r]=="function")?e:q}const Ze=new Set(["GET","HEAD","OPTIONS"]);function _e(f){return Ze.has(f.toUpperCase())}function et(f,e){for(const[t,r]of Object.entries(e))r!==void 0&&(r===null?f.append(t,""):Array.isArray(r)?r.forEach(i=>{f.append(t,String(i))}):typeof r=="object"||typeof r=="function"?f.append(t,JSON.stringify(r)):f.append(t,String(r)))}function tt(f,e){const t=new URL(f,window.location.href),r=new URLSearchParams(t.search);return et(r,e),t.search=r.toString(),t.toString()}function rt(f){return f==null?null:typeof f=="string"?f:f instanceof URLSearchParams?f.toString():f instanceof FormData?Array.from(f.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(f)}function it(f,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:f,method:String(e.method||"GET").toUpperCase(),headers:r,body:rt(e.body||null)})}const g=class g{constructor(e,t=null,r=null){this.reentrantBind=!1,g.isElementFragment(e)?(this.options=g.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static attrName(e,t,r=!1){return e?`${c.prefix}${e}-${t}`:r?`${c.prefix}fetch-${t}`:`${c.prefix}${t}`}static resolveDataParamString(e,t){return g.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(g.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=G.evaluateDetailed(s??a??"",t);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(e,t){let r=!1,i=!1;for(let n=0;n<t;n+=1){const s=e[n];if(i){i=!1;continue}if(s==="\\"){i=!0;continue}s==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(e){if(e===void 0||Number.isNaN(e))return"null";try{return JSON.stringify(e)??JSON.stringify(String(e))}catch{return JSON.stringify(String(e))}}static stringifyJsonTemplateStringContent(e){if(e==null||Number.isNaN(e))return"";const t=typeof e=="object"?g.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return g.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(g.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const l=G.evaluateDetailed(s??a??"",t);return r=r||l.unresolvedReference,g.isJsonStringContext(e,o)?g.stringifyJsonTemplateStringContent(l.value):g.stringifyJsonTemplateValue(l.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return g.resolveDataAttributeDetailed(e,t).value}static resolveDataAttributeDetailed(e,t){const r=e.getRawAttribute(t),i=e.getAttributeEvaluation(t),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(g.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:x.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const l=g.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:x.parseDataBind(l.value),hasUnresolvedReference:s||l.hasUnresolvedReference}}const o=g.resolveDataParamStringDetailed(r,e.getBindingData());return{value:x.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e};if(t){if(e.hasAttribute(g.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(g.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(g.attrName(t,"confirm")).replace(/\\n/g,`
|
|
7
7
|
`)),e.hasAttribute(g.attrName(t,"data"))&&(r.dataAttrName=g.attrName(t,"data")),e.hasAttribute(g.attrName(t,"form"))){const y=e.getRawAttribute(g.attrName(t,"form"));if(y){const b=document.body.querySelector(y);b!==null?r.formFragment=E.getFormFragment(T.get(b)):m.error("Haori",`Form element not found: ${y} (${g.attrName(t,"form")})`)}else r.formFragment=E.getFormFragment(e)}else(t==="change"||t==="input")&&(r.formFragment=E.getFormFragment(e));if(e.hasAttribute(`${c.prefix}${t}-before-run`)){const y=e.getRawAttribute(`${c.prefix}${t}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
|
|
8
8
|
"use strict";
|
|
9
9
|
${y}
|
|
@@ -15,8 +15,8 @@ ${y}
|
|
|
15
15
|
"use strict";
|
|
16
16
|
${b}
|
|
17
17
|
`)}catch(S){m.error("Haori",`Invalid after script: ${S}`)}}if(e.hasAttribute(g.attrName(t,"dialog"))&&(r.dialogMessage=e.getAttribute(g.attrName(t,"dialog")).replace(/\\n/g,`
|
|
18
|
-
`)),e.hasAttribute(g.attrName(t,"toast"))){r.toastMessage=e.getAttribute(g.attrName(t,"toast"));const b=e.getRawAttribute(g.attrName(t,"toast-level")),k=["info","warning","error","success"].includes(b);r.toastLevel=k?b:null}if(e.hasAttribute(g.attrName(t,"redirect"))){r.redirectUrl=e.getAttribute(g.attrName(t,"redirect"));const b=g.attrName(t,"redirect-return-param");e.hasAttribute(b)&&(r.redirectReturnParam=e.getAttribute(b))}if(e.hasAttribute(g.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(g.attrName(t,"scroll"))&&(r.scrollTarget=e.getAttribute(g.attrName(t,"scroll"))),e.hasAttribute(g.attrName(t,"history"))&&(r.historyUrl=e.getAttribute(g.attrName(t,"history"))),e.hasAttribute(g.attrName(t,"history-data"))&&(r.historyDataAttrName=g.attrName(t,"history-data")),e.hasAttribute(g.attrName(t,"history-form"))){const b=e.getRawAttribute(g.attrName(t,"history-form"));if(b){const S=document.body.querySelector(b);S!==null?r.historyFormFragment=E.getFormFragment(T.get(S)):m.error("Haori",`Form element not found: ${b} (${g.attrName(t,"history-form")})`)}else r.historyFormFragment=E.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(b=>{const S=g.attrName(t,b);if(!e.hasAttribute(S))return;const k=e.getRawAttribute(S),C=[];if(k?(document.body.querySelectorAll(k).forEach(j=>{const $=T.get(j);$&&C.push($)}),C.length===0&&m.error("Haori",`Element not found: ${k} (${S})`)):C.push(e),C.length>0)switch(b){case"reset-before":r.resetBeforeFragments=C;break;case"reset":r.resetFragments=C;break;case"refetch":r.refetchFragments=C;break;case"click":r.clickFragments=C;break;case"copy":r.copyFragments=C;break;case"open":r.openFragments=C;break;case"close":r.closeFragments=C;break}});const y=g.attrName(t,"copy-source");if(e.hasAttribute(y)){const b=e.getRawAttribute(y);if(b){const S=document.body.querySelector(b);if(S!==null){const k=T.get(S);k?r.copySourceFragment=k:m.error("Haori",`Element is not managed by Haori: ${b} (${y})`)}else m.error("Haori",`Element not found: ${b} (${y})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(g.attrName(null,"data",!0))&&(r.dataAttrName=g.attrName(null,"data",!0)),e.hasAttribute(g.attrName(null,"form",!0)))){const A=e.getRawAttribute(g.attrName(null,"form",!0));if(A){const y=document.body.querySelector(A);y!==null?r.formFragment=E.getFormFragment(T.get(y)):m.error("Haori",`Form element not found: ${A} (${g.attrName(null,"fetch-form",!0)})`)}else r.formFragment=E.getFormFragment(e)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),r}static isElementFragment(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.getTarget=="function"&&typeof t.getChildElementFragments=="function"}static resolveAutoFetchSignature(e){return new g(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}markReentrantBind(){this.reentrantBind=!0}runWithResult(){return this.execute()}async execute(){const e=this.acquireExecutionLock();if(e===!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 h=this.options.targetFragment?.getTarget()??null;try{const u=this.options.runScript.call(h,this.domEvent);u===!1&&this.domEvent&&this.domEvent.preventDefault(),u!=null&&typeof u.then=="function"&&await u}catch(u){m.error("Haori",`Run script execution error: ${u}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(h=>E.reset(h))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let n=r.url,s=r.options;if(this.options.beforeCallback){const h=this.options.beforeCallback(n||null,s||null);if(h!=null){if(h===!1||typeof h=="object"&&h.stop)return!1;typeof h=="object"&&(n="fetchUrl"in h?h.fetchUrl:n,s="fetchOptions"in h?h.fetchOptions:s)}}const a=Object.keys(i).length>0;if(n){const h={...s||{}},u=r.requestedMethod,p=r.effectiveMethod,v=r.transportMode==="query-get",R=r.queryString;if(v&&m.info("Haori demo fetch normalization",{runtime:c.runtime,requestedMethod:u,effectiveMethod:p,transportMode:"query-get",url:n,payload:a?i:void 0,queryString:R}),this.options.targetFragment&&n){const I=performance.now(),A={runtime:c.runtime,requestedMethod:u,effectiveMethod:p,transportMode:v?"query-get":"http",...v?{queryString:R}:{}};return F.fetchStart(this.options.targetFragment.getTarget(),n,h,a?i:void 0,A),fetch(n,h).then(y=>this.handleFetchResult(y,n||void 0,I)).catch(y=>{throw n&&F.fetchError(this.options.targetFragment.getTarget(),n,y),y})}return fetch(n,h).then(I=>this.handleFetchResult(I,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const h=this.options.formFragment,u=h.getTarget(),p=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&p.add(this.options.targetFragment);const v=h.getBindingData();Object.assign(v,i),await x.setBindingData(u,v,p)}const o=a?i:{},l=new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(l)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const t=this.options.targetFragment.getTarget();if(g.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(he))return!1;const r=t.hasAttribute(`${c.prefix}click-no-disabled`);return g.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(he,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(g.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(he),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=ie();if(!e.ok)return Be(e.status)||(this.options.targetFragment&&t&&F.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r),await this.handleFetchError(e)),!1;if(this.options.targetFragment&&t&&r&&F.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const a=this.options.afterCallback(e);if(a!=null){if(a===!1||typeof a=="object"&&a.stop)return!1;typeof a=="object"&&"response"in a&&(e="response"in a?a.response:e)}}const n=[];n.push(this.bindResult(e)),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 g(a,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const a of this.options.clickFragments){await x.evaluateAll(a);const o=a.getTarget();typeof o.click=="function"?o.click():o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}if(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){let a=this.options.redirectUrl;const o=this.options.redirectReturnParam;if(o){const h=new URLSearchParams(window.location.search).get(o);if(h!==null){const u=h.trim();$e.isSafeLocalPath(u)?a=u:m.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${h}`)}}window.location.href=a}return!0}pushHistory(){const e=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,t=this.resolveHistoryDataValues(),r=this.resolveHistoryFormValues(),i=t!=null,n=r!=null;if(!(!e&&!i&&!n))try{const s=e?this.options.historyUrl:window.location.pathname,a=new URL(s,window.location.href);if(a.origin!==window.location.origin){const l="history.pushState: cross-origin URL is not allowed: "+a.toString();m.error("Haori",l);return}const o=l=>{for(const[h,u]of Object.entries(l))u!=null&&(Array.isArray(u)?u.forEach(p=>a.searchParams.append(h,String(p))):typeof u=="object"?a.searchParams.set(h,JSON.stringify(u)):a.searchParams.set(h,String(u)))};i&&o(t),n&&o(r),history.pushState({[Qe]:!0},"",a.toString())}catch(s){m.error("Haori",`history.pushState failed: ${s}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=E.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=t?t.getTarget():document.body;await ie().clearMessages(r);const i=async a=>{const o=t?t.getTarget():document.body;await ie().addErrorMessage(o,a)},n=()=>{if(!this.options.scrollOnError)return;const a=t?t.getTarget():document.body;(a.getAttribute("data-message-level")==="error"?a:a.parentElement?.getAttribute("data-message-level")==="error"?a.parentElement:a.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const a=await e.json(),o=[];if(Array.isArray(a)){const l=new Map,h=[];for(const u of a)if(u&&typeof u=="object"&&!Array.isArray(u)){const p=u.key,v=u.message,R=typeof p=="string"&&p.length>0?p:null,I=typeof v=="string"?v:v!=null?String(v):"";if(I.length===0)continue;if(R!==null){const A=l.get(R)??[];A.push(I),l.set(R,A)}else h.push(I)}else typeof u=="string"&&u.length>0&&h.push(u);for(const[u,p]of l)o.push({key:u,message:p.join(`
|
|
18
|
+
`)),e.hasAttribute(g.attrName(t,"toast"))){r.toastMessage=e.getAttribute(g.attrName(t,"toast"));const b=e.getRawAttribute(g.attrName(t,"toast-level")),k=["info","warning","error","success"].includes(b);r.toastLevel=k?b:null}if(e.hasAttribute(g.attrName(t,"redirect"))){r.redirectUrl=e.getAttribute(g.attrName(t,"redirect"));const b=g.attrName(t,"redirect-return-param");e.hasAttribute(b)&&(r.redirectReturnParam=e.getAttribute(b))}if(e.hasAttribute(g.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(g.attrName(t,"scroll"))&&(r.scrollTarget=e.getAttribute(g.attrName(t,"scroll"))),e.hasAttribute(g.attrName(t,"history"))&&(r.historyUrl=e.getAttribute(g.attrName(t,"history"))),e.hasAttribute(g.attrName(t,"history-data"))&&(r.historyDataAttrName=g.attrName(t,"history-data")),e.hasAttribute(g.attrName(t,"history-form"))){const b=e.getRawAttribute(g.attrName(t,"history-form"));if(b){const S=document.body.querySelector(b);S!==null?r.historyFormFragment=E.getFormFragment(T.get(S)):m.error("Haori",`Form element not found: ${b} (${g.attrName(t,"history-form")})`)}else r.historyFormFragment=E.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(b=>{const S=g.attrName(t,b);if(!e.hasAttribute(S))return;const k=e.getRawAttribute(S),C=[];if(k)document.body.querySelectorAll(k).forEach(j=>{const $=T.get(j);$&&C.push($)}),C.length===0&&m.error("Haori",`Element not found: ${k} (${S})`);else if(b==="open"||b==="close"){const O=e.getTarget().closest("dialog");O?C.push(T.get(O)):m.error("Haori",`Ancestor <dialog> not found (${S})`)}else C.push(e);if(C.length>0)switch(b){case"reset-before":r.resetBeforeFragments=C;break;case"reset":r.resetFragments=C;break;case"refetch":r.refetchFragments=C;break;case"click":r.clickFragments=C;break;case"copy":r.copyFragments=C;break;case"open":r.openFragments=C;break;case"close":r.closeFragments=C;break}});const y=g.attrName(t,"copy-source");if(e.hasAttribute(y)){const b=e.getRawAttribute(y);if(b){const S=document.body.querySelector(b);if(S!==null){const k=T.get(S);k?r.copySourceFragment=k:m.error("Haori",`Element is not managed by Haori: ${b} (${y})`)}else m.error("Haori",`Element not found: ${b} (${y})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(g.attrName(null,"data",!0))&&(r.dataAttrName=g.attrName(null,"data",!0)),e.hasAttribute(g.attrName(null,"form",!0)))){const A=e.getRawAttribute(g.attrName(null,"form",!0));if(A){const y=document.body.querySelector(A);y!==null?r.formFragment=E.getFormFragment(T.get(y)):m.error("Haori",`Form element not found: ${A} (${g.attrName(null,"fetch-form",!0)})`)}else r.formFragment=E.getFormFragment(e)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),r}static isElementFragment(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.getTarget=="function"&&typeof t.getChildElementFragments=="function"}static resolveAutoFetchSignature(e){return new g(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}markReentrantBind(){this.reentrantBind=!0}runWithResult(){return this.execute()}async execute(){const e=this.acquireExecutionLock();if(e===!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 h=this.options.targetFragment?.getTarget()??null;try{const u=this.options.runScript.call(h,this.domEvent);u===!1&&this.domEvent&&this.domEvent.preventDefault(),u!=null&&typeof u.then=="function"&&await u}catch(u){m.error("Haori",`Run script execution error: ${u}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(h=>E.reset(h))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let n=r.url,s=r.options;if(this.options.beforeCallback){const h=this.options.beforeCallback(n||null,s||null);if(h!=null){if(h===!1||typeof h=="object"&&h.stop)return!1;typeof h=="object"&&(n="fetchUrl"in h?h.fetchUrl:n,s="fetchOptions"in h?h.fetchOptions:s)}}const a=Object.keys(i).length>0;if(n){const h={...s||{}},u=r.requestedMethod,p=r.effectiveMethod,v=r.transportMode==="query-get",R=r.queryString;if(v&&m.info("Haori demo fetch normalization",{runtime:c.runtime,requestedMethod:u,effectiveMethod:p,transportMode:"query-get",url:n,payload:a?i:void 0,queryString:R}),this.options.targetFragment&&n){const I=performance.now(),A={runtime:c.runtime,requestedMethod:u,effectiveMethod:p,transportMode:v?"query-get":"http",...v?{queryString:R}:{}};return F.fetchStart(this.options.targetFragment.getTarget(),n,h,a?i:void 0,A),fetch(n,h).then(y=>this.handleFetchResult(y,n||void 0,I)).catch(y=>{throw n&&F.fetchError(this.options.targetFragment.getTarget(),n,y),y})}return fetch(n,h).then(I=>this.handleFetchResult(I,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const h=this.options.formFragment,u=h.getTarget(),p=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&p.add(this.options.targetFragment);const v=h.getBindingData();Object.assign(v,i),await x.setBindingData(u,v,p)}const o=a?i:{},l=new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(l)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const t=this.options.targetFragment.getTarget();if(g.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(he))return!1;const r=t.hasAttribute(`${c.prefix}click-no-disabled`);return g.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(he,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(g.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(he),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=ie();if(!e.ok)return Be(e.status)||(this.options.targetFragment&&t&&F.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r),await this.handleFetchError(e)),!1;if(this.options.targetFragment&&t&&r&&F.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const a=this.options.afterCallback(e);if(a!=null){if(a===!1||typeof a=="object"&&a.stop)return!1;typeof a=="object"&&"response"in a&&(e="response"in a?a.response:e)}}const n=[];n.push(this.bindResult(e)),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 g(a,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const a of this.options.clickFragments){await x.evaluateAll(a);const o=a.getTarget();typeof o.click=="function"?o.click():o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}if(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){let a=this.options.redirectUrl;const o=this.options.redirectReturnParam;if(o){const h=new URLSearchParams(window.location.search).get(o);if(h!==null){const u=h.trim();$e.isSafeLocalPath(u)?a=u:m.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${h}`)}}window.location.href=a}return!0}pushHistory(){const e=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,t=this.resolveHistoryDataValues(),r=this.resolveHistoryFormValues(),i=t!=null,n=r!=null;if(!(!e&&!i&&!n))try{const s=e?this.options.historyUrl:window.location.pathname,a=new URL(s,window.location.href);if(a.origin!==window.location.origin){const l="history.pushState: cross-origin URL is not allowed: "+a.toString();m.error("Haori",l);return}const o=l=>{for(const[h,u]of Object.entries(l))u!=null&&(Array.isArray(u)?u.forEach(p=>a.searchParams.append(h,String(p))):typeof u=="object"?a.searchParams.set(h,JSON.stringify(u)):a.searchParams.set(h,String(u)))};i&&o(t),n&&o(r),history.pushState({[Qe]:!0},"",a.toString())}catch(s){m.error("Haori",`history.pushState failed: ${s}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=E.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=t?t.getTarget():document.body;await ie().clearMessages(r);const i=async a=>{const o=t?t.getTarget():document.body;await ie().addErrorMessage(o,a)},n=()=>{if(!this.options.scrollOnError)return;const a=t?t.getTarget():document.body;(a.getAttribute("data-message-level")==="error"?a:a.parentElement?.getAttribute("data-message-level")==="error"?a.parentElement:a.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const a=await e.json(),o=[];if(Array.isArray(a)){const l=new Map,h=[];for(const u of a)if(u&&typeof u=="object"&&!Array.isArray(u)){const p=u.key,v=u.message,R=typeof p=="string"&&p.length>0?p:null,I=typeof v=="string"?v:v!=null?String(v):"";if(I.length===0)continue;if(R!==null){const A=l.get(R)??[];A.push(I),l.set(R,A)}else h.push(I)}else typeof u=="string"&&u.length>0&&h.push(u);for(const[u,p]of l)o.push({key:u,message:p.join(`
|
|
19
19
|
`)});for(const u of h)o.push({message:u})}else if(a&&typeof a=="object"){if(typeof a.message=="string"&&o.push({message:a.message}),Array.isArray(a.messages))for(const l of a.messages)typeof l=="string"&&o.push({message:l});if(a.errors&&typeof a.errors=="object")for(const[l,h]of Object.entries(a.errors))Array.isArray(h)?o.push({key:l,message:h.join(`
|
|
20
20
|
`)}):typeof h=="string"?o.push({key:l,message:h}):h!=null&&o.push({key:l,message:String(h)});if(o.length===0)for(const[l,h]of Object.entries(a))l==="message"||l==="messages"||l==="errors"||(Array.isArray(h)?o.push({key:l,message:h.join(`
|
|
21
|
-
`)}):typeof h=="string"&&o.push({key:l,message:h}))}if(o.length===0)return await i(`${e.status} ${e.statusText}`),n(),!1;for(const l of o)l.key&&t?await E.addErrorMessage(t,l.key,l.message):await i(l.message);return n(),!1}catch{}try{const a=await e.text();a&&a.trim().length>0?await i(a.trim()):await i(`${e.status} ${e.statusText}`)}catch{await i(`${e.status} ${e.statusText}`)}return n(),!1}validate(e){if(this.options.valid!==!0)return!0;const t=this.findFirstInvalid(e);return t===null?!0:(t.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(e){let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):ie().confirm(e)}bindResult(e){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const t=e.headers.get("Content-Type")?.includes("application/json");return e.text().then(r=>{if(r==="")return;let i=t?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 l=a[o],h=l&&typeof l=="object"&&!Array.isArray(l)?l:{};a[o]=this.mergeAppendBindingData(s,i,h)}else a[o]=i;n.push(x.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(x.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=>{F.bindComplete(a.getTarget(),s)})})})}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},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 e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=this.options.copyFragments.map(i=>{const n={...i.getBindingData(),...t};return x.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 e={};let t=!1;if(this.options.formFragment&&Object.assign(e,E.getValues(this.options.formFragment)),this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const r=g.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||r.hasUnresolvedReference,r.value&&Object.assign(e,r.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}}prepareFetchRequest(){const e=this.buildPayloadResolution(),t=e.payload,r=!!this.options.fetchHasUnresolvedReference||e.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:t,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=c.runtime==="demo"&&!_e(a),l=o?"GET":a;if(n.method=l,l==="GET"||l==="HEAD"||l==="OPTIONS")Object.keys(t).length>0&&(i=tt(i,t));else if(Object.keys(t).length>0){const u=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(u)){s.delete("Content-Type");const p=new FormData;for(const[v,R]of Object.entries(t))R==null?p.append(v,""):R instanceof Blob?p.append(v,R):Array.isArray(R)?R.forEach(I=>p.append(v,String(I))):typeof R=="object"?p.append(v,JSON.stringify(R)):p.append(v,String(R));n.body=p}else if(/application\/x-www-form-urlencoded/i.test(u)){const p=new URLSearchParams;for(const[v,R]of Object.entries(t))R!==void 0&&(R===null?p.append(v,""):Array.isArray(R)?R.forEach(I=>p.append(v,String(I))):typeof R=="object"?p.append(v,JSON.stringify(R)):p.append(v,String(R)));n.body=p}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}n.headers=s;let h;return o&&(h=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,options:n,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:l,queryString:h,transportMode:o?"query-get":"http",signature:it(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=g.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?g.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(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=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}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(s=>{s in e&&(r.has(s)||(i[s]=e[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];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+=e,t.push(r.setValue(String(n)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return m.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${c.prefix}row`);return e||(m.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=[],r=e.clone();return t.push(e.getParent().insertAfter(r,e)),t.push(x.evaluateAll(r)),t.push(E.reset(r)),Promise.all(t).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getParent();return t&&t.getChildElementFragments().filter(i=>!i.hasAttribute(`${c.prefix}each-before`)&&!i.hasAttribute(`${c.prefix}each-after`)).length<=1?Promise.resolve():e.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getPrevious();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertBefore(e,t):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getNext();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertAfter(e,t):Promise.resolve()}};g.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,g.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,g.RUNNING_CLICK_TARGETS=new WeakSet;let q=g;class nt{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw m.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){Be(r.status);const n=`${r.status} ${r.statusText}`;throw m.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw m.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}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:",e),i)}catch(n){return m.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const d=class d{static isDeferredAttributeName(e){return d.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${c.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${c.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!d.isEvaluateAllExcludedAttributeName(e)&&d.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${c.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=T.get(e);return r instanceof M?r.hasAttribute(`${c.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);d.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>d.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof M?t.push(d.evaluateAll(r)):r instanceof V&&t.push(d.evaluateText(r))}),Promise.all(t).then(()=>{})}static getReactiveFetchState(e){const t=d.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return d.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=d.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return d.REACTIVE_IMPORT_STATES.set(e,r),r}static reevaluateReactiveSpecialAttributes(e,t=new Set){if(t.has(e))return Promise.resolve();const r=[];return e.hasAttribute(`${c.prefix}fetch`)&&r.push(d.executeManagedFetch(e)),e.hasAttribute(`${c.prefix}import`)&&r.push(d.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof M&&r.push(d.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=d.getReactiveFetchState(t),i=q.resolveAutoFetchSignature(e);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 q(e,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,d.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=d.getReactiveImportState(t),i=e.getAttributeEvaluation(`${c.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 t.setAttribute(`${c.prefix}importing`,""),F.importStart(t,n),nt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return P.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${c.prefix}importing`),F.importEnd(t,n,o,s),!document.body.hasAttribute("data-haori-ready")){const l=[];return t.childNodes.forEach(h=>{const u=T.get(h);u instanceof M?l.push(d.scan(u.getTarget())):u instanceof V&&l.push(d.evaluateText(u))}),Promise.all(l).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${c.prefix}importing`),F.importError(t,n,a),m.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,d.executeManagedImport(e)})}static scan(e){const t=T.get(e);return t?d.initializeElementFragment(t,!1):Promise.resolve()}static initializeFreshEachRow(e){return d.initializeElementFragment(e,!0).then(()=>{d.needsScheduledEvaluateAll(e)&&d.scheduleEvaluateAll(e)})}static initializeElementFragment(e,t){return d.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():d.initializeElementAttributes(e).then(()=>{if(d.shouldSkipChildInitialization(e,t)){d.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof M?r.push(d.initializeElementFragment(i,t)):i instanceof V&&r.push(d.evaluateText(i))}),Promise.all(r).then(()=>{d.refreshDerivedSubtreeSignature(e)})})}static syncMountedState(e){if(e.getParent()?.isMounted()){e.setMounted(!0);return}const r=e.getTarget();if(r.parentNode&&document.body.contains(r)){e.setMounted(!0);return}e.setMounted(!1)}static initializeElementAttributes(e){let t=Promise.resolve();const r=new Set;for(const i of d.PRIORITY_ATTRIBUTE_SUFFIXES){const n=c.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>d.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||d.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>d.setAttribute(e.getTarget(),i,n)))}for(const i of d.DEFERRED_ATTRIBUTE_SUFFIXES){const n=c.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>d.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}return t.then(()=>{})}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${c.prefix}if`);return e.hasAttribute(`${c.prefix}if`)&&d.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${c.prefix}each`)}static setAttribute(e,t,r,i=!1){const n=T.get(e),s=d.getAliasedAttributeName(t);if(s!==null)return r===null?n.removeAliasedAttribute(t,s):n.setAliasedAttribute(t,s,r,i);const a=[];let o=null,l=null;switch(t){case`${c.prefix}bind`:{if(r===null)n.clearBindingDataCache(),n.setBindingData({});else{if(i&&n instanceof M&&n.consumeSelfWrittenBind(r))break;n.setBindingData(d.parseDataBind(r))}break}case`${c.prefix}derive`:l=d.createDeriveInputSignature(n,r,n.getRawAttribute(`${c.prefix}derive-name`)),o=d.evaluateDerive(n,r,n.getRawAttribute(`${c.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${c.prefix}derive-name`:l=d.createDeriveInputSignature(n,n.getRawAttribute(`${c.prefix}derive`),r),o=d.evaluateDerive(n,n.getRawAttribute(`${c.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${c.prefix}if`:a.push(d.evaluateIf(n));break;case`${c.prefix}each`:a.push(d.evaluateEach(n));break;case`${c.prefix}fetch`:a.push(d.executeManagedFetch(n));break;case`${c.prefix}import`:typeof r=="string"&&a.push(d.executeManagedImport(n));break;case`${c.prefix}url-param`:{const h=n.getAttribute(`${c.prefix}url-arg`),u=$e.readParams();if(h===null)a.push(d.setBindingData(e,u,new Set,!0));else{const p=n.getRawBindingData()||{};p[String(h)]=u,a.push(d.setBindingData(e,p,new Set,!0))}break}}return r===null?a.push(n.removeAttribute(t)):a.push(n.setAttribute(t,r,i)),Promise.all(a).then(()=>{if(o!==null)return n.setDeriveInputSignature(l),o.then(h=>{if(h)return d.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(e,t,r=new Set,i=!1,n=!0){const s=T.get(e),a=s.getRawBindingData();s.setBindingData(t),n&&F.bindChange(e,a,t,"manual");const o=()=>{s.markBindingWorkStart();const l=s.getRawBindingData()??t;let h=n?s.setAttribute(`${c.prefix}bind`,JSON.stringify(l)):Promise.resolve();if(e.tagName==="FORM"){const u=s.getAttribute(`${c.prefix}form-arg`),p=u&&l[String(u)]&&typeof l[String(u)]=="object"&&!Array.isArray(l[String(u)])?l[String(u)]:u?{}:l;h=h.then(()=>E.syncValues(s,p))}return h=h.then(()=>d.evaluateAll(s,r)),h=h.then(()=>d.reevaluateReactiveSpecialAttributes(s,r)),h.then(()=>s.markBindingWorkEnd(),u=>{throw s.markBindingWorkEnd(),u})};return i?o():s.enqueueBindingWork(o)}static getBindingData(e,t={}){const r=T.get(e);return r instanceof M?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=T.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=l=>{const h=l.getTarget();return h.id?`#${h.id}`:h.tagName.toLowerCase()},s=(l,h,u,p)=>{if(l)for(const v of Object.keys(l))v in i||(i[v]={value:l[v],source:n(h),kind:u,depth:p})};let a=t,o=0;for(;a;)a!==t&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return L.isEnabled()&&m.info("[Haori]","scope dump for",e,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return m.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,n]of t.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(e,t){const r=T.get(e);if(r.isSkipMutationNodes())return;const i=T.get(t.nextSibling),n=T.get(t);n&&(r.insertBefore(n,i),n instanceof M?d.scan(n.getTarget()):n instanceof V&&d.evaluateText(n))}static removeNode(e){const t=T.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=T.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=T.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=d.getFormFragment(r);if(n){const s=E.getValues(n),a=n.getAttribute(`${c.prefix}form-arg`);let o;a?(o=n.getRawBindingData(),o||(o={}),o[String(a)]=s):o=s,i.push(d.setBindingData(n.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?d.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=d.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${c.prefix}derive`),n=e.hasAttribute(`${c.prefix}if`),s=e.hasAttribute(`${c.prefix}each`),a=e.getRawAttribute(`${c.prefix}derive`),o=e.getRawAttribute(`${c.prefix}derive-name`);let l=!1,h=!1,u=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const p=d.createDeriveInputSignature(e,a,o);p===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>d.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==p&&(r=r.then(()=>d.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(p)})))}return n&&(r=r.then(()=>d.evaluateIf(e))),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>d.evaluateEach(e))):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!d.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}u=d.createDescendantBindingSignature(e,"evaluateAll"),h=!0,l=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===u,d.logDerivedSubtreeProfileSnapshot(e,l?"skip-hit":"skip-miss")})),r.then(()=>{if(l)return;const p=[];return e.getChildren().forEach(v=>{if(v instanceof M){if(d.canSkipUnchangedNestedEach(v))return;p.push(d.evaluateAll(v,t))}else v instanceof V&&p.push(d.evaluateText(v))}),Promise.all(p).then(()=>{})}).then(()=>{h&&u!==null&&e.setDeriveSubtreeSignature(u)}))}static evaluateDerive(e,t=e.getRawAttribute(`${c.prefix}derive`),r=e.getRawAttribute(`${c.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!t||n==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const s=z.evaluateDetailed(t,e.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return d.createBindingSignature(i)===d.createBindingSignature(a)?Promise.resolve(!1):(e.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(e){return e.evaluate()}static isHiddenIfCondition(e){return!e}static logFalsyIfDiagnostics(e){const t=e.getRawAttribute(`${c.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;const{sources:r}=d.dumpScope(e.getTarget()),i=new Set,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const l=t.indexOf(o,s);s=l+o.length,!(l>0&&t[l-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),m.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${c.prefix}if`);if(d.isHiddenIfCondition(r))L.isEnabled()&&d.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{F.hide(e.getTarget())}));else{const i=e.isVisible(),n=[];e.getChildren().forEach(s=>{s instanceof M?n.push(s.isMounted()?d.evaluateAll(s):d.scan(s.getTarget())):s instanceof V&&n.push(d.evaluateText(s))}),t.push(e.show().then(()=>{F.show(e.getTarget()),i||d.triggerLoadOnShow(e)})),t.push(Promise.all(n).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${c.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new q(e,"load").run().catch(i=>{m.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=d.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},d.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(!e.isVisible()||!e.isMounted())return Promise.resolve();const t=d.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):d.runEachUpdateLoop(e,t)}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${c.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await d.performEachUpdate(e);while(t.rerunRequested);e.getTarget().setAttribute(`${c.prefix}each-done`,"")}finally{t.running=!1,t.settled=null}})();return t.settled=r,r}static performEachUpdate(e){const t=d.resolveEachItems(e);if(t===null)return Promise.reject(new Error("Invalid each attribute."));let r=e.getTemplate();const i=e.getAttribute(`${c.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let s=!1;if(e.getChildren().forEach(a=>{if(!s&&a instanceof M){if(a.hasAttribute(`${c.prefix}each-before`)||a.hasAttribute(`${c.prefix}each-after`))return;r=a.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=e.getTarget();Array.from(a.children).filter(l=>!l.hasAttribute(`${c.prefix}each-before`)&&!l.hasAttribute(`${c.prefix}each-after`)).forEach(l=>{if(!s){const u=T.get(l);u instanceof M&&(r=u.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const h=T.get(l);h instanceof M&&e.getChildren().includes(h)&&(e.removeChild(h),h.setMounted(!1)),l.parentNode&&l.parentNode.removeChild(l)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}return e.getEachInputSignature()===n?Promise.resolve():this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}static resolveEachItems(e){const t=e.getAttributeEvaluation(`${c.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(m.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${c.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${c.prefix}derive`)||t?.closestByAttribute(`${c.prefix}derive-name`)||t?.closestByAttribute(`${c.prefix}if`)||t?.closestByAttribute(`${c.prefix}fetch`)||t?.closestByAttribute(`${c.prefix}import`)||d.hasNonEachDynamicElementState(e))return!1;const r=d.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${c.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===n}static canSkipStableDerivedSubtree(e){return!e.hasAttribute(`${c.prefix}derive`)||e.hasAttribute(`${c.prefix}if`)||e.hasAttribute(`${c.prefix}each`)||e.hasAttribute(`${c.prefix}fetch`)||e.hasAttribute(`${c.prefix}import`)?!1:!d.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof M?t.hasAttribute(`${c.prefix}derive`)||t.hasAttribute(`${c.prefix}derive-name`)||t.hasAttribute(`${c.prefix}fetch`)||t.hasAttribute(`${c.prefix}import`)?!0:d.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return d.recordDerivedSubtreeSignatureComputation(e,t),d.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:d.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!d.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(d.createDescendantBindingSignature(e,"refresh")),d.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!L.isEnabled()||!e.hasAttribute(`${c.prefix}derive`))return null;const t=d.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:d.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return d.DERIVE_SUBTREE_PROFILES.set(e,r),r}static createDerivedSubtreeHostId(e){const t=[];let r=e;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();if(i.id.trim()!==""){n+=`#${i.id.trim()}`,t.unshift(n);break}const s=r.getRawAttribute(`${c.prefix}derive-name`);typeof s=="string"&&s.trim()!==""&&(n+=`[${c.prefix}derive-name="${s.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(l=>l instanceof M).findIndex(l=>l===r);n+=`:nth-child(${o+1})`}t.unshift(n),r=a}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),m.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${c.prefix}each`,`${c.prefix}each-key`,`${c.prefix}each-arg`,`${c.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${c.prefix}attr-`)||i.startsWith(c.prefix))return!0;const n=e.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:e.getChildren().some(i=>i instanceof V&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>d.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof M?!d.markFreshInitializationSkippable(n):n instanceof V?n.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${c.prefix}attr-`)||t.startsWith(c.prefix))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static updateDiff(e,t){const r=e.getTemplate();if(r===null)return m.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=e.getAttribute(`${c.prefix}each-index`);i&&(i=String(i));const n=e.getAttribute(`${c.prefix}each-key`),s=e.getAttribute(`${c.prefix}each-arg`),a=new Map,o=[];t.forEach((b,S)=>{const k=d.createListKey(b,n?String(n):null,S);o.push(k),a.set(k,{item:b,itemIndex:S})});const l=new Set(o),h=[];let u=e.getChildren().filter(b=>b instanceof M).filter(b=>!b.hasAttribute(`${c.prefix}each-before`)&&!b.hasAttribute(`${c.prefix}each-after`));const p=u.map(b=>b.getListKey());u=u.filter(b=>l.has(String(b.getListKey()))?!0:(h.push(b.remove()),!1));const v=u.map(b=>b.getListKey()),R=new Map;u.forEach(b=>{const S=b.getListKey();S!==null&&!R.has(S)&&R.set(S,b)});const I=e.getChildElementFragments().slice(),A=I.filter(b=>b.hasAttribute(`${c.prefix}each-before`)).length;let y=Promise.resolve();return o.forEach((b,S)=>{const{item:k,itemIndex:C}=a.get(b);let O;const j=R.get(b);if(j)O=j,y=y.then(()=>d.updateRowFragment(O,k,i,C,s?String(s):null,b).then($=>{if($)return d.evaluateAll(O)}));else{O=r.clone();const $=A+S;y=y.then(()=>d.updateRowFragment(O,k,i,C,s?String(s):null,b).then(()=>{const ee=I[$]??null;return e.insertBefore(O,ee).then(()=>{I.splice($,0,O)}).then(()=>d.initializeFreshEachRow(O))}))}}),Promise.all(h).then(()=>y).then(()=>{const b=o.filter($=>$!==null),S=v.filter($=>$!==null),k=new Set(S),C=b.filter($=>!k.has($)),j=p.filter($=>$!==null).filter($=>!l.has($));F.eachUpdate(e.getTarget(),C,j,b)})}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const n=e[t];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,n,s){let a=t;if(typeof t=="object"&&t!==null)a={...t},r&&(a[r]=i),n&&(a={[n]:a});else if(n)a={[n]:t},r&&(a[r]=i);else return m.error("[Haori]",`Primitive value requires '${c.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);const o=a,l=d.createBindingSignature({listKey:s,bindingData:o});return e.getListKey()===s&&e.getRenderSignature()===l?Promise.resolve(!1):(e.setListKey(s),e.setRenderSignature(l),e.setBindingData(o),e.setAttribute(`${c.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(e){const t=[e];for(;t.length>0;){const r=t.pop();if(r.getChildElementFragments().forEach(i=>{t.push(i)}),r!==e&&!r.isMounted()&&d.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${c.prefix}${t}`))}static createBindingSignature(e,t=new WeakMap,r={value:0}){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="function")return`[Function:${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e instanceof Date)return`[Date:${e.toISOString()}]`;if(Array.isArray(e)){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`array-${r.value}`;return r.value+=1,t.set(e,i),`[${e.map(n=>d.createBindingSignature(n,t,r)).join(",")}]`}if(typeof e=="object"){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`object-${r.value}`;r.value+=1,t.set(e,i);const n=e;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${d.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{d.evaluateAll(e)},100)}};d.ATTRIBUTE_ALIAS_SUFFIX="attr-",d.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],d.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],d.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,d.REACTIVE_FETCH_STATES=new WeakMap,d.REACTIVE_IMPORT_STATES=new WeakMap,d.DERIVE_SUBTREE_PROFILES=new WeakMap,d.EACH_UPDATE_STATES=new WeakMap;let x=d;const _=class _{constructor(e=document){this.customEventHandlers=new Map,this.onClick=t=>this.delegate(t,"click"),this.onChange=t=>this.delegate(t,"change"),this.onInput=t=>this.delegate(t,"input"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{const t=document.documentElement,r=T.get(t);r&&new q(r,"load").run()},this.onPopstate=t=>{const r=t.state;!r||r[_.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}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[e,t]of this.customEventHandlers)window.removeEventListener(e,t,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${c.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(_.BUILTIN_EVENT_NAMES.has(e)){m.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==e)return;const n=T.get(i);n instanceof M&&new q(n,"on",t).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const e=this.root instanceof Document?this.root:this.root.ownerDocument??document,t=this.root instanceof Document?e.body:this.root;t&&(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(t,{childList:!0,subtree:!0}))}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(!r)return;if(t==="input"){const s=`${c.prefix}input-`;if(!r.getAttributeNames().some(o=>o.startsWith(s)))return}r.hasAttribute(`${c.prefix}${t}-prevent`)&&e.preventDefault();const i=T.get(r);if(!i)return;(t==="change"||t==="input")&&i instanceof M&&i.syncValue();const n=()=>{new q(i,t,e).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})};if(t==="click"&&r.hasAttribute(`${c.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}getElementFromTarget(e,t){if(!e)return null;if(e instanceof HTMLElement)return t==="click"?this.findClickableElement(e):e;if(e instanceof Node){const r=e.parentElement;return r?t==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(e){const t=`${c.prefix}click-`,r=`${c.prefix}click-passive`;let i=e;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(t)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};_.HISTORY_STATE_KEY="__haoriHistoryState__",_.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let fe=_;const D=class D{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(D.isHtmlElement(e)&&D.syncElement(e),e.querySelectorAll("*").forEach(t=>{D.syncElement(t)}))}static syncElement(e){const t=D.registrations.get(e),r=T.get(e);if(!r||!D.shouldObserve(r)){t&&(t.observer.disconnect(),D.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=D.resolveRoot(r),n=D.resolveRootMargin(r),s=D.resolveThreshold(r),a=r.hasAttribute(`${c.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===n&&D.sameThreshold(t.observer.thresholds,s)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),D.registrations.delete(e));const o=new IntersectionObserver(l=>{const h=D.registrations.get(e);h&&l.forEach(u=>{!u.isIntersecting||h.running||D.isDisabled(h.fragment)||(h.running=!0,new q(h.fragment,"intersect").runWithResult().then(p=>{p&&h.once&&(h.observer.disconnect(),D.registrations.delete(e))}).catch(p=>{m.error("[Haori]","Intersect procedure execution error:",p)}).finally(()=>{const p=D.registrations.get(e);p&&(p.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(e),D.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(D.isHtmlElement(e)){const t=D.registrations.get(e);t&&(t.observer.disconnect(),D.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=D.registrations.get(t);r&&(r.observer.disconnect(),D.registrations.delete(t))})}static disconnectAll(){D.registrations.forEach(e=>{e.observer.disconnect()}),D.registrations.clear()}static shouldObserve(e){return e.getAttributeNames().some(t=>{if(!t.startsWith(`${c.prefix}intersect-`))return!1;const r=t.slice(`${c.prefix}intersect-`.length);return!D.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${c.prefix}intersect-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);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(e){const t=`${c.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${c.prefix}intersect-threshold`,r=e.getAttribute(t),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(e){const t=`${c.prefix}intersect-disabled`,r=e.getAttribute(t);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(e,t){return e.length===1&&e[0]===t}};D.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),D.registrations=new Map;let Z=D;function st(f){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>f()):Promise.resolve().then(f)}const w=class w{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(w.isHtmlElement(e)&&w.syncElement(e),e.querySelectorAll("*").forEach(t=>{w.syncElement(t)}))}static syncElement(e){const t=w.registrations.get(e),r=T.get(e);if(!(r instanceof M)||!w.shouldObserve(r)){t&&(t.observer.disconnect(),w.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=w.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),w.registrations.delete(e)),m.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=w.resolveRoot(r),s=w.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,w.refreshRows(t);return}t&&(t.observer.disconnect(),w.registrations.delete(e));const a=new IntersectionObserver(l=>{const h=w.registrations.get(e);if(!h)return;let u=!1;l.forEach(p=>{const v=p.target;h.observedRows.has(v)&&(p.isIntersecting?h.visibleRows.has(v)||(h.visibleRows.add(v),u=!0):h.visibleRows.delete(v)&&(u=!0))}),u&&w.scheduleCompute(h)},{root:n,rootMargin:s,threshold:w.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};w.registrations.set(e,o),w.refreshRows(o)}static cleanupTree(e){if(w.isHtmlElement(e)){const t=w.registrations.get(e);t&&(t.observer.disconnect(),w.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=w.registrations.get(t);r&&(r.observer.disconnect(),w.registrations.delete(t))})}static disconnectAll(){w.registrations.forEach(e=>{e.observer.disconnect()}),w.registrations.clear()}static shouldObserve(e){return e.hasAttribute(`${c.prefix}each`)&&e.hasAttribute(`${c.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${c.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${c.prefix}each-visible-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return w.isHtmlElement(i)?i:(m.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${c.prefix}each-visible-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?w.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof M&&!t.hasAttribute(`${c.prefix}each-before`)&&!t.hasAttribute(`${c.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=w.realRowElements(e.fragment),r=new Set(t);for(const i of[...e.observedRows])r.has(i)||(e.observer.unobserve(i),e.observedRows.delete(i),e.visibleRows.delete(i));for(const i of t)e.observedRows.has(i)||(e.observer.observe(i),e.observedRows.add(i));w.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,st(()=>{e.scheduled=!1;const t=e.fragment.getTarget();w.registrations.get(t)===e&&w.computeAndPublish(e)}))}static computeAndPublish(e){const t=w.realRowElements(e.fragment),r=new Map;t.forEach((a,o)=>r.set(a,o));const i=[];for(const a of e.visibleRows){const o=r.get(a);o!==void 0&&i.push(o)}let n;if(i.length===0)n={first:-1,last:-1,firstLabel:0,lastLabel:0,count:0,total:t.length,empty:!0};else{let a=i[0],o=i[0];for(const l of i)l<a&&(a=l),l>o&&(o=l);n={first:a,last:o,firstLabel:a+1,lastLabel:o+1,count:i.length,total:t.length,empty:!1}}const s=JSON.stringify(n);s!==e.lastSnapshot&&(e.lastSnapshot=s,w.publish(e,n))}static publish(e,t){const r=w.resolveBindOwner(e.fragment);if(!r){m.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);x.setBindingData(i,n,a,!1,!1).catch(o=>{m.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${c.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};w.THRESHOLD=0,w.DEFAULT_ROOT_MARGIN="0px",w.registrations=new Map;let Y=w;const H=class H{static disconnectMutationObservers(){H._mutationObservers.forEach(e=>{e.disconnect()}),H._mutationObservers.length=0}static async init(){if(H._initialized)return;H._initialized=!0,H.disconnectMutationObservers();const e=await Promise.allSettled([x.scan(document.head),x.scan(document.body)]),[t,r]=e;t.status!=="fulfilled"&&m.error("[Haori]","Failed to build head fragment:",t.reason),r.status!=="fulfilled"&&m.error("[Haori]","Failed to build body fragment:",r.reason),await P.wait(),document.body.setAttribute("data-haori-ready",""),H.observe(document.head),H.observe(document.body),new fe().start(),Z.syncTree(document.body),Y.syncTree(document.body)}static observe(e){const t=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&&x.isAliasedAttributeReflection(n,i.attributeName))break;x.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),Z.syncElement(n),Y.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{Z.cleanupTree(n),Y.cleanupTree(n),x.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(x.addNode(n.parentElement,n),Z.syncTree(n),Y.syncTree(n))}),i.target instanceof Element&&Y.syncElement(i.target);break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?x.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)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),H._mutationObservers.push(t)}};H._initialized=!1,H._mutationObservers=[];let ae=H;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ae.init):ae.init();const at=()=>Q.waitForRenders(),ot="0.20.0";exports.Core=x;exports.Env=c;exports.Form=E;exports.Fragment=T;exports.Haori=Q;exports.Log=m;exports.Queue=P;exports.default=Q;exports.version=ot;exports.waitForRenders=at;
|
|
21
|
+
`)}):typeof h=="string"&&o.push({key:l,message:h}))}if(o.length===0)return await i(`${e.status} ${e.statusText}`),n(),!1;for(const l of o)l.key&&t?await E.addErrorMessage(t,l.key,l.message):await i(l.message);return n(),!1}catch{}try{const a=await e.text();a&&a.trim().length>0?await i(a.trim()):await i(`${e.status} ${e.statusText}`)}catch{await i(`${e.status} ${e.statusText}`)}return n(),!1}validate(e){if(this.options.valid!==!0)return!0;const t=this.findFirstInvalid(e);return t===null?!0:(t.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(e){let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):ie().confirm(e)}bindResult(e){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const t=e.headers.get("Content-Type")?.includes("application/json");return e.text().then(r=>{if(r==="")return;let i=t?JSON.parse(r):r;if(this.options.bindTransform)try{i=G.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 l=a[o],h=l&&typeof l=="object"&&!Array.isArray(l)?l:{};a[o]=this.mergeAppendBindingData(s,i,h)}else a[o]=i;n.push(x.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(x.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=>{F.bindComplete(a.getTarget(),s)})})})}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},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 e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=this.options.copyFragments.map(i=>{const n={...i.getBindingData(),...t};return x.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 e={};let t=!1;if(this.options.formFragment&&Object.assign(e,E.getValues(this.options.formFragment)),this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const r=g.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||r.hasUnresolvedReference,r.value&&Object.assign(e,r.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}}prepareFetchRequest(){const e=this.buildPayloadResolution(),t=e.payload,r=!!this.options.fetchHasUnresolvedReference||e.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:t,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=c.runtime==="demo"&&!_e(a),l=o?"GET":a;if(n.method=l,l==="GET"||l==="HEAD"||l==="OPTIONS")Object.keys(t).length>0&&(i=tt(i,t));else if(Object.keys(t).length>0){const u=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(u)){s.delete("Content-Type");const p=new FormData;for(const[v,R]of Object.entries(t))R==null?p.append(v,""):R instanceof Blob?p.append(v,R):Array.isArray(R)?R.forEach(I=>p.append(v,String(I))):typeof R=="object"?p.append(v,JSON.stringify(R)):p.append(v,String(R));n.body=p}else if(/application\/x-www-form-urlencoded/i.test(u)){const p=new URLSearchParams;for(const[v,R]of Object.entries(t))R!==void 0&&(R===null?p.append(v,""):Array.isArray(R)?R.forEach(I=>p.append(v,String(I))):typeof R=="object"?p.append(v,JSON.stringify(R)):p.append(v,String(R)));n.body=p}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}n.headers=s;let h;return o&&(h=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,options:n,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:l,queryString:h,transportMode:o?"query-get":"http",signature:it(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=g.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?g.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(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=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}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(s=>{s in e&&(r.has(s)||(i[s]=e[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];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+=e,t.push(r.setValue(String(n)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return m.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${c.prefix}row`);return e||(m.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=[],r=e.clone();return t.push(e.getParent().insertAfter(r,e)),t.push(x.evaluateAll(r)),t.push(E.reset(r)),Promise.all(t).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getParent();return t&&t.getChildElementFragments().filter(i=>!i.hasAttribute(`${c.prefix}each-before`)&&!i.hasAttribute(`${c.prefix}each-after`)).length<=1?Promise.resolve():e.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getPrevious();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertBefore(e,t):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getNext();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertAfter(e,t):Promise.resolve()}};g.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,g.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,g.RUNNING_CLICK_TARGETS=new WeakSet;let W=g;class nt{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw m.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){Be(r.status);const n=`${r.status} ${r.statusText}`;throw m.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw m.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}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:",e),i)}catch(n){return m.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const d=class d{static isDeferredAttributeName(e){return d.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${c.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${c.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!d.isEvaluateAllExcludedAttributeName(e)&&d.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${c.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=T.get(e);return r instanceof M?r.hasAttribute(`${c.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);d.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>d.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof M?t.push(d.evaluateAll(r)):r instanceof V&&t.push(d.evaluateText(r))}),Promise.all(t).then(()=>{})}static getReactiveFetchState(e){const t=d.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return d.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=d.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return d.REACTIVE_IMPORT_STATES.set(e,r),r}static reevaluateReactiveSpecialAttributes(e,t=new Set){if(t.has(e))return Promise.resolve();const r=[];return e.hasAttribute(`${c.prefix}fetch`)&&r.push(d.executeManagedFetch(e)),e.hasAttribute(`${c.prefix}import`)&&r.push(d.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof M&&r.push(d.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=d.getReactiveFetchState(t),i=W.resolveAutoFetchSignature(e);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 W(e,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,d.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=d.getReactiveImportState(t),i=e.getAttributeEvaluation(`${c.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 t.setAttribute(`${c.prefix}importing`,""),F.importStart(t,n),nt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return P.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${c.prefix}importing`),F.importEnd(t,n,o,s),!document.body.hasAttribute("data-haori-ready")){const l=[];return t.childNodes.forEach(h=>{const u=T.get(h);u instanceof M?l.push(d.scan(u.getTarget())):u instanceof V&&l.push(d.evaluateText(u))}),Promise.all(l).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${c.prefix}importing`),F.importError(t,n,a),m.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,d.executeManagedImport(e)})}static scan(e){const t=T.get(e);return t?d.initializeElementFragment(t,!1):Promise.resolve()}static initializeFreshEachRow(e){return d.initializeElementFragment(e,!0).then(()=>{d.needsScheduledEvaluateAll(e)&&d.scheduleEvaluateAll(e)})}static initializeElementFragment(e,t){return d.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():d.initializeElementAttributes(e).then(()=>{if(d.shouldSkipChildInitialization(e,t)){d.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof M?r.push(d.initializeElementFragment(i,t)):i instanceof V&&r.push(d.evaluateText(i))}),Promise.all(r).then(()=>{d.refreshDerivedSubtreeSignature(e)})})}static syncMountedState(e){if(e.getParent()?.isMounted()){e.setMounted(!0);return}const r=e.getTarget();if(r.parentNode&&document.body.contains(r)){e.setMounted(!0);return}e.setMounted(!1)}static initializeElementAttributes(e){let t=Promise.resolve();const r=new Set;for(const i of d.PRIORITY_ATTRIBUTE_SUFFIXES){const n=c.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>d.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||d.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>d.setAttribute(e.getTarget(),i,n)))}for(const i of d.DEFERRED_ATTRIBUTE_SUFFIXES){const n=c.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>d.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}return t.then(()=>{})}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${c.prefix}if`);return e.hasAttribute(`${c.prefix}if`)&&d.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${c.prefix}each`)}static setAttribute(e,t,r,i=!1){const n=T.get(e),s=d.getAliasedAttributeName(t);if(s!==null)return r===null?n.removeAliasedAttribute(t,s):n.setAliasedAttribute(t,s,r,i);const a=[];let o=null,l=null;switch(t){case`${c.prefix}bind`:{if(r===null)n.clearBindingDataCache(),n.setBindingData({});else{if(i&&n instanceof M&&n.consumeSelfWrittenBind(r))break;n.setBindingData(d.parseDataBind(r))}break}case`${c.prefix}derive`:l=d.createDeriveInputSignature(n,r,n.getRawAttribute(`${c.prefix}derive-name`)),o=d.evaluateDerive(n,r,n.getRawAttribute(`${c.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${c.prefix}derive-name`:l=d.createDeriveInputSignature(n,n.getRawAttribute(`${c.prefix}derive`),r),o=d.evaluateDerive(n,n.getRawAttribute(`${c.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${c.prefix}if`:a.push(d.evaluateIf(n));break;case`${c.prefix}each`:a.push(d.evaluateEach(n));break;case`${c.prefix}fetch`:a.push(d.executeManagedFetch(n));break;case`${c.prefix}import`:typeof r=="string"&&a.push(d.executeManagedImport(n));break;case`${c.prefix}url-param`:{const h=n.getAttribute(`${c.prefix}url-arg`),u=$e.readParams();if(h===null)a.push(d.setBindingData(e,u,new Set,!0));else{const p=n.getRawBindingData()||{};p[String(h)]=u,a.push(d.setBindingData(e,p,new Set,!0))}break}}return r===null?a.push(n.removeAttribute(t)):a.push(n.setAttribute(t,r,i)),Promise.all(a).then(()=>{if(o!==null)return n.setDeriveInputSignature(l),o.then(h=>{if(h)return d.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(e,t,r=new Set,i=!1,n=!0){const s=T.get(e),a=s.getRawBindingData();s.setBindingData(t),n&&F.bindChange(e,a,t,"manual");const o=()=>{s.markBindingWorkStart();const l=s.getRawBindingData()??t;let h=n?s.setAttribute(`${c.prefix}bind`,JSON.stringify(l)):Promise.resolve();if(e.tagName==="FORM"){const u=s.getAttribute(`${c.prefix}form-arg`),p=u&&l[String(u)]&&typeof l[String(u)]=="object"&&!Array.isArray(l[String(u)])?l[String(u)]:u?{}:l;h=h.then(()=>E.syncValues(s,p))}return h=h.then(()=>d.evaluateAll(s,r)),h=h.then(()=>d.reevaluateReactiveSpecialAttributes(s,r)),h.then(()=>s.markBindingWorkEnd(),u=>{throw s.markBindingWorkEnd(),u})};return i?o():s.enqueueBindingWork(o)}static getBindingData(e,t={}){const r=T.get(e);return r instanceof M?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=T.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=l=>{const h=l.getTarget();return h.id?`#${h.id}`:h.tagName.toLowerCase()},s=(l,h,u,p)=>{if(l)for(const v of Object.keys(l))v in i||(i[v]={value:l[v],source:n(h),kind:u,depth:p})};let a=t,o=0;for(;a;)a!==t&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return L.isEnabled()&&m.info("[Haori]","scope dump for",e,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return m.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,n]of t.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(e,t){const r=T.get(e);if(r.isSkipMutationNodes())return;const i=T.get(t.nextSibling),n=T.get(t);n&&(r.insertBefore(n,i),n instanceof M?d.scan(n.getTarget()):n instanceof V&&d.evaluateText(n))}static removeNode(e){const t=T.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=T.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=T.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=d.getFormFragment(r);if(n){const s=E.getValues(n),a=n.getAttribute(`${c.prefix}form-arg`);let o;a?(o=n.getRawBindingData(),o||(o={}),o[String(a)]=s):o=s,i.push(d.setBindingData(n.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?d.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=d.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${c.prefix}derive`),n=e.hasAttribute(`${c.prefix}if`),s=e.hasAttribute(`${c.prefix}each`),a=e.getRawAttribute(`${c.prefix}derive`),o=e.getRawAttribute(`${c.prefix}derive-name`);let l=!1,h=!1,u=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const p=d.createDeriveInputSignature(e,a,o);p===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>d.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==p&&(r=r.then(()=>d.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(p)})))}return n&&(r=r.then(()=>d.evaluateIf(e))),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>d.evaluateEach(e))):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!d.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}u=d.createDescendantBindingSignature(e,"evaluateAll"),h=!0,l=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===u,d.logDerivedSubtreeProfileSnapshot(e,l?"skip-hit":"skip-miss")})),r.then(()=>{if(l)return;const p=[];return e.getChildren().forEach(v=>{if(v instanceof M){if(d.canSkipUnchangedNestedEach(v))return;p.push(d.evaluateAll(v,t))}else v instanceof V&&p.push(d.evaluateText(v))}),Promise.all(p).then(()=>{})}).then(()=>{h&&u!==null&&e.setDeriveSubtreeSignature(u)}))}static evaluateDerive(e,t=e.getRawAttribute(`${c.prefix}derive`),r=e.getRawAttribute(`${c.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!t||n==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const s=G.evaluateDetailed(t,e.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return d.createBindingSignature(i)===d.createBindingSignature(a)?Promise.resolve(!1):(e.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(e){return e.evaluate()}static isHiddenIfCondition(e){return!e}static logFalsyIfDiagnostics(e){const t=e.getRawAttribute(`${c.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;const{sources:r}=d.dumpScope(e.getTarget()),i=new Set,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const l=t.indexOf(o,s);s=l+o.length,!(l>0&&t[l-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),m.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${c.prefix}if`);if(d.isHiddenIfCondition(r))L.isEnabled()&&d.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{F.hide(e.getTarget())}));else{const i=e.isVisible(),n=[];e.getChildren().forEach(s=>{s instanceof M?n.push(s.isMounted()?d.evaluateAll(s):d.scan(s.getTarget())):s instanceof V&&n.push(d.evaluateText(s))}),t.push(e.show().then(()=>{F.show(e.getTarget()),i||d.triggerLoadOnShow(e)})),t.push(Promise.all(n).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${c.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new W(e,"load").run().catch(i=>{m.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=d.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},d.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(!e.isVisible()||!e.isMounted())return Promise.resolve();const t=d.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):d.runEachUpdateLoop(e,t)}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${c.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await d.performEachUpdate(e);while(t.rerunRequested);e.getTarget().setAttribute(`${c.prefix}each-done`,"")}finally{t.running=!1,t.settled=null}})();return t.settled=r,r}static performEachUpdate(e){const t=d.resolveEachItems(e);if(t===null)return Promise.reject(new Error("Invalid each attribute."));let r=e.getTemplate();const i=e.getAttribute(`${c.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let s=!1;if(e.getChildren().forEach(a=>{if(!s&&a instanceof M){if(a.hasAttribute(`${c.prefix}each-before`)||a.hasAttribute(`${c.prefix}each-after`))return;r=a.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=e.getTarget();Array.from(a.children).filter(l=>!l.hasAttribute(`${c.prefix}each-before`)&&!l.hasAttribute(`${c.prefix}each-after`)).forEach(l=>{if(!s){const u=T.get(l);u instanceof M&&(r=u.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const h=T.get(l);h instanceof M&&e.getChildren().includes(h)&&(e.removeChild(h),h.setMounted(!1)),l.parentNode&&l.parentNode.removeChild(l)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}return e.getEachInputSignature()===n?Promise.resolve():this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}static resolveEachItems(e){const t=e.getAttributeEvaluation(`${c.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(m.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${c.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${c.prefix}derive`)||t?.closestByAttribute(`${c.prefix}derive-name`)||t?.closestByAttribute(`${c.prefix}if`)||t?.closestByAttribute(`${c.prefix}fetch`)||t?.closestByAttribute(`${c.prefix}import`)||d.hasNonEachDynamicElementState(e))return!1;const r=d.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${c.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===n}static canSkipStableDerivedSubtree(e){return!e.hasAttribute(`${c.prefix}derive`)||e.hasAttribute(`${c.prefix}if`)||e.hasAttribute(`${c.prefix}each`)||e.hasAttribute(`${c.prefix}fetch`)||e.hasAttribute(`${c.prefix}import`)?!1:!d.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof M?t.hasAttribute(`${c.prefix}derive`)||t.hasAttribute(`${c.prefix}derive-name`)||t.hasAttribute(`${c.prefix}fetch`)||t.hasAttribute(`${c.prefix}import`)?!0:d.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return d.recordDerivedSubtreeSignatureComputation(e,t),d.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:d.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!d.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(d.createDescendantBindingSignature(e,"refresh")),d.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!L.isEnabled()||!e.hasAttribute(`${c.prefix}derive`))return null;const t=d.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:d.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return d.DERIVE_SUBTREE_PROFILES.set(e,r),r}static createDerivedSubtreeHostId(e){const t=[];let r=e;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();if(i.id.trim()!==""){n+=`#${i.id.trim()}`,t.unshift(n);break}const s=r.getRawAttribute(`${c.prefix}derive-name`);typeof s=="string"&&s.trim()!==""&&(n+=`[${c.prefix}derive-name="${s.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(l=>l instanceof M).findIndex(l=>l===r);n+=`:nth-child(${o+1})`}t.unshift(n),r=a}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),m.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${c.prefix}each`,`${c.prefix}each-key`,`${c.prefix}each-arg`,`${c.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${c.prefix}attr-`)||i.startsWith(c.prefix))return!0;const n=e.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:e.getChildren().some(i=>i instanceof V&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>d.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof M?!d.markFreshInitializationSkippable(n):n instanceof V?n.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${c.prefix}attr-`)||t.startsWith(c.prefix))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static updateDiff(e,t){const r=e.getTemplate();if(r===null)return m.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=e.getAttribute(`${c.prefix}each-index`);i&&(i=String(i));const n=e.getAttribute(`${c.prefix}each-key`),s=e.getAttribute(`${c.prefix}each-arg`),a=new Map,o=[];t.forEach((b,S)=>{const k=d.createListKey(b,n?String(n):null,S);o.push(k),a.set(k,{item:b,itemIndex:S})});const l=new Set(o),h=[];let u=e.getChildren().filter(b=>b instanceof M).filter(b=>!b.hasAttribute(`${c.prefix}each-before`)&&!b.hasAttribute(`${c.prefix}each-after`));const p=u.map(b=>b.getListKey());u=u.filter(b=>l.has(String(b.getListKey()))?!0:(h.push(b.remove()),!1));const v=u.map(b=>b.getListKey()),R=new Map;u.forEach(b=>{const S=b.getListKey();S!==null&&!R.has(S)&&R.set(S,b)});const I=e.getChildElementFragments().slice(),A=I.filter(b=>b.hasAttribute(`${c.prefix}each-before`)).length;let y=Promise.resolve();return o.forEach((b,S)=>{const{item:k,itemIndex:C}=a.get(b);let O;const j=R.get(b);if(j)O=j,y=y.then(()=>d.updateRowFragment(O,k,i,C,s?String(s):null,b).then($=>{if($)return d.evaluateAll(O)}));else{O=r.clone();const $=A+S;y=y.then(()=>d.updateRowFragment(O,k,i,C,s?String(s):null,b).then(()=>{const ee=I[$]??null;return e.insertBefore(O,ee).then(()=>{I.splice($,0,O)}).then(()=>d.initializeFreshEachRow(O))}))}}),Promise.all(h).then(()=>y).then(()=>{const b=o.filter($=>$!==null),S=v.filter($=>$!==null),k=new Set(S),C=b.filter($=>!k.has($)),j=p.filter($=>$!==null).filter($=>!l.has($));F.eachUpdate(e.getTarget(),C,j,b)})}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const n=e[t];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,n,s){let a=t;if(typeof t=="object"&&t!==null)a={...t},r&&(a[r]=i),n&&(a={[n]:a});else if(n)a={[n]:t},r&&(a[r]=i);else return m.error("[Haori]",`Primitive value requires '${c.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);const o=a,l=d.createBindingSignature({listKey:s,bindingData:o});return e.getListKey()===s&&e.getRenderSignature()===l?Promise.resolve(!1):(e.setListKey(s),e.setRenderSignature(l),e.setBindingData(o),e.setAttribute(`${c.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(e){const t=[e];for(;t.length>0;){const r=t.pop();if(r.getChildElementFragments().forEach(i=>{t.push(i)}),r!==e&&!r.isMounted()&&d.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${c.prefix}${t}`))}static createBindingSignature(e,t=new WeakMap,r={value:0}){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="function")return`[Function:${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e instanceof Date)return`[Date:${e.toISOString()}]`;if(Array.isArray(e)){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`array-${r.value}`;return r.value+=1,t.set(e,i),`[${e.map(n=>d.createBindingSignature(n,t,r)).join(",")}]`}if(typeof e=="object"){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`object-${r.value}`;r.value+=1,t.set(e,i);const n=e;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${d.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{d.evaluateAll(e)},100)}};d.ATTRIBUTE_ALIAS_SUFFIX="attr-",d.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],d.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],d.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,d.REACTIVE_FETCH_STATES=new WeakMap,d.REACTIVE_IMPORT_STATES=new WeakMap,d.DERIVE_SUBTREE_PROFILES=new WeakMap,d.EACH_UPDATE_STATES=new WeakMap;let x=d;const _=class _{constructor(e=document){this.customEventHandlers=new Map,this.onClick=t=>this.delegate(t,"click"),this.onChange=t=>this.delegate(t,"change"),this.onInput=t=>this.delegate(t,"input"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{const t=document.documentElement,r=T.get(t);r&&new W(r,"load").run()},this.onPopstate=t=>{const r=t.state;!r||r[_.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}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[e,t]of this.customEventHandlers)window.removeEventListener(e,t,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${c.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(_.BUILTIN_EVENT_NAMES.has(e)){m.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==e)return;const n=T.get(i);n instanceof M&&new W(n,"on",t).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const e=this.root instanceof Document?this.root:this.root.ownerDocument??document,t=this.root instanceof Document?e.body:this.root;t&&(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(t,{childList:!0,subtree:!0}))}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(!r)return;if(t==="input"){const s=`${c.prefix}input-`;if(!r.getAttributeNames().some(o=>o.startsWith(s)))return}r.hasAttribute(`${c.prefix}${t}-prevent`)&&e.preventDefault();const i=T.get(r);if(!i)return;(t==="change"||t==="input")&&i instanceof M&&i.syncValue();const n=()=>{new W(i,t,e).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})};if(t==="click"&&r.hasAttribute(`${c.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}getElementFromTarget(e,t){if(!e)return null;if(e instanceof HTMLElement)return t==="click"?this.findClickableElement(e):e;if(e instanceof Node){const r=e.parentElement;return r?t==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(e){const t=`${c.prefix}click-`,r=`${c.prefix}click-passive`;let i=e;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(t)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};_.HISTORY_STATE_KEY="__haoriHistoryState__",_.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let fe=_;const D=class D{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(D.isHtmlElement(e)&&D.syncElement(e),e.querySelectorAll("*").forEach(t=>{D.syncElement(t)}))}static syncElement(e){const t=D.registrations.get(e),r=T.get(e);if(!r||!D.shouldObserve(r)){t&&(t.observer.disconnect(),D.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=D.resolveRoot(r),n=D.resolveRootMargin(r),s=D.resolveThreshold(r),a=r.hasAttribute(`${c.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===n&&D.sameThreshold(t.observer.thresholds,s)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),D.registrations.delete(e));const o=new IntersectionObserver(l=>{const h=D.registrations.get(e);h&&l.forEach(u=>{!u.isIntersecting||h.running||D.isDisabled(h.fragment)||(h.running=!0,new W(h.fragment,"intersect").runWithResult().then(p=>{p&&h.once&&(h.observer.disconnect(),D.registrations.delete(e))}).catch(p=>{m.error("[Haori]","Intersect procedure execution error:",p)}).finally(()=>{const p=D.registrations.get(e);p&&(p.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(e),D.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(D.isHtmlElement(e)){const t=D.registrations.get(e);t&&(t.observer.disconnect(),D.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=D.registrations.get(t);r&&(r.observer.disconnect(),D.registrations.delete(t))})}static disconnectAll(){D.registrations.forEach(e=>{e.observer.disconnect()}),D.registrations.clear()}static shouldObserve(e){return e.getAttributeNames().some(t=>{if(!t.startsWith(`${c.prefix}intersect-`))return!1;const r=t.slice(`${c.prefix}intersect-`.length);return!D.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${c.prefix}intersect-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);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(e){const t=`${c.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${c.prefix}intersect-threshold`,r=e.getAttribute(t),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(e){const t=`${c.prefix}intersect-disabled`,r=e.getAttribute(t);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(e,t){return e.length===1&&e[0]===t}};D.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),D.registrations=new Map;let Z=D;function st(f){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>f()):Promise.resolve().then(f)}const w=class w{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(w.isHtmlElement(e)&&w.syncElement(e),e.querySelectorAll("*").forEach(t=>{w.syncElement(t)}))}static syncElement(e){const t=w.registrations.get(e),r=T.get(e);if(!(r instanceof M)||!w.shouldObserve(r)){t&&(t.observer.disconnect(),w.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=w.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),w.registrations.delete(e)),m.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=w.resolveRoot(r),s=w.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,w.refreshRows(t);return}t&&(t.observer.disconnect(),w.registrations.delete(e));const a=new IntersectionObserver(l=>{const h=w.registrations.get(e);if(!h)return;let u=!1;l.forEach(p=>{const v=p.target;h.observedRows.has(v)&&(p.isIntersecting?h.visibleRows.has(v)||(h.visibleRows.add(v),u=!0):h.visibleRows.delete(v)&&(u=!0))}),u&&w.scheduleCompute(h)},{root:n,rootMargin:s,threshold:w.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};w.registrations.set(e,o),w.refreshRows(o)}static cleanupTree(e){if(w.isHtmlElement(e)){const t=w.registrations.get(e);t&&(t.observer.disconnect(),w.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=w.registrations.get(t);r&&(r.observer.disconnect(),w.registrations.delete(t))})}static disconnectAll(){w.registrations.forEach(e=>{e.observer.disconnect()}),w.registrations.clear()}static shouldObserve(e){return e.hasAttribute(`${c.prefix}each`)&&e.hasAttribute(`${c.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${c.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${c.prefix}each-visible-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return w.isHtmlElement(i)?i:(m.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${c.prefix}each-visible-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?w.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof M&&!t.hasAttribute(`${c.prefix}each-before`)&&!t.hasAttribute(`${c.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=w.realRowElements(e.fragment),r=new Set(t);for(const i of[...e.observedRows])r.has(i)||(e.observer.unobserve(i),e.observedRows.delete(i),e.visibleRows.delete(i));for(const i of t)e.observedRows.has(i)||(e.observer.observe(i),e.observedRows.add(i));w.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,st(()=>{e.scheduled=!1;const t=e.fragment.getTarget();w.registrations.get(t)===e&&w.computeAndPublish(e)}))}static computeAndPublish(e){const t=w.realRowElements(e.fragment),r=new Map;t.forEach((a,o)=>r.set(a,o));const i=[];for(const a of e.visibleRows){const o=r.get(a);o!==void 0&&i.push(o)}let n;if(i.length===0)n={first:-1,last:-1,firstLabel:0,lastLabel:0,count:0,total:t.length,empty:!0};else{let a=i[0],o=i[0];for(const l of i)l<a&&(a=l),l>o&&(o=l);n={first:a,last:o,firstLabel:a+1,lastLabel:o+1,count:i.length,total:t.length,empty:!1}}const s=JSON.stringify(n);s!==e.lastSnapshot&&(e.lastSnapshot=s,w.publish(e,n))}static publish(e,t){const r=w.resolveBindOwner(e.fragment);if(!r){m.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);x.setBindingData(i,n,a,!1,!1).catch(o=>{m.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${c.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};w.THRESHOLD=0,w.DEFAULT_ROOT_MARGIN="0px",w.registrations=new Map;let J=w;const H=class H{static disconnectMutationObservers(){H._mutationObservers.forEach(e=>{e.disconnect()}),H._mutationObservers.length=0}static async init(){if(H._initialized)return;H._initialized=!0,H.disconnectMutationObservers();const e=await Promise.allSettled([x.scan(document.head),x.scan(document.body)]),[t,r]=e;t.status!=="fulfilled"&&m.error("[Haori]","Failed to build head fragment:",t.reason),r.status!=="fulfilled"&&m.error("[Haori]","Failed to build body fragment:",r.reason),await P.wait(),document.body.setAttribute("data-haori-ready",""),H.observe(document.head),H.observe(document.body),new fe().start(),Z.syncTree(document.body),J.syncTree(document.body)}static observe(e){const t=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&&x.isAliasedAttributeReflection(n,i.attributeName))break;x.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),Z.syncElement(n),J.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{Z.cleanupTree(n),J.cleanupTree(n),x.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(x.addNode(n.parentElement,n),Z.syncTree(n),J.syncTree(n))}),i.target instanceof Element&&J.syncElement(i.target);break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?x.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)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),H._mutationObservers.push(t)}};H._initialized=!1,H._mutationObservers=[];let ae=H;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ae.init):ae.init();const at=()=>q.waitForRenders(),ot="0.20.0";exports.Core=x;exports.Env=c;exports.Form=E;exports.Fragment=T;exports.Haori=q;exports.Log=m;exports.Queue=P;exports.default=q;exports.version=ot;exports.waitForRenders=at;
|
|
22
22
|
//# sourceMappingURL=haori.cjs.js.map
|