haori 0.44.0 → 0.44.1

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 CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Haori.js は、HTML 属性を中心にして動的な UI を実現する軽量なライブラリです。JavaScript をほとんど書かずに、データバインディング、条件分岐、繰り返し処理、フォームの双方向バインディング、サーバー通信などを HTML 属性で宣言できます。
4
4
 
5
- バージョン: 0.44.0
5
+ バージョン: 0.44.1
6
6
 
7
7
  ---
8
8
 
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Haori.js is a lightweight, HTML-first UI library that enables dynamic user interfaces primarily through HTML attributes. It lets you declare data bindings, conditional rendering, list rendering, form two-way binding, server fetches, and HTML imports without writing much JavaScript.
4
4
 
5
- Version: 0.44.0
5
+ Version: 0.44.1
6
6
 
7
7
  ---
8
8
 
package/dist/haori.cjs.js CHANGED
@@ -5,7 +5,7 @@ ${t}`;this.loggedScopeMissingIdentifiers.has(s)||(this.loggedScopeMissingIdentif
5
5
  ${d};
6
6
  return (${g});${p}`:`"use strict";
7
7
  return (${g});${p}`;try{return u=new Function(...n,A),this.EXPRESSION_CACHE.set(l,u),this.compileFailedExpressions.delete(e),{bindKeys:n,evaluator:u,compileFailed:!1}}catch(v){return o.length>0?(b.warn("[Haori]","Failed to shadow undeclared identifier(s): "+o.join(", ")+". Falling back to evaluation without shadowing.",e),this.prepareEvaluator(e,t,[])):(b.error("[Haori]","Failed to compile expression:",e,v),this.compileFailedExpressions.add(e),{bindKeys:n,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,u=t[n-3]||null;if(this.startsObjectKey(o,i,l,u)&&(s.value==="["||s.type==="identifier"&&this.FORBIDDEN_PROPERTY_NAMES.has(s.value)||s.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(s.value)))||s.type==="identifier"&&(this.DISALLOWED_KEYWORDS.has(s.value)||this.STRICT_FORBIDDEN_NAMES.includes(s.value)||(i?.value==="."||i?.value==="?.")&&this.FORBIDDEN_PROPERTY_NAMES.has(s.value))||o==="member"&&s.value!=="]"&&s.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(s.value))||s.value==="."&&a?.type!=="identifier"||s.value==="?."&&a?.type!=="identifier"&&a?.value!=="["&&a?.value!=="(")return!1;switch(s.value){case"(":r.push("paren");break;case")":{if(r.pop()!=="paren")return!1;break}case"[":{const d=this.startsMemberAccess(i)?"member":"array";r.push(d);break}case"{":r.push("object");break;case"]":{if(r.pop()===void 0)return!1;break}case"}":{if(r.pop()!=="object")return!1;break}}i=s}return r.length===0}static tokenizeExpression(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"||e.type==="string"?!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`
8
- `;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){if(!e||typeof e!="object")return!1;const i=r??this.getForbiddenBindingValueSet(),n=this.forbiddenBindingValueCache.get(e);if(n!==void 0)return n;if(t.has(e))return!1;if(t.add(e),i.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const s of Object.values(e)){if(typeof s=="function"){if(i.has(s))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(s,t,i))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};M.MAX_IDENTIFIER_RECOVERY_COUNT=8,M.BUILTIN_NAMESPACE="haori",M.BUILTIN_HELPERS={...Rt},M.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,M.BUILTIN_DATA_PROPERTY="data",M.BUILTIN_DATA_REFERENCE_PATTERN=/(^|[^\w$.])haori\s*(\.\s*data(?![\w$])|\[)/,M.IDENTIFIER_NAME_PATTERN=/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u,M.usableBindingKeyCache=new Map,M.loggedUnusableBindingKeys=new Set,M.compileFailedExpressions=new Set,M.forbiddenBindingValueCache=new WeakMap,M.forbiddenBindingValueCacheResetScheduled=!1,M.loggedForbiddenKeySignatures=new Set,M.loggedForbiddenKeyResetScheduled=!1,M.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"],M.STRICT_FORBIDDEN_NAMES=["eval","arguments"],M.REBINDABLE_FORBIDDEN_NAMES=new Set(["location","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),M.FORBIDDEN_BINDING_NAMES=new Set([...M.FORBIDDEN_NAMES.filter(e=>!M.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...M.STRICT_FORBIDDEN_NAMES]),M.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),M.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),M.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"]),M.NON_SHADOWABLE_IDENTIFIERS=new Set(["true","false","null","undefined","NaN","Infinity","enum","implements","interface","package","private","protected","public","static","super"]),M.ALLOWED_GLOBAL_IDENTIFIERS=new Set(["Math","JSON","Intl","Atomics","Array","String","Number","Boolean","Date","RegExp","Symbol","BigInt","Map","Set","WeakMap","WeakSet","WeakRef","FinalizationRegistry","Promise","Proxy","Error","AggregateError","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","ArrayBuffer","SharedArrayBuffer","DataView","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","parseInt","parseFloat","isNaN","isFinite","encodeURI","encodeURIComponent","decodeURI","decodeURIComponent"]),M.EXPRESSION_CACHE=new Map,M.FREE_IDENTIFIER_CACHE=new Map,M.BOUND_IDENTIFIER_CACHE=new Map,M.OPTIONAL_CHAIN_CACHE=new Map,M.GUARDED_MEMBER_CACHE=new Map,M.MEMBER_KEY_GUARD_OPEN="(_hk=>_hk==='constructor'||_hk==='__proto__'||_hk==='prototype'?undefined:_hk)(",M.FORBIDDEN_NAME_PATTERNS=M.FORBIDDEN_NAMES.map(e=>({name:e,pattern:new RegExp(`(^|[^\\w$.])${e}(?![\\w$])`)})),M.FORBIDDEN_IDENTIFIER_CACHE=new Map,M.pendingUnresolvedIdentifiers=new Set,M.unresolvedReportScheduled=!1,M.suppliedIdentifiers=new Set,M.pendingScopeMissingIdentifiers=new Map,M.scopeMissingReportScheduled=!1,M.rowScopeIdentifiers=new Set,M.loggedScopeMissingIdentifiers=new Set,M.loggedBlockedIdentifierExpressions=new Set;let _=M;const ye="data-haori-if-disabled",Ge="input, select, textarea, button, fieldset",K=class K{static reset(){K.ELEMENT_STORES.clear(),K.ensureGlobalAccess()}static snapshot(){return K.ensureGlobalAccess(),[...K.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:K.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:K.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(!j.isEnabled()||!e||t.length===0)return;K.ensureGlobalAccess();const i=K.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const s=K.getOrCreateCounter(i.attributes,e.rawName,e.template);K.updateCounter(s,t,r);return}const n=K.getOrCreateCounter(i.texts,String(e.childIndex),e.template);K.updateCounter(n,t,r)}static ensureGlobalAccess(){if(!j.isEnabled())return;const e=globalThis;e[K.GLOBAL_KEY]===void 0&&(e[K.GLOBAL_KEY]={reset:()=>K.reset(),snapshot:()=>K.snapshot()})}static getOrCreateElementStore(e){const t=K.createElementId(e),r=K.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return K.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=K.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=K.now();return{value:e(),durationMs:K.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(" > ")}};K.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",K.ELEMENT_STORES=new Map;let De=K;const ue=class ue{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,ue.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(ue.FRAGMENT_CACHE.has(e))return ue.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new D(e);break;case Node.TEXT_NODE:t=new ee(e);break;case Node.COMMENT_NODE:t=new Ue(e);break;default:return b.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 W.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 W.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 W.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),ue.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};ue.FRAGMENT_CACHE=new WeakMap;let N=ue;const R=class R extends N{constructor(e){super(e),this.children=[],this.attributeMap=new Map,this.bindingData=null,this.bindingWorkChain=Promise.resolve(),this.bindingWorkActive=0,this.lastSupplySequence=0,this.lastResetSequence=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.rowLocalTemplate=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.selfWritingAttributes=new Map,this.skipChangeValue=!1,this.valueWriteUnapplied=!1,this.pendingValueWrite=null,this.userEditSequence=0,this.authoritativeValueSequence=0,this.lastValueSequence=0,this.lastValueKind="nonSupply",this.selfWrittenBind=new Map,this.lastPathApplied=new Map,this.lastChangeSequence=0,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 Ie(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=N.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof R)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){b.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new R(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.rowLocalTemplate=this.rowLocalTemplate,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.restoreFormControlsDisabledByIf()),this.children.forEach(e=>{e instanceof R&&e.normalizeClonedVisibilityState()})}remove(e=!0){const t=[];return e&&re.destroySubtree(this.getTarget()),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,this.clearUnappliedValueWrite(),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}static isExecutingAnyBindingWork(){return R.bindingWorkActiveCount>0}markBindingWorkStart(){this.bindingWorkActive++,R.bindingWorkActiveCount++}markBindingWorkEnd(){this.bindingWorkActive>0&&(this.bindingWorkActive--,R.bindingWorkActiveCount--)}markSupplyApplied(e){e>this.lastSupplySequence&&(this.lastSupplySequence=e)}isSupplyStale(e){return this.lastSupplySequence>e}markResetAt(e){this.lastResetSequence=e}wasResetAfter(e){return this.lastResetSequence>e}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 R&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e,this.rowLocalTemplate=null}getRowLocalTemplate(){return this.rowLocalTemplate}setRowLocalTemplate(e){this.rowLocalTemplate=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,t=null){return this.applyValue(e,!0,t)}syncBindingValue(e,t=null){return this.applyValue(e,!1,t)}applyValue(e,t,r=null){if(this.skipChangeValue)return(this.pendingValueWrite??Promise.resolve()).then(()=>this.applyValue(e,t,r));if(r&&!this.canApplyValue(r)||(r&&this.markValueApplied(r),this.value===e))return Promise.resolve();const i=this.getTarget();if(i instanceof HTMLInputElement&&i.type==="file")return e===null||e===""?(this.value=null,i.value===""?Promise.resolve():W.enqueue(()=>{i.value=""})):(b.warn("[Haori]","A value cannot be assigned to input[type=file]; only clearing is supported.",i),Promise.resolve());if(i instanceof HTMLInputElement&&(i.type==="checkbox"||i.type==="radio")){const n=this.hasAttribute("value")?this.getAttribute("value"):i.value,s=i.type==="checkbox"&&n==="true";let a;if(s?a=e===!0||e==="true":n==="false"?a=e===!1:Array.isArray(e)?a=e.map(String).includes(String(n)):a=n===String(e),s?this.value=a:a?Array.isArray(e)?this.value=String(n):this.value=e:this.value=null,i.checked===a)return Promise.resolve();const o=this.userEditSequence;return this.enqueueValueWrite(()=>{this.isSupersededByUserEdit(o)||r&&!this.canApplyValue(r)||(i.checked=a,t&&i.dispatchEvent(new Event("change",{bubbles:!0})))})}else if(i instanceof HTMLSelectElement&&i.multiple){const n=(Array.isArray(e)?e:e===null?[]:[e]).map(String);return this.writeSelectedValues(n,t,r)}else return i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement?this.writeScalarValue(Array.isArray(e)?e.join(","):e,t,r):(b.warn("[Haori]","setValue is not supported for this element type.",i),Promise.resolve())}writeScalarValue(e,t,r=null){const i=this.getTarget(),n=e===null?"":String(e);this.value=this.normalizeValueForElement(i,e);const s=this.userEditSequence;return this.enqueueValueWrite(()=>{this.isSupersededByUserEdit(s)||r&&!this.canApplyValue(r)||(i.value=n,this.recordValueWriteResult(i.value===n),t&&((i instanceof HTMLInputElement&&R.INPUT_EVENT_TYPES.includes(i.type)||i instanceof HTMLTextAreaElement)&&i.dispatchEvent(new Event("input",{bubbles:!0})),i.dispatchEvent(new Event("change",{bubbles:!0}))))})}writeSelectedValues(e,t,r=null){const i=this.getTarget();this.value=e.slice();const n=this.userEditSequence;return this.enqueueValueWrite(()=>{if(this.isSupersededByUserEdit(n)||r&&!this.canApplyValue(r))return;let s=!1;const a=new Set;Array.from(i.options).forEach(o=>{const l=e.includes(o.value);o.selected!==l&&(o.selected=l,s=!0),l&&a.add(o.value)}),this.recordValueWriteResult(e.every(o=>a.has(o))),s&&t&&i.dispatchEvent(new Event("change",{bubbles:!0}))})}enqueueValueWrite(e){this.skipChangeValue=!0;const t=W.enqueue(e).finally(()=>{this.skipChangeValue=!1});return this.pendingValueWrite=t,t}isSupersededByUserEdit(e){return this.userEditSequence!==e}static retryUnappliedValueWrites(e,t){if(R.UNAPPLIED_VALUE_WRITES.size===0)return Promise.resolve();const r=[];for(const i of Array.from(R.UNAPPLIED_VALUE_WRITES)){const n=i.getTarget();if(i.wasResetAfter(t)){i.clearUnappliedValueWrite();continue}if(!n.isConnected){i.clearUnappliedValueWrite();continue}e.contains(n)&&r.push(i.retryValueWrite())}return Promise.all(r).then(()=>{})}retryValueWrite(){const e=this.getTarget();if(this.skipChangeValue||!(e instanceof HTMLSelectElement))return Promise.resolve();if(e.multiple){const r=Array.isArray(this.value)?this.value.slice():[];return r.every(i=>Array.from(e.options).some(n=>n.value===i))?this.writeSelectedValues(r,!1):Promise.resolve()}const t=this.value===null?"":String(this.value);return Array.from(e.options).some(r=>r.value===t)?this.writeScalarValue(this.value,!1):Promise.resolve()}clearUnappliedValueWrite(){this.valueWriteUnapplied=!1,R.UNAPPLIED_VALUE_WRITES.delete(this)}getValue(){return this.value}static currentSequence(){return R.sequenceCounter}static nextSequence(){return R.sequenceCounter+=1,R.sequenceCounter}static setPendingMutationFlusher(e){R.pendingMutationFlusher=e}static nextOperationSequence(){return R.pendingMutationFlusher&&!R.isExecutingAnyBindingWork()&&R.pendingMutationFlusher(),R.nextSequence()}canApplyValue(e){return e.kind==="nonSupply"&&e.editedPaths!==void 0&&this.userEditSequence>0&&this.wasResetAfter(this.userEditSequence)?!1:R.isApplicable({sequence:this.lastValueSequence,kind:this.lastValueKind},e)}static isApplicable(e,t){return e===null?!0:t.kind==="nonSupply"&&e.kind==="edit"?!1:t.sequence>e.sequence?!0:t.sequence===e.sequence?e.kind!=="edit"||t.kind==="edit":!1}canApplyPath(e,t){return R.isApplicable(this.lastPathApplied.get(e)??null,t)}markPathApplied(e,t){if(t.kind==="nonSupply")return;const r=this.lastPathApplied.get(e)??null;(r===null||t.sequence>r.sequence||t.sequence===r.sequence&&t.kind==="edit")&&this.lastPathApplied.set(e,{sequence:t.sequence,kind:t.kind})}markValueApplied(e){e.kind!=="nonSupply"&&(e.sequence>this.lastValueSequence||e.sequence===this.lastValueSequence&&e.kind==="edit")&&(this.lastValueSequence=e.sequence,this.lastValueKind=e.kind)}markUserEdit(){return this.userEditSequence=R.nextSequence(),this.markValueApplied({sequence:this.userEditSequence,kind:"edit"}),this.userEditSequence}markUserEditOnChange(){const t=this.userEditSequence>this.lastChangeSequence?this.userEditSequence:this.markUserEdit();return this.lastChangeSequence=t,t}getUserEditSequence(){return this.userEditSequence}hasPendingUserEdit(){return this.userEditSequence>this.authoritativeValueSequence}clearUserEditMark(e=R.currentSequence()){e>this.authoritativeValueSequence&&(this.authoritativeValueSequence=e),this.lastValueKind==="edit"&&this.lastValueSequence<=e&&(this.lastValueKind="supply")}static warnUnresolvedAttribute(e,t,r,i){if(!j.isEnabled())return;const n=`${e} ${r}`;R.loggedUnresolvedAttributes.has(n)||(R.loggedUnresolvedAttributes.add(n),b.warn("[Haori]",`Attribute "${t}" was not applied because the expression has an unresolved reference; the attribute is removed and the synchronized value is emptied: ${e}="${r}"`,i))}hasPendingCheckableUserEdit(e){if(!e)return this.hasPendingUserEdit();const t=this.getTarget().closest("select");if(!t)return!1;const r=N.get(t);return r instanceof R?r.hasPendingUserEdit():!1}clearValue(){this.value=null,this.clearUnappliedValueWrite()}normalizeValueForElement(e,t){const r=R.resolveDeclaredValueType(e);return r==="boolean"?R.normalizeBooleanValue(t):r==="string"?t===null?null:String(t):r==="number"||r===null&&e instanceof HTMLInputElement&&e.type==="number"?R.normalizeNumberValue(t):t}static normalizeNumberValue(e){if(e===null||e==="")return null;if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||!R.NUMBER_INPUT_PATTERN.test(e))return null;const t=Number(e);return Number.isFinite(t)?t:null}static normalizeBooleanValue(e){if(typeof e=="boolean")return e;if(typeof e!="string")return null;const t=e.toLowerCase();return t==="true"?!0:t==="false"?!1:null}static resolveDeclaredValueType(e){const t=e.getAttribute(`${c.prefix}value-type`);if(t===null)return null;const r=t.trim().toLowerCase();return R.VALUE_TYPE_NAMES.has(r)?R.acceptsDeclaredValueType(e)?r:(R.warnValueTypeDeclaration(e,t,"値を持つ入力(checkbox / radio / file と複数選択の select を除く)にのみ指定できます"),null):(R.warnValueTypeDeclaration(e,t,"boolean / number / string のいずれかを指定してください"),null)}static acceptsDeclaredValueType(e){return e instanceof HTMLInputElement?e.type!=="checkbox"&&e.type!=="radio"&&e.type!=="file":e instanceof HTMLSelectElement?!e.multiple:e instanceof HTMLTextAreaElement}static warnValueTypeDeclaration(e,t,r){if(!j.isEnabled())return;const i=e instanceof HTMLInputElement?`[type=${e.type}]`:"",n=`${e.tagName}${i} ${t} ${r}`;R.loggedValueTypeDeclarations.has(n)||(R.loggedValueTypeDeclarations.add(n),b.warn("Haori",`${c.prefix}value-type="${t}" を無視しました(${r}):`,e))}static isValuePropertyTarget(e){return e instanceof HTMLInputElement?R.INPUT_EVENT_TYPES.includes(e.type)||e.type==="hidden":e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement}syncValue(){this.clearUnappliedValueWrite(),this.value=this.readValueFromDom()}readValueFromDom(){const e=this.getTarget();if(R.resolveDeclaredValueType(e),e instanceof HTMLInputElement){if(e.type==="checkbox"||e.type==="radio"){const t=e.type==="checkbox"&&e.value==="true",r=e.value;return e.checked?t?!0:r==="false"?!1:r:t?!1:r==="false"?!0:null}else if(e.type==="file"){const t=e.files;return t&&t.length>0?t[0].name:null}return this.normalizeValueForElement(e,e.value)}else{if(e instanceof HTMLTextAreaElement)return this.normalizeValueForElement(e,e.value);if(e instanceof HTMLSelectElement)return e.multiple?Array.from(e.selectedOptions).map(t=>t.value):this.normalizeValueForElement(e,e.value)}return this.value}recordValueWriteResult(e){if(!e&&this.value!==null&&this.value!==""){this.valueWriteUnapplied=!0,R.UNAPPLIED_VALUE_WRITES.add(this);return}this.clearUnappliedValueWrite()}getValueForCollection(){return this.skipChangeValue||this.valueWriteUnapplied?this.value:R.isValuePropertyTarget(this.getTarget())?this.readValueFromDom():this.value}syncCheckableValueFromDom(e){if(!e){this.syncValue();return}const t=this.getTarget().closest("select");if(!t)return;const r=N.get(t);r instanceof R&&r.syncValue()}getSelfWritingAttribute(e){for(const t of e){const r=this.selfWritingAttributes.get(t);if(r!==void 0)return r}return null}holdSelfWritingAttributes(e,t){for(const r of e)this.selfWritingAttributes.set(r,t)}releaseSelfWritingAttributes(e){for(const t of e)this.selfWritingAttributes.delete(t)}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,!0,i)}removeAliasedAttribute(e,t){const r=[e,t];if(this.getSelfWritingAttribute(r)!==null)return Promise.resolve();this.attributeMap.delete(e);const i=this.getTarget(),n=i.hasAttribute(e),s=t!==e&&i.hasAttribute(t);if(!n&&!s)return Promise.resolve();const a=W.enqueue(()=>{n&&i.removeAttribute(e),s&&i.removeAttribute(t)}).finally(()=>{this.releaseSelfWritingAttributes(r)});return this.holdSelfWritingAttributes(r,a),a}setAttributeInternal(e,t,r,i,n=!1){const s=[e,t],a=this.getSelfWritingAttribute(s);if(a!==null)return n||r===null?Promise.resolve():a.then(()=>this.setAttributeInternal(e,t,r,i,n));if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const o=new Ie(e,r);if(n){const xe=this.attributeMap.get(e);if(xe&&(xe.isEvaluate||xe.isForceEvaluation())&&!o.isEvaluate&&!o.isForceEvaluation()){const We=W.enqueue(()=>{}).finally(()=>{this.releaseSelfWritingAttributes(s)});return this.holdSelfWritingAttributes(s,We),We}}this.attributeMap.set(e,o);const l=this.getTarget(),u=o.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:l,rawName:e,template:r}),d=o.isEvaluate||o.isRawEvaluate,p=e===t&&R.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),g=o.isSingleExpression(),A=se.joinEvaluateResults(u.results),v=u.results.length===1?u.results[0]:A,T=t==="value"&&R.resolveDeclaredValueType(l)==="boolean",F=v===!1&&!T,H=!o.isForceEvaluation()&&(t!==e?u.hasUnresolvedReference||v===null||v===void 0||F:p?u.hasUnresolvedReference||v===null||v===void 0||v===!1:g?u.hasUnresolvedReference||v===null||v===void 0||F:d&&A==="");H&&u.hasUnresolvedReference&&R.warnUnresolvedAttribute(e,t,r,l);const E=o.isForceEvaluation()?r:g?v:A,S=i&&o.isEvaluate&&t==="value"&&R.isValuePropertyTarget(l),C=l.getRootNode(),U=S&&(l===C.activeElement||this.hasPendingUserEdit()),P=H||E===null||E===!1&&!T?null:String(E),Q=e!==t&&l.getAttribute(e)!==r,x=P===null?l.hasAttribute(t):l.getAttribute(t)!==P,V=P===null?"":P,X=S&&!U&&l.value!==V,Y=t==="checked"&&l instanceof HTMLInputElement&&(l.type==="checkbox"||l.type==="radio"),te=t==="selected"&&l instanceof HTMLOptionElement,be=C.activeElement,de=be!==null&&(Y&&l===be||te&&l.closest("select")===be)||(Y||te)&&this.hasPendingCheckableUserEdit(te),ve=P!==null,Ce=Y&&!de&&l.checked!==ve,Se=te&&!de&&l.selected!==ve;if(!Q&&!x&&!X&&!Ce&&!Se)return S&&!U&&(this.value=this.normalizeValueForElement(l,V),this.clearUnappliedValueWrite()),(Y||te)&&!de&&this.syncCheckableValueFromDom(te),Promise.resolve();const qe=W.enqueue(()=>{Q&&l.setAttribute(e,r),P===null?l.removeAttribute(t):x&&(l.setAttribute(t,P),t===`${c.prefix}bind`&&this.recordSelfWrittenBind(P)),S&&!U&&(this.value=this.normalizeValueForElement(l,V),X&&(l.value=V),this.recordValueWriteResult(l.value===V)),Ce&&(l.checked=ve),Se&&(l.selected=ve),(Ce||Se)&&this.syncCheckableValueFromDom(Se)}).finally(()=>{this.releaseSelfWritingAttributes(s)});return this.holdSelfWritingAttributes(s,qe),qe}removeAttribute(e){if(this.getSelfWritingAttribute([e])!==null)return Promise.resolve();this.attributeMap.delete(e);const t=this.getTarget();if(!t.hasAttribute(e))return Promise.resolve();const r=W.enqueue(()=>{t.removeAttribute(e)}).finally(()=>{this.releaseSelfWritingAttributes([e])});return this.holdSelfWritingAttributes([e],r),r}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:se.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=N.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 b.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 b.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 u=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 g=this.resolveInsertionPointFromDom(t,!1);g===null?(b.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(g.index,0,e),u=g.referenceNode)}else this.children.splice(p,0,e)}e.setParent(this),e.setMounted(this.mounted);const d=this.skipMutationNodes;return this.skipMutationNodes=!0,W.enqueue(()=>{this.target.insertBefore(e.getTarget(),u)}).finally(()=>{this.skipMutationNodes=d})}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?(b.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`,""),R.disableFormControlsInBranch(e),Promise.resolve()}static forEachFormControlInBranch(e,t){e.matches(Ge)&&t(e);const r=i=>{Array.from(i.children).forEach(n=>{n.hasAttribute(`${c.prefix}if-false`)||(n instanceof HTMLElement&&n.matches(Ge)&&t(n),r(n))})};r(e)}static disableFormControlsInBranch(e){R.forEachFormControlInBranch(e,t=>{t.hasAttribute("disabled")||(t.setAttribute(ye,""),t.setAttribute("disabled",""))})}restoreFormControlsDisabledByIf(){R.forEachFormControlInBranch(this.getTarget(),e=>{e.hasAttribute(ye)&&(e.removeAttribute(ye),e.removeAttribute("disabled"))})}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.restoreFormControlsDisabledByIf(),this.visible=!0,Promise.resolve()}closestByAttribute(e){if(this.hasAttribute(e))return this;const t=this.getParent();return t===null?null:t.closestByAttribute(e)}};R.NUMBER_INPUT_PATTERN=/^-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/,R.VALUE_TYPE_NAMES=new Set(["boolean","number","string"]),R.loggedValueTypeDeclarations=new Set,R.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"]),R.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],R.UNAPPLIED_VALUE_WRITES=new Set,R.sequenceCounter=0,R.bindingWorkActiveCount=0,R.pendingMutationFlusher=null,R.loggedUnresolvedAttributes=new Set;let D=R;class ee extends N{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new se(this.text)}clone(){const e=new ee(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}getRawText(){return this.text}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new se(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):W.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=se.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 Ue extends N{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new Ue(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,W.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const Fe=class Fe{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(Fe.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&&(b.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 u=De.measure(()=>_.evaluateDetailed(l.text,e)),d=u.value;a+=u.durationMs,s.push({expression:l.text,durationMs:u.durationMs}),o=o||d.unresolvedReference,n.push(d.value)}else n.push(l.text)}catch(u){b.error("[Haori]",`Error evaluating ${i} expression: ${l.text}`,u),s.push({expression:l.text,durationMs:0}),n.push("")}}),De.record(t,s,a),{results:n,hasUnresolvedReference:o}}};Fe.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let se=Fe;const Z=class Z extends se{constructor(e,t){super(t),this.forceEvaluation=Z.needsForceEvaluation(e)}static needsForceEvaluation(e){if(Z.forceEvaluationNames===null||Z.forceEvaluationPrefix!==c.prefix){const t=new Set;for(const r of[c.prefix,...Z.FORCE_EVALUATION_PREFIXES])for(const i of Z.FORCE_EVALUATION_SUFFIXES)t.add(`${r}${i}`);Z.forceEvaluationNames=t,Z.forceEvaluationPrefix=c.prefix}return Z.forceEvaluationNames.has(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?(b.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};Z.FORCE_EVALUATION_SUFFIXES=["if","each","derive"],Z.FORCE_EVALUATION_PREFIXES=["data-","hor-"],Z.forceEvaluationNames=null,Z.forceEvaluationPrefix=null;let Ie=Z;const ge=class ge{static get runtime(){return c.runtime}static setRuntime(e){c.setRuntime(e)}static waitForRenders(){return W.waitForIdle()}static dialog(e){return W.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 W.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return W.enqueue(()=>{e instanceof HTMLDialogElement?(ge.clearMessagesSync(e),e.showModal()):b.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return W.enqueue(()=>{e instanceof HTMLDialogElement?e.close():b.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return ge.addMessage(e,t,"error")}static addMessage(e,t,r){return W.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 W.enqueue(()=>{ge.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 ke(e,t,r)}static now(e,t){return et(e,t)}static today(e,t,r){return tt(e,t,r)}static number(e,t){return rt(e,t)}static range(e,t,r){return it(e,t,r)}static pages(e,t,r){return nt(e,t,r)}static monthAdd(e,t){return Me(e,t)}static monthRange(e,t){return st(e,t)}static pageSummary(e,t){return at(e,t)}static findBy(e,t,r){return ot(e,t,r)}static sum(e,t){return lt(e,t)}static distinct(e,t){return ut(e,t)}static groupBy(e,t){return dt(e,t)}};ge.enhancers={register(e,t){re.register(e,t)},has(e){return re.has(e)}};let ae=ge;const Tt="入力内容を確認してください",Dt=["addErrorMessage","clearMessages"],ze="data-haori-group-name";function Ye(){const e=globalThis.window?.Haori;return Dt.every(r=>typeof e?.[r]=="function")?e:ae}const h=class h{static getValues(e){const t={},r=new Set;return h.getPartValues(e,t,null,r),h.registerCollectedExcludedKeys(t,r),t}static resolveCollectedValue(e){const t=e.getTarget();if(h.isFileInput(e)){const r=t,i=r.files?Array.from(r.files):[];return r.multiple?i:i.length>0?i[0]:null}if(h.isBooleanCheckbox(e)){const r=t;return r.value==="false"?!r.checked:r.checked}return e.getValueForCollection()}static isBooleanCheckbox(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="checkbox"&&(t.value==="true"||t.value==="false")}static resolveFieldName(e){const t=e.getAttribute(`${c.prefix}form-name`);return t||e.getAttribute("name")}static prepareFormName(e){if(!e.hasAttribute(`${c.prefix}form-name`))return;const t=e.getAttribute(`${c.prefix}form-name`);if(!t){b.warn("Haori",`${c.prefix}form-name evaluated to an empty key; the field falls back to the name attribute or is not collected.`,e.getTarget());return}const r=e.getTarget();if(!(r instanceof HTMLInputElement)||r.type!=="radio"||r.hasAttribute("name")&&!r.hasAttribute(ze))return;const i=h.resolveGroupScope(e),n=`${String(t)}--haori${h.resolveGroupScopeId(i)}`;if(r.getAttribute("name")!==n)return e.setAttribute(ze,"").then(()=>e.setAttribute("name",n))}static resolveGroupScope(e){let t=e,r=t.getParent();for(;r!==null;){if(r.hasAttribute(`${c.prefix}form-list`))return t;if(r.getTarget()instanceof HTMLFormElement||r.hasAttribute(`${c.prefix}form`))return r;t=r,r=r.getParent()}return t}static resolveGroupScopeId(e){const t=h.GROUP_SCOPE_IDS.get(e);return t!==void 0?t:(h.groupScopeSequence+=1,h.GROUP_SCOPE_IDS.set(e,h.groupScopeSequence),h.groupScopeSequence)}static hasResolvedDeclarativeState(e){if(!h.isDeclarativeStateBound(e))return!1;const t=e.getTarget();if(t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio"))return h.isDeclarationResolved(e,"checked");if(h.hasDeclarativeBinding(e,"value"))return h.isDeclarationResolved(e,"value");if(t instanceof HTMLSelectElement){for(const r of Array.from(t.options)){const i=N.get(r);if(i instanceof D&&h.hasDeclarativeBinding(i,"selected")&&!h.isDeclarationResolved(i,"selected"))return!1}return!0}return!1}static isDeclarationResolved(e,t){for(const r of[`${c.prefix}attr-${t}`,t]){const i=e.getAttributeEvaluation(r);if(i!==null)return!i.hasUnresolvedReference}return!1}static isDeclarativeStateBound(e){const t=e.getTarget();return t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")?h.hasDeclarativeBinding(e,"checked"):D.isValuePropertyTarget(t)?h.hasDeclarativeBinding(e,"value")?!0:t instanceof HTMLSelectElement?h.hasDeclarativeSelectedOption(t):!1:!1}static restoreDefaultValues(e){const t="input, textarea, select",r=[];e.matches(t)&&r.push(e),r.push(...e.querySelectorAll(t));for(const i of r)i instanceof HTMLInputElement?i.type==="checkbox"||i.type==="radio"?i.checked=i.defaultChecked:i.type==="file"?i.value="":i.value=i.defaultValue:i instanceof HTMLTextAreaElement?i.value=i.defaultValue:i instanceof HTMLSelectElement&&h.restoreDefaultSelection(i)}static restoreDefaultSelection(e){const t=Array.from(e.options);for(const r of t)r.selected=r.defaultSelected;if(!e.multiple&&e.selectedIndex<0){const r=t.find(i=>!i.disabled);r&&(r.selected=!0)}}static clearDeclarativeStateFromDom(e){if(h.isDeclarativeStateBound(e)){const t=e.getTarget();t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")?t.checked=!1:t instanceof HTMLSelectElement?(Array.from(t.options).forEach(r=>{r.selected=!1}),t.selectedIndex=-1):(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&(t.value="")}e.getChildren().forEach(t=>{t instanceof D&&h.clearDeclarativeStateFromDom(t)})}static hasDeclarativeBinding(e,t){if(e.hasAttribute(`${c.prefix}attr-${t}`))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static hasDeclarativeSelectedOption(e){for(const t of Array.from(e.options)){const r=N.get(t);if(r instanceof D&&h.hasDeclarativeBinding(r,"selected"))return!0}return!1}static isFileInput(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="file"}static getValuesEditedAfter(e,t){return h.getPartValues(e,{},t)}static collectEditedPaths(e,t,r="",i=null){const n=new Map;for(const a of h.collectUserEditSequences(e)){const o=new Set;h.walkEditedPaths(h.getValuesEditedAfter(e,a-1),r,o);for(const l of o)n.has(l)||n.set(l,a)}const s=new Set;h.walkExcludedPaths(i??h.getValues(e),r,s);for(const a of s)n.has(a)||n.set(a,t);return n}static collectUserEditSequences(e){const t=new Set;return h.walkUserEditSequences(e,t),[...t].sort((r,i)=>i-r)}static walkUserEditSequences(e,t){const r=e.getUserEditSequence();r>0&&t.add(r);for(const i of e.getChildElementFragments())h.walkUserEditSequences(i,t)}static walkExcludedPaths(e,t,r){if(Array.isArray(e))return;const i=h.asPlainRecord(e);if(i===null)return;const n=h.COLLECTED_EXCLUDED_KEYS.get(i);if(n)for(const s of n)s in i||r.add(t===""?s:`${t}.${s}`);for(const[s,a]of Object.entries(i))h.walkExcludedPaths(a,t===""?s:`${t}.${s}`,r)}static walkEditedPaths(e,t,r){if(Array.isArray(e))return;const i=h.asPlainRecord(e);if(i!==null){for(const[n,s]of Object.entries(i))h.walkEditedPaths(s,t===""?n:`${t}.${n}`,r);return}t!==""&&r.add(t)}static getPartValues(e,t,r=null,i=null){if(e.hasAttribute(`${c.prefix}form-detach`))return t;if(e.getTarget().hasAttribute(`${c.prefix}if-false`)){if(i!==null)for(const u of h.collectDeclaredKeysInFragment(e))i.add(u);return t}const n=h.resolveFieldName(e),s=e.getAttribute(`${c.prefix}form-object`),a=e.getAttribute(`${c.prefix}form-list`),o=e.hasAttribute(`${c.prefix}form-list`),l=r!==null&&e.getUserEditSequence()<=r;if(n){if(r!==null&&h.isGroupedCheckable(e)){const u=h.collectGroupSelection(e,o,r);u.edited&&(t[String(n)]=u.value)}else if(o&&h.isGroupedCheckable(e)){const u=String(n),d=e.getTarget();r===null&&!Array.isArray(t[u])&&(t[u]=[]),!l&&d.checked&&(Array.isArray(t[u])||(t[u]=[]),t[u].push(d.value))}else if(o&&l)Array.isArray(t[String(n)])?t[String(n)].push(null):t[String(n)]=[null];else if(!l)if(o){const u=h.resolveCollectedValue(e),d=h.isFileInput(e)&&Array.isArray(u)?u:[u];Array.isArray(t[String(n)])?t[String(n)].push(...d):t[String(n)]=d}else if(h.isGroupedCheckable(e)){const u=e.getTarget(),d=u instanceof HTMLInputElement?u.checked:!0,p=u instanceof HTMLInputElement?u.value:e.getValue(),g=d?p:null,A=String(n);g===null?A in t||(t[A]=null):t[A]===null||t[A]===void 0?t[A]=g:Array.isArray(t[A])?t[A].push(g):t[A]=[t[A],g]}else t[String(n)]=h.resolveCollectedValue(e);s&&b.warn("Haori",`Element cannot have both ${c.prefix}form-object and name attributes.`);for(const u of e.getChildElementFragments())h.getPartValues(u,t,r,i)}else if(s){const u={},d=i===null?null:new Set;for(const p of e.getChildElementFragments())h.getPartValues(p,u,r,d);d!==null&&h.registerCollectedExcludedKeys(u,d),Object.keys(u).length>0?t[String(s)]=u:i!==null&&(d?.size??0)>0&&i.add(String(s)),a&&b.warn("Haori",`Element cannot have both ${c.prefix}form-list and ${c.prefix}form-object attributes.`)}else if(a){const u=[],d=[];let p=!1;for(const g of e.getChildElementFragments()){const A={},v=i===null?null:new Set;h.getPartValues(g,A,r,v),v!==null&&h.registerCollectedExcludedKeys(A,v),Object.keys(A).length>0?(p=!0,u.push(A),d.push(g.getListKey())):r!==null&&(u.push({}),d.push(g.getListKey()))}if(r===null){const g=e.getAttribute(`${c.prefix}each-key`);h.registerCollectedRowIdentity(u,g==null?null:String(g),d,h.isCollectedListFromEachSource(e)),t[String(a)]=u}else p&&(t[String(a)]=u)}else for(const u of e.getChildElementFragments())h.getPartValues(u,t,r,i);return t}static setValues(e,t,r=!1){return h.setPartValues(e,t,r,!0)}static syncValues(e,t,r=!1,i=null){return h.setPartValues(e,t,r,!1,!1,new Map,i)}static syncRowValues(e,t,r=null){return h.setPartValues(e,t,!1,!1,!0,new Map,r)}static resolveSyncValues(e,t){const r=e.getAttribute(`${c.prefix}form-arg`);if(!r)return t;const i=String(r);return Object.prototype.hasOwnProperty.call(t,i)?h.asPlainRecord(t[i])??{}:h.resolveAncestorArgOwner(e,i)?.value??{}}static resolveAncestorArgOwner(e,t){let r=e.getParent();for(;r;){const i=r.getRawBindingData();if(i&&Object.prototype.hasOwnProperty.call(i,t)){if(r.getListKey()!==null)return null;const n=h.asPlainRecord(i[t]);return n?{owner:r,value:n}:null}r=r.getParent()}return null}static buildConditionScope(e,t=null){const r={...e.getBindingData()},i=t?{source:t,argKey:h.resolveFormArgKey(t)}:h.resolveConditionValueSource(e);if(!i)return r;const n=h.getValues(i.source),s=h.collectDeclaredFieldKeys(i.source);if(i.argKey===null){for(const o of s)r[o]=n[o];return r}const a={...h.asPlainRecord(r[i.argKey])??{}};for(const o of s)a[o]=n[o];return r[i.argKey]=a,r}static resolveConditionValueSource(e){let t=e;for(;t;){const i=t.getParent();if(i&&i.hasAttribute(`${c.prefix}each`)&&i.hasAttribute(`${c.prefix}form-list`)){const n=i.getRawAttribute(`${c.prefix}each-arg`);return{source:t,argKey:typeof n=="string"&&n!==""?n:null}}t=i}const r=h.getFormFragment(e);return r?{source:r,argKey:h.resolveFormArgKey(r)}:null}static resolveFormArgKey(e){const t=e.getAttribute(`${c.prefix}form-arg`);return t?String(t):null}static collectDeclaredFieldKeys(e){return h.collectDeclaredKeysInFragment(e)}static collectDeclaredKeysInFragment(e){const t=new Set,r=e.getTarget(),i=h.resolveFieldName(e);i&&t.add(String(i));const n=`${c.prefix}form-object`,s=`${c.prefix}form-list`,a=r.getAttribute(n)??r.getAttribute(s);if(a)return t.add(a),t;const o=`input[name],select[name],textarea[name],[${c.prefix}form-name],[${n}],[${s}]`;return r.querySelectorAll(o).forEach(l=>{if(!(l instanceof HTMLElement))return;let u=null,d=!1,p=l;for(;p&&p!==r;)p.hasAttribute(`${c.prefix}form-detach`)&&(d=!0),(p.hasAttribute(n)||p.hasAttribute(s))&&(u=p),p=p.parentElement;if(d)return;const g=u??l,A=g.getAttribute(n)||g.getAttribute(s)||g.getAttribute(`${c.prefix}form-name`)||g.getAttribute("name");A&&t.add(A)}),t}static applyCustomValidity(e){const t=`${c.prefix}validity`,r=i=>{i.hasAttribute(t)&&h.applyOneCustomValidity(i,t),i.getChildElementFragments().forEach(r)};r(e)}static applyOneCustomValidity(e,t){const r=e.getTarget();if(!(r instanceof HTMLInputElement)&&!(r instanceof HTMLSelectElement)&&!(r instanceof HTMLTextAreaElement)){b.warn("Haori",`${t} は入力要素にのみ指定できます: ${r.tagName}`);return}const i=e.getRawAttribute(t);if(typeof i!="string"||i.trim()===""){r.setCustomValidity("");return}const n=h.buildConditionScope(e),s=_.evaluateDetailed(h.unwrapConditionExpression(i),n);if(s.unresolvedReference){b.warn("Haori",`${t} の参照が解決できないため無効として扱います: ${i}`),r.setCustomValidity(h.resolveValidityMessage(e));return}r.setCustomValidity(s.value?"":h.resolveValidityMessage(e))}static resolveValidityMessage(e){const t=e.getAttribute(`${c.prefix}validity-message`);return typeof t=="string"&&t.trim()!==""?t:Tt}static unwrapConditionExpression(e){const t=e.trim();return t.startsWith("{{{")&&t.endsWith("}}}")?t.slice(3,-3):t.startsWith("{{")&&t.endsWith("}}")?t.slice(2,-2):t}static warnUnvalidatedCustomValidity(e,t){if(!j.isEnabled()||!e)return;const r=`${c.prefix}validity`;(e.hasAttribute(r)||e.getTarget().querySelector(`[${r}]`)!==null)&&b.warn("Haori",`${r} は指定されていますが検証は行われません(${t})。${c.prefix}{event}-validate を指定するか、${c.prefix}{event}-if を使用してください。`)}static asPlainRecord(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}static registerCollectedRowIdentity(e,t,r,i){h.COLLECTED_ROW_IDENTITY.set(e,{keyArg:t,keys:r,identifiesItems:i})}static registerCollectedExcludedKeys(e,t){t.size>0&&h.COLLECTED_EXCLUDED_KEYS.set(e,t)}static carryCollectedRowIdentity(e,t){const r=h.COLLECTED_ROW_IDENTITY.get(e);r&&h.COLLECTED_ROW_IDENTITY.set(t,r);const i=h.COLLECTED_EXCLUDED_KEYS.get(e);i&&h.COLLECTED_EXCLUDED_KEYS.set(t,i)}static warnPositionalRowFallback(e){!j.isEnabled()||h.warnedPositionalRowFallbacks.has(e)||(h.warnedPositionalRowFallbacks.add(e),b.warn("[Haori]",`${c.prefix}form-list の行を出現順で対応付けます(${e})。配列と画面の行数・並びが一致していない場合、行の値を取り違えます。`))}static mergeCollectedValues(e,t){const r={...e??{}};for(const[n,s]of Object.entries(t))h.UNSAFE_MERGE_KEYS.has(n)||(r[n]=h.overlayCollectedValue(e?.[n],s));const i=h.COLLECTED_EXCLUDED_KEYS.get(t);if(i)for(const n of i)n in t||delete r[n];return r}static overlayCollectedValue(e,t){if(Array.isArray(t)){if(!Array.isArray(e))return t;const n=h.overlayIdentifiedRows(e,t);return n!==null?n:t.map((s,a)=>h.overlayCollectedValue(e[a],s))}const r=h.asPlainRecord(t),i=h.asPlainRecord(e);return r===null||i===null?t:h.mergeCollectedValues(i,r)}static resolveLeadingPath(e){const t=h.LEADING_PATH_PATTERN.exec(e);if(!t)return null;const r=t[2].trim();return r!==""&&!r.startsWith("||")&&!r.startsWith("??")?null:t[1].replace(/\s+/g,"")}static isCollectedListFromEachSource(e){const t=e.getAttribute(`${c.prefix}form-list`);if(t==null||t==="")return!0;const r=e.getRawAttribute(`${c.prefix}each`);if(typeof r!="string"||r.trim()==="")return!0;const i=h.resolveLeadingPath(r);if(i===null)return!0;const n=i.split(".");return n[n.length-1]===String(t)}static createRowKeyIndexes(e,t){const r=new Map;return e.forEach((i,n)=>{const s=B.createListKey(i,t,n),a=r.get(s);a?a.push(n):r.set(s,[n])}),r}static pairRowsWithItems(e,t,r){const i=e.map(s=>s.getListKey());if(i.some(s=>s===null))return null;const n=h.createRowKeyIndexes(t,r);return i.map(s=>{const a=n.get(s);return!a||a.length===0?null:t[a.shift()]})}static overlayIdentifiedRows(e,t){const r=h.COLLECTED_ROW_IDENTITY.get(t);if(r&&!r.identifiesItems)return null;if(!r)return t.some(s=>h.asPlainRecord(s)!==null)&&h.warnPositionalRowFallback("識別情報が引き継がれていません"),null;if(r.keys.length!==t.length)return h.warnPositionalRowFallback("収集後に行の数が変わっています"),null;if(r.keys.some(s=>s===null))return null;const i=h.createRowKeyIndexes(e,r.keyArg),n=[];for(let s=0;s<t.length;s+=1){const a=r.keys[s],o=i.get(a);if(!o||o.length===0)continue;const l=o.shift();n.push(h.overlayCollectedValue(e[l],t[s]))}return n}static syncAncestorArgForms(e,t,r=null){const i=[];for(const{form:n,key:s}of h.collectArgForms(e)){if(n.wasResetAfter(t))continue;const a=h.resolveAncestorArgOwner(n,s);!a||a.owner!==e||i.push(h.pushAncestorArgValue(n,s,a.value,r))}return Promise.all(i).then(()=>{})}static collectArgForms(e){const t=`${c.prefix}form-arg`,r=e.getTarget().querySelectorAll(`form[${t}]`),i=[];return r.forEach(n=>{const s=N.get(n);if(!(s instanceof D))return;const a=s.getAttribute(t);a&&i.push({form:s,key:String(a)})}),i}static pushAncestorArgValue(e,t,r,i=null){const n=e.getTarget(),s=h.createArgValueSignature(r);if(s!==null){if(h.LAST_ANCESTOR_ARG_VALUES.get(n)===s)return Promise.resolve();h.LAST_ANCESTOR_ARG_VALUES.set(n,s)}else h.LAST_ANCESTOR_ARG_VALUES.delete(n);const a=e.getRawBindingData();if(a&&Object.prototype.hasOwnProperty.call(a,t)){const o={...a};return delete o[t],B.setBindingData(n,o,{kind:i?.kind??"supply",sequence:i?.sequence??D.nextSequence()})}return h.syncValues(e,r,!1,i)}static createArgValueSignature(e){try{return JSON.stringify(e)??null}catch{return null}}static restoreInitialValues(e){const t=[];e instanceof HTMLFormElement&&t.push(e),e.querySelectorAll("form").forEach(i=>{t.push(i)});const r=[];for(const i of t){if(h.INITIAL_RESTORED_FORMS.has(i))continue;const n=N.get(i);if(!(n instanceof D))continue;const s=n.getRawBindingData(),a=n.getAttribute(`${c.prefix}form-arg`),o=a?String(a):null,l=o!==null&&!(s&&Object.prototype.hasOwnProperty.call(s,o))?h.resolveAncestorArgOwner(n,o):null;if(!(!s&&!l)){if(h.INITIAL_RESTORED_FORMS.add(i),l){r.push(h.pushAncestorArgValue(n,o,l.value));continue}r.push(h.syncValues(n,h.resolveSyncValues(n,s)))}}return Promise.all(r).then(()=>{})}static collectGroupSelection(e,t,r){const i=[];h.collectGroupMembers(h.resolveCollectionScope(e),String(h.resolveFieldName(e)),i);let n=!1;const s=[];for(const a of i){a.getUserEditSequence()>r&&(n=!0);const o=a.getTarget();o instanceof HTMLInputElement&&o.checked&&s.push(o.value)}return t?{edited:n,value:h.markCompleteSet(s)}:s.length===0?{edited:n,value:null}:{edited:n,value:s.length===1?s[0]:h.markCompleteSet(s)}}static startsCollectionLevel(e){return h.resolveFieldName(e)?!1:!!(e.getAttribute(`${c.prefix}form-object`)||e.getAttribute(`${c.prefix}form-list`))}static resolveCollectionScope(e){let t=e,r=t.getParent();for(;r!==null;){if(h.startsCollectionLevel(r))return r.getAttribute(`${c.prefix}form-object`)?r:t;if(h.isFormScopeRoot(r))return r;t=r,r=r.getParent()}return t}static isFormScopeRoot(e){return e.getTarget()instanceof HTMLFormElement||e.hasAttribute(`${c.prefix}form`)}static collectGroupMembers(e,t,r){h.isGroupedCheckable(e)&&String(h.resolveFieldName(e))===t&&r.push(e);for(const i of e.getChildElementFragments())h.startsCollectionLevel(i)||i.hasAttribute(`${c.prefix}form-detach`)||i.getTarget().hasAttribute(`${c.prefix}if-false`)||h.collectGroupMembers(i,t,r)}static markCompleteSet(e){return h.COMPLETE_SET_VALUES.add(e),e}static isCompleteSetValue(e){return e!==null&&typeof e=="object"&&h.COMPLETE_SET_VALUES.has(e)}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 isMultipleSelect(e){const t=e.getTarget();return t instanceof HTMLSelectElement&&t.multiple}static applyFragmentValue(e,t,r,i=null){return r?e.setValue(t,i):e.syncBindingValue(t,i)}static setPartValues(e,t,r=!1,i=!0,n=!1,s=new Map,a=null){const o=[];if(e.hasAttribute(`${c.prefix}form-detach`)&&!r)return Promise.resolve();const l=h.resolveFieldName(e),u=e.getAttribute(`${c.prefix}form-object`),d=e.getAttribute(`${c.prefix}form-list`),p=e.hasAttribute(`${c.prefix}form-list`);if(l){const g=t[String(l)],A=n&&h.hasResolvedDeclarativeState(e),v=n&&typeof g>"u"&&!h.isDeclarativeStateBound(e);let T=g;if(A?T=void 0:v&&(T=null),h.isFileInput(e))return(T===null||T==="")&&o.push(h.applyFragmentValue(e,null,i,a)),Promise.all(o).then(()=>{});if(p&&Array.isArray(T)&&!h.isGroupedCheckable(e)&&!h.isMultipleSelect(e)){const F=String(l),H=s.get(F)??0;s.set(F,H+1),o.push(h.applyFragmentValue(e,T[H]??null,i,a))}else typeof T>"u"||(Array.isArray(T)&&h.isGroupedCheckable(e)||Array.isArray(T)&&h.isMultipleSelect(e)||typeof T=="string"||typeof T=="number"||typeof T=="boolean"||T===null?o.push(h.applyFragmentValue(e,T,i,a)):o.push(h.applyFragmentValue(e,String(T),i,a)))}else if(u){const g=t[String(u)];if(g&&typeof g=="object"){const A=new Map;for(const v of e.getChildElementFragments())o.push(h.setPartValues(v,g,r,i,n,A,a))}}else if(d){const g=t[String(d)];if(Array.isArray(g)){const A=e.getChildElementFragments(),v=e.getAttribute(`${c.prefix}each-key`),T=h.isCollectedListFromEachSource(e)?h.pairRowsWithItems(A,g,v==null?null:String(v)):null;for(let F=0;F<A.length;F++){const H=A[F],E=T?T[F]:g.length>F?g[F]:null;o.push(h.setPartValues(H,h.asPlainRecord(E)??{},r,i,n,new Map,a))}}}else for(const g of e.getChildElementFragments())o.push(h.setPartValues(g,t,r,i,n,s,a));return Promise.all(o).then(()=>{})}static async reset(e,t=D.nextSequence()){const r=h.collectBindingTargetForms(e);if(r.length>0&&r.every(n=>n.isSupplyStale(t)))return;h.markResetSubtree(e,t),B.clearUserEditMarks(e,t),h.clearValues(e),await Promise.all([h.clearMessages(e),h.clearEachClones(e)]),await W.enqueue(()=>{const n=h.collectEditsAfter(e,t),s=e.getTarget();s instanceof HTMLFormElement?s.reset():(s.querySelectorAll("form").forEach(a=>a.reset()),h.restoreDefaultValues(s)),h.clearDeclarativeStateFromDom(e),h.restoreEdits(n)});const i=r;for(const n of i){const s=h.getInitialBindingData(n);s===null&&n.getRawBindingData()===null||await B.setBindingData(n.getTarget(),s??{},{sequence:t})}h.syncValuesFromDom(e),await B.evaluateAll(e);for(const n of i)h.getInitialBindingData(n)!==null||n.getRawBindingData()!==null||await h.restoreAncestorArgValues(n,{sequence:t,kind:"supply"});for(const n of i){const s=h.getInitialBindingData(n);if(n.getRawBindingData()===null&&s===null)continue;const a=h.getValues(n),o=n.getAttribute(`${c.prefix}form-arg`);let l={...s||{}};if(o){const u=String(o);!Object.prototype.hasOwnProperty.call(s??{},u)&&h.resolveAncestorArgOwner(n,u)!==null||(l[u]=h.mergeCollectedValues(l[u]??null,a))}else l=h.mergeCollectedValues(l,a);await B.setBindingData(n.getTarget(),l,{sequence:t})}}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:B.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())h.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=N.get(n);s instanceof D&&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())}n.setEachInputSignature(null)}},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())h.clearValues(t)}static collectEditsAfter(e,t,r=[]){const i=e.getTarget();(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement)&&e.getUserEditSequence()>t&&(i instanceof HTMLInputElement&&(i.type==="checkbox"||i.type==="radio")?r.push({element:i,checked:i.checked}):i instanceof HTMLSelectElement&&i.multiple?r.push({element:i,selected:Array.from(i.selectedOptions).map(n=>n.value)}):r.push({element:i,value:i.value}));for(const n of e.getChildElementFragments())h.collectEditsAfter(n,t,r);return r}static restoreEdits(e){for(const t of e){const{element:r}=t;if(t.checked!==void 0&&r instanceof HTMLInputElement){r.checked=t.checked;continue}if(t.selected!==void 0&&r instanceof HTMLSelectElement){for(const i of Array.from(r.options))i.selected=t.selected.includes(i.value);continue}t.value!==void 0&&(r.value=t.value)}}static async restoreAncestorArgValues(e,t=null){const r=e.getAttribute(`${c.prefix}form-arg`);if(!r)return;const i=String(r),n=h.resolveAncestorArgOwner(e,i);n&&(h.LAST_ANCESTOR_ARG_VALUES.delete(e.getTarget()),await h.pushAncestorArgValue(e,i,n.value,t))}static markResetSubtree(e,t){e.markResetAt(t),e.markSupplyApplied(t);for(const r of e.getChildElementFragments())h.markResetSubtree(r,t)}static clearMessages(e){return Ye().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return h.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=Ye(),a=s.addMessage,o=u=>typeof a=="function"?a.call(s,u,r,i):s.addErrorMessage(u,r),l=h.findFragmentsByKey(e,t);return l.forEach(u=>{n.push(o(u.getTarget()))}),l.length===0&&n.push(o(e.getTarget())),Promise.all(n).then(()=>{})}static findFragmentsByKey(e,t){return h.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&h.resolveFieldName(e)===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(...h.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),u=Number(l);if(isNaN(u))b.error("Haori",`Invalid index: ${i}`);else{const d=e.getChildElementFragments().filter(p=>p.hasAttribute(`${c.prefix}row`));u<d.length&&r.push(...h.findFragmentByKeyParts(d[u],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(n=>{r.push(...h.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}};h.INITIAL_RESTORED_FORMS=new WeakSet,h.LAST_ANCESTOR_ARG_VALUES=new WeakMap,h.GROUP_SCOPE_IDS=new WeakMap,h.groupScopeSequence=0,h.UNSAFE_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]),h.COLLECTED_ROW_IDENTITY=new WeakMap,h.COMPLETE_SET_VALUES=new WeakSet,h.COLLECTED_EXCLUDED_KEYS=new WeakMap,h.warnedPositionalRowFallbacks=new Set,h.LEADING_PATH_PATTERN=/^\s*([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*)\s*([\s\S]*)$/;let k=h;class O{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){O.dispatch(document,"ready",{version:e})}static importStart(e,t){O.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){O.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){O.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 u=t?.[l],d=r[l];u!==d&&n.push(l)}O.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){O.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){O.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){O.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){O.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){O.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){O.dispatch(e,"show",{visible:!0})}static hide(e){O.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){O.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){O.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){O.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:n?performance.now()-n:void 0})}static pollTimeout(e,t,r){O.dispatch(e,"polltimeout",{count:t,elapsedMs:r})}static pollStop(e,t,r,i){O.dispatch(e,"pollstop",{reason:t,count:r,elapsedMs:i})}}const It={401:"unauthorized-redirect",403:"forbidden-redirect"};function Nt(m,e){return m.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=_.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function Ft(m,e){const t=m.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=N.get(m),i=r instanceof D?r.getBindingData():{},n=Nt(t,i);return n===""?null:n}function kt(m,e,t){const r=m.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,s=`${encodeURIComponent(r)}=${encodeURIComponent(i)}`,a=t.indexOf("#"),o=a>=0?t.slice(a):"",l=a>=0?t.slice(0,a):t,u=l.includes("?")?"&":"?";return`${l}${u}${s}${o}`}function ft(m){const e=It[m];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=Ft(i,t);if(n===null)continue;const s=kt(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 z{static read(e,t){if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);return typeof r=="string"?r:null}static queryAll(e,t,r=document.body){try{return Array.from(r.querySelectorAll(e))}catch(i){return b.error("Haori",`Invalid selector: ${e} (${t})`,i),[]}}static query(e,t,r=document.body){try{return r.querySelector(e)}catch(i){return b.error("Haori",`Invalid selector: ${e} (${t})`,i),null}}}const I=class I{static resolveStorage(e){try{const t=e==="local"?window.localStorage:window.sessionStorage;if(!t)throw new Error("storage is not available");return t}catch(t){return I.WARNED_KINDS.has(e)||(I.WARNED_KINDS.add(e),b.warn("Haori",`${e}Storage が利用できないため ${c.prefix}store を無効にします:`,t)),null}}static isReservedKey(e){return e.startsWith("_")}static isPlainRecord(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}static warnOnce(e,t,r){let i=I.WARNED_ELEMENTS.get(e);i||(i=new Set,I.WARNED_ELEMENTS.set(e,i)),!i.has(t)&&(i.add(t),b.warn("Haori",r))}static isInsideEachRow(e){let t=e;for(;t;){if(t.getListKey()!==null)return!0;t=t.getParent()}return!1}static readDeclaration(e){const t=e.getTarget(),r=e.getRawAttribute(`${c.prefix}store`);if(r===null)return null;const i=r.trim();if(i==="")return I.warnOnce(t,"key",`${c.prefix}store にストレージキーが指定されていません。`),null;if(i.includes("{{"))return I.warnOnce(t,"expression",`${c.prefix}store に式は使用できません(静的な文字列を指定してください): ${i}`),null;const n=e.getRawAttribute(`${c.prefix}store-type`);let s="session";if(n!==null){const d=n.trim();d==="local"||d==="session"?s=d:I.warnOnce(t,"type",`${c.prefix}store-type は session または local を指定してください(session として扱います): ${d}`)}const a=e.getRawAttribute(`${c.prefix}store-arg`),o=a===null||a.trim()===""?null:a.trim(),l=e.getRawAttribute(`${c.prefix}store-params`);let u=null;if(l!==null){const d=l.split("&").map(g=>g.trim()).filter(g=>g!==""),p=d.filter(g=>!I.isReservedKey(g));p.length!==d.length&&I.warnOnce(t,"reserved",`${c.prefix}store-params の予約キー(先頭が _ のキー)は対象外です。`),u=p.length>0?p:null}return u===null&&o===null?(I.warnOnce(t,"target",`${c.prefix}store には ${c.prefix}store-params または ${c.prefix}store-arg のいずれかが必要です。`),null):{key:i,kind:s,params:u,arg:o}}static readRecord(e){const t=I.resolveStorage(e.kind);if(!t)return null;let r;try{r=t.getItem(e.key)}catch(n){return b.warn("Haori",`ストレージの読み取りに失敗しました: ${e.key}`,n),null}if(r===null)return null;let i;try{i=JSON.parse(r)}catch(n){return b.warn("Haori",`保存済みデータが JSON として解釈できません: ${e.key}`,n),null}return I.isPlainRecord(i)?i:(b.warn("Haori",`保存済みデータがオブジェクトではありません: ${e.key}`),null)}static extractFromRecord(e,t){let r=t;if(e.arg!==null){const s=t[e.arg];if(s===void 0)return{};if(!I.isPlainRecord(s))return b.warn("Haori",`保存済みデータの ${e.arg} がオブジェクトではありません: `+e.key),{};r=s}const i=e.params??Object.keys(r),n={};for(const s of i)I.isReservedKey(s)||Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s]);return n}static selectFromData(e,t){const r=e.params??Object.keys(t),i={};for(const n of r){if(I.isReservedKey(n)||!Object.prototype.hasOwnProperty.call(t,n))continue;const s=t[n];s!==void 0&&(i[n]=s)}return i}static stringify(e){try{return JSON.stringify(e)??null}catch{return null}}static createRefs(e){const t=new Map;for(const[r,i]of Object.entries(e))t.set(r,i);return t}static hasSameRefs(e,t){const r=Object.entries(t);if(e.refs.size!==r.length)return!1;for(const[i,n]of r)if(!e.refs.has(i)||e.refs.get(i)!==n)return!1;return!0}static seedSignature(e,t){const r=I.stringify(t);if(r===null){I.SIGNATURES.delete(e);return}I.SIGNATURES.set(e,{json:r,refs:I.createRefs(t)})}static writeRecord(e,t){const r=I.resolveStorage(e.kind);if(!r)return!1;const i=I.readRecord(e)??{};if(e.arg!==null){const n=i[e.arg],s=I.isPlainRecord(n)?{...n}:{};i[e.arg]={...s,...t}}else Object.assign(i,t);try{return r.setItem(e.key,JSON.stringify(i)),!0}catch(n){return b.warn("Haori",`ストレージへの保存に失敗しました: ${e.key}`,n),!1}}static restore(e){const t=I.readDeclaration(e);if(!t)return Promise.resolve();const r=e.getTarget();if(I.isInsideEachRow(e))return I.warnOnce(r,"each-row",`${c.prefix}each の行の内側では ${c.prefix}store を使用できません(行データは親要素側で配列キーを指定してください)。`),Promise.resolve();I.RESTORED_ELEMENTS.add(r);const i=I.readRecord(t),n=i?I.extractFromRecord(t,i):{},s={...e.getRawBindingData()??{},...n};return I.seedSignature(r,I.selectFromData(t,s)),Object.keys(n).length===0?Promise.resolve():B.setBindingData(r,s,{reentrant:!0,kind:"nonSupply",sequence:D.nextSequence()})}static mirror(e){const t=I.readDeclaration(e);if(!t||I.isInsideEachRow(e))return;const r=e.getTarget();if(!I.RESTORED_ELEMENTS.has(r))return;const i=e.getRawBindingData();if(!i)return;const n=I.selectFromData(t,i);if(Object.keys(n).length===0)return;const s=I.SIGNATURES.get(r);if(s&&I.hasSameRefs(s,n))return;const a=I.stringify(n);if(a===null){b.warn("Haori",`保存対象を直列化できないためミラーを行いません: ${t.key}`);return}if(s&&s.json===a){s.refs=I.createRefs(n);return}I.writeRecord(t,n)&&I.SIGNATURES.set(r,{json:a,refs:I.createRefs(n)})}static clear(e,t){const r=I.resolveStorage(t);if(r){try{r.removeItem(e)}catch(i){b.warn("Haori",`ストレージの破棄に失敗しました: ${e}`,i);return}I.reseedDeclaringElements(e,t)}}static reseedDeclaringElements(e,t){document.querySelectorAll(`[${c.prefix}store]`).forEach(i=>{if(!I.RESTORED_ELEMENTS.has(i))return;const n=N.get(i);if(!(n instanceof D))return;const s=I.readDeclaration(n);if(!s||s.key!==e||s.kind!==t)return;const a=n.getRawBindingData();I.seedSignature(i,a?I.selectFromData(s,a):{})})}};I.SIGNATURES=new WeakMap,I.RESTORED_ELEMENTS=new WeakSet,I.WARNED_ELEMENTS=new WeakMap,I.WARNED_KINDS=new Set;let Ee=I;class ht{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 Mt=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],Ct="__haoriHistoryState__",$e="data-haori-click-lock";function Re(){const e=globalThis.window?.Haori;return Mt.every(r=>typeof e?.[r]=="function")?e:ae}const xt=new Set(["GET","HEAD","OPTIONS"]);function Le(m){return xt.has(m.toUpperCase())}function $t(m,e){for(const[t,r]of Object.entries(e))r!==void 0&&(Array.isArray(r)?r.forEach(i=>{m.append(t,fe(i))}):m.append(t,fe(r)))}function fe(m){if(m==null)return"";if(typeof m=="object"||typeof m=="function")try{return JSON.stringify(m)??""}catch{return""}return String(m)}function pt(m,e){const t=new URL(m,window.location.href),r=new URLSearchParams(t.search);return $t(r,e),t.search=r.toString(),t.toString()}function Pt(m){if(m==null)return{payload:{},dropped:!1};if(typeof m=="string"){const e=m.trim();if(e==="")return{payload:{},dropped:!1};if(e.startsWith("{")){try{const t=JSON.parse(e);if(t!==null&&typeof t=="object"&&!Array.isArray(t))return{payload:t,dropped:!1}}catch{}return{payload:{},dropped:!0}}return e.includes("=")?{payload:Xe(new URLSearchParams(e)),dropped:!1}:{payload:{},dropped:!0}}if(m instanceof URLSearchParams)return{payload:Xe(m),dropped:!1};if(typeof FormData<"u"&&m instanceof FormData){const e={};let t=!1;for(const[r,i]of m.entries()){if(typeof i!="string"){t=!0;continue}gt(e,r,i)}return{payload:e,dropped:t}}return{payload:{},dropped:!0}}function Xe(m){const e={};for(const[t,r]of m.entries())gt(e,t,r);return e}function gt(m,e,t){const r=m[e];r===void 0?m[e]=t:Array.isArray(r)?r.push(t):m[e]=[r,t]}function oe(m,e){if(k.isCompleteSetValue(e))return e;if(Array.isArray(e)){const t=Array.isArray(m)?m.slice():[];let r=!1;return e.forEach((i,n)=>{i!=null&&(typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0||(t[n]=oe(t[n],i),r=!0))}),r?t:m}if(e!==null&&typeof e=="object"){const t=m!==null&&typeof m=="object"&&!Array.isArray(m)?{...m}:{};for(const[r,i]of Object.entries(e))t[r]=oe(t[r],i);return t}return e}function Lt(m){const e=m?.body;return e==null?!1:typeof e=="string"?e!=="":!0}function Bt(m,e){const t={...e||{}},r=(t.method||"GET").toUpperCase();if(c.runtime!=="demo"||Le(r))return{url:m,options:t,requestedMethod:r,effectiveMethod:r,normalized:!1};const{payload:i,dropped:n}=Pt(t.body);let s=m;Object.keys(i).length>0&&(s=pt(s,i)),n&&b.warn("Haori",`The ${r} body cannot be converted into a query string and is dropped by the demo runtime normalization. Send the values with ${c.prefix}{event}-data / ${c.prefix}{event}-form, or use the embedded runtime.`),delete t.body,t.method="GET";const a=new Headers(t.headers||void 0);return a.delete("Content-Type"),t.headers=a,{url:s,options:t,requestedMethod:r,effectiveMethod:"GET",normalized:!0,queryString:new URL(s,window.location.href).search||void 0}}function Ot(m){return m==null?null:typeof m=="string"?m:m instanceof URLSearchParams?m.toString():m instanceof FormData?Array.from(m.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(m)}function Ae(m){return m instanceof Blob?!0:Array.isArray(m)?m.some(Ae):m!==null&&typeof m=="object"?Object.values(m).some(Ae):!1}function Ht(m){return Object.values(m).some(e=>e instanceof Blob?!1:Array.isArray(e)?e.some(t=>!(t instanceof Blob)&&Ae(t)):Ae(e))}function Te(m){return Be(k.getValues(m))}function Be(m){const e=r=>{if(r instanceof File)return r.name;if(r instanceof Blob)return"";if(Array.isArray(r)){const i=r.map(e);return k.carryCollectedRowIdentity(r,i),i}if(r!==null&&typeof r=="object"){const i={};for(const[n,s]of Object.entries(r))i[n]=e(s);return k.carryCollectedRowIdentity(r,i),i}return r},t={};for(const[r,i]of Object.entries(m))t[r]=e(i);return k.carryCollectedRowIdentity(m,t),t}function Ut(m,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:m,method:String(e.method||"GET").toUpperCase(),headers:r,body:Ot(e.body||null)})}const y=class y{constructor(e,t=null,r=null){this.reentrantBind=!1,this.suppressEmptyReplaceBind=!1,this.requestUserEditSequence=null,this.twoWayCommitBind=!1,this.operationSequence=r!=null?D.nextOperationSequence():D.nextSequence(),y.isElementFragment(e)?(this.options=y.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 readLateAttribute(e,t,r,i){const n=e.getAttributeEvaluation(i);return t.lateAttributes||(t.lateAttributes=new Map),t.lateAttributes.set(r,{attributeName:i,hasUnresolvedReference:n?.hasUnresolvedReference??!1}),n?.value??null}static unescapeNewlines(e){return typeof e=="string"?e.replace(/\\n/g,`
8
+ `;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){if(!e||typeof e!="object")return!1;const i=r??this.getForbiddenBindingValueSet(),n=this.forbiddenBindingValueCache.get(e);if(n!==void 0)return n;if(t.has(e))return!1;if(t.add(e),i.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const s of Object.values(e)){if(typeof s=="function"){if(i.has(s))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(s,t,i))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};M.MAX_IDENTIFIER_RECOVERY_COUNT=8,M.BUILTIN_NAMESPACE="haori",M.BUILTIN_HELPERS={...Rt},M.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,M.BUILTIN_DATA_PROPERTY="data",M.BUILTIN_DATA_REFERENCE_PATTERN=/(^|[^\w$.])haori\s*(\.\s*data(?![\w$])|\[)/,M.IDENTIFIER_NAME_PATTERN=/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u,M.usableBindingKeyCache=new Map,M.loggedUnusableBindingKeys=new Set,M.compileFailedExpressions=new Set,M.forbiddenBindingValueCache=new WeakMap,M.forbiddenBindingValueCacheResetScheduled=!1,M.loggedForbiddenKeySignatures=new Set,M.loggedForbiddenKeyResetScheduled=!1,M.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"],M.STRICT_FORBIDDEN_NAMES=["eval","arguments"],M.REBINDABLE_FORBIDDEN_NAMES=new Set(["location","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),M.FORBIDDEN_BINDING_NAMES=new Set([...M.FORBIDDEN_NAMES.filter(e=>!M.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...M.STRICT_FORBIDDEN_NAMES]),M.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),M.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),M.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"]),M.NON_SHADOWABLE_IDENTIFIERS=new Set(["true","false","null","undefined","NaN","Infinity","enum","implements","interface","package","private","protected","public","static","super"]),M.ALLOWED_GLOBAL_IDENTIFIERS=new Set(["Math","JSON","Intl","Atomics","Array","String","Number","Boolean","Date","RegExp","Symbol","BigInt","Map","Set","WeakMap","WeakSet","WeakRef","FinalizationRegistry","Promise","Proxy","Error","AggregateError","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","ArrayBuffer","SharedArrayBuffer","DataView","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","parseInt","parseFloat","isNaN","isFinite","encodeURI","encodeURIComponent","decodeURI","decodeURIComponent"]),M.EXPRESSION_CACHE=new Map,M.FREE_IDENTIFIER_CACHE=new Map,M.BOUND_IDENTIFIER_CACHE=new Map,M.OPTIONAL_CHAIN_CACHE=new Map,M.GUARDED_MEMBER_CACHE=new Map,M.MEMBER_KEY_GUARD_OPEN="(_hk=>_hk==='constructor'||_hk==='__proto__'||_hk==='prototype'?undefined:_hk)(",M.FORBIDDEN_NAME_PATTERNS=M.FORBIDDEN_NAMES.map(e=>({name:e,pattern:new RegExp(`(^|[^\\w$.])${e}(?![\\w$])`)})),M.FORBIDDEN_IDENTIFIER_CACHE=new Map,M.pendingUnresolvedIdentifiers=new Set,M.unresolvedReportScheduled=!1,M.suppliedIdentifiers=new Set,M.pendingScopeMissingIdentifiers=new Map,M.scopeMissingReportScheduled=!1,M.rowScopeIdentifiers=new Set,M.loggedScopeMissingIdentifiers=new Set,M.loggedBlockedIdentifierExpressions=new Set;let _=M;const ye="data-haori-if-disabled",Ge="input, select, textarea, button, fieldset",K=class K{static reset(){K.ELEMENT_STORES.clear(),K.ensureGlobalAccess()}static snapshot(){return K.ensureGlobalAccess(),[...K.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:K.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:K.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(!j.isEnabled()||!e||t.length===0)return;K.ensureGlobalAccess();const i=K.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const s=K.getOrCreateCounter(i.attributes,e.rawName,e.template);K.updateCounter(s,t,r);return}const n=K.getOrCreateCounter(i.texts,String(e.childIndex),e.template);K.updateCounter(n,t,r)}static ensureGlobalAccess(){if(!j.isEnabled())return;const e=globalThis;e[K.GLOBAL_KEY]===void 0&&(e[K.GLOBAL_KEY]={reset:()=>K.reset(),snapshot:()=>K.snapshot()})}static getOrCreateElementStore(e){const t=K.createElementId(e),r=K.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return K.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=K.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=K.now();return{value:e(),durationMs:K.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(" > ")}};K.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",K.ELEMENT_STORES=new Map;let De=K;const ue=class ue{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,ue.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(ue.FRAGMENT_CACHE.has(e))return ue.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new D(e);break;case Node.TEXT_NODE:t=new ee(e);break;case Node.COMMENT_NODE:t=new Ue(e);break;default:return b.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 W.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 W.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 W.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),ue.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};ue.FRAGMENT_CACHE=new WeakMap;let N=ue;const R=class R extends N{constructor(e){super(e),this.children=[],this.attributeMap=new Map,this.bindingData=null,this.bindingWorkChain=Promise.resolve(),this.bindingWorkActive=0,this.lastSupplySequence=0,this.lastResetSequence=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.rowLocalTemplate=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.selfWritingAttributes=new Map,this.skipChangeValue=!1,this.valueWriteUnapplied=!1,this.pendingValueWrite=null,this.userEditSequence=0,this.authoritativeValueSequence=0,this.lastValueSequence=0,this.lastValueKind="nonSupply",this.selfWrittenBind=new Map,this.lastPathApplied=new Map,this.lastChangeSequence=0,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 Ie(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=N.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof R)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){b.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new R(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.rowLocalTemplate=this.rowLocalTemplate,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.restoreFormControlsDisabledByIf()),this.children.forEach(e=>{e instanceof R&&e.normalizeClonedVisibilityState()})}remove(e=!0){const t=[];return e&&re.destroySubtree(this.getTarget()),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,this.clearUnappliedValueWrite(),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}static isExecutingAnyBindingWork(){return R.bindingWorkActiveCount>0}markBindingWorkStart(){this.bindingWorkActive++,R.bindingWorkActiveCount++}markBindingWorkEnd(){this.bindingWorkActive>0&&(this.bindingWorkActive--,R.bindingWorkActiveCount--)}markSupplyApplied(e){e>this.lastSupplySequence&&(this.lastSupplySequence=e)}isSupplyStale(e){return this.lastSupplySequence>e}markResetAt(e){this.lastResetSequence=e}wasResetAfter(e){return this.lastResetSequence>e}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 R&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e,this.rowLocalTemplate=null}getRowLocalTemplate(){return this.rowLocalTemplate}setRowLocalTemplate(e){this.rowLocalTemplate=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,t=null){return this.applyValue(e,!0,t)}syncBindingValue(e,t=null){return this.applyValue(e,!1,t)}applyValue(e,t,r=null){if(this.skipChangeValue)return(this.pendingValueWrite??Promise.resolve()).then(()=>this.applyValue(e,t,r));if(r&&!this.canApplyValue(r)||(r&&this.markValueApplied(r),this.value===e))return Promise.resolve();const i=this.getTarget();if(i instanceof HTMLInputElement&&i.type==="file")return e===null||e===""?(this.value=null,i.value===""?Promise.resolve():W.enqueue(()=>{i.value=""})):(b.warn("[Haori]","A value cannot be assigned to input[type=file]; only clearing is supported.",i),Promise.resolve());if(i instanceof HTMLInputElement&&(i.type==="checkbox"||i.type==="radio")){const n=this.hasAttribute("value")?this.getAttribute("value"):i.value,s=i.type==="checkbox"&&n==="true";let a;if(s?a=e===!0||e==="true":n==="false"?a=e===!1:Array.isArray(e)?a=e.map(String).includes(String(n)):a=n===String(e),s?this.value=a:a?Array.isArray(e)?this.value=String(n):this.value=e:this.value=null,i.checked===a)return Promise.resolve();const o=this.userEditSequence;return this.enqueueValueWrite(()=>{this.isSupersededByUserEdit(o)||r&&!this.canApplyValue(r)||(i.checked=a,t&&i.dispatchEvent(new Event("change",{bubbles:!0})))})}else if(i instanceof HTMLSelectElement&&i.multiple){const n=(Array.isArray(e)?e:e===null?[]:[e]).map(String);return this.writeSelectedValues(n,t,r)}else return i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement?this.writeScalarValue(Array.isArray(e)?e.join(","):e,t,r):(b.warn("[Haori]","setValue is not supported for this element type.",i),Promise.resolve())}writeScalarValue(e,t,r=null){const i=this.getTarget(),n=e===null?"":String(e);this.value=this.normalizeValueForElement(i,e);const s=this.userEditSequence;return this.enqueueValueWrite(()=>{this.isSupersededByUserEdit(s)||r&&!this.canApplyValue(r)||(i.value=n,this.recordValueWriteResult(i.value===n),t&&((i instanceof HTMLInputElement&&R.INPUT_EVENT_TYPES.includes(i.type)||i instanceof HTMLTextAreaElement)&&i.dispatchEvent(new Event("input",{bubbles:!0})),i.dispatchEvent(new Event("change",{bubbles:!0}))))})}writeSelectedValues(e,t,r=null){const i=this.getTarget();this.value=e.slice();const n=this.userEditSequence;return this.enqueueValueWrite(()=>{if(this.isSupersededByUserEdit(n)||r&&!this.canApplyValue(r))return;let s=!1;const a=new Set;Array.from(i.options).forEach(o=>{const l=e.includes(o.value);o.selected!==l&&(o.selected=l,s=!0),l&&a.add(o.value)}),this.recordValueWriteResult(e.every(o=>a.has(o))),s&&t&&i.dispatchEvent(new Event("change",{bubbles:!0}))})}enqueueValueWrite(e){this.skipChangeValue=!0;const t=W.enqueue(e).finally(()=>{this.skipChangeValue=!1});return this.pendingValueWrite=t,t}isSupersededByUserEdit(e){return this.userEditSequence!==e}static retryUnappliedValueWrites(e,t){if(R.UNAPPLIED_VALUE_WRITES.size===0)return Promise.resolve();const r=[];for(const i of Array.from(R.UNAPPLIED_VALUE_WRITES)){const n=i.getTarget();if(i.wasResetAfter(t)){i.clearUnappliedValueWrite();continue}if(!n.isConnected){i.clearUnappliedValueWrite();continue}e.contains(n)&&r.push(i.retryValueWrite())}return Promise.all(r).then(()=>{})}retryValueWrite(){const e=this.getTarget();if(this.skipChangeValue||!(e instanceof HTMLSelectElement))return Promise.resolve();if(e.multiple){const r=Array.isArray(this.value)?this.value.slice():[];return r.every(i=>Array.from(e.options).some(n=>n.value===i))?this.writeSelectedValues(r,!1):Promise.resolve()}const t=this.value===null?"":String(this.value);return Array.from(e.options).some(r=>r.value===t)?this.writeScalarValue(this.value,!1):Promise.resolve()}clearUnappliedValueWrite(){this.valueWriteUnapplied=!1,R.UNAPPLIED_VALUE_WRITES.delete(this)}getValue(){return this.value}static currentSequence(){return R.sequenceCounter}static nextSequence(){return R.sequenceCounter+=1,R.sequenceCounter}static setPendingMutationFlusher(e){R.pendingMutationFlusher=e}static nextOperationSequence(){return R.pendingMutationFlusher&&!R.isExecutingAnyBindingWork()&&R.pendingMutationFlusher(),R.nextSequence()}canApplyValue(e){return e.kind==="nonSupply"&&e.editedPaths!==void 0&&this.userEditSequence>0&&this.wasResetAfter(this.userEditSequence)?!1:R.isApplicable({sequence:this.lastValueSequence,kind:this.lastValueKind},e)}static isApplicable(e,t){return e===null?!0:t.kind==="nonSupply"&&e.kind==="edit"?!1:t.sequence>e.sequence?!0:t.sequence===e.sequence?e.kind!=="edit"||t.kind==="edit":!1}canApplyPath(e,t){return R.isApplicable(this.lastPathApplied.get(e)??null,t)}markPathApplied(e,t){if(t.kind==="nonSupply")return;const r=this.lastPathApplied.get(e)??null;(r===null||t.sequence>r.sequence||t.sequence===r.sequence&&t.kind==="edit")&&this.lastPathApplied.set(e,{sequence:t.sequence,kind:t.kind})}markValueApplied(e){e.kind!=="nonSupply"&&(e.sequence>this.lastValueSequence||e.sequence===this.lastValueSequence&&e.kind==="edit")&&(this.lastValueSequence=e.sequence,this.lastValueKind=e.kind)}markUserEdit(){return this.userEditSequence=R.nextSequence(),this.markValueApplied({sequence:this.userEditSequence,kind:"edit"}),this.userEditSequence}markUserEditOnChange(){const t=this.userEditSequence>this.lastChangeSequence?this.userEditSequence:this.markUserEdit();return this.lastChangeSequence=t,t}getUserEditSequence(){return this.userEditSequence}hasPendingUserEdit(){return this.userEditSequence>this.authoritativeValueSequence}clearUserEditMark(e=R.currentSequence()){e>this.authoritativeValueSequence&&(this.authoritativeValueSequence=e),this.lastValueKind==="edit"&&this.lastValueSequence<=e&&(this.lastValueKind="supply")}static warnUnresolvedAttribute(e,t,r,i){if(!j.isEnabled())return;const n=`${e} ${r}`;R.loggedUnresolvedAttributes.has(n)||(R.loggedUnresolvedAttributes.add(n),b.warn("[Haori]",`Attribute "${t}" was not applied because the expression has an unresolved reference; the attribute is removed and the synchronized value is emptied: ${e}="${r}"`,i))}hasPendingCheckableUserEdit(e){if(!e)return this.hasPendingUserEdit();const t=this.getTarget().closest("select");if(!t)return!1;const r=N.get(t);return r instanceof R?r.hasPendingUserEdit():!1}clearValue(){this.value=null,this.clearUnappliedValueWrite()}normalizeValueForElement(e,t){const r=R.resolveDeclaredValueType(e);return r==="boolean"?R.normalizeBooleanValue(t):r==="string"?t===null?null:String(t):r==="number"||r===null&&e instanceof HTMLInputElement&&e.type==="number"?R.normalizeNumberValue(t):t}static normalizeNumberValue(e){if(e===null||e==="")return null;if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||!R.NUMBER_INPUT_PATTERN.test(e))return null;const t=Number(e);return Number.isFinite(t)?t:null}static normalizeBooleanValue(e){if(typeof e=="boolean")return e;if(typeof e!="string")return null;const t=e.toLowerCase();return t==="true"?!0:t==="false"?!1:null}static resolveDeclaredValueType(e){const t=e.getAttribute(`${c.prefix}value-type`);if(t===null)return null;const r=t.trim().toLowerCase();return R.VALUE_TYPE_NAMES.has(r)?R.acceptsDeclaredValueType(e)?r:(R.warnValueTypeDeclaration(e,t,"値を持つ入力(checkbox / radio / file と複数選択の select を除く)にのみ指定できます"),null):(R.warnValueTypeDeclaration(e,t,"boolean / number / string のいずれかを指定してください"),null)}static acceptsDeclaredValueType(e){return e instanceof HTMLInputElement?e.type!=="checkbox"&&e.type!=="radio"&&e.type!=="file":e instanceof HTMLSelectElement?!e.multiple:e instanceof HTMLTextAreaElement}static warnValueTypeDeclaration(e,t,r){if(!j.isEnabled())return;const i=e instanceof HTMLInputElement?`[type=${e.type}]`:"",n=`${e.tagName}${i} ${t} ${r}`;R.loggedValueTypeDeclarations.has(n)||(R.loggedValueTypeDeclarations.add(n),b.warn("Haori",`${c.prefix}value-type="${t}" を無視しました(${r}):`,e))}static isValuePropertyTarget(e){return e instanceof HTMLInputElement?R.INPUT_EVENT_TYPES.includes(e.type)||e.type==="hidden":e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement}static isUserEditableValue(e){return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?!e.readOnly:!0}syncValue(){this.clearUnappliedValueWrite(),this.value=this.readValueFromDom()}readValueFromDom(){const e=this.getTarget();if(R.resolveDeclaredValueType(e),e instanceof HTMLInputElement){if(e.type==="checkbox"||e.type==="radio"){const t=e.type==="checkbox"&&e.value==="true",r=e.value;return e.checked?t?!0:r==="false"?!1:r:t?!1:r==="false"?!0:null}else if(e.type==="file"){const t=e.files;return t&&t.length>0?t[0].name:null}return this.normalizeValueForElement(e,e.value)}else{if(e instanceof HTMLTextAreaElement)return this.normalizeValueForElement(e,e.value);if(e instanceof HTMLSelectElement)return e.multiple?Array.from(e.selectedOptions).map(t=>t.value):this.normalizeValueForElement(e,e.value)}return this.value}recordValueWriteResult(e){if(!e&&this.value!==null&&this.value!==""){this.valueWriteUnapplied=!0,R.UNAPPLIED_VALUE_WRITES.add(this);return}this.clearUnappliedValueWrite()}getValueForCollection(){return this.skipChangeValue||this.valueWriteUnapplied?this.value:R.isValuePropertyTarget(this.getTarget())?this.readValueFromDom():this.value}syncCheckableValueFromDom(e){if(!e){this.syncValue();return}const t=this.getTarget().closest("select");if(!t)return;const r=N.get(t);r instanceof R&&r.syncValue()}getSelfWritingAttribute(e){for(const t of e){const r=this.selfWritingAttributes.get(t);if(r!==void 0)return r}return null}holdSelfWritingAttributes(e,t){for(const r of e)this.selfWritingAttributes.set(r,t)}releaseSelfWritingAttributes(e){for(const t of e)this.selfWritingAttributes.delete(t)}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,!0,i)}removeAliasedAttribute(e,t){const r=[e,t];if(this.getSelfWritingAttribute(r)!==null)return Promise.resolve();this.attributeMap.delete(e);const i=this.getTarget(),n=i.hasAttribute(e),s=t!==e&&i.hasAttribute(t);if(!n&&!s)return Promise.resolve();const a=W.enqueue(()=>{n&&i.removeAttribute(e),s&&i.removeAttribute(t)}).finally(()=>{this.releaseSelfWritingAttributes(r)});return this.holdSelfWritingAttributes(r,a),a}setAttributeInternal(e,t,r,i,n=!1){const s=[e,t],a=this.getSelfWritingAttribute(s);if(a!==null)return n||r===null?Promise.resolve():a.then(()=>this.setAttributeInternal(e,t,r,i,n));if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const o=new Ie(e,r);if(n){const xe=this.attributeMap.get(e);if(xe&&(xe.isEvaluate||xe.isForceEvaluation())&&!o.isEvaluate&&!o.isForceEvaluation()){const We=W.enqueue(()=>{}).finally(()=>{this.releaseSelfWritingAttributes(s)});return this.holdSelfWritingAttributes(s,We),We}}this.attributeMap.set(e,o);const l=this.getTarget(),u=o.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:l,rawName:e,template:r}),d=o.isEvaluate||o.isRawEvaluate,p=e===t&&R.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),g=o.isSingleExpression(),A=se.joinEvaluateResults(u.results),v=u.results.length===1?u.results[0]:A,T=t==="value"&&R.resolveDeclaredValueType(l)==="boolean",F=v===!1&&!T,H=!o.isForceEvaluation()&&(t!==e?u.hasUnresolvedReference||v===null||v===void 0||F:p?u.hasUnresolvedReference||v===null||v===void 0||v===!1:g?u.hasUnresolvedReference||v===null||v===void 0||F:d&&A==="");H&&u.hasUnresolvedReference&&R.warnUnresolvedAttribute(e,t,r,l);const E=o.isForceEvaluation()?r:g?v:A,S=i&&o.isEvaluate&&t==="value"&&R.isValuePropertyTarget(l),C=l.getRootNode(),U=S&&R.isUserEditableValue(l)&&(l===C.activeElement||this.hasPendingUserEdit()),P=H||E===null||E===!1&&!T?null:String(E),Q=e!==t&&l.getAttribute(e)!==r,x=P===null?l.hasAttribute(t):l.getAttribute(t)!==P,V=P===null?"":P,X=S&&!U&&l.value!==V,Y=t==="checked"&&l instanceof HTMLInputElement&&(l.type==="checkbox"||l.type==="radio"),te=t==="selected"&&l instanceof HTMLOptionElement,be=C.activeElement,de=be!==null&&(Y&&l===be||te&&l.closest("select")===be)||(Y||te)&&this.hasPendingCheckableUserEdit(te),ve=P!==null,Ce=Y&&!de&&l.checked!==ve,Se=te&&!de&&l.selected!==ve;if(!Q&&!x&&!X&&!Ce&&!Se)return S&&!U&&(this.value=this.normalizeValueForElement(l,V),this.clearUnappliedValueWrite()),(Y||te)&&!de&&this.syncCheckableValueFromDom(te),Promise.resolve();const qe=W.enqueue(()=>{Q&&l.setAttribute(e,r),P===null?l.removeAttribute(t):x&&(l.setAttribute(t,P),t===`${c.prefix}bind`&&this.recordSelfWrittenBind(P)),S&&!U&&(this.value=this.normalizeValueForElement(l,V),X&&(l.value=V),this.recordValueWriteResult(l.value===V)),Ce&&(l.checked=ve),Se&&(l.selected=ve),(Ce||Se)&&this.syncCheckableValueFromDom(Se)}).finally(()=>{this.releaseSelfWritingAttributes(s)});return this.holdSelfWritingAttributes(s,qe),qe}removeAttribute(e){if(this.getSelfWritingAttribute([e])!==null)return Promise.resolve();this.attributeMap.delete(e);const t=this.getTarget();if(!t.hasAttribute(e))return Promise.resolve();const r=W.enqueue(()=>{t.removeAttribute(e)}).finally(()=>{this.releaseSelfWritingAttributes([e])});return this.holdSelfWritingAttributes([e],r),r}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:se.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=N.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 b.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 b.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 u=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 g=this.resolveInsertionPointFromDom(t,!1);g===null?(b.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(g.index,0,e),u=g.referenceNode)}else this.children.splice(p,0,e)}e.setParent(this),e.setMounted(this.mounted);const d=this.skipMutationNodes;return this.skipMutationNodes=!0,W.enqueue(()=>{this.target.insertBefore(e.getTarget(),u)}).finally(()=>{this.skipMutationNodes=d})}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?(b.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`,""),R.disableFormControlsInBranch(e),Promise.resolve()}static forEachFormControlInBranch(e,t){e.matches(Ge)&&t(e);const r=i=>{Array.from(i.children).forEach(n=>{n.hasAttribute(`${c.prefix}if-false`)||(n instanceof HTMLElement&&n.matches(Ge)&&t(n),r(n))})};r(e)}static disableFormControlsInBranch(e){R.forEachFormControlInBranch(e,t=>{t.hasAttribute("disabled")||(t.setAttribute(ye,""),t.setAttribute("disabled",""))})}restoreFormControlsDisabledByIf(){R.forEachFormControlInBranch(this.getTarget(),e=>{e.hasAttribute(ye)&&(e.removeAttribute(ye),e.removeAttribute("disabled"))})}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.restoreFormControlsDisabledByIf(),this.visible=!0,Promise.resolve()}closestByAttribute(e){if(this.hasAttribute(e))return this;const t=this.getParent();return t===null?null:t.closestByAttribute(e)}};R.NUMBER_INPUT_PATTERN=/^-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/,R.VALUE_TYPE_NAMES=new Set(["boolean","number","string"]),R.loggedValueTypeDeclarations=new Set,R.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"]),R.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],R.UNAPPLIED_VALUE_WRITES=new Set,R.sequenceCounter=0,R.bindingWorkActiveCount=0,R.pendingMutationFlusher=null,R.loggedUnresolvedAttributes=new Set;let D=R;class ee extends N{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new se(this.text)}clone(){const e=new ee(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}getRawText(){return this.text}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new se(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):W.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=se.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 Ue extends N{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new Ue(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,W.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const Fe=class Fe{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(Fe.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&&(b.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 u=De.measure(()=>_.evaluateDetailed(l.text,e)),d=u.value;a+=u.durationMs,s.push({expression:l.text,durationMs:u.durationMs}),o=o||d.unresolvedReference,n.push(d.value)}else n.push(l.text)}catch(u){b.error("[Haori]",`Error evaluating ${i} expression: ${l.text}`,u),s.push({expression:l.text,durationMs:0}),n.push("")}}),De.record(t,s,a),{results:n,hasUnresolvedReference:o}}};Fe.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let se=Fe;const Z=class Z extends se{constructor(e,t){super(t),this.forceEvaluation=Z.needsForceEvaluation(e)}static needsForceEvaluation(e){if(Z.forceEvaluationNames===null||Z.forceEvaluationPrefix!==c.prefix){const t=new Set;for(const r of[c.prefix,...Z.FORCE_EVALUATION_PREFIXES])for(const i of Z.FORCE_EVALUATION_SUFFIXES)t.add(`${r}${i}`);Z.forceEvaluationNames=t,Z.forceEvaluationPrefix=c.prefix}return Z.forceEvaluationNames.has(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?(b.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};Z.FORCE_EVALUATION_SUFFIXES=["if","each","derive"],Z.FORCE_EVALUATION_PREFIXES=["data-","hor-"],Z.forceEvaluationNames=null,Z.forceEvaluationPrefix=null;let Ie=Z;const ge=class ge{static get runtime(){return c.runtime}static setRuntime(e){c.setRuntime(e)}static waitForRenders(){return W.waitForIdle()}static dialog(e){return W.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 W.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return W.enqueue(()=>{e instanceof HTMLDialogElement?(ge.clearMessagesSync(e),e.showModal()):b.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return W.enqueue(()=>{e instanceof HTMLDialogElement?e.close():b.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return ge.addMessage(e,t,"error")}static addMessage(e,t,r){return W.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 W.enqueue(()=>{ge.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 ke(e,t,r)}static now(e,t){return et(e,t)}static today(e,t,r){return tt(e,t,r)}static number(e,t){return rt(e,t)}static range(e,t,r){return it(e,t,r)}static pages(e,t,r){return nt(e,t,r)}static monthAdd(e,t){return Me(e,t)}static monthRange(e,t){return st(e,t)}static pageSummary(e,t){return at(e,t)}static findBy(e,t,r){return ot(e,t,r)}static sum(e,t){return lt(e,t)}static distinct(e,t){return ut(e,t)}static groupBy(e,t){return dt(e,t)}};ge.enhancers={register(e,t){re.register(e,t)},has(e){return re.has(e)}};let ae=ge;const Tt="入力内容を確認してください",Dt=["addErrorMessage","clearMessages"],ze="data-haori-group-name";function Ye(){const e=globalThis.window?.Haori;return Dt.every(r=>typeof e?.[r]=="function")?e:ae}const h=class h{static getValues(e){const t={},r=new Set;return h.getPartValues(e,t,null,r),h.registerCollectedExcludedKeys(t,r),t}static resolveCollectedValue(e){const t=e.getTarget();if(h.isFileInput(e)){const r=t,i=r.files?Array.from(r.files):[];return r.multiple?i:i.length>0?i[0]:null}if(h.isBooleanCheckbox(e)){const r=t;return r.value==="false"?!r.checked:r.checked}return e.getValueForCollection()}static isBooleanCheckbox(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="checkbox"&&(t.value==="true"||t.value==="false")}static resolveFieldName(e){const t=e.getAttribute(`${c.prefix}form-name`);return t||e.getAttribute("name")}static prepareFormName(e){if(!e.hasAttribute(`${c.prefix}form-name`))return;const t=e.getAttribute(`${c.prefix}form-name`);if(!t){b.warn("Haori",`${c.prefix}form-name evaluated to an empty key; the field falls back to the name attribute or is not collected.`,e.getTarget());return}const r=e.getTarget();if(!(r instanceof HTMLInputElement)||r.type!=="radio"||r.hasAttribute("name")&&!r.hasAttribute(ze))return;const i=h.resolveGroupScope(e),n=`${String(t)}--haori${h.resolveGroupScopeId(i)}`;if(r.getAttribute("name")!==n)return e.setAttribute(ze,"").then(()=>e.setAttribute("name",n))}static resolveGroupScope(e){let t=e,r=t.getParent();for(;r!==null;){if(r.hasAttribute(`${c.prefix}form-list`))return t;if(r.getTarget()instanceof HTMLFormElement||r.hasAttribute(`${c.prefix}form`))return r;t=r,r=r.getParent()}return t}static resolveGroupScopeId(e){const t=h.GROUP_SCOPE_IDS.get(e);return t!==void 0?t:(h.groupScopeSequence+=1,h.GROUP_SCOPE_IDS.set(e,h.groupScopeSequence),h.groupScopeSequence)}static hasResolvedDeclarativeState(e){if(!h.isDeclarativeStateBound(e))return!1;const t=e.getTarget();if(t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio"))return h.isDeclarationResolved(e,"checked");if(h.hasDeclarativeBinding(e,"value"))return h.isDeclarationResolved(e,"value");if(t instanceof HTMLSelectElement){for(const r of Array.from(t.options)){const i=N.get(r);if(i instanceof D&&h.hasDeclarativeBinding(i,"selected")&&!h.isDeclarationResolved(i,"selected"))return!1}return!0}return!1}static isDeclarationResolved(e,t){for(const r of[`${c.prefix}attr-${t}`,t]){const i=e.getAttributeEvaluation(r);if(i!==null)return!i.hasUnresolvedReference}return!1}static isDeclarativeStateBound(e){const t=e.getTarget();return t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")?h.hasDeclarativeBinding(e,"checked"):D.isValuePropertyTarget(t)?h.hasDeclarativeBinding(e,"value")?!0:t instanceof HTMLSelectElement?h.hasDeclarativeSelectedOption(t):!1:!1}static restoreDefaultValues(e){const t="input, textarea, select",r=[];e.matches(t)&&r.push(e),r.push(...e.querySelectorAll(t));for(const i of r)i instanceof HTMLInputElement?i.type==="checkbox"||i.type==="radio"?i.checked=i.defaultChecked:i.type==="file"?i.value="":i.value=i.defaultValue:i instanceof HTMLTextAreaElement?i.value=i.defaultValue:i instanceof HTMLSelectElement&&h.restoreDefaultSelection(i)}static restoreDefaultSelection(e){const t=Array.from(e.options);for(const r of t)r.selected=r.defaultSelected;if(!e.multiple&&e.selectedIndex<0){const r=t.find(i=>!i.disabled);r&&(r.selected=!0)}}static clearDeclarativeStateFromDom(e){if(h.isDeclarativeStateBound(e)){const t=e.getTarget();t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")?t.checked=!1:t instanceof HTMLSelectElement?(Array.from(t.options).forEach(r=>{r.selected=!1}),t.selectedIndex=-1):(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&(t.value="")}e.getChildren().forEach(t=>{t instanceof D&&h.clearDeclarativeStateFromDom(t)})}static hasDeclarativeBinding(e,t){if(e.hasAttribute(`${c.prefix}attr-${t}`))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static hasDeclarativeSelectedOption(e){for(const t of Array.from(e.options)){const r=N.get(t);if(r instanceof D&&h.hasDeclarativeBinding(r,"selected"))return!0}return!1}static isFileInput(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="file"}static getValuesEditedAfter(e,t){return h.getPartValues(e,{},t)}static collectEditedPaths(e,t,r="",i=null){const n=new Map;for(const a of h.collectUserEditSequences(e)){const o=new Set;h.walkEditedPaths(h.getValuesEditedAfter(e,a-1),r,o);for(const l of o)n.has(l)||n.set(l,a)}const s=new Set;h.walkExcludedPaths(i??h.getValues(e),r,s);for(const a of s)n.has(a)||n.set(a,t);return n}static collectUserEditSequences(e){const t=new Set;return h.walkUserEditSequences(e,t),[...t].sort((r,i)=>i-r)}static walkUserEditSequences(e,t){const r=e.getUserEditSequence();r>0&&t.add(r);for(const i of e.getChildElementFragments())h.walkUserEditSequences(i,t)}static walkExcludedPaths(e,t,r){if(Array.isArray(e))return;const i=h.asPlainRecord(e);if(i===null)return;const n=h.COLLECTED_EXCLUDED_KEYS.get(i);if(n)for(const s of n)s in i||r.add(t===""?s:`${t}.${s}`);for(const[s,a]of Object.entries(i))h.walkExcludedPaths(a,t===""?s:`${t}.${s}`,r)}static walkEditedPaths(e,t,r){if(Array.isArray(e))return;const i=h.asPlainRecord(e);if(i!==null){for(const[n,s]of Object.entries(i))h.walkEditedPaths(s,t===""?n:`${t}.${n}`,r);return}t!==""&&r.add(t)}static getPartValues(e,t,r=null,i=null){if(e.hasAttribute(`${c.prefix}form-detach`))return t;if(e.getTarget().hasAttribute(`${c.prefix}if-false`)){if(i!==null)for(const u of h.collectDeclaredKeysInFragment(e))i.add(u);return t}const n=h.resolveFieldName(e),s=e.getAttribute(`${c.prefix}form-object`),a=e.getAttribute(`${c.prefix}form-list`),o=e.hasAttribute(`${c.prefix}form-list`),l=r!==null&&e.getUserEditSequence()<=r;if(n){if(r!==null&&h.isGroupedCheckable(e)){const u=h.collectGroupSelection(e,o,r);u.edited&&(t[String(n)]=u.value)}else if(o&&h.isGroupedCheckable(e)){const u=String(n),d=e.getTarget();r===null&&!Array.isArray(t[u])&&(t[u]=[]),!l&&d.checked&&(Array.isArray(t[u])||(t[u]=[]),t[u].push(d.value))}else if(o&&l)Array.isArray(t[String(n)])?t[String(n)].push(null):t[String(n)]=[null];else if(!l)if(o){const u=h.resolveCollectedValue(e),d=h.isFileInput(e)&&Array.isArray(u)?u:[u];Array.isArray(t[String(n)])?t[String(n)].push(...d):t[String(n)]=d}else if(h.isGroupedCheckable(e)){const u=e.getTarget(),d=u instanceof HTMLInputElement?u.checked:!0,p=u instanceof HTMLInputElement?u.value:e.getValue(),g=d?p:null,A=String(n);g===null?A in t||(t[A]=null):t[A]===null||t[A]===void 0?t[A]=g:Array.isArray(t[A])?t[A].push(g):t[A]=[t[A],g]}else t[String(n)]=h.resolveCollectedValue(e);s&&b.warn("Haori",`Element cannot have both ${c.prefix}form-object and name attributes.`);for(const u of e.getChildElementFragments())h.getPartValues(u,t,r,i)}else if(s){const u={},d=i===null?null:new Set;for(const p of e.getChildElementFragments())h.getPartValues(p,u,r,d);d!==null&&h.registerCollectedExcludedKeys(u,d),Object.keys(u).length>0?t[String(s)]=u:i!==null&&(d?.size??0)>0&&i.add(String(s)),a&&b.warn("Haori",`Element cannot have both ${c.prefix}form-list and ${c.prefix}form-object attributes.`)}else if(a){const u=[],d=[];let p=!1;for(const g of e.getChildElementFragments()){const A={},v=i===null?null:new Set;h.getPartValues(g,A,r,v),v!==null&&h.registerCollectedExcludedKeys(A,v),Object.keys(A).length>0?(p=!0,u.push(A),d.push(g.getListKey())):r!==null&&(u.push({}),d.push(g.getListKey()))}if(r===null){const g=e.getAttribute(`${c.prefix}each-key`);h.registerCollectedRowIdentity(u,g==null?null:String(g),d,h.isCollectedListFromEachSource(e)),t[String(a)]=u}else p&&(t[String(a)]=u)}else for(const u of e.getChildElementFragments())h.getPartValues(u,t,r,i);return t}static setValues(e,t,r=!1){return h.setPartValues(e,t,r,!0)}static syncValues(e,t,r=!1,i=null){return h.setPartValues(e,t,r,!1,!1,new Map,i)}static syncRowValues(e,t,r=null){return h.setPartValues(e,t,!1,!1,!0,new Map,r)}static resolveSyncValues(e,t){const r=e.getAttribute(`${c.prefix}form-arg`);if(!r)return t;const i=String(r);return Object.prototype.hasOwnProperty.call(t,i)?h.asPlainRecord(t[i])??{}:h.resolveAncestorArgOwner(e,i)?.value??{}}static resolveAncestorArgOwner(e,t){let r=e.getParent();for(;r;){const i=r.getRawBindingData();if(i&&Object.prototype.hasOwnProperty.call(i,t)){if(r.getListKey()!==null)return null;const n=h.asPlainRecord(i[t]);return n?{owner:r,value:n}:null}r=r.getParent()}return null}static buildConditionScope(e,t=null){const r={...e.getBindingData()},i=t?{source:t,argKey:h.resolveFormArgKey(t)}:h.resolveConditionValueSource(e);if(!i)return r;const n=h.getValues(i.source),s=h.collectDeclaredFieldKeys(i.source);if(i.argKey===null){for(const o of s)r[o]=n[o];return r}const a={...h.asPlainRecord(r[i.argKey])??{}};for(const o of s)a[o]=n[o];return r[i.argKey]=a,r}static resolveConditionValueSource(e){let t=e;for(;t;){const i=t.getParent();if(i&&i.hasAttribute(`${c.prefix}each`)&&i.hasAttribute(`${c.prefix}form-list`)){const n=i.getRawAttribute(`${c.prefix}each-arg`);return{source:t,argKey:typeof n=="string"&&n!==""?n:null}}t=i}const r=h.getFormFragment(e);return r?{source:r,argKey:h.resolveFormArgKey(r)}:null}static resolveFormArgKey(e){const t=e.getAttribute(`${c.prefix}form-arg`);return t?String(t):null}static collectDeclaredFieldKeys(e){return h.collectDeclaredKeysInFragment(e)}static collectDeclaredKeysInFragment(e){const t=new Set,r=e.getTarget(),i=h.resolveFieldName(e);i&&t.add(String(i));const n=`${c.prefix}form-object`,s=`${c.prefix}form-list`,a=r.getAttribute(n)??r.getAttribute(s);if(a)return t.add(a),t;const o=`input[name],select[name],textarea[name],[${c.prefix}form-name],[${n}],[${s}]`;return r.querySelectorAll(o).forEach(l=>{if(!(l instanceof HTMLElement))return;let u=null,d=!1,p=l;for(;p&&p!==r;)p.hasAttribute(`${c.prefix}form-detach`)&&(d=!0),(p.hasAttribute(n)||p.hasAttribute(s))&&(u=p),p=p.parentElement;if(d)return;const g=u??l,A=g.getAttribute(n)||g.getAttribute(s)||g.getAttribute(`${c.prefix}form-name`)||g.getAttribute("name");A&&t.add(A)}),t}static applyCustomValidity(e){const t=`${c.prefix}validity`,r=i=>{i.hasAttribute(t)&&h.applyOneCustomValidity(i,t),i.getChildElementFragments().forEach(r)};r(e)}static applyOneCustomValidity(e,t){const r=e.getTarget();if(!(r instanceof HTMLInputElement)&&!(r instanceof HTMLSelectElement)&&!(r instanceof HTMLTextAreaElement)){b.warn("Haori",`${t} は入力要素にのみ指定できます: ${r.tagName}`);return}const i=e.getRawAttribute(t);if(typeof i!="string"||i.trim()===""){r.setCustomValidity("");return}const n=h.buildConditionScope(e),s=_.evaluateDetailed(h.unwrapConditionExpression(i),n);if(s.unresolvedReference){b.warn("Haori",`${t} の参照が解決できないため無効として扱います: ${i}`),r.setCustomValidity(h.resolveValidityMessage(e));return}r.setCustomValidity(s.value?"":h.resolveValidityMessage(e))}static resolveValidityMessage(e){const t=e.getAttribute(`${c.prefix}validity-message`);return typeof t=="string"&&t.trim()!==""?t:Tt}static unwrapConditionExpression(e){const t=e.trim();return t.startsWith("{{{")&&t.endsWith("}}}")?t.slice(3,-3):t.startsWith("{{")&&t.endsWith("}}")?t.slice(2,-2):t}static warnUnvalidatedCustomValidity(e,t){if(!j.isEnabled()||!e)return;const r=`${c.prefix}validity`;(e.hasAttribute(r)||e.getTarget().querySelector(`[${r}]`)!==null)&&b.warn("Haori",`${r} は指定されていますが検証は行われません(${t})。${c.prefix}{event}-validate を指定するか、${c.prefix}{event}-if を使用してください。`)}static asPlainRecord(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}static registerCollectedRowIdentity(e,t,r,i){h.COLLECTED_ROW_IDENTITY.set(e,{keyArg:t,keys:r,identifiesItems:i})}static registerCollectedExcludedKeys(e,t){t.size>0&&h.COLLECTED_EXCLUDED_KEYS.set(e,t)}static carryCollectedRowIdentity(e,t){const r=h.COLLECTED_ROW_IDENTITY.get(e);r&&h.COLLECTED_ROW_IDENTITY.set(t,r);const i=h.COLLECTED_EXCLUDED_KEYS.get(e);i&&h.COLLECTED_EXCLUDED_KEYS.set(t,i)}static warnPositionalRowFallback(e){!j.isEnabled()||h.warnedPositionalRowFallbacks.has(e)||(h.warnedPositionalRowFallbacks.add(e),b.warn("[Haori]",`${c.prefix}form-list の行を出現順で対応付けます(${e})。配列と画面の行数・並びが一致していない場合、行の値を取り違えます。`))}static mergeCollectedValues(e,t){const r={...e??{}};for(const[n,s]of Object.entries(t))h.UNSAFE_MERGE_KEYS.has(n)||(r[n]=h.overlayCollectedValue(e?.[n],s));const i=h.COLLECTED_EXCLUDED_KEYS.get(t);if(i)for(const n of i)n in t||delete r[n];return r}static overlayCollectedValue(e,t){if(Array.isArray(t)){if(!Array.isArray(e))return t;const n=h.overlayIdentifiedRows(e,t);return n!==null?n:t.map((s,a)=>h.overlayCollectedValue(e[a],s))}const r=h.asPlainRecord(t),i=h.asPlainRecord(e);return r===null||i===null?t:h.mergeCollectedValues(i,r)}static resolveLeadingPath(e){const t=h.LEADING_PATH_PATTERN.exec(e);if(!t)return null;const r=t[2].trim();return r!==""&&!r.startsWith("||")&&!r.startsWith("??")?null:t[1].replace(/\s+/g,"")}static isCollectedListFromEachSource(e){const t=e.getAttribute(`${c.prefix}form-list`);if(t==null||t==="")return!0;const r=e.getRawAttribute(`${c.prefix}each`);if(typeof r!="string"||r.trim()==="")return!0;const i=h.resolveLeadingPath(r);if(i===null)return!0;const n=i.split(".");return n[n.length-1]===String(t)}static createRowKeyIndexes(e,t){const r=new Map;return e.forEach((i,n)=>{const s=B.createListKey(i,t,n),a=r.get(s);a?a.push(n):r.set(s,[n])}),r}static pairRowsWithItems(e,t,r){const i=e.map(s=>s.getListKey());if(i.some(s=>s===null))return null;const n=h.createRowKeyIndexes(t,r);return i.map(s=>{const a=n.get(s);return!a||a.length===0?null:t[a.shift()]})}static overlayIdentifiedRows(e,t){const r=h.COLLECTED_ROW_IDENTITY.get(t);if(r&&!r.identifiesItems)return null;if(!r)return t.some(s=>h.asPlainRecord(s)!==null)&&h.warnPositionalRowFallback("識別情報が引き継がれていません"),null;if(r.keys.length!==t.length)return h.warnPositionalRowFallback("収集後に行の数が変わっています"),null;if(r.keys.some(s=>s===null))return null;const i=h.createRowKeyIndexes(e,r.keyArg),n=[];for(let s=0;s<t.length;s+=1){const a=r.keys[s],o=i.get(a);if(!o||o.length===0)continue;const l=o.shift();n.push(h.overlayCollectedValue(e[l],t[s]))}return n}static syncAncestorArgForms(e,t,r=null){const i=[];for(const{form:n,key:s}of h.collectArgForms(e)){if(n.wasResetAfter(t))continue;const a=h.resolveAncestorArgOwner(n,s);!a||a.owner!==e||i.push(h.pushAncestorArgValue(n,s,a.value,r))}return Promise.all(i).then(()=>{})}static collectArgForms(e){const t=`${c.prefix}form-arg`,r=e.getTarget().querySelectorAll(`form[${t}]`),i=[];return r.forEach(n=>{const s=N.get(n);if(!(s instanceof D))return;const a=s.getAttribute(t);a&&i.push({form:s,key:String(a)})}),i}static pushAncestorArgValue(e,t,r,i=null){const n=e.getTarget(),s=h.createArgValueSignature(r);if(s!==null){if(h.LAST_ANCESTOR_ARG_VALUES.get(n)===s)return Promise.resolve();h.LAST_ANCESTOR_ARG_VALUES.set(n,s)}else h.LAST_ANCESTOR_ARG_VALUES.delete(n);const a=e.getRawBindingData();if(a&&Object.prototype.hasOwnProperty.call(a,t)){const o={...a};return delete o[t],B.setBindingData(n,o,{kind:i?.kind??"supply",sequence:i?.sequence??D.nextSequence()})}return h.syncValues(e,r,!1,i)}static createArgValueSignature(e){try{return JSON.stringify(e)??null}catch{return null}}static restoreInitialValues(e){const t=[];e instanceof HTMLFormElement&&t.push(e),e.querySelectorAll("form").forEach(i=>{t.push(i)});const r=[];for(const i of t){if(h.INITIAL_RESTORED_FORMS.has(i))continue;const n=N.get(i);if(!(n instanceof D))continue;const s=n.getRawBindingData(),a=n.getAttribute(`${c.prefix}form-arg`),o=a?String(a):null,l=o!==null&&!(s&&Object.prototype.hasOwnProperty.call(s,o))?h.resolveAncestorArgOwner(n,o):null;if(!(!s&&!l)){if(h.INITIAL_RESTORED_FORMS.add(i),l){r.push(h.pushAncestorArgValue(n,o,l.value));continue}r.push(h.syncValues(n,h.resolveSyncValues(n,s)))}}return Promise.all(r).then(()=>{})}static collectGroupSelection(e,t,r){const i=[];h.collectGroupMembers(h.resolveCollectionScope(e),String(h.resolveFieldName(e)),i);let n=!1;const s=[];for(const a of i){a.getUserEditSequence()>r&&(n=!0);const o=a.getTarget();o instanceof HTMLInputElement&&o.checked&&s.push(o.value)}return t?{edited:n,value:h.markCompleteSet(s)}:s.length===0?{edited:n,value:null}:{edited:n,value:s.length===1?s[0]:h.markCompleteSet(s)}}static startsCollectionLevel(e){return h.resolveFieldName(e)?!1:!!(e.getAttribute(`${c.prefix}form-object`)||e.getAttribute(`${c.prefix}form-list`))}static resolveCollectionScope(e){let t=e,r=t.getParent();for(;r!==null;){if(h.startsCollectionLevel(r))return r.getAttribute(`${c.prefix}form-object`)?r:t;if(h.isFormScopeRoot(r))return r;t=r,r=r.getParent()}return t}static isFormScopeRoot(e){return e.getTarget()instanceof HTMLFormElement||e.hasAttribute(`${c.prefix}form`)}static collectGroupMembers(e,t,r){h.isGroupedCheckable(e)&&String(h.resolveFieldName(e))===t&&r.push(e);for(const i of e.getChildElementFragments())h.startsCollectionLevel(i)||i.hasAttribute(`${c.prefix}form-detach`)||i.getTarget().hasAttribute(`${c.prefix}if-false`)||h.collectGroupMembers(i,t,r)}static markCompleteSet(e){return h.COMPLETE_SET_VALUES.add(e),e}static isCompleteSetValue(e){return e!==null&&typeof e=="object"&&h.COMPLETE_SET_VALUES.has(e)}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 isMultipleSelect(e){const t=e.getTarget();return t instanceof HTMLSelectElement&&t.multiple}static applyFragmentValue(e,t,r,i=null){return r?e.setValue(t,i):e.syncBindingValue(t,i)}static setPartValues(e,t,r=!1,i=!0,n=!1,s=new Map,a=null){const o=[];if(e.hasAttribute(`${c.prefix}form-detach`)&&!r)return Promise.resolve();const l=h.resolveFieldName(e),u=e.getAttribute(`${c.prefix}form-object`),d=e.getAttribute(`${c.prefix}form-list`),p=e.hasAttribute(`${c.prefix}form-list`);if(l){const g=t[String(l)],A=n&&h.hasResolvedDeclarativeState(e),v=n&&typeof g>"u"&&!h.isDeclarativeStateBound(e);let T=g;if(A?T=void 0:v&&(T=null),h.isFileInput(e))return(T===null||T==="")&&o.push(h.applyFragmentValue(e,null,i,a)),Promise.all(o).then(()=>{});if(p&&Array.isArray(T)&&!h.isGroupedCheckable(e)&&!h.isMultipleSelect(e)){const F=String(l),H=s.get(F)??0;s.set(F,H+1),o.push(h.applyFragmentValue(e,T[H]??null,i,a))}else typeof T>"u"||(Array.isArray(T)&&h.isGroupedCheckable(e)||Array.isArray(T)&&h.isMultipleSelect(e)||typeof T=="string"||typeof T=="number"||typeof T=="boolean"||T===null?o.push(h.applyFragmentValue(e,T,i,a)):o.push(h.applyFragmentValue(e,String(T),i,a)))}else if(u){const g=t[String(u)];if(g&&typeof g=="object"){const A=new Map;for(const v of e.getChildElementFragments())o.push(h.setPartValues(v,g,r,i,n,A,a))}}else if(d){const g=t[String(d)];if(Array.isArray(g)){const A=e.getChildElementFragments(),v=e.getAttribute(`${c.prefix}each-key`),T=h.isCollectedListFromEachSource(e)?h.pairRowsWithItems(A,g,v==null?null:String(v)):null;for(let F=0;F<A.length;F++){const H=A[F],E=T?T[F]:g.length>F?g[F]:null;o.push(h.setPartValues(H,h.asPlainRecord(E)??{},r,i,n,new Map,a))}}}else for(const g of e.getChildElementFragments())o.push(h.setPartValues(g,t,r,i,n,s,a));return Promise.all(o).then(()=>{})}static async reset(e,t=D.nextSequence()){const r=h.collectBindingTargetForms(e);if(r.length>0&&r.every(n=>n.isSupplyStale(t)))return;h.markResetSubtree(e,t),B.clearUserEditMarks(e,t),h.clearValues(e),await Promise.all([h.clearMessages(e),h.clearEachClones(e)]),await W.enqueue(()=>{const n=h.collectEditsAfter(e,t),s=e.getTarget();s instanceof HTMLFormElement?s.reset():(s.querySelectorAll("form").forEach(a=>a.reset()),h.restoreDefaultValues(s)),h.clearDeclarativeStateFromDom(e),h.restoreEdits(n)});const i=r;for(const n of i){const s=h.getInitialBindingData(n);s===null&&n.getRawBindingData()===null||await B.setBindingData(n.getTarget(),s??{},{sequence:t})}h.syncValuesFromDom(e),await B.evaluateAll(e);for(const n of i)h.getInitialBindingData(n)!==null||n.getRawBindingData()!==null||await h.restoreAncestorArgValues(n,{sequence:t,kind:"supply"});for(const n of i){const s=h.getInitialBindingData(n);if(n.getRawBindingData()===null&&s===null)continue;const a=h.getValues(n),o=n.getAttribute(`${c.prefix}form-arg`);let l={...s||{}};if(o){const u=String(o);!Object.prototype.hasOwnProperty.call(s??{},u)&&h.resolveAncestorArgOwner(n,u)!==null||(l[u]=h.mergeCollectedValues(l[u]??null,a))}else l=h.mergeCollectedValues(l,a);await B.setBindingData(n.getTarget(),l,{sequence:t})}}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:B.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())h.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=N.get(n);s instanceof D&&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())}n.setEachInputSignature(null)}},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())h.clearValues(t)}static collectEditsAfter(e,t,r=[]){const i=e.getTarget();(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement)&&e.getUserEditSequence()>t&&(i instanceof HTMLInputElement&&(i.type==="checkbox"||i.type==="radio")?r.push({element:i,checked:i.checked}):i instanceof HTMLSelectElement&&i.multiple?r.push({element:i,selected:Array.from(i.selectedOptions).map(n=>n.value)}):r.push({element:i,value:i.value}));for(const n of e.getChildElementFragments())h.collectEditsAfter(n,t,r);return r}static restoreEdits(e){for(const t of e){const{element:r}=t;if(t.checked!==void 0&&r instanceof HTMLInputElement){r.checked=t.checked;continue}if(t.selected!==void 0&&r instanceof HTMLSelectElement){for(const i of Array.from(r.options))i.selected=t.selected.includes(i.value);continue}t.value!==void 0&&(r.value=t.value)}}static async restoreAncestorArgValues(e,t=null){const r=e.getAttribute(`${c.prefix}form-arg`);if(!r)return;const i=String(r),n=h.resolveAncestorArgOwner(e,i);n&&(h.LAST_ANCESTOR_ARG_VALUES.delete(e.getTarget()),await h.pushAncestorArgValue(e,i,n.value,t))}static markResetSubtree(e,t){e.markResetAt(t),e.markSupplyApplied(t);for(const r of e.getChildElementFragments())h.markResetSubtree(r,t)}static clearMessages(e){return Ye().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return h.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=Ye(),a=s.addMessage,o=u=>typeof a=="function"?a.call(s,u,r,i):s.addErrorMessage(u,r),l=h.findFragmentsByKey(e,t);return l.forEach(u=>{n.push(o(u.getTarget()))}),l.length===0&&n.push(o(e.getTarget())),Promise.all(n).then(()=>{})}static findFragmentsByKey(e,t){return h.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&h.resolveFieldName(e)===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(...h.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),u=Number(l);if(isNaN(u))b.error("Haori",`Invalid index: ${i}`);else{const d=e.getChildElementFragments().filter(p=>p.hasAttribute(`${c.prefix}row`));u<d.length&&r.push(...h.findFragmentByKeyParts(d[u],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(n=>{r.push(...h.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}};h.INITIAL_RESTORED_FORMS=new WeakSet,h.LAST_ANCESTOR_ARG_VALUES=new WeakMap,h.GROUP_SCOPE_IDS=new WeakMap,h.groupScopeSequence=0,h.UNSAFE_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]),h.COLLECTED_ROW_IDENTITY=new WeakMap,h.COMPLETE_SET_VALUES=new WeakSet,h.COLLECTED_EXCLUDED_KEYS=new WeakMap,h.warnedPositionalRowFallbacks=new Set,h.LEADING_PATH_PATTERN=/^\s*([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*)\s*([\s\S]*)$/;let k=h;class O{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){O.dispatch(document,"ready",{version:e})}static importStart(e,t){O.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){O.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){O.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 u=t?.[l],d=r[l];u!==d&&n.push(l)}O.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){O.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){O.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){O.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){O.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){O.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){O.dispatch(e,"show",{visible:!0})}static hide(e){O.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){O.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){O.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){O.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:n?performance.now()-n:void 0})}static pollTimeout(e,t,r){O.dispatch(e,"polltimeout",{count:t,elapsedMs:r})}static pollStop(e,t,r,i){O.dispatch(e,"pollstop",{reason:t,count:r,elapsedMs:i})}}const It={401:"unauthorized-redirect",403:"forbidden-redirect"};function Nt(m,e){return m.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=_.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function Ft(m,e){const t=m.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=N.get(m),i=r instanceof D?r.getBindingData():{},n=Nt(t,i);return n===""?null:n}function kt(m,e,t){const r=m.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,s=`${encodeURIComponent(r)}=${encodeURIComponent(i)}`,a=t.indexOf("#"),o=a>=0?t.slice(a):"",l=a>=0?t.slice(0,a):t,u=l.includes("?")?"&":"?";return`${l}${u}${s}${o}`}function ft(m){const e=It[m];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=Ft(i,t);if(n===null)continue;const s=kt(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 z{static read(e,t){if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);return typeof r=="string"?r:null}static queryAll(e,t,r=document.body){try{return Array.from(r.querySelectorAll(e))}catch(i){return b.error("Haori",`Invalid selector: ${e} (${t})`,i),[]}}static query(e,t,r=document.body){try{return r.querySelector(e)}catch(i){return b.error("Haori",`Invalid selector: ${e} (${t})`,i),null}}}const I=class I{static resolveStorage(e){try{const t=e==="local"?window.localStorage:window.sessionStorage;if(!t)throw new Error("storage is not available");return t}catch(t){return I.WARNED_KINDS.has(e)||(I.WARNED_KINDS.add(e),b.warn("Haori",`${e}Storage が利用できないため ${c.prefix}store を無効にします:`,t)),null}}static isReservedKey(e){return e.startsWith("_")}static isPlainRecord(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}static warnOnce(e,t,r){let i=I.WARNED_ELEMENTS.get(e);i||(i=new Set,I.WARNED_ELEMENTS.set(e,i)),!i.has(t)&&(i.add(t),b.warn("Haori",r))}static isInsideEachRow(e){let t=e;for(;t;){if(t.getListKey()!==null)return!0;t=t.getParent()}return!1}static readDeclaration(e){const t=e.getTarget(),r=e.getRawAttribute(`${c.prefix}store`);if(r===null)return null;const i=r.trim();if(i==="")return I.warnOnce(t,"key",`${c.prefix}store にストレージキーが指定されていません。`),null;if(i.includes("{{"))return I.warnOnce(t,"expression",`${c.prefix}store に式は使用できません(静的な文字列を指定してください): ${i}`),null;const n=e.getRawAttribute(`${c.prefix}store-type`);let s="session";if(n!==null){const d=n.trim();d==="local"||d==="session"?s=d:I.warnOnce(t,"type",`${c.prefix}store-type は session または local を指定してください(session として扱います): ${d}`)}const a=e.getRawAttribute(`${c.prefix}store-arg`),o=a===null||a.trim()===""?null:a.trim(),l=e.getRawAttribute(`${c.prefix}store-params`);let u=null;if(l!==null){const d=l.split("&").map(g=>g.trim()).filter(g=>g!==""),p=d.filter(g=>!I.isReservedKey(g));p.length!==d.length&&I.warnOnce(t,"reserved",`${c.prefix}store-params の予約キー(先頭が _ のキー)は対象外です。`),u=p.length>0?p:null}return u===null&&o===null?(I.warnOnce(t,"target",`${c.prefix}store には ${c.prefix}store-params または ${c.prefix}store-arg のいずれかが必要です。`),null):{key:i,kind:s,params:u,arg:o}}static readRecord(e){const t=I.resolveStorage(e.kind);if(!t)return null;let r;try{r=t.getItem(e.key)}catch(n){return b.warn("Haori",`ストレージの読み取りに失敗しました: ${e.key}`,n),null}if(r===null)return null;let i;try{i=JSON.parse(r)}catch(n){return b.warn("Haori",`保存済みデータが JSON として解釈できません: ${e.key}`,n),null}return I.isPlainRecord(i)?i:(b.warn("Haori",`保存済みデータがオブジェクトではありません: ${e.key}`),null)}static extractFromRecord(e,t){let r=t;if(e.arg!==null){const s=t[e.arg];if(s===void 0)return{};if(!I.isPlainRecord(s))return b.warn("Haori",`保存済みデータの ${e.arg} がオブジェクトではありません: `+e.key),{};r=s}const i=e.params??Object.keys(r),n={};for(const s of i)I.isReservedKey(s)||Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s]);return n}static selectFromData(e,t){const r=e.params??Object.keys(t),i={};for(const n of r){if(I.isReservedKey(n)||!Object.prototype.hasOwnProperty.call(t,n))continue;const s=t[n];s!==void 0&&(i[n]=s)}return i}static stringify(e){try{return JSON.stringify(e)??null}catch{return null}}static createRefs(e){const t=new Map;for(const[r,i]of Object.entries(e))t.set(r,i);return t}static hasSameRefs(e,t){const r=Object.entries(t);if(e.refs.size!==r.length)return!1;for(const[i,n]of r)if(!e.refs.has(i)||e.refs.get(i)!==n)return!1;return!0}static seedSignature(e,t){const r=I.stringify(t);if(r===null){I.SIGNATURES.delete(e);return}I.SIGNATURES.set(e,{json:r,refs:I.createRefs(t)})}static writeRecord(e,t){const r=I.resolveStorage(e.kind);if(!r)return!1;const i=I.readRecord(e)??{};if(e.arg!==null){const n=i[e.arg],s=I.isPlainRecord(n)?{...n}:{};i[e.arg]={...s,...t}}else Object.assign(i,t);try{return r.setItem(e.key,JSON.stringify(i)),!0}catch(n){return b.warn("Haori",`ストレージへの保存に失敗しました: ${e.key}`,n),!1}}static restore(e){const t=I.readDeclaration(e);if(!t)return Promise.resolve();const r=e.getTarget();if(I.isInsideEachRow(e))return I.warnOnce(r,"each-row",`${c.prefix}each の行の内側では ${c.prefix}store を使用できません(行データは親要素側で配列キーを指定してください)。`),Promise.resolve();I.RESTORED_ELEMENTS.add(r);const i=I.readRecord(t),n=i?I.extractFromRecord(t,i):{},s={...e.getRawBindingData()??{},...n};return I.seedSignature(r,I.selectFromData(t,s)),Object.keys(n).length===0?Promise.resolve():B.setBindingData(r,s,{reentrant:!0,kind:"nonSupply",sequence:D.nextSequence()})}static mirror(e){const t=I.readDeclaration(e);if(!t||I.isInsideEachRow(e))return;const r=e.getTarget();if(!I.RESTORED_ELEMENTS.has(r))return;const i=e.getRawBindingData();if(!i)return;const n=I.selectFromData(t,i);if(Object.keys(n).length===0)return;const s=I.SIGNATURES.get(r);if(s&&I.hasSameRefs(s,n))return;const a=I.stringify(n);if(a===null){b.warn("Haori",`保存対象を直列化できないためミラーを行いません: ${t.key}`);return}if(s&&s.json===a){s.refs=I.createRefs(n);return}I.writeRecord(t,n)&&I.SIGNATURES.set(r,{json:a,refs:I.createRefs(n)})}static clear(e,t){const r=I.resolveStorage(t);if(r){try{r.removeItem(e)}catch(i){b.warn("Haori",`ストレージの破棄に失敗しました: ${e}`,i);return}I.reseedDeclaringElements(e,t)}}static reseedDeclaringElements(e,t){document.querySelectorAll(`[${c.prefix}store]`).forEach(i=>{if(!I.RESTORED_ELEMENTS.has(i))return;const n=N.get(i);if(!(n instanceof D))return;const s=I.readDeclaration(n);if(!s||s.key!==e||s.kind!==t)return;const a=n.getRawBindingData();I.seedSignature(i,a?I.selectFromData(s,a):{})})}};I.SIGNATURES=new WeakMap,I.RESTORED_ELEMENTS=new WeakSet,I.WARNED_ELEMENTS=new WeakMap,I.WARNED_KINDS=new Set;let Ee=I;class ht{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 Mt=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],Ct="__haoriHistoryState__",$e="data-haori-click-lock";function Re(){const e=globalThis.window?.Haori;return Mt.every(r=>typeof e?.[r]=="function")?e:ae}const xt=new Set(["GET","HEAD","OPTIONS"]);function Le(m){return xt.has(m.toUpperCase())}function $t(m,e){for(const[t,r]of Object.entries(e))r!==void 0&&(Array.isArray(r)?r.forEach(i=>{m.append(t,fe(i))}):m.append(t,fe(r)))}function fe(m){if(m==null)return"";if(typeof m=="object"||typeof m=="function")try{return JSON.stringify(m)??""}catch{return""}return String(m)}function pt(m,e){const t=new URL(m,window.location.href),r=new URLSearchParams(t.search);return $t(r,e),t.search=r.toString(),t.toString()}function Pt(m){if(m==null)return{payload:{},dropped:!1};if(typeof m=="string"){const e=m.trim();if(e==="")return{payload:{},dropped:!1};if(e.startsWith("{")){try{const t=JSON.parse(e);if(t!==null&&typeof t=="object"&&!Array.isArray(t))return{payload:t,dropped:!1}}catch{}return{payload:{},dropped:!0}}return e.includes("=")?{payload:Xe(new URLSearchParams(e)),dropped:!1}:{payload:{},dropped:!0}}if(m instanceof URLSearchParams)return{payload:Xe(m),dropped:!1};if(typeof FormData<"u"&&m instanceof FormData){const e={};let t=!1;for(const[r,i]of m.entries()){if(typeof i!="string"){t=!0;continue}gt(e,r,i)}return{payload:e,dropped:t}}return{payload:{},dropped:!0}}function Xe(m){const e={};for(const[t,r]of m.entries())gt(e,t,r);return e}function gt(m,e,t){const r=m[e];r===void 0?m[e]=t:Array.isArray(r)?r.push(t):m[e]=[r,t]}function oe(m,e){if(k.isCompleteSetValue(e))return e;if(Array.isArray(e)){const t=Array.isArray(m)?m.slice():[];let r=!1;return e.forEach((i,n)=>{i!=null&&(typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0||(t[n]=oe(t[n],i),r=!0))}),r?t:m}if(e!==null&&typeof e=="object"){const t=m!==null&&typeof m=="object"&&!Array.isArray(m)?{...m}:{};for(const[r,i]of Object.entries(e))t[r]=oe(t[r],i);return t}return e}function Lt(m){const e=m?.body;return e==null?!1:typeof e=="string"?e!=="":!0}function Bt(m,e){const t={...e||{}},r=(t.method||"GET").toUpperCase();if(c.runtime!=="demo"||Le(r))return{url:m,options:t,requestedMethod:r,effectiveMethod:r,normalized:!1};const{payload:i,dropped:n}=Pt(t.body);let s=m;Object.keys(i).length>0&&(s=pt(s,i)),n&&b.warn("Haori",`The ${r} body cannot be converted into a query string and is dropped by the demo runtime normalization. Send the values with ${c.prefix}{event}-data / ${c.prefix}{event}-form, or use the embedded runtime.`),delete t.body,t.method="GET";const a=new Headers(t.headers||void 0);return a.delete("Content-Type"),t.headers=a,{url:s,options:t,requestedMethod:r,effectiveMethod:"GET",normalized:!0,queryString:new URL(s,window.location.href).search||void 0}}function Ot(m){return m==null?null:typeof m=="string"?m:m instanceof URLSearchParams?m.toString():m instanceof FormData?Array.from(m.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(m)}function Ae(m){return m instanceof Blob?!0:Array.isArray(m)?m.some(Ae):m!==null&&typeof m=="object"?Object.values(m).some(Ae):!1}function Ht(m){return Object.values(m).some(e=>e instanceof Blob?!1:Array.isArray(e)?e.some(t=>!(t instanceof Blob)&&Ae(t)):Ae(e))}function Te(m){return Be(k.getValues(m))}function Be(m){const e=r=>{if(r instanceof File)return r.name;if(r instanceof Blob)return"";if(Array.isArray(r)){const i=r.map(e);return k.carryCollectedRowIdentity(r,i),i}if(r!==null&&typeof r=="object"){const i={};for(const[n,s]of Object.entries(r))i[n]=e(s);return k.carryCollectedRowIdentity(r,i),i}return r},t={};for(const[r,i]of Object.entries(m))t[r]=e(i);return k.carryCollectedRowIdentity(m,t),t}function Ut(m,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:m,method:String(e.method||"GET").toUpperCase(),headers:r,body:Ot(e.body||null)})}const y=class y{constructor(e,t=null,r=null){this.reentrantBind=!1,this.suppressEmptyReplaceBind=!1,this.requestUserEditSequence=null,this.twoWayCommitBind=!1,this.operationSequence=r!=null?D.nextOperationSequence():D.nextSequence(),y.isElementFragment(e)?(this.options=y.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 readLateAttribute(e,t,r,i){const n=e.getAttributeEvaluation(i);return t.lateAttributes||(t.lateAttributes=new Map),t.lateAttributes.set(r,{attributeName:i,hasUnresolvedReference:n?.hasUnresolvedReference??!1}),n?.value??null}static unescapeNewlines(e){return typeof e=="string"?e.replace(/\\n/g,`
9
9
  `):e}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(y.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=_.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"?y.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(y.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const l=_.evaluateDetailed(s??a??"",t);return r=r||l.unresolvedReference,y.isJsonStringContext(e,o)?y.stringifyJsonTemplateStringContent(l.value):y.stringifyJsonTemplateValue(l.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return y.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(y.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:B.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const l=y.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:B.parseDataBind(l.value),hasUnresolvedReference:s||l.hasUnresolvedReference}}const o=y.resolveDataParamStringDetailed(r,e.getBindingData());return{value:B.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e},i=t?y.attrName(t,"if"):y.attrName(null,"if",!0);if(e.hasAttribute(i)){const E=e.getRawAttribute(i);typeof E=="string"&&E.trim()!==""?(r.conditionExpression=k.unwrapConditionExpression(E),r.conditionAttributeName=i):b.warn("Haori",`${i} に条件式が指定されていません。`)}if(t){if(e.hasAttribute(y.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(y.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(y.attrName(t,"confirm")).replace(/\\n/g,`
10
10
  `)),e.hasAttribute(y.attrName(t,"data"))&&(r.dataAttrName=y.attrName(t,"data")),e.hasAttribute(y.attrName(t,"form"))){const S=z.read(e,y.attrName(t,"form"));if(S){const C=z.query(S,y.attrName(t,"form"));C!==null?r.formFragment=k.getFormFragment(N.get(C)):b.error("Haori",`Form element not found: ${S} (${y.attrName(t,"form")})`)}else r.formFragment=k.getFormFragment(e)}else(t==="change"||t==="input")&&(r.formFragment=k.getFormFragment(e),r.formFragment===null&&y.isNamedInputFragment(e)&&(r.selfValueFragment=e));if(e.hasAttribute(`${c.prefix}${t}-before-run`)){const S=e.getRawAttribute(`${c.prefix}${t}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
11
11
  "use strict";
@@ -25,5 +25,5 @@ ${r}
25
25
  );`)}catch{try{i=new Function(`"use strict";
26
26
  ${r}
27
27
  `)}catch(n){b.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(i)try{i.call(e)}catch(n){b.error("[Haori]",`each-rendered-run execution error: ${n}`)}}static runEachRenderedChange(e){const t=`${c.prefix}each-rendered-change`,r=e.getTarget();if(!r.hasAttribute(t))return;const i=String(r.getAttribute(t)??"").trim().toLowerCase();let n=!1;if(i==="always"?n=!0:i!==""&&i!=="once"&&(f.EACH_RENDERED_CHANGE_WARNED.has(r)||(f.EACH_RENDERED_CHANGE_WARNED.add(r),b.warn("[Haori]",`Invalid ${t} value: "${i}". Use "once" (default) or "always".`))),f.countEachRenderedRows(e)!==0){if(!n){if(f.EACH_RENDERED_CHANGE_FIRED.has(r))return;f.EACH_RENDERED_CHANGE_FIRED.add(r)}try{r.dispatchEvent(new Event("change",{bubbles:!0}))}catch(s){b.error("[Haori]",`each-rendered-change dispatch error: ${s}`)}}}static countEachRenderedRows(e){let t=0;for(const r of e.getChildElementFragments())r.getTarget().hasAttribute(`${c.prefix}row`)&&(t+=1);return t}static performEachUpdate(e){const t=f.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=f.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let s=!1;if(e.getChildren().forEach(a=>{if(!s&&a instanceof D){if(a.hasAttribute(`${c.prefix}each-before`)||a.hasAttribute(`${c.prefix}each-after`))return;r=a.clone(),f.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 d=N.get(l);d instanceof D&&(r=d.clone(),f.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const u=N.get(l);u instanceof D&&e.getChildren().includes(u)&&(e.removeChild(u),u.setMounted(!1)),l.parentNode&&l.parentNode.removeChild(l)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}return e.getEachInputSignature()===n?f.reevaluateEachRows(e):this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}static reevaluateEachRows(e){if(f.isRowLocalEachTemplate(e))return Promise.resolve();const t=e.getChildElementFragments().filter(r=>!r.hasAttribute(`${c.prefix}each-before`)&&!r.hasAttribute(`${c.prefix}each-after`));return t.length===0?Promise.resolve():Promise.all(t.map(r=>f.evaluateAll(r))).then(()=>{})}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:(b.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`)||f.hasNonEachDynamicElementState(e)||!f.isRowLocalEachTemplate(e))return!1;const r=f.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${c.prefix}each-key`),n=f.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===n}static isRowLocalEachTemplate(e){const t=e.getRowLocalTemplate();if(t!==null)return t;const r=e.getTemplate(),i=e.getAttribute(`${c.prefix}each-arg`);if(r===null||!i)return e.setRowLocalTemplate(!1),!1;const n=new Set([String(i)]),s=e.getAttribute(`${c.prefix}each-index`);s&&n.add(String(s));const a=f.isRowLocalSubtree(r,n);return e.setRowLocalTemplate(a),a}static isRowLocalSubtree(e,t){for(const i of e.getAttributeNames()){const n=e.getRawAttribute(i),s=typeof n=="string"?n:"";if(s.includes("{{")){if(!f.areExpressionsRowLocal(f.extractInterpolations(s),t))return!1;continue}if(!i.startsWith(c.prefix))continue;const a=i.slice(c.prefix.length);if(f.ROW_LOCAL_EXPRESSION_ATTRIBUTES.has(a)){if(!f.areExpressionsRowLocal([s],t))return!1;continue}if(!f.ROW_LOCAL_STATIC_ATTRIBUTES.has(a))return!1}let r=t;if(e.hasAttribute(`${c.prefix}each`)){const i=e.getRawAttribute(`${c.prefix}each-arg`);if(typeof i!="string"||i==="")return!1;const n=new Set(t);n.add(i);const s=e.getRawAttribute(`${c.prefix}each-index`);typeof s=="string"&&s!==""&&n.add(s),r=n}for(const i of e.getChildren())if(i instanceof D){if(!f.isRowLocalSubtree(i,r))return!1}else if(i instanceof ee){const n=i.getRawText();if(n.includes("{{")&&!f.areExpressionsRowLocal(f.extractInterpolations(n),t))return!1}return!0}static areExpressionsRowLocal(e,t){for(const r of e){const i=r.trim();if(i==="")continue;const n=_.getFreeIdentifiers(i);if(n.length===0||n.some(s=>!t.has(s)))return!1}return!0}static extractInterpolations(e){const t=[],r=/\{\{([\s\S]*?)\}\}/g;let i=r.exec(e);for(;i!==null;)t.push(i[1]),i=r.exec(e);return t}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:!f.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof D?t.hasAttribute(`${c.prefix}derive`)||t.hasAttribute(`${c.prefix}derive-name`)||t.hasAttribute(`${c.prefix}fetch`)||t.hasAttribute(`${c.prefix}import`)?!0:f.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return f.recordDerivedSubtreeSignatureComputation(e,t),f.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:f.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!f.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),f.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(f.createDescendantBindingSignature(e,"refresh")),f.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!j.isEnabled()||!e.hasAttribute(`${c.prefix}derive`))return null;const t=f.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:f.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return f.DERIVE_SUBTREE_PROFILES.set(e,r),r}static resolveElementId(e){return e.getAttribute("id")??""}static createDerivedSubtreeHostId(e){const t=[];let r=e;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();const s=f.resolveElementId(i).trim();if(s!==""){n+=`#${s}`,t.unshift(n);break}const a=r.getRawAttribute(`${c.prefix}derive-name`);typeof a=="string"&&a.trim()!==""&&(n+=`[${c.prefix}derive-name="${a.trim()}"]`);const o=r.getParent();if(o){const l=o.getChildren().filter(u=>u instanceof D).findIndex(u=>u===r);n+=`:nth-child(${l+1})`}t.unshift(n),r=o}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=f.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=f.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),b.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 ee&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>f.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof D?!f.markFreshInitializationSkippable(n):n instanceof ee?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 b.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=t.map((E,S)=>f.createListKey(E,n?String(n):null,S)),o=new Set(a),l=new Map;a.forEach(E=>{l.set(E,(l.get(E)??0)+1)}),n&&o.size!==a.length&&f.warnDuplicateEachKey(String(n));const u=[];let d=e.getChildren().filter(E=>E instanceof D).filter(E=>!E.hasAttribute(`${c.prefix}each-before`)&&!E.hasAttribute(`${c.prefix}each-after`));const p=d.map(E=>E.getListKey()),g=new Set;d=d.filter((E,S)=>{const C=String(E.getListKey()),U=l.get(C)??0;if(U===0){g.add(E);const P=E.getListKey();return P!==null&&O.rowRemove(E.getTarget(),P,S),u.push(E.remove()),!1}return l.set(C,U-1),!0});const A=d.map(E=>E.getListKey()),v=new Map;d.forEach(E=>{const S=E.getListKey();if(S===null)return;const C=v.get(S);C?C.push(E):v.set(S,[E])});const T=e.getChildElementFragments().filter(E=>!g.has(E)),F=T.filter(E=>E.hasAttribute(`${c.prefix}each-before`)).length;let H=Promise.resolve();return a.forEach((E,S)=>{const C=t[S],U=S;let P;const Q=v.get(E)?.shift();if(Q){P=Q;const x=F+S;H=H.then(()=>f.updateRowFragment(P,C,i,U,s?String(s):null,E).then(V=>f.repositionEachRow(e,P,T,x).then(X=>{if(X!==null&&O.rowMove(P.getTarget(),E,X-F,S),!!V)return f.clearUserEditMarks(P),f.evaluateAll(P).then(()=>f.applyRowFormValues(e,P,C))})))}else{P=r.clone();const x=F+S;H=H.then(()=>f.updateRowFragment(P,C,i,U,s?String(s):null,E).then(()=>{const V=T[x]??null;return e.insertBefore(P,V).then(()=>{T.splice(x,0,P)}).then(()=>f.initializeFreshEachRow(P)).then(()=>f.applyRowFormValues(e,P,C)).then(()=>{O.rowAdd(P.getTarget(),E,U,C)})}))}}),Promise.all(u).then(()=>H).then(()=>{const E=a.filter(x=>x!==null),S=A.filter(x=>x!==null),C=new Set(S),U=E.filter(x=>!C.has(x)),Q=p.filter(x=>x!==null).filter(x=>!o.has(x));O.eachUpdate(e.getTarget(),U,Q,E)})}static warnDuplicateEachKey(e){!j.isEnabled()||f.WARNED_DUPLICATE_EACH_KEYS.has(e)||(f.WARNED_DUPLICATE_EACH_KEYS.add(e),b.warn("[Haori]",`${c.prefix}each-key="${e}" の値が配列の中で重複しています。行は出現順で対応付けますが、キーによる行の識別はできません。`))}static repositionEachRow(e,t,r,i){const n=r.indexOf(t);if(n===-1||n===i)return Promise.resolve(null);r.splice(n,1);const s=r[i]??null;return r.splice(i,0,t),e.insertBefore(t,s).then(()=>n)}static applyRowFormValues(e,t,r){return!e.hasAttribute(`${c.prefix}form-list`)||!k.isCollectedListFromEachSource(e)||typeof r!="object"||r===null||Array.isArray(r)?Promise.resolve():k.syncRowValues(t,r)}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;if(typeof t=="object"&&t!==null)a=n?{[n]:{...t}}:{...t};else if(n)a={[n]:t};else return b.error("[Haori]",`Primitive value requires '${c.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);r&&(a[r]=i);const o=a,l=f.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()&&f.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(typeof File<"u"&&e instanceof File)return`[File:${e.name}:${e.size}:${e.lastModified}:${e.type}]`;if(typeof Blob<"u"&&e instanceof Blob)return`[Blob:${e.size}:${e.type}]`;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=>f.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)}:${f.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{f.evaluateAll(e)},100)}};f.ATTRIBUTE_ALIAS_SUFFIX="attr-",f.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","store","url-param","derive-name","derive","if","each"],f.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],f.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param","store","validity","validity-message"],f.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,f.ROW_LOCAL_EXPRESSION_ATTRIBUTES=new Set(["each","if","derive"]),f.ROW_LOCAL_STATIC_ATTRIBUTES=new Set(["each-arg","each-key","each-index","each-before","each-after","derive-name","row","form","form-arg","form-list","form-object","form-detach","value-type","store","store-params","store-arg","store-type","enhance","enhance-new"]),f.REACTIVE_FETCH_STATES=new WeakMap,f.REACTIVE_IMPORT_STATES=new WeakMap,f.DERIVE_SUBTREE_PROFILES=new WeakMap,f.EACH_UPDATE_STATES=new WeakMap,f.EACH_RENDERED_CHANGE_FIRED=new WeakSet,f.EACH_RENDERED_CHANGE_WARNED=new WeakSet,f.WARNED_DUPLICATE_EACH_KEYS=new Set,f.ABSENT_PATH=Symbol("absent");let B=f;const me=class me{constructor(e=document){this.customEventHandlers=new Map,this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures=[],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=()=>{if(this.deferred){this.deferredProcedures.push(()=>this.runWindowLoadProcedure());return}this.runWindowLoadProcedure()},this.onPopstate=t=>{const r=t.state;!r||r[me.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=N.get(e);t&&new ie(t,"load").run()}start(){this.deferred=!1,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations()}startDeferred(){this.deferred=!0,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents()}release(){if(!this.deferred)return;this.deferred=!1,this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations();const e=this.deferredProcedures.splice(0);for(const t of e)try{t()}catch(r){b.error("[Haori]","Deferred event handling error:",r)}}addBuiltinListeners(){this.builtinListenersAdded||(this.builtinListenersAdded=!0,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))}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),this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures.length=0;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(me.BUILTIN_EVENT_NAMES.has(e)){b.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){if(this.deferred){this.deferredProcedures.push(()=>this.runCustomEventProcedures(e,t));return}this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==e)return;const n=N.get(i);n instanceof D&&new ie(n,"on",t).run().catch(s=>{b.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){if(t==="input"){const i=`${c.prefix}input-`;if(!r.getAttributeNames().some(s=>s.startsWith(i))){this.recordUserEdit(r);return}}if(r.hasAttribute(`${c.prefix}${t}-prevent`)&&e.preventDefault(),this.deferred){this.deferredProcedures.push(()=>{r.isConnected&&this.runProcedureFor(r,t,e)});return}this.runProcedureFor(r,t,e)}}runProcedureFor(e,t,r){const i=N.get(e);if(!i)return;(t==="change"||t==="input")&&this.syncUserEdit(e,t==="change");const n=()=>{new ie(i,t,r).run().catch(s=>{b.error("[Haori]","Procedure execution error:",s)})};if(t==="click"&&e.hasAttribute(`${c.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}recordUserEdit(e){if(!(!(e instanceof HTMLInputElement)&&!(e instanceof HTMLSelectElement)&&!(e instanceof HTMLTextAreaElement))){if(this.deferred){this.deferredProcedures.push(()=>{e.isConnected&&this.markUserEditOnly(e)});return}this.markUserEditOnly(e)}}markUserEditOnly(e){const t=N.get(e);t instanceof D&&t.markUserEdit()}syncUserEdit(e,t){const r=N.get(e);if(r instanceof D&&(r.syncValue(),t?r.markUserEditOnChange():r.markUserEdit(),e instanceof HTMLInputElement&&e.type==="radio"&&e.name)){const i=document.getElementsByName(e.name);for(const n of Array.from(i)){if(n===e||!(n instanceof HTMLInputElement)||n.type!=="radio"||n.form!==e.form)continue;const s=N.get(n);s instanceof D&&(s.syncValue(),s.markUserEdit())}}}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}};me.HISTORY_STATE_KEY="__haoriHistoryState__",me.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let Oe=me;const q=class q{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)&&(q.isHtmlElement(e)&&q.syncElement(e),e.querySelectorAll("*").forEach(t=>{q.syncElement(t)}))}static syncElement(e){const t=q.registrations.get(e),r=N.get(e);if(!r||!q.shouldObserve(r)){t&&(t.observer.disconnect(),q.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=q.resolveRoot(r),n=q.resolveRootMargin(r),s=q.resolveThreshold(r),a=r.hasAttribute(`${c.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===n&&q.sameThreshold(t.observer.thresholds,s)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),q.registrations.delete(e));const o=new IntersectionObserver(l=>{const u=q.registrations.get(e);u&&l.forEach(d=>{!d.isIntersecting||u.running||q.isDisabled(u.fragment)||(u.running=!0,new ie(u.fragment,"intersect").runWithResult().then(p=>{p&&u.once&&(u.observer.disconnect(),q.registrations.delete(e))}).catch(p=>{b.error("[Haori]","Intersect procedure execution error:",p)}).finally(()=>{const p=q.registrations.get(e);p&&(p.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(e),q.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(q.isHtmlElement(e)){const t=q.registrations.get(e);t&&(t.observer.disconnect(),q.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=q.registrations.get(t);r&&(r.observer.disconnect(),q.registrations.delete(t))})}static disconnectAll(){q.registrations.forEach(e=>{e.observer.disconnect()}),q.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!q.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=z.query(r,t,document);return q.isHtmlElement(i)?i:(b.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}};q.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),q.registrations=new Map;let he=q;const w=class w{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);if(!t&&!w.hasPollAttribute(e))return;const r=N.get(e);if(!(r instanceof D)||!w.shouldObserve(r)){t&&w.teardown(e,t);return}const i=w.buildConfigKey(r);if(t){if(t.configKey===i){t.fragment=r;return}w.teardown(e,t)}w.startPolling(e,r,i)}static cleanupTree(e){if(w.isHtmlElement(e)){const t=w.registrations.get(e);t&&w.teardown(e,t)}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=w.registrations.get(t);r&&w.teardown(t,r)})}static disconnectAll(){w.registrations.forEach(e=>{w.clearTimers(e)}),w.registrations.clear(),w.visibilityListener&&typeof document<"u"&&document.removeEventListener("visibilitychange",w.visibilityListener),w.visibilityListener=null}static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static hasPollAttribute(e){const t=`${c.prefix}poll-`,r=e.attributes;for(let i=0;i<r.length;i+=1)if(r[i].name.startsWith(t))return!0;return!1}static shouldObserve(e){const t=`${c.prefix}poll-`;return e.getAttributeNames().some(r=>r.startsWith(t)?!w.CONFIG_KEYS.has(r.slice(t.length)):!1)}static buildConfigKey(e){const t=`${c.prefix}poll-`;return e.getAttributeNames().filter(r=>r.startsWith(t)).sort().map(r=>`${r}=${e.getRawAttribute(r)??""}`).join(`
28
- `)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:w.resolveInterval(t),timeoutMs:w.resolveTimeout(t),errorLimit:w.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};w.registrations.set(e,i),w.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{w.handleTimeout(e)},i.timeoutMs)),w.injectState(i),w.tick(e)}static async tick(e){const t=w.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await w.stop(e,t,"detached");return}const r=w.isHidden(e)||w.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await w.injectState(t)),r){w.schedule(e,t);return}if(w.isUntilSatisfied(t.fragment)){await w.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new ie(t.fragment,"poll").runWithResult()}catch(n){b.error("[Haori]","Poll procedure execution error:",n)}finally{t.fetching=!1}if(!(w.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await w.stop(e,t,"error");return}if(await w.restoreStateIfCleared(t),i&&w.isUntilSatisfied(t.fragment)){await w.stop(e,t,"until");return}w.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{w.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=w.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&O.pollTimeout(e,t.count,w.elapsed(t)),await w.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,w.clearTimers(t),r==="detached"){w.registrations.delete(e);return}await w.injectState(t),e.isConnected&&O.pollStop(e,r,t.count,w.elapsed(t))}}static teardown(e,t){w.clearTimers(t),w.registrations.delete(e)}static clearTimers(e){e.intervalTimerId!==null&&(clearTimeout(e.intervalTimerId),e.intervalTimerId=null),e.timeoutTimerId!==null&&(clearTimeout(e.timeoutTimerId),e.timeoutTimerId=null)}static elapsed(e){return Math.round(performance.now()-e.startedAt)}static ensureVisibilityListener(){if(w.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(w.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),w.tick(t))})};w.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=w.resolveStateFragments(e);if(t.length===0)return Promise.resolve();const r={running:!e.stopped,paused:e.paused,stopped:e.stopped,timedOut:e.timedOut,stopReason:e.stopReason,count:e.count,elapsedMs:w.elapsed(e)};return Promise.all(t.map(i=>{const n=i.getTarget(),s={...i.getRawBindingData()??{},_poll:r};return B.setBindingData(n,s,{reflectToAttribute:!1,kind:"nonSupply",sequence:D.nextSequence()})})).then(()=>{})}static async restoreStateIfCleared(e){w.resolveStateFragments(e).some(i=>(i.getRawBindingData()??{})._poll===void 0)&&await w.injectState(e)}static resolveStateFragments(e){const t=`${c.prefix}poll-state`,r=e.fragment;if(!r.hasAttribute(t))return[];const i=r.getAttribute(t);if(typeof i!="string"||i.trim()==="")return r.getTarget().isConnected?[r]:[];const n=z.queryAll(i,t,document);if(n.length===0)return b.error("[Haori]",`Poll state element not found: ${i}`),[];const s=[];return n.forEach(a=>{if(!a.isConnected)return;const o=N.get(a);o instanceof D&&s.push(o)}),s}static resolveInterval(e){const t=`${c.prefix}poll-interval`;if(!e.hasAttribute(t))return w.DEFAULT_INTERVAL_MS;const r=w.toNumber(e.getAttribute(t));return r===null?(b.warn("[Haori]",`${t} は数値で指定してください。既定値 ${w.DEFAULT_INTERVAL_MS}ms を使用します。`),w.DEFAULT_INTERVAL_MS):r<w.MIN_INTERVAL_MS?(b.warn("[Haori]",`${t} の下限は ${w.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),w.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${c.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=w.toNumber(e.getAttribute(t));return r===null||r<=0?(b.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${c.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=w.toNumber(e.getAttribute(t));return r===null||r<1?(b.warn("[Haori]",`${t} は 1 以上の数値で指定してください。無制限として扱います。`),null):Math.floor(r)}static toNumber(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim()==="")return null;const t=Number(e.trim());return Number.isFinite(t)?t:null}static isHidden(e){return e.closest(`[${c.prefix}if-false]`)!==null}static isDisabled(e){const t=`${c.prefix}poll-disabled`;return e.hasAttribute(t)?w.isTruthy(e.getAttribute(t)):!1}static isUntilSatisfied(e){const t=`${c.prefix}poll-until`;if(!e.hasAttribute(t))return!1;const r=e.getAttributeEvaluation(t);return r?r.hasUnresolvedReference?(b.warn("[Haori]",`${t} に未解決の参照が含まれています(停止条件は成立扱いにしません):`,e.getRawAttribute(t),e.getTarget()),!1):w.isTruthy(r.value):!1}static isTruthy(e){if(e==null||e===!1)return!1;if(typeof e=="boolean")return e;if(typeof e=="string"){const t=e.trim().toLowerCase();return t!==""&&t!=="false"&&t!=="0"}return!!e}};w.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),w.DEFAULT_INTERVAL_MS=5e3,w.MIN_INTERVAL_MS=100,w.registrations=new Map,w.visibilityListener=null;let pe=w;const mt="0.44.0";function qt(m){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>m()):Promise.resolve().then(m)}const L=class L{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)&&(L.isHtmlElement(e)&&L.syncElement(e),e.querySelectorAll("*").forEach(t=>{L.syncElement(t)}))}static syncElement(e){const t=L.registrations.get(e),r=N.get(e);if(!(r instanceof D)||!L.shouldObserve(r)){t&&(t.observer.disconnect(),L.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=L.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),L.registrations.delete(e)),b.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=L.resolveRoot(r),s=L.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,L.refreshRows(t);return}t&&(t.observer.disconnect(),L.registrations.delete(e));const a=new IntersectionObserver(l=>{const u=L.registrations.get(e);if(!u)return;let d=!1;l.forEach(p=>{const g=p.target;u.observedRows.has(g)&&(p.isIntersecting?u.visibleRows.has(g)||(u.visibleRows.add(g),d=!0):u.visibleRows.delete(g)&&(d=!0))}),d&&L.scheduleCompute(u)},{root:n,rootMargin:s,threshold:L.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};L.registrations.set(e,o),L.refreshRows(o)}static cleanupTree(e){if(L.isHtmlElement(e)){const t=L.registrations.get(e);t&&(t.observer.disconnect(),L.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=L.registrations.get(t);r&&(r.observer.disconnect(),L.registrations.delete(t))})}static disconnectAll(){L.registrations.forEach(e=>{e.observer.disconnect()}),L.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=z.query(r,t,document);return L.isHtmlElement(i)?i:(b.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===""?L.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof D&&!t.hasAttribute(`${c.prefix}each-before`)&&!t.hasAttribute(`${c.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=L.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));L.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,qt(()=>{e.scheduled=!1;const t=e.fragment.getTarget();L.registrations.get(t)===e&&L.computeAndPublish(e)}))}static computeAndPublish(e){const t=L.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,L.publish(e,n))}static publish(e,t){const r=L.resolveBindOwner(e.fragment);if(!r){b.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]);B.setBindingData(i,n,{skipFragments:a,reflectToAttribute:!1,kind:"nonSupply",sequence:D.nextSequence()}).catch(o=>{b.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}};L.THRESHOLD=0,L.DEFAULT_ROOT_MARGIN="0px",L.registrations=new Map;let le=L;const G=class G{static disconnectMutationObservers(){G._mutationObservers.forEach(e=>{e.disconnect()}),G._mutationObservers.length=0}static async init(){if(G._initialized)return;G._initialized=!0,G.disconnectMutationObservers(),D.setPendingMutationFlusher(()=>{G.flushPendingMutations()});const e=new Oe;G._dispatcher=e,e.startDeferred();try{const t=await Promise.allSettled([B.scan(document.head),B.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&b.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&b.error("[Haori]","Failed to build body fragment:",i.reason),await W.wait(),document.body.setAttribute("data-haori-ready",""),G.observe(document.head),G.observe(document.body),he.syncTree(document.body),pe.syncTree(document.body),le.syncTree(document.body)}finally{e.release()}O.ready(mt)}static getDispatcher(){return G._dispatcher}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${c.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(r=>{G.processMutations(r)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),G._mutationObservers.push(t)}static flushPendingMutations(){for(const e of G._mutationObservers){const t=e.takeRecords();if(t.length===0)continue;const r=t.filter(G.isBindAttributeRecord),i=t.filter(n=>!G.isBindAttributeRecord(n));r.length>0&&G.processMutations(r,D.nextSequence()),i.length>0&&Promise.resolve().then(()=>{G.processMutations(i)})}}static isBindAttributeRecord(e){return e.type==="attributes"&&e.attributeName===`${c.prefix}bind`}static processMutations(e,t){for(const r of e)try{if(G.isExternallyManaged(r.target))continue;switch(r.type){case"attributes":{const i=r.target;if(r.attributeName&&i.hasAttribute("data-haori-click-lock")&&(r.attributeName==="disabled"||r.attributeName==="data-haori-click-lock")||r.attributeName&&i.hasAttribute(ye)&&(r.attributeName==="disabled"||r.attributeName===ye)||r.attributeName&&B.isAliasedAttributeReflection(i,r.attributeName))break;B.setAttribute(i,r.attributeName,i.getAttribute(r.attributeName),!0,t),he.syncElement(i),pe.syncElement(i),le.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{he.cleanupTree(i),pe.cleanupTree(i),le.cleanupTree(i),B.removeNode(i)}),Array.from(r.addedNodes).forEach(i=>{i.parentElement instanceof Element&&(B.addNode(i.parentElement,i),he.syncTree(i),pe.syncTree(i),le.syncTree(i))}),r.target instanceof Element&&le.syncElement(r.target);break}case"characterData":{r.target instanceof Text||r.target instanceof Comment?B.changeText(r.target,r.target.textContent):b.warn("[Haori]","Unsupported character data type:",r.target);break}default:b.warn("[Haori]","Unknown mutation type:",r.type);continue}}catch(i){b.error("[Haori]","Error processing mutation:",i)}}};G._initialized=!1,G._mutationObservers=[],G._dispatcher=null;let Ne=G;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Ne.init):Ne.init();const Wt=()=>ae.waitForRenders(),jt=ae.enhancers;exports.Core=B;exports.Enhance=re;exports.Env=c;exports.Form=k;exports.Fragment=N;exports.Haori=ae;exports.Log=b;exports.Queue=W;exports.default=ae;exports.enhancers=jt;exports.version=mt;exports.waitForRenders=Wt;
28
+ `)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:w.resolveInterval(t),timeoutMs:w.resolveTimeout(t),errorLimit:w.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};w.registrations.set(e,i),w.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{w.handleTimeout(e)},i.timeoutMs)),w.injectState(i),w.tick(e)}static async tick(e){const t=w.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await w.stop(e,t,"detached");return}const r=w.isHidden(e)||w.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await w.injectState(t)),r){w.schedule(e,t);return}if(w.isUntilSatisfied(t.fragment)){await w.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new ie(t.fragment,"poll").runWithResult()}catch(n){b.error("[Haori]","Poll procedure execution error:",n)}finally{t.fetching=!1}if(!(w.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await w.stop(e,t,"error");return}if(await w.restoreStateIfCleared(t),i&&w.isUntilSatisfied(t.fragment)){await w.stop(e,t,"until");return}w.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{w.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=w.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&O.pollTimeout(e,t.count,w.elapsed(t)),await w.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,w.clearTimers(t),r==="detached"){w.registrations.delete(e);return}await w.injectState(t),e.isConnected&&O.pollStop(e,r,t.count,w.elapsed(t))}}static teardown(e,t){w.clearTimers(t),w.registrations.delete(e)}static clearTimers(e){e.intervalTimerId!==null&&(clearTimeout(e.intervalTimerId),e.intervalTimerId=null),e.timeoutTimerId!==null&&(clearTimeout(e.timeoutTimerId),e.timeoutTimerId=null)}static elapsed(e){return Math.round(performance.now()-e.startedAt)}static ensureVisibilityListener(){if(w.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(w.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),w.tick(t))})};w.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=w.resolveStateFragments(e);if(t.length===0)return Promise.resolve();const r={running:!e.stopped,paused:e.paused,stopped:e.stopped,timedOut:e.timedOut,stopReason:e.stopReason,count:e.count,elapsedMs:w.elapsed(e)};return Promise.all(t.map(i=>{const n=i.getTarget(),s={...i.getRawBindingData()??{},_poll:r};return B.setBindingData(n,s,{reflectToAttribute:!1,kind:"nonSupply",sequence:D.nextSequence()})})).then(()=>{})}static async restoreStateIfCleared(e){w.resolveStateFragments(e).some(i=>(i.getRawBindingData()??{})._poll===void 0)&&await w.injectState(e)}static resolveStateFragments(e){const t=`${c.prefix}poll-state`,r=e.fragment;if(!r.hasAttribute(t))return[];const i=r.getAttribute(t);if(typeof i!="string"||i.trim()==="")return r.getTarget().isConnected?[r]:[];const n=z.queryAll(i,t,document);if(n.length===0)return b.error("[Haori]",`Poll state element not found: ${i}`),[];const s=[];return n.forEach(a=>{if(!a.isConnected)return;const o=N.get(a);o instanceof D&&s.push(o)}),s}static resolveInterval(e){const t=`${c.prefix}poll-interval`;if(!e.hasAttribute(t))return w.DEFAULT_INTERVAL_MS;const r=w.toNumber(e.getAttribute(t));return r===null?(b.warn("[Haori]",`${t} は数値で指定してください。既定値 ${w.DEFAULT_INTERVAL_MS}ms を使用します。`),w.DEFAULT_INTERVAL_MS):r<w.MIN_INTERVAL_MS?(b.warn("[Haori]",`${t} の下限は ${w.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),w.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${c.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=w.toNumber(e.getAttribute(t));return r===null||r<=0?(b.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${c.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=w.toNumber(e.getAttribute(t));return r===null||r<1?(b.warn("[Haori]",`${t} は 1 以上の数値で指定してください。無制限として扱います。`),null):Math.floor(r)}static toNumber(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim()==="")return null;const t=Number(e.trim());return Number.isFinite(t)?t:null}static isHidden(e){return e.closest(`[${c.prefix}if-false]`)!==null}static isDisabled(e){const t=`${c.prefix}poll-disabled`;return e.hasAttribute(t)?w.isTruthy(e.getAttribute(t)):!1}static isUntilSatisfied(e){const t=`${c.prefix}poll-until`;if(!e.hasAttribute(t))return!1;const r=e.getAttributeEvaluation(t);return r?r.hasUnresolvedReference?(b.warn("[Haori]",`${t} に未解決の参照が含まれています(停止条件は成立扱いにしません):`,e.getRawAttribute(t),e.getTarget()),!1):w.isTruthy(r.value):!1}static isTruthy(e){if(e==null||e===!1)return!1;if(typeof e=="boolean")return e;if(typeof e=="string"){const t=e.trim().toLowerCase();return t!==""&&t!=="false"&&t!=="0"}return!!e}};w.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),w.DEFAULT_INTERVAL_MS=5e3,w.MIN_INTERVAL_MS=100,w.registrations=new Map,w.visibilityListener=null;let pe=w;const mt="0.44.1";function qt(m){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>m()):Promise.resolve().then(m)}const L=class L{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)&&(L.isHtmlElement(e)&&L.syncElement(e),e.querySelectorAll("*").forEach(t=>{L.syncElement(t)}))}static syncElement(e){const t=L.registrations.get(e),r=N.get(e);if(!(r instanceof D)||!L.shouldObserve(r)){t&&(t.observer.disconnect(),L.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=L.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),L.registrations.delete(e)),b.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=L.resolveRoot(r),s=L.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,L.refreshRows(t);return}t&&(t.observer.disconnect(),L.registrations.delete(e));const a=new IntersectionObserver(l=>{const u=L.registrations.get(e);if(!u)return;let d=!1;l.forEach(p=>{const g=p.target;u.observedRows.has(g)&&(p.isIntersecting?u.visibleRows.has(g)||(u.visibleRows.add(g),d=!0):u.visibleRows.delete(g)&&(d=!0))}),d&&L.scheduleCompute(u)},{root:n,rootMargin:s,threshold:L.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};L.registrations.set(e,o),L.refreshRows(o)}static cleanupTree(e){if(L.isHtmlElement(e)){const t=L.registrations.get(e);t&&(t.observer.disconnect(),L.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=L.registrations.get(t);r&&(r.observer.disconnect(),L.registrations.delete(t))})}static disconnectAll(){L.registrations.forEach(e=>{e.observer.disconnect()}),L.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=z.query(r,t,document);return L.isHtmlElement(i)?i:(b.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===""?L.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof D&&!t.hasAttribute(`${c.prefix}each-before`)&&!t.hasAttribute(`${c.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=L.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));L.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,qt(()=>{e.scheduled=!1;const t=e.fragment.getTarget();L.registrations.get(t)===e&&L.computeAndPublish(e)}))}static computeAndPublish(e){const t=L.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,L.publish(e,n))}static publish(e,t){const r=L.resolveBindOwner(e.fragment);if(!r){b.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]);B.setBindingData(i,n,{skipFragments:a,reflectToAttribute:!1,kind:"nonSupply",sequence:D.nextSequence()}).catch(o=>{b.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}};L.THRESHOLD=0,L.DEFAULT_ROOT_MARGIN="0px",L.registrations=new Map;let le=L;const G=class G{static disconnectMutationObservers(){G._mutationObservers.forEach(e=>{e.disconnect()}),G._mutationObservers.length=0}static async init(){if(G._initialized)return;G._initialized=!0,G.disconnectMutationObservers(),D.setPendingMutationFlusher(()=>{G.flushPendingMutations()});const e=new Oe;G._dispatcher=e,e.startDeferred();try{const t=await Promise.allSettled([B.scan(document.head),B.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&b.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&b.error("[Haori]","Failed to build body fragment:",i.reason),await W.wait(),document.body.setAttribute("data-haori-ready",""),G.observe(document.head),G.observe(document.body),he.syncTree(document.body),pe.syncTree(document.body),le.syncTree(document.body)}finally{e.release()}O.ready(mt)}static getDispatcher(){return G._dispatcher}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${c.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(r=>{G.processMutations(r)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),G._mutationObservers.push(t)}static flushPendingMutations(){for(const e of G._mutationObservers){const t=e.takeRecords();if(t.length===0)continue;const r=t.filter(G.isBindAttributeRecord),i=t.filter(n=>!G.isBindAttributeRecord(n));r.length>0&&G.processMutations(r,D.nextSequence()),i.length>0&&Promise.resolve().then(()=>{G.processMutations(i)})}}static isBindAttributeRecord(e){return e.type==="attributes"&&e.attributeName===`${c.prefix}bind`}static processMutations(e,t){for(const r of e)try{if(G.isExternallyManaged(r.target))continue;switch(r.type){case"attributes":{const i=r.target;if(r.attributeName&&i.hasAttribute("data-haori-click-lock")&&(r.attributeName==="disabled"||r.attributeName==="data-haori-click-lock")||r.attributeName&&i.hasAttribute(ye)&&(r.attributeName==="disabled"||r.attributeName===ye)||r.attributeName&&B.isAliasedAttributeReflection(i,r.attributeName))break;B.setAttribute(i,r.attributeName,i.getAttribute(r.attributeName),!0,t),he.syncElement(i),pe.syncElement(i),le.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{he.cleanupTree(i),pe.cleanupTree(i),le.cleanupTree(i),B.removeNode(i)}),Array.from(r.addedNodes).forEach(i=>{i.parentElement instanceof Element&&(B.addNode(i.parentElement,i),he.syncTree(i),pe.syncTree(i),le.syncTree(i))}),r.target instanceof Element&&le.syncElement(r.target);break}case"characterData":{r.target instanceof Text||r.target instanceof Comment?B.changeText(r.target,r.target.textContent):b.warn("[Haori]","Unsupported character data type:",r.target);break}default:b.warn("[Haori]","Unknown mutation type:",r.type);continue}}catch(i){b.error("[Haori]","Error processing mutation:",i)}}};G._initialized=!1,G._mutationObservers=[],G._dispatcher=null;let Ne=G;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Ne.init):Ne.init();const Wt=()=>ae.waitForRenders(),jt=ae.enhancers;exports.Core=B;exports.Enhance=re;exports.Env=c;exports.Form=k;exports.Fragment=N;exports.Haori=ae;exports.Log=b;exports.Queue=W;exports.default=ae;exports.enhancers=jt;exports.version=mt;exports.waitForRenders=Wt;
29
29
  //# sourceMappingURL=haori.cjs.js.map