haori 0.57.0 → 0.57.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.
@@ -1,15 +1,15 @@
1
- var Haori=function(){"use strict";const me=class me{static isEnabled(){return me.devMode}static enable(){me.devMode=!0}static disable(){me.devMode=!1}static set(e){me.devMode=e}};me.devMode=!1;let q=me;const Oe="embedded";function ze(b){return b==="embedded"||b==="demo"}function At(b){return b===null?null:ze(b)?b:Oe}const _=class _{static get strictBind(){return _._strictBind}static setStrictBind(e){_._strictBind=e}static get runtime(){return _._runtime}static setRuntime(e){_._runtime=ze(e)?e:Oe}static detect(){try{const e=document.currentScript||document.querySelector('script[src*="haori"]');if(e instanceof HTMLScriptElement){const r=e.getAttribute("data-prefix")||_._prefix;_._prefix=r.endsWith("-")?r:r+"-";const i=At(e.getAttribute("data-runtime"));i!==null&&(_._runtime=i),_._strictBind=e.hasAttribute(`${_._prefix}strict-bind`)}if(e instanceof HTMLScriptElement&&e.hasAttribute(`${_._prefix}dev`)){const r=(e.getAttribute(`${_._prefix}dev`)??"").trim().toLowerCase();q.set(r!=="false"&&r!=="off"&&r!=="0");return}const t=window.location.hostname;if(t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="::1"||t.endsWith(".local")){q.set(!0);return}q.set(!1)}catch{}}static get prefix(){return _._prefix}};_._prefix="data-",_._runtime=Oe,_._strictBind=!1;let l=_;typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",l.detect):l.detect());class m{static info(e,...t){q.isEnabled()&&console.log&&console.log(e,...t)}static warn(e,...t){q.isEnabled()&&console.warn&&console.warn(e,...t)}static error(e,...t){console.error(e,...t)}}const vt=/^[A-Za-z_$][A-Za-z0-9_$]*(\.[A-Za-z_$][A-Za-z0-9_$]*)*$/,Ge="new:",M=class M{static register(e,t){const r=typeof e=="string"?e.trim():"";if(r===""){m.error("[Haori]","Enhancer name is required.");return}if(!t||typeof t.init!="function"){m.error("[Haori]",`Enhancer "${r}" must have an init function.`);return}M.enhancers.set(r,t),M.warnedUnknownNames.delete(r),typeof document<"u"&&document.body&&M.forEachTarget(document.body,i=>{M.visited.has(i)&&M.applyElement(i)})}static setMutationCapture(e){M.mutationCapture=e}static has(e){return M.enhancers.has(e)}static applySubtree(e){M.forEachTarget(e,t=>{M.visited.add(t),M.applyElement(t)})}static isApplied(e){return(M.instances.get(e)?.size??0)>0}static refreshSubtree(e,t=!0){M.forEachTarget(e,r=>{M.refreshElement(r,t)})}static destroySubtree(e){M.forEachTarget(e,t=>{M.destroyElement(t)})}static forEachTarget(e,t){if(!e||typeof e.querySelectorAll!="function")return;const r=`[${l.prefix}enhance],[${l.prefix}enhance-new]`;typeof e.matches=="function"&&e.matches(r)&&t(e),e.querySelectorAll(r).forEach(i=>{t(i)})}static applyElement(e){if(e.closest(`[${l.prefix}if-false]`))return;const t=M.instances.get(e)??null;M.names(e,`${l.prefix}enhance`).forEach(r=>{if(t?.has(r))return;const i=M.enhancers.get(r);if(!i){M.warnUnknownName(r);return}M.run(`enhance "${r}"`,()=>{const n=i.init(e);M.appliedKeys(e).set(r,n)})}),M.names(e,`${l.prefix}enhance-new`).forEach(r=>{const i=`${Ge}${r}`;if(M.instances.get(e)?.has(i))return;const n=M.resolveGlobal(r);n!==null&&M.run(`enhance-new "${r}"`,()=>{const s=new n(e);M.appliedKeys(e).set(i,s)})})}static refreshElement(e,t){const r=M.instances.get(e);M.names(e,`${l.prefix}enhance`).forEach(i=>{if(!r||!r.has(i))return;const n=M.enhancers.get(i);!n||typeof n.refresh!="function"||M.run(`enhance "${i}" refresh`,()=>{n.refresh(e,r.get(i))})}),t&&M.applyElement(e)}static destroyElement(e){const t=M.instances.get(e);t&&(t.forEach((r,i)=>{if(i.startsWith(Ge))return;const n=M.enhancers.get(i);!n||typeof n.destroy!="function"||M.run(`enhance "${i}" destroy`,()=>{n.destroy(e,r)})}),M.instances.delete(e))}static appliedKeys(e){const t=M.instances.get(e);if(t)return t;const r=new Map;return M.instances.set(e,r),r}static names(e,t){const r=e.getAttribute(t);return r===null?[]:Array.from(new Set(r.split(/\s+/).map(i=>i.trim()).filter(i=>i!=="")))}static resolveGlobal(e){if(!vt.test(e))return m.error("[Haori]",`${l.prefix}enhance-new accepts a dot-separated global reference only: ${e}`),null;let t=globalThis;for(const r of e.split(".")){if(t===null||typeof t!="object"){t=void 0;break}if(t=t[r],t===void 0)break}return typeof t!="function"?(q.isEnabled()&&!M.warnedMissingGlobals.has(e)&&(M.warnedMissingGlobals.add(e),m.warn("[Haori]",`${l.prefix}enhance-new could not resolve the global reference (load the library before Haori runs): ${e}`)),null):t}static warnUnknownName(e){!q.isEnabled()||M.warnedUnknownNames.has(e)||(M.warnedUnknownNames.add(e),m.warn("[Haori]",`Enhancer "${e}" is not registered yet; the declaration is kept pending and applied when it is registered (Haori.enhancers.register('${e}', {init(el) {...}})).`))}static run(e,t){const r=()=>{try{t()}catch(i){m.error("[Haori]",`${e} failed:`,i)}};M.mutationCapture?M.mutationCapture(r):r()}};M.enhancers=new Map,M.instances=new WeakMap,M.warnedUnknownNames=new Set,M.warnedMissingGlobals=new Set,M.visited=new WeakSet,M.mutationCapture=null;let te=M;const Ye="yyyy/MM/dd HH:mm",wt="en-US",Xe=1e4;function ce(b){return String(b).padStart(2,"0")}function Je(b,e,t,r,i,n){return{yyyy:String(b).padStart(4,"0"),yy:ce(b%100),MM:ce(e),M:String(e),dd:ce(t),d:String(t),HH:ce(r),H:String(r),mm:ce(i),ss:ce(n)}}function Ze(b,e){let t;try{t=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(b)}catch{return null}const r={};for(const u of t)u.type!=="literal"&&(r[u.type]=u.value);const i=Number(r.year),n=Number(r.month),s=Number(r.day),a=Number(r.hour),o=Number(r.minute),c=Number(r.second);return!Number.isFinite(i)||!Number.isFinite(n)||!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(o)||!Number.isFinite(c)?null:Je(i,n,s,a,o,c)}function Ne(b,e=Ye,t){if(b==null||b==="")return"";const r=b instanceof Date?b:new Date(b);if(Number.isNaN(r.getTime()))return"";let i;if(typeof t=="string"&&t.trim()!==""){if(i=Ze(r,t.trim()),i===null)return""}else i=Je(r.getFullYear(),r.getMonth()+1,r.getDate(),r.getHours(),r.getMinutes(),r.getSeconds());const n=i;return e.replace(/'([^']*)'|yyyy|yy|MM|dd|HH|mm|ss|M|d|H/g,(s,a)=>a!==void 0?a===""?"'":a:n[s])}const St="yyyy-MM-dd";function Qe(b=Ye,e){return Ne(new Date,b,e)}function _e(b=0,e=St,t){const r=Number.isFinite(b)?Math.trunc(b):0,i=typeof t=="string"&&t.trim()!==""?t.trim():"";let n,s,a;if(i!==""){const c=Ze(new Date,i);if(c===null)return"";n=Number(c.yyyy),s=Number(c.MM),a=Number(c.dd)}else{const c=new Date;n=c.getFullYear(),s=c.getMonth()+1,a=c.getDate()}const o=new Date(Date.UTC(n,s-1,a+r));return Ne(o,e,"UTC")}function et(b,e){if(b==null)return"";let t;if(typeof b=="number")t=b;else{const i=String(b).trim();if(i==="")return"";t=Number(i)}if(!Number.isFinite(t))return"";const r={};if(e!==void 0&&Number.isFinite(e)){const i=Math.max(0,Math.trunc(e));r.minimumFractionDigits=i,r.maximumFractionDigits=i}return new Intl.NumberFormat(wt,r).format(t)}function tt(b,e,t){let r,i,n;if(e===void 0?(r=0,i=b,n=1):(r=b,i=e,n=t===void 0?1:t),!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(n)||n===0)return[];r=Math.trunc(r),i=Math.trunc(i),n=Math.trunc(n);const s=[];if(n>0)for(let a=r;a<i&&s.length<Xe;a+=n)s.push(a);else for(let a=r;a>i&&s.length<Xe;a+=n)s.push(a);return s}function rt(b,e,t={}){const r=Math.trunc(Number(b));if(!Number.isFinite(r)||r<=0)return[];const i=Math.min(Math.max(Math.trunc(Number(e))||0,0),r-1),n=Math.max(0,Math.trunc(t.window??2)),s=Math.max(0,Math.trunc(t.boundary??1)),a=new Set;for(let d=0;d<s&&d<r;d+=1)a.add(d);for(let d=Math.max(0,r-s);d<r;d+=1)a.add(d);for(let d=Math.max(0,i-n);d<=Math.min(r-1,i+n);d+=1)a.add(d);const o=Array.from(a).sort((d,g)=>d-g),c=[];let u=null;for(const d of o){if(u!==null&&d-u>1)if(d-u===2){const g=u+1;c.push({page:g,label:g+1,active:g===i,ellipsis:!1})}else c.push({page:null,label:"…",active:!1,ellipsis:!0});c.push({page:d,label:d+1,active:d===i,ellipsis:!1}),u=d}return c}const Rt=/^(\d{4})-(\d{1,2})$/,Tt=1200;function xe(b,e){const t=Number(b);return Number.isFinite(t)?Math.trunc(t):e}function Me(b,e){if(typeof b!="string")return"";const t=Rt.exec(b.trim());if(!t)return"";const r=Number(t[1]),i=Number(t[2]);if(i<1||i>12)return"";const n=Number.isFinite(e)?Math.trunc(e):0,s=r*12+(i-1)+n,a=Math.floor(s/12),o=s-a*12+1;return`${String(a).padStart(4,"0")}-${ce(o)}`}function Dt(b){if(typeof b=="string"&&b.trim()!=="")return Me(b,0);const e=new Date;return`${String(e.getFullYear()).padStart(4,"0")}-${ce(e.getMonth()+1)}`}function it(b,e){const t=Math.trunc(Number(b));if(!Number.isFinite(t)||t<0)return[];const r=Dt(e);if(r==="")return[];const i=Math.min(t,Tt),n=[];for(let s=0;s<=i;s+=1){const a=Me(r,-s);n.push({targetMonth:a,label:a.replace(/-/g,"/")})}return n}function nt(b,e){const t={start:0,end:0,total:0,empty:!0};if(!b||typeof b!="object")return t;const r=b,i=xe(r.totalElements??r.totalCount,0);if(i<=0)return t;const n=Math.max(0,xe(r.number,0)),s=Math.max(0,xe(r.size,0)),a=n*s,o=Math.min(a+1,i);let c;if(e!==void 0&&Number.isFinite(e))c=Math.max(0,Math.trunc(e));else{const d=xe(r.numberOfElements,NaN);c=Number.isFinite(d)?d:Math.min(s,i-a)}const u=Math.min(a+c,i);return{start:o,end:Math.max(u,o),total:i,empty:!1}}function st(b,e,t){if(!Array.isArray(b)||b.length===0)return null;const r=String(t),i=b.find(n=>n!=null&&String(n[e])===r);return i===void 0?null:i}function at(b,e){if(!Array.isArray(b))return 0;let t=0;for(const r of b){const i=e==null?r:r?.[e];if(i==null||i==="")continue;const n=typeof i=="number"?i:Number(i);Number.isNaN(n)||(t+=n)}return t}function ot(b,e){return e==null||b==null?String(b):String(b[e])}function lt(b,e){if(!Array.isArray(b))return[];const t=new Set,r=[];for(const i of b){const n=ot(i,e);t.has(n)||(t.add(n),r.push(i))}return r}function ct(b,e){if(!Array.isArray(b))return[];const t=new Map,r=[];for(const i of b){const n=ot(i,e),s=t.get(n);if(s===void 0){const a=i==null?i:i[e];t.set(n,r.length),r.push({key:a,items:[i]})}else r[s].items.push(i)}return r}const Ft=Object.freeze({date:Ne,now:Qe,today:_e,number:et,pages:rt,range:tt,monthAdd:Me,monthRange:it,pageSummary:nt,findBy:st,sum:at,distinct:lt,groupBy:ct});class Be{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(e,t=!1){let r,i;const n=new Promise((a,o)=>{r=a,i=o}),s={task:e,timestamp:performance.now(),promise:n,resolve:r,reject:i};return t?this.queue.unshift(s):this.queue.push(s),this.scheduleProcessing(),n}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const e=performance.now();for(;this.queue.length>0;){const t=this.queue.shift();if(!t)return;try{const r=await t.task();t.resolve(r)}catch(r){t.reject(r),m.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){m.error("[Haori]","Error processing queue:",e)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const e=this.queue.map(t=>t.promise);e.length>0&&await Promise.allSettled(e)}async waitForIdle(e=1e3){let t=0,r=0;for(;t<2&&r<e;)this.processing||this.queue.length>0?(await this.wait(),t=0):t+=1,await Be.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const Ke=class Ke{static enqueue(e,t=!1){return this.ASYNC_QUEUE.enqueue(e,t)}static wait(){return this.ASYNC_QUEUE.wait()}static waitForIdle(e=1e3){return this.ASYNC_QUEUE.waitForIdle(e)}};Ke.ASYNC_QUEUE=new Be;let K=Ke;const R=class R{static readStorageSafely(e){try{return e()}catch{return}}static getForbiddenBindingValues(){const e=globalThis,t=[e,e.window,e.document,e.navigator,e.history,R.readStorageSafely(()=>e.localStorage),R.readStorageSafely(()=>e.sessionStorage),e.fetch,e.Function,e.setTimeout,e.setInterval,e.requestAnimationFrame,e.alert,e.confirm,e.prompt];return e.window?.location&&t.push(e.window.location),t.filter(r=>r!=null)}static getForbiddenBindingValueSet(){return new Set(this.getForbiddenBindingValues())}static scheduleForbiddenBindingValueCacheReset(){this.forbiddenBindingValueCacheResetScheduled||(this.forbiddenBindingValueCacheResetScheduled=!0,queueMicrotask(()=>{this.forbiddenBindingValueCache=new WeakMap,this.forbiddenBindingValueCacheResetScheduled=!1}))}static scheduleForbiddenKeyLogReset(){this.loggedForbiddenKeyResetScheduled||(this.loggedForbiddenKeyResetScheduled=!0,queueMicrotask(()=>{this.loggedForbiddenKeySignatures.clear(),this.loggedForbiddenKeyResetScheduled=!1}))}static getFreeIdentifiers(e){return this.extractFreeIdentifiers(e)}static hasCompileFailure(e){return this.compileFailedExpressions.has(e)}static isUsableBindingKey(e){const t=this.usableBindingKeyCache.get(e);if(t!==void 0)return t;let r=this.IDENTIFIER_NAME_PATTERN.test(e);if(r)try{new Function(e,"")}catch{r=!1}return this.usableBindingKeyCache.set(e,r),r}static reportUnusableBindingKeys(e){if(e.length===0||!q.isEnabled())return;const t=e.filter(r=>!this.loggedUnusableBindingKeys.has(r));t.length!==0&&(t.forEach(r=>this.loggedUnusableBindingKeys.add(r)),m.warn("[Haori]",`Binding key(s) that cannot be used as identifiers are excluded from expressions: ${t.join(", ")}. Read them as haori.data['key'], or use ${l.prefix}form-object to collect nested values.`))}static buildAssignments(e){const t=new Set(e);return this.FORBIDDEN_NAMES.filter(r=>!t.has(r)).map(r=>`const ${r} = undefined`).join(`;
1
+ var Haori=function(){"use strict";const me=class me{static isEnabled(){return me.devMode}static enable(){me.devMode=!0}static disable(){me.devMode=!1}static set(e){me.devMode=e}};me.devMode=!1;let q=me;const Oe="embedded";function ze(b){return b==="embedded"||b==="demo"}function Et(b){return b===null?null:ze(b)?b:Oe}const _=class _{static get strictBind(){return _._strictBind}static setStrictBind(e){_._strictBind=e}static get runtime(){return _._runtime}static setRuntime(e){_._runtime=ze(e)?e:Oe}static detect(){try{const e=document.currentScript||document.querySelector('script[src*="haori"]');if(e instanceof HTMLScriptElement){const r=e.getAttribute("data-prefix")||_._prefix;_._prefix=r.endsWith("-")?r:r+"-";const i=Et(e.getAttribute("data-runtime"));i!==null&&(_._runtime=i),_._strictBind=e.hasAttribute(`${_._prefix}strict-bind`)}if(e instanceof HTMLScriptElement&&e.hasAttribute(`${_._prefix}dev`)){const r=(e.getAttribute(`${_._prefix}dev`)??"").trim().toLowerCase();q.set(r!=="false"&&r!=="off"&&r!=="0");return}const t=window.location.hostname;if(t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="::1"||t.endsWith(".local")){q.set(!0);return}q.set(!1)}catch{}}static get prefix(){return _._prefix}};_._prefix="data-",_._runtime=Oe,_._strictBind=!1;let l=_;typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",l.detect):l.detect());class m{static info(e,...t){q.isEnabled()&&console.log&&console.log(e,...t)}static warn(e,...t){q.isEnabled()&&console.warn&&console.warn(e,...t)}static error(e,...t){console.error(e,...t)}}const vt=/^[A-Za-z_$][A-Za-z0-9_$]*(\.[A-Za-z_$][A-Za-z0-9_$]*)*$/,Ge="new:",M=class M{static register(e,t){const r=typeof e=="string"?e.trim():"";if(r===""){m.error("[Haori]","Enhancer name is required.");return}if(!t||typeof t.init!="function"){m.error("[Haori]",`Enhancer "${r}" must have an init function.`);return}M.enhancers.set(r,t),M.warnedUnknownNames.delete(r),typeof document<"u"&&document.body&&M.forEachTarget(document.body,i=>{M.visited.has(i)&&M.applyElement(i)})}static setMutationCapture(e){M.mutationCapture=e}static has(e){return M.enhancers.has(e)}static applySubtree(e){M.forEachTarget(e,t=>{M.visited.add(t),M.applyElement(t)})}static isApplied(e){return(M.instances.get(e)?.size??0)>0}static refreshSubtree(e,t=!0){M.forEachTarget(e,r=>{M.refreshElement(r,t)})}static destroySubtree(e){M.forEachTarget(e,t=>{M.destroyElement(t)})}static forEachTarget(e,t){if(!e||typeof e.querySelectorAll!="function")return;const r=`[${l.prefix}enhance],[${l.prefix}enhance-new]`;typeof e.matches=="function"&&e.matches(r)&&t(e),e.querySelectorAll(r).forEach(i=>{t(i)})}static applyElement(e){if(e.closest(`[${l.prefix}if-false]`))return;const t=M.instances.get(e)??null;M.names(e,`${l.prefix}enhance`).forEach(r=>{if(t?.has(r))return;const i=M.enhancers.get(r);if(!i){M.warnUnknownName(r);return}M.run(`enhance "${r}"`,()=>{const n=i.init(e);M.appliedKeys(e).set(r,n)})}),M.names(e,`${l.prefix}enhance-new`).forEach(r=>{const i=`${Ge}${r}`;if(M.instances.get(e)?.has(i))return;const n=M.resolveGlobal(r);n!==null&&M.run(`enhance-new "${r}"`,()=>{const s=new n(e);M.appliedKeys(e).set(i,s)})})}static refreshElement(e,t){const r=M.instances.get(e);M.names(e,`${l.prefix}enhance`).forEach(i=>{if(!r||!r.has(i))return;const n=M.enhancers.get(i);!n||typeof n.refresh!="function"||M.run(`enhance "${i}" refresh`,()=>{n.refresh(e,r.get(i))})}),t&&M.applyElement(e)}static destroyElement(e){const t=M.instances.get(e);t&&(t.forEach((r,i)=>{if(i.startsWith(Ge))return;const n=M.enhancers.get(i);!n||typeof n.destroy!="function"||M.run(`enhance "${i}" destroy`,()=>{n.destroy(e,r)})}),M.instances.delete(e))}static appliedKeys(e){const t=M.instances.get(e);if(t)return t;const r=new Map;return M.instances.set(e,r),r}static names(e,t){const r=e.getAttribute(t);return r===null?[]:Array.from(new Set(r.split(/\s+/).map(i=>i.trim()).filter(i=>i!=="")))}static resolveGlobal(e){if(!vt.test(e))return m.error("[Haori]",`${l.prefix}enhance-new accepts a dot-separated global reference only: ${e}`),null;let t=globalThis;for(const r of e.split(".")){if(t===null||typeof t!="object"){t=void 0;break}if(t=t[r],t===void 0)break}return typeof t!="function"?(q.isEnabled()&&!M.warnedMissingGlobals.has(e)&&(M.warnedMissingGlobals.add(e),m.warn("[Haori]",`${l.prefix}enhance-new could not resolve the global reference (load the library before Haori runs): ${e}`)),null):t}static warnUnknownName(e){!q.isEnabled()||M.warnedUnknownNames.has(e)||(M.warnedUnknownNames.add(e),m.warn("[Haori]",`Enhancer "${e}" is not registered yet; the declaration is kept pending and applied when it is registered (Haori.enhancers.register('${e}', {init(el) {...}})).`))}static run(e,t){const r=()=>{try{t()}catch(i){m.error("[Haori]",`${e} failed:`,i)}};M.mutationCapture?M.mutationCapture(r):r()}};M.enhancers=new Map,M.instances=new WeakMap,M.warnedUnknownNames=new Set,M.warnedMissingGlobals=new Set,M.visited=new WeakSet,M.mutationCapture=null;let te=M;const Ye="yyyy/MM/dd HH:mm",wt="en-US",Xe=1e4;function ce(b){return String(b).padStart(2,"0")}function Je(b,e,t,r,i,n){return{yyyy:String(b).padStart(4,"0"),yy:ce(b%100),MM:ce(e),M:String(e),dd:ce(t),d:String(t),HH:ce(r),H:String(r),mm:ce(i),ss:ce(n)}}function Ze(b,e){let t;try{t=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(b)}catch{return null}const r={};for(const u of t)u.type!=="literal"&&(r[u.type]=u.value);const i=Number(r.year),n=Number(r.month),s=Number(r.day),a=Number(r.hour),o=Number(r.minute),c=Number(r.second);return!Number.isFinite(i)||!Number.isFinite(n)||!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(o)||!Number.isFinite(c)?null:Je(i,n,s,a,o,c)}function Ne(b,e=Ye,t){if(b==null||b==="")return"";const r=b instanceof Date?b:new Date(b);if(Number.isNaN(r.getTime()))return"";let i;if(typeof t=="string"&&t.trim()!==""){if(i=Ze(r,t.trim()),i===null)return""}else i=Je(r.getFullYear(),r.getMonth()+1,r.getDate(),r.getHours(),r.getMinutes(),r.getSeconds());const n=i;return e.replace(/'([^']*)'|yyyy|yy|MM|dd|HH|mm|ss|M|d|H/g,(s,a)=>a!==void 0?a===""?"'":a:n[s])}const St="yyyy-MM-dd";function Qe(b=Ye,e){return Ne(new Date,b,e)}function _e(b=0,e=St,t){const r=Number.isFinite(b)?Math.trunc(b):0,i=typeof t=="string"&&t.trim()!==""?t.trim():"";let n,s,a;if(i!==""){const c=Ze(new Date,i);if(c===null)return"";n=Number(c.yyyy),s=Number(c.MM),a=Number(c.dd)}else{const c=new Date;n=c.getFullYear(),s=c.getMonth()+1,a=c.getDate()}const o=new Date(Date.UTC(n,s-1,a+r));return Ne(o,e,"UTC")}function et(b,e){if(b==null)return"";let t;if(typeof b=="number")t=b;else{const i=String(b).trim();if(i==="")return"";t=Number(i)}if(!Number.isFinite(t))return"";const r={};if(e!==void 0&&Number.isFinite(e)){const i=Math.max(0,Math.trunc(e));r.minimumFractionDigits=i,r.maximumFractionDigits=i}return new Intl.NumberFormat(wt,r).format(t)}function tt(b,e,t){let r,i,n;if(e===void 0?(r=0,i=b,n=1):(r=b,i=e,n=t===void 0?1:t),!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(n)||n===0)return[];r=Math.trunc(r),i=Math.trunc(i),n=Math.trunc(n);const s=[];if(n>0)for(let a=r;a<i&&s.length<Xe;a+=n)s.push(a);else for(let a=r;a>i&&s.length<Xe;a+=n)s.push(a);return s}function rt(b,e,t={}){const r=Math.trunc(Number(b));if(!Number.isFinite(r)||r<=0)return[];const i=Math.min(Math.max(Math.trunc(Number(e))||0,0),r-1),n=Math.max(0,Math.trunc(t.window??2)),s=Math.max(0,Math.trunc(t.boundary??1)),a=new Set;for(let d=0;d<s&&d<r;d+=1)a.add(d);for(let d=Math.max(0,r-s);d<r;d+=1)a.add(d);for(let d=Math.max(0,i-n);d<=Math.min(r-1,i+n);d+=1)a.add(d);const o=Array.from(a).sort((d,g)=>d-g),c=[];let u=null;for(const d of o){if(u!==null&&d-u>1)if(d-u===2){const g=u+1;c.push({page:g,label:g+1,active:g===i,ellipsis:!1})}else c.push({page:null,label:"…",active:!1,ellipsis:!0});c.push({page:d,label:d+1,active:d===i,ellipsis:!1}),u=d}return c}const Rt=/^(\d{4})-(\d{1,2})$/,Tt=1200;function xe(b,e){const t=Number(b);return Number.isFinite(t)?Math.trunc(t):e}function Me(b,e){if(typeof b!="string")return"";const t=Rt.exec(b.trim());if(!t)return"";const r=Number(t[1]),i=Number(t[2]);if(i<1||i>12)return"";const n=Number.isFinite(e)?Math.trunc(e):0,s=r*12+(i-1)+n,a=Math.floor(s/12),o=s-a*12+1;return`${String(a).padStart(4,"0")}-${ce(o)}`}function Dt(b){if(typeof b=="string"&&b.trim()!=="")return Me(b,0);const e=new Date;return`${String(e.getFullYear()).padStart(4,"0")}-${ce(e.getMonth()+1)}`}function it(b,e){const t=Math.trunc(Number(b));if(!Number.isFinite(t)||t<0)return[];const r=Dt(e);if(r==="")return[];const i=Math.min(t,Tt),n=[];for(let s=0;s<=i;s+=1){const a=Me(r,-s);n.push({targetMonth:a,label:a.replace(/-/g,"/")})}return n}function nt(b,e){const t={start:0,end:0,total:0,empty:!0};if(!b||typeof b!="object")return t;const r=b,i=xe(r.totalElements??r.totalCount,0);if(i<=0)return t;const n=Math.max(0,xe(r.number,0)),s=Math.max(0,xe(r.size,0)),a=n*s,o=Math.min(a+1,i);let c;if(e!==void 0&&Number.isFinite(e))c=Math.max(0,Math.trunc(e));else{const d=xe(r.numberOfElements,NaN);c=Number.isFinite(d)?d:Math.min(s,i-a)}const u=Math.min(a+c,i);return{start:o,end:Math.max(u,o),total:i,empty:!1}}function st(b,e,t){if(!Array.isArray(b)||b.length===0)return null;const r=String(t),i=b.find(n=>n!=null&&String(n[e])===r);return i===void 0?null:i}function at(b,e){if(!Array.isArray(b))return 0;let t=0;for(const r of b){const i=e==null?r:r?.[e];if(i==null||i==="")continue;const n=typeof i=="number"?i:Number(i);Number.isNaN(n)||(t+=n)}return t}function ot(b,e){return e==null||b==null?String(b):String(b[e])}function lt(b,e){if(!Array.isArray(b))return[];const t=new Set,r=[];for(const i of b){const n=ot(i,e);t.has(n)||(t.add(n),r.push(i))}return r}function ct(b,e){if(!Array.isArray(b))return[];const t=new Map,r=[];for(const i of b){const n=ot(i,e),s=t.get(n);if(s===void 0){const a=i==null?i:i[e];t.set(n,r.length),r.push({key:a,items:[i]})}else r[s].items.push(i)}return r}const Ft=Object.freeze({date:Ne,now:Qe,today:_e,number:et,pages:rt,range:tt,monthAdd:Me,monthRange:it,pageSummary:nt,findBy:st,sum:at,distinct:lt,groupBy:ct});class Be{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(e,t=!1){let r,i;const n=new Promise((a,o)=>{r=a,i=o}),s={task:e,timestamp:performance.now(),promise:n,resolve:r,reject:i};return t?this.queue.unshift(s):this.queue.push(s),this.scheduleProcessing(),n}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const e=performance.now();for(;this.queue.length>0;){const t=this.queue.shift();if(!t)return;try{const r=await t.task();t.resolve(r)}catch(r){t.reject(r),m.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){m.error("[Haori]","Error processing queue:",e)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const e=this.queue.map(t=>t.promise);e.length>0&&await Promise.allSettled(e)}async waitForIdle(e=1e3){let t=0,r=0;for(;t<2&&r<e;)this.processing||this.queue.length>0?(await this.wait(),t=0):t+=1,await Be.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const Ke=class Ke{static enqueue(e,t=!1){return this.ASYNC_QUEUE.enqueue(e,t)}static wait(){return this.ASYNC_QUEUE.wait()}static waitForIdle(e=1e3){return this.ASYNC_QUEUE.waitForIdle(e)}};Ke.ASYNC_QUEUE=new Be;let K=Ke;const R=class R{static readStorageSafely(e){try{return e()}catch{return}}static getForbiddenBindingValues(){const e=globalThis,t=[e,e.window,e.document,e.navigator,e.history,R.readStorageSafely(()=>e.localStorage),R.readStorageSafely(()=>e.sessionStorage),e.fetch,e.Function,e.setTimeout,e.setInterval,e.requestAnimationFrame,e.alert,e.confirm,e.prompt];return e.window?.location&&t.push(e.window.location),t.filter(r=>r!=null)}static getForbiddenBindingValueSet(){return new Set(this.getForbiddenBindingValues())}static scheduleForbiddenBindingValueCacheReset(){this.forbiddenBindingValueCacheResetScheduled||(this.forbiddenBindingValueCacheResetScheduled=!0,queueMicrotask(()=>{this.forbiddenBindingValueCache=new WeakMap,this.forbiddenBindingValueCacheResetScheduled=!1}))}static scheduleForbiddenKeyLogReset(){this.loggedForbiddenKeyResetScheduled||(this.loggedForbiddenKeyResetScheduled=!0,queueMicrotask(()=>{this.loggedForbiddenKeySignatures.clear(),this.loggedForbiddenKeyResetScheduled=!1}))}static getFreeIdentifiers(e){return this.extractFreeIdentifiers(e)}static hasCompileFailure(e){return this.compileFailedExpressions.has(e)}static isUsableBindingKey(e){const t=this.usableBindingKeyCache.get(e);if(t!==void 0)return t;let r=this.IDENTIFIER_NAME_PATTERN.test(e);if(r)try{new Function(e,"")}catch{r=!1}return this.usableBindingKeyCache.set(e,r),r}static reportUnusableBindingKeys(e){if(e.length===0||!q.isEnabled())return;const t=e.filter(r=>!this.loggedUnusableBindingKeys.has(r));t.length!==0&&(t.forEach(r=>this.loggedUnusableBindingKeys.add(r)),m.warn("[Haori]",`Binding key(s) that cannot be used as identifiers are excluded from expressions: ${t.join(", ")}. Read them as haori.data['key'], or use ${l.prefix}form-object to collect nested values.`))}static buildAssignments(e){const t=new Set(e);return this.FORBIDDEN_NAMES.filter(r=>!t.has(r)).map(r=>`const ${r} = undefined`).join(`;
2
2
  `)}static detectForbiddenIdentifiers(e){const t=this.FORBIDDEN_IDENTIFIER_CACHE.get(e);if(t!==void 0)return t;const r=this.FORBIDDEN_NAME_PATTERNS.filter(i=>i.pattern.test(e)).map(i=>i.name);return this.FORBIDDEN_IDENTIFIER_CACHE.set(e,r),r}static extractFreeIdentifiers(e){const t=this.FREE_IDENTIFIER_CACHE.get(e);if(t!==void 0)return t;const r=this.tokenizeExpression(e),i=[];if(r!==null){let n=null;for(const s of r){const a=n?.value==="."||n?.value==="?.";s.type==="identifier"&&!a&&!this.NON_SHADOWABLE_IDENTIFIERS.has(s.value)&&!this.DISALLOWED_KEYWORDS.has(s.value)&&!this.STRICT_FORBIDDEN_NAMES.includes(s.value)&&/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(s.value)&&!i.includes(s.value)&&i.push(s.value),n=s}}return this.FREE_IDENTIFIER_CACHE.set(e,i),i}static extractBoundIdentifiers(e){const t=this.BOUND_IDENTIFIER_CACHE.get(e);if(t!==void 0)return t;const r=new Set,i=this.tokenizeExpression(e);if(i!==null){const n=new Set(["(",",","{","["]);for(let s=0;s<i.length;s+=1){if(i[s].value!=="=>")continue;const a=i[s-1];if(a===void 0)continue;if(a.type==="identifier"){r.add(a.value);continue}if(a.value!==")")continue;let o=0,c=0;for(let u=s-1;u>=0;u-=1){const d=i[u].value;if(d===")"||d==="]"||d==="}"){o+=1,d===")"&&(c+=1);continue}if(d==="("||d==="["||d==="{"){if(o-=1,d==="("&&(c-=1),o===0)break;continue}c===1&&i[u].type==="identifier"&&n.has(i[u-1]?.value??"")&&r.add(i[u].value)}}}return this.BOUND_IDENTIFIER_CACHE.set(e,r),r}static buildShadowDeclarations(e){return e.length===0?"":`
3
- let ${e.join(", ")};`}static warnBlockedIdentifiers(e){if(this.loggedBlockedIdentifierExpressions.has(e))return;const t=this.detectForbiddenIdentifiers(e);t.length!==0&&(this.loggedBlockedIdentifierExpressions.add(e),m.warn("[Haori]","Expression references blocked identifier(s): "+t.join(", ")+". These are blocked in expressions and evaluate to undefined (often the cause of an empty result). Use spread {...a, ...b} instead of Object.assign.",e))}static startsCall(e){return e===null?!1:e.type==="identifier"?!this.NON_SHADOWABLE_IDENTIFIERS.has(e.value):e.value===")"||e.value==="]"}static toOptionalChainExpression(e){const t=this.OPTIONAL_CHAIN_CACHE.get(e);if(t!==void 0)return t;const r=this.tokenizeExpression(e);let i=e;if(r!==null){const n=[];let s=null;for(const a of r)a.type==="operator"&&s?.value!=="?."&&(a.value==="."?n.push({start:a.position,end:a.position+1,text:"?."}):(a.value==="["&&this.startsMemberAccess(s)||a.value==="("&&this.startsCall(s))&&n.push({start:a.position,end:a.position,text:"?."})),s=a;for(let a=n.length-1;a>=0;a-=1){const o=n[a];i=i.slice(0,o.start)+o.text+i.slice(o.end)}}return this.OPTIONAL_CHAIN_CACHE.set(e,i),i}static toGuardedMemberExpression(e){const t=this.GUARDED_MEMBER_CACHE.get(e);if(t!==void 0)return t;const r=this.tokenizeExpression(e);let i=e;if(r!==null){const n=[],s=[];let a=null;for(const o of r){if(o.value==="["){const c=this.startsMemberAccess(a);s.push(c),c&&n.push({start:o.position+1,end:o.position+1,text:R.MEMBER_KEY_GUARD_OPEN})}else o.value==="]"&&s.pop()===!0&&n.push({start:o.position,end:o.position,text:")"});a=o}for(let o=n.length-1;o>=0;o-=1){const c=n[o];i=i.slice(0,c.start)+c.text+i.slice(c.end)}}return this.GUARDED_MEMBER_CACHE.set(e,i),i}static extractUninitializedIdentifiers(e,t){const r=String(e.message||""),i=t.filter(n=>["'",'"',"`"].some(s=>r.includes(`${s}${n}${s}`)));return i.length>0?i:t}static recordUnresolvedIdentifiers(e,t){if(e.length!==0){if(l.strictBind){m.error("[Haori]","Expression references key(s) that are not in the binding data: "+e.join(", ")+". The result is treated as an unresolved reference.",t);return}q.isEnabled()&&(e.forEach(r=>{this.pendingUnresolvedIdentifiers.add(r)}),this.scheduleUnresolvedIdentifierReport())}}static scheduleUnresolvedIdentifierReport(){this.unresolvedReportScheduled||(this.unresolvedReportScheduled=!0,K.waitForIdle().then(()=>{this.unresolvedReportScheduled=!1,this.reportUnresolvedIdentifiers()}))}static reportUnresolvedIdentifiers(){if(this.pendingUnresolvedIdentifiers.size===0)return;const e=Array.from(this.pendingUnresolvedIdentifiers);this.pendingUnresolvedIdentifiers.clear(),m.warn("[Haori]","Expression key(s) were never provided by any binding: "+e.join(", ")+". They are treated as unresolved references (rendered as empty). Check for typos if this is unexpected.")}static recordSuppliedIdentifiers(e){for(const t of Object.keys(e))this.suppliedIdentifiers.add(t)}static recordRowScopeIdentifiers(e){if(q.isEnabled())for(const t of e)typeof t=="string"&&t!==""&&this.rowScopeIdentifiers.add(t)}static recordScopeMissingIdentifiers(e,t){if(e.length===0){this.pendingScopeMissingIdentifiers.delete(t);return}this.pendingScopeMissingIdentifiers.set(t,new Set(e)),!this.scopeMissingReportScheduled&&(this.scopeMissingReportScheduled=!0,K.waitForIdle().then(()=>{this.scopeMissingReportScheduled=!1,this.reportScopeMissingIdentifiers()}))}static reportScopeMissingIdentifiers(){if(this.pendingScopeMissingIdentifiers.size===0)return;const e=Array.from(this.pendingScopeMissingIdentifiers.entries());this.pendingScopeMissingIdentifiers.clear();for(const[t,r]of e){const i=[];for(const n of r){if(!this.suppliedIdentifiers.has(n)||this.rowScopeIdentifiers.has(n))continue;const s=`${n}
4
- ${t}`;this.loggedScopeMissingIdentifiers.has(s)||(this.loggedScopeMissingIdentifiers.add(s),i.push(n))}i.length!==0&&m.warn("[Haori]",`Expression key(s) are missing from this scope but are provided in another scope: ${i.join(", ")}. A binding is visible only to the target element itself and its descendants, so bind the response to this element or one of its ancestors (data-fetch-bind / data-{event}-bind):`,t)}}static evaluateAsCondition(e,t,r){const i={...t};r.forEach(s=>{i[s]=void 0});const n=this.prepareEvaluator(e,i);if(!(n.compileFailed||n.evaluator===null))try{const s=this.wrapBoundValues(i),a=n.bindKeys.map(c=>s[c]),o=this.withBlockedPropertyAccess(()=>n.evaluator(...a));return typeof o=="boolean"?o:void 0}catch{return}}static pruneResolvedIdentifiers(e){this.pendingUnresolvedIdentifiers.size!==0&&this.pendingUnresolvedIdentifiers.forEach(t=>{t in e&&this.pendingUnresolvedIdentifiers.delete(t)})}static evaluate(e,t={}){return this.evaluateDetailed(e,t).value}static evaluateDetailed(e,t={}){if(this.scheduleForbiddenBindingValueCacheReset(),e.trim()==="")return m.warn("[Haori]",e,"Expression is empty"),{value:null,unresolvedReference:!1};if(this.containsDangerousPatterns(e)){const d=this.detectDisallowedKeywords(e);if(d.length>0){const g=d.some(y=>y==="function"||y==="return")?" Statement keywords are not allowed in expressions; use an arrow function such as `x => ({key: value})` instead of `function(x){ return {key: value}; }`.":" These are statement keywords and cannot be used in expressions.";m.warn("[Haori]",e,"Expression uses disallowed keyword(s): "+d.join(", ")+"."+g)}else m.warn("[Haori]",e,"Expression contains dangerous patterns");return{value:null,unresolvedReference:!1}}const r=this.collectForbiddenKeys(t);if(r.length>0){const d=r.join(",");this.loggedForbiddenKeySignatures.has(d)||(this.loggedForbiddenKeySignatures.add(d),this.scheduleForbiddenKeyLogReset(),m.error("[Haori]","Binding keys are reserved and ignored: "+r.join(", ")+". These collide with blocked global/prototype names and cannot be used as top-level binding keys; the remaining keys are still evaluated."))}const i=this.getForbiddenBindingValueSet();if(this.containsForbiddenBindingValues(t,new WeakSet,i))return m.warn("[Haori]",t,"Binded values contain forbidden values"),{value:null,unresolvedReference:!1};const n=e.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g,""),s=this.BUILTIN_REFERENCE_PATTERN.test(n);s&&this.BUILTIN_NAMESPACE in t&&m.warn("[Haori]",`Binding key "${this.BUILTIN_NAMESPACE}" is reserved for built-in helpers; the bound value is ignored in expressions.`);const a={};for(const d of Object.keys(t))this.FORBIDDEN_BINDING_NAMES.has(d)||(a[d]=t[d]);s&&(this.BUILTIN_DATA_REFERENCE_PATTERN.test(n)?a[this.BUILTIN_NAMESPACE]={...this.BUILTIN_HELPERS,[this.BUILTIN_DATA_PROPERTY]:{...a}}:a[this.BUILTIN_NAMESPACE]=this.BUILTIN_HELPERS),this.pruneResolvedIdentifiers(a),q.isEnabled()&&this.recordSuppliedIdentifiers(a);const o=this.canAttemptMissingIdentifierRecovery(e),c=this.extractFreeIdentifiers(e).filter(d=>!(d in a)&&!this.FORBIDDEN_NAMES.includes(d)&&!this.ALLOWED_GLOBAL_IDENTIFIERS.has(d));if(q.isEnabled()){const d=this.extractBoundIdentifiers(e);this.recordScopeMissingIdentifiers(d.size===0?c:c.filter(g=>!d.has(g)),e)}o&&c.forEach(d=>{a[d]=void 0});const u=o?[]:c;for(let d=0;d<=this.MAX_IDENTIFIER_RECOVERY_COUNT;d+=1){const g=this.prepareEvaluator(e,a,u);if(g.compileFailed||g.evaluator===null)return{value:null,unresolvedReference:!1};try{const y=[],E=this.wrapBoundValues(a);g.bindKeys.forEach(I=>{y.push(E[I])});const A=this.withBlockedPropertyAccess(()=>g.evaluator(...y));return A===void 0&&this.warnBlockedIdentifiers(e),{value:A,unresolvedReference:A===void 0}}catch(y){if(o&&y instanceof ReferenceError){const E=this.extractMissingIdentifier(y);if(E!==null&&this.canRecoverMissingIdentifier(E,a)){a[E]=void 0;continue}}if(this.warnBlockedIdentifiers(e),y instanceof ReferenceError&&u.length>0){const E=this.evaluateAsCondition(e,a,u);return E!==void 0?{value:E,unresolvedReference:!1}:(this.recordUnresolvedIdentifiers(this.extractUninitializedIdentifiers(y,u),e),{value:void 0,unresolvedReference:!0})}return m.error("[Haori]","Expression evaluation error:",e,y),y instanceof ReferenceError?{value:void 0,unresolvedReference:!0}:{value:null,unresolvedReference:!1}}}return m.error("[Haori]","Failed to recover missing identifiers:",e,a),{value:void 0,unresolvedReference:!0}}static prepareEvaluator(e,t,r=[]){const i=Object.keys(t).filter(A=>!this.FORBIDDEN_BINDING_NAMES.has(A)),n=[],s=[];i.forEach(A=>{this.isUsableBindingKey(A)?n.push(A):s.push(A)}),n.sort(),this.reportUnusableBindingKeys(s);const a=new Set(n),o=r.filter(A=>!a.has(A)),c=`${e}:${n.join(",")}:${o.join(",")}`;let u=this.EXPRESSION_CACHE.get(c)||null;if(u!==null)return this.compileFailedExpressions.delete(e),{bindKeys:n,evaluator:u,compileFailed:!1};const d=this.buildAssignments(n),g=this.buildShadowDeclarations(o),y=this.toGuardedMemberExpression(this.toOptionalChainExpression(e)),E=d?`"use strict";
3
+ let ${e.join(", ")};`}static warnBlockedIdentifiers(e){if(this.loggedBlockedIdentifierExpressions.has(e))return;const t=this.detectForbiddenIdentifiers(e);t.length!==0&&(this.loggedBlockedIdentifierExpressions.add(e),m.warn("[Haori]","Expression references blocked identifier(s): "+t.join(", ")+". These are blocked in expressions and evaluate to undefined (often the cause of an empty result). Use spread {...a, ...b} instead of Object.assign.",e))}static startsCall(e){return e===null?!1:e.type==="identifier"?!this.NON_SHADOWABLE_IDENTIFIERS.has(e.value):e.value===")"||e.value==="]"}static toOptionalChainExpression(e){const t=this.OPTIONAL_CHAIN_CACHE.get(e);if(t!==void 0)return t;const r=this.tokenizeExpression(e);let i=e;if(r!==null){const n=[];let s=null;for(const a of r)a.type==="operator"&&s?.value!=="?."&&(a.value==="."?n.push({start:a.position,end:a.position+1,text:"?."}):(a.value==="["&&this.startsMemberAccess(s)||a.value==="("&&this.startsCall(s))&&n.push({start:a.position,end:a.position,text:"?."})),s=a;for(let a=n.length-1;a>=0;a-=1){const o=n[a];i=i.slice(0,o.start)+o.text+i.slice(o.end)}}return this.OPTIONAL_CHAIN_CACHE.set(e,i),i}static toGuardedMemberExpression(e){const t=this.GUARDED_MEMBER_CACHE.get(e);if(t!==void 0)return t;const r=this.tokenizeExpression(e);let i=e;if(r!==null){const n=[],s=[];let a=null;for(const o of r){if(o.value==="["){const c=this.startsMemberAccess(a);s.push(c),c&&n.push({start:o.position+1,end:o.position+1,text:R.MEMBER_KEY_GUARD_OPEN})}else o.value==="]"&&s.pop()===!0&&n.push({start:o.position,end:o.position,text:")"});a=o}for(let o=n.length-1;o>=0;o-=1){const c=n[o];i=i.slice(0,c.start)+c.text+i.slice(c.end)}}return this.GUARDED_MEMBER_CACHE.set(e,i),i}static extractUninitializedIdentifiers(e,t){const r=String(e.message||""),i=t.filter(n=>["'",'"',"`"].some(s=>r.includes(`${s}${n}${s}`)));return i.length>0?i:t}static recordUnresolvedIdentifiers(e,t){if(!(e.length===0||this.evaluatingForDiagnosis)){if(l.strictBind){m.error("[Haori]","Expression references key(s) that are not in the binding data: "+e.join(", ")+". The result is treated as an unresolved reference.",t);return}q.isEnabled()&&(e.forEach(r=>{this.pendingUnresolvedIdentifiers.add(r)}),this.scheduleUnresolvedIdentifierReport())}}static scheduleUnresolvedIdentifierReport(){this.unresolvedReportScheduled||(this.unresolvedReportScheduled=!0,K.waitForIdle().then(()=>{this.unresolvedReportScheduled=!1,this.reportUnresolvedIdentifiers()}))}static reportUnresolvedIdentifiers(){if(this.pendingUnresolvedIdentifiers.size===0)return;const e=Array.from(this.pendingUnresolvedIdentifiers);this.pendingUnresolvedIdentifiers.clear(),m.warn("[Haori]","Expression key(s) were never provided by any binding: "+e.join(", ")+". They are treated as unresolved references (rendered as empty). Check for typos if this is unexpected.")}static recordSuppliedIdentifiers(e){for(const t of Object.keys(e))this.suppliedIdentifiers.add(t)}static recordRowScopeIdentifiers(e){if(q.isEnabled())for(const t of e)typeof t=="string"&&t!==""&&this.rowScopeIdentifiers.add(t)}static recordScopeMissingIdentifiers(e,t){if(!this.evaluatingForDiagnosis){if(e.length===0){this.pendingScopeMissingIdentifiers.delete(t);return}this.pendingScopeMissingIdentifiers.set(t,new Set(e)),!this.scopeMissingReportScheduled&&(this.scopeMissingReportScheduled=!0,K.waitForIdle().then(()=>{this.scopeMissingReportScheduled=!1,this.reportScopeMissingIdentifiers()}))}}static reportScopeMissingIdentifiers(){if(this.pendingScopeMissingIdentifiers.size===0)return;const e=Array.from(this.pendingScopeMissingIdentifiers.entries());this.pendingScopeMissingIdentifiers.clear();for(const[t,r]of e){const i=[];for(const n of r){if(!this.suppliedIdentifiers.has(n)||this.rowScopeIdentifiers.has(n))continue;const s=`${n}
4
+ ${t}`;this.loggedScopeMissingIdentifiers.has(s)||(this.loggedScopeMissingIdentifiers.add(s),i.push(n))}i.length!==0&&m.warn("[Haori]",`Expression key(s) are missing from this scope but are provided in another scope: ${i.join(", ")}. A binding is visible only to the target element itself and its descendants, so bind the response to this element or one of its ancestors (data-fetch-bind / data-{event}-bind):`,t)}}static evaluateAsCondition(e,t,r){const i={...t};r.forEach(s=>{i[s]=void 0});const n=this.prepareEvaluator(e,i);if(!(n.compileFailed||n.evaluator===null))try{const s=this.wrapBoundValues(i),a=n.bindKeys.map(c=>s[c]),o=this.withBlockedPropertyAccess(()=>n.evaluator(...a));return typeof o=="boolean"?o:void 0}catch{return}}static pruneResolvedIdentifiers(e){this.pendingUnresolvedIdentifiers.size!==0&&this.pendingUnresolvedIdentifiers.forEach(t=>{t in e&&this.pendingUnresolvedIdentifiers.delete(t)})}static evaluate(e,t={}){return this.evaluateDetailed(e,t).value}static evaluateDetailed(e,t={}){if(this.scheduleForbiddenBindingValueCacheReset(),e.trim()==="")return m.warn("[Haori]",e,"Expression is empty"),{value:null,unresolvedReference:!1};if(this.containsDangerousPatterns(e)){const d=this.detectDisallowedKeywords(e);if(d.length>0){const g=d.some(y=>y==="function"||y==="return")?" Statement keywords are not allowed in expressions; use an arrow function such as `x => ({key: value})` instead of `function(x){ return {key: value}; }`.":" These are statement keywords and cannot be used in expressions.";m.warn("[Haori]",e,"Expression uses disallowed keyword(s): "+d.join(", ")+"."+g)}else m.warn("[Haori]",e,"Expression contains dangerous patterns");return{value:null,unresolvedReference:!1}}const r=this.collectForbiddenKeys(t);if(r.length>0){const d=r.join(",");this.loggedForbiddenKeySignatures.has(d)||(this.loggedForbiddenKeySignatures.add(d),this.scheduleForbiddenKeyLogReset(),m.error("[Haori]","Binding keys are reserved and ignored: "+r.join(", ")+". These collide with blocked global/prototype names and cannot be used as top-level binding keys; the remaining keys are still evaluated."))}const i=this.getForbiddenBindingValueSet();if(this.containsForbiddenBindingValues(t,new WeakSet,i))return m.warn("[Haori]",t,"Binded values contain forbidden values"),{value:null,unresolvedReference:!1};const n=e.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g,""),s=this.BUILTIN_REFERENCE_PATTERN.test(n);s&&this.BUILTIN_NAMESPACE in t&&m.warn("[Haori]",`Binding key "${this.BUILTIN_NAMESPACE}" is reserved for built-in helpers; the bound value is ignored in expressions.`);const a={};for(const d of Object.keys(t))this.FORBIDDEN_BINDING_NAMES.has(d)||(a[d]=t[d]);s&&(this.BUILTIN_DATA_REFERENCE_PATTERN.test(n)?a[this.BUILTIN_NAMESPACE]={...this.BUILTIN_HELPERS,[this.BUILTIN_DATA_PROPERTY]:{...a}}:a[this.BUILTIN_NAMESPACE]=this.BUILTIN_HELPERS),this.pruneResolvedIdentifiers(a),q.isEnabled()&&this.recordSuppliedIdentifiers(a);const o=this.canAttemptMissingIdentifierRecovery(e),c=this.extractFreeIdentifiers(e).filter(d=>!(d in a)&&!this.FORBIDDEN_NAMES.includes(d)&&!this.ALLOWED_GLOBAL_IDENTIFIERS.has(d));if(q.isEnabled()){const d=this.extractBoundIdentifiers(e);this.recordScopeMissingIdentifiers(d.size===0?c:c.filter(g=>!d.has(g)),e)}o&&c.forEach(d=>{a[d]=void 0});const u=o?[]:c;for(let d=0;d<=this.MAX_IDENTIFIER_RECOVERY_COUNT;d+=1){const g=this.prepareEvaluator(e,a,u);if(g.compileFailed||g.evaluator===null)return{value:null,unresolvedReference:!1};try{const y=[],A=this.wrapBoundValues(a);g.bindKeys.forEach(I=>{y.push(A[I])});const E=this.withBlockedPropertyAccess(()=>g.evaluator(...y));return E===void 0&&this.warnBlockedIdentifiers(e),{value:E,unresolvedReference:E===void 0}}catch(y){if(o&&y instanceof ReferenceError){const A=this.extractMissingIdentifier(y);if(A!==null&&this.canRecoverMissingIdentifier(A,a)){a[A]=void 0;continue}}if(this.warnBlockedIdentifiers(e),y instanceof ReferenceError&&u.length>0){const A=this.evaluateAsCondition(e,a,u);return A!==void 0?{value:A,unresolvedReference:!1}:(this.recordUnresolvedIdentifiers(this.extractUninitializedIdentifiers(y,u),e),{value:void 0,unresolvedReference:!0})}return m.error("[Haori]","Expression evaluation error:",e,y),y instanceof ReferenceError?{value:void 0,unresolvedReference:!0}:{value:null,unresolvedReference:!1}}}return m.error("[Haori]","Failed to recover missing identifiers:",e,a),{value:void 0,unresolvedReference:!0}}static prepareEvaluator(e,t,r=[]){const i=Object.keys(t).filter(E=>!this.FORBIDDEN_BINDING_NAMES.has(E)),n=[],s=[];i.forEach(E=>{this.isUsableBindingKey(E)?n.push(E):s.push(E)}),n.sort(),this.reportUnusableBindingKeys(s);const a=new Set(n),o=r.filter(E=>!a.has(E)),c=`${e}:${n.join(",")}:${o.join(",")}`;let u=this.EXPRESSION_CACHE.get(c)||null;if(u!==null)return this.compileFailedExpressions.delete(e),{bindKeys:n,evaluator:u,compileFailed:!1};const d=this.buildAssignments(n),g=this.buildShadowDeclarations(o),y=this.toGuardedMemberExpression(this.toOptionalChainExpression(e)),A=d?`"use strict";
5
5
  ${d};
6
6
  return (${y});${g}`:`"use strict";
7
- return (${y});${g}`;try{return u=new Function(...n,E),this.EXPRESSION_CACHE.set(c,u),this.compileFailedExpressions.delete(e),{bindKeys:n,evaluator:u,compileFailed:!1}}catch(A){return o.length>0?(m.warn("[Haori]","Failed to shadow undeclared identifier(s): "+o.join(", ")+". Falling back to evaluation without shadowing.",e),this.prepareEvaluator(e,t,[])):(m.error("[Haori]","Failed to compile expression:",e,A),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,c=t[n-2]||null,u=t[n-3]||null;if(this.startsObjectKey(o,i,c,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 diagnoseStrictComparison(e,t={}){const r=R.splitStrictComparison(e);if(r===null)return null;const i=R.evaluateDetailed(r.left,t),n=R.evaluateDetailed(r.right,t);if(i.unresolvedReference||n.unresolvedReference)return null;const s=i.value,a=n.value;return typeof s==typeof a||!R.isLooselyEqual(s,a)?null:{left:typeof s,right:typeof a}}static isLooselyEqual(e,t){return e==t}static splitStrictComparison(e){const t=R.strictComparisonSplits.get(e);if(t!==void 0)return t;const r=R.computeStrictComparisonSplit(e);return R.strictComparisonSplits.set(e,r),r}static computeStrictComparisonSplit(e){const t=R.tokenizeExpression(e);if(t===null)return null;let r=0,i=null;for(const a of t)if(a.type==="operator"){if(a.value==="("||a.value==="["||a.value==="{"){r+=1;continue}if(a.value===")"||a.value==="]"||a.value==="}"){r-=1;continue}if(r===0){if(a.value==="&&")return R.splitStrictComparison(e.slice(0,a.position));if(a.value==="==="){if(i!==null)return null;i=a;continue}if(R.COMPOSING_OPERATORS.has(a.value))return null}}if(i===null)return null;const n=e.slice(0,i.position).trim(),s=e.slice(i.position+i.value.length).trim();return n===""||s===""?null:{left:n,right:s}}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==="/"&&this.startsRegexpLiteral(t)){const o=this.readRegexpToken(e,n);if(o===null)return null;t.push(o.token),n=o.nextIndex;continue}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 startsRegexpLiteral(e){const t=e[e.length-1];if(t===void 0)return!0;if(t.type!=="operator"||t.value===")"||t.value==="]"||t.value==="}")return!1;const r=e[e.length-2];return!((t.value==="+"||t.value==="-")&&r?.value===t.value)}static readRegexpToken(e,t){let r=t+1,i=!1;for(;r<e.length;){const n=e[r];if(n==="\\"){r+=2;continue}if(n==="[")i=!0;else if(n==="]")i=!1;else if(n==="/"&&!i){for(r+=1;r<e.length&&/[A-Za-z]/.test(e[r]);)r+=1;return{token:{type:"regexp",value:e.slice(t,r),position:t},nextIndex:r}}r+=1}return null}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"||e.type==="regexp"?!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;if(this.WRAPPED_VALUES.has(r))return r;const 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 c=Reflect.get(s,a,o);return typeof a=="symbol"?c:this.wrapBoundValue(c,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 c=Reflect.apply(s,a,o);return this.isIteratorLike(c)?c:this.wrapBoundValue(c,t)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),t)});return this.WRAPPED_VALUES.add(n),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}};R.MAX_IDENTIFIER_RECOVERY_COUNT=8,R.BUILTIN_NAMESPACE="haori",R.BUILTIN_HELPERS={...Ft},R.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,R.BUILTIN_DATA_PROPERTY="data",R.BUILTIN_DATA_REFERENCE_PATTERN=/(^|[^\w$.])haori\s*(\.\s*data(?![\w$])|\[)/,R.IDENTIFIER_NAME_PATTERN=/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u,R.usableBindingKeyCache=new Map,R.loggedUnusableBindingKeys=new Set,R.compileFailedExpressions=new Set,R.forbiddenBindingValueCache=new WeakMap,R.forbiddenBindingValueCacheResetScheduled=!1,R.loggedForbiddenKeySignatures=new Set,R.loggedForbiddenKeyResetScheduled=!1,R.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"],R.STRICT_FORBIDDEN_NAMES=["eval","arguments"],R.REBINDABLE_FORBIDDEN_NAMES=new Set(["location","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),R.FORBIDDEN_BINDING_NAMES=new Set([...R.FORBIDDEN_NAMES.filter(e=>!R.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...R.STRICT_FORBIDDEN_NAMES]),R.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),R.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),R.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"]),R.NON_SHADOWABLE_IDENTIFIERS=new Set(["true","false","null","undefined","NaN","Infinity","enum","implements","interface","package","private","protected","public","static","super"]),R.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"]),R.EXPRESSION_CACHE=new Map,R.FREE_IDENTIFIER_CACHE=new Map,R.BOUND_IDENTIFIER_CACHE=new Map,R.OPTIONAL_CHAIN_CACHE=new Map,R.GUARDED_MEMBER_CACHE=new Map,R.MEMBER_KEY_GUARD_OPEN="(_hk=>_hk==='constructor'||_hk==='__proto__'||_hk==='prototype'?undefined:_hk)(",R.FORBIDDEN_NAME_PATTERNS=R.FORBIDDEN_NAMES.map(e=>({name:e,pattern:new RegExp(`(^|[^\\w$.])${e}(?![\\w$])`)})),R.FORBIDDEN_IDENTIFIER_CACHE=new Map,R.pendingUnresolvedIdentifiers=new Set,R.unresolvedReportScheduled=!1,R.suppliedIdentifiers=new Set,R.pendingScopeMissingIdentifiers=new Map,R.scopeMissingReportScheduled=!1,R.rowScopeIdentifiers=new Set,R.loggedScopeMissingIdentifiers=new Set,R.loggedBlockedIdentifierExpressions=new Set,R.COMPOSING_OPERATORS=new Set(["||","?",":","==","!=",">=","<=",">","<","=>",",","!","+","-","*","/","%","..."]),R.strictComparisonSplits=new Map,R.WRAPPED_VALUES=new WeakSet;let re=R;const fe="data-haori-if-disabled",ut="input, select, textarea, button, fieldset",C=class C{static reset(){C.ELEMENT_STORES.clear(),C.ensureGlobalAccess()}static start(){C.collecting=!0}static stop(){C.collecting=!1}static isCollecting(){return C.collecting&&q.isEnabled()}static snapshot(){return C.ensureGlobalAccess(),[...C.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:C.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:C.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 report(e=C.DEFAULT_REPORT_LIMIT){const t=new Map;let r=0,i=0;const n=(c,u,d)=>{r+=d.totalDurationMs,i+=d.calls;const g=t.get(c);if(g===void 0){t.set(c,{where:u,template:d.template,elements:1,calls:d.calls,totalDurationMs:d.totalDurationMs,maxDurationMs:d.maxDurationMs,sharePercent:0,representativeDurationMs:d.totalDurationMs});return}g.elements+=1,g.calls+=d.calls,g.totalDurationMs+=d.totalDurationMs,g.maxDurationMs=Math.max(g.maxDurationMs,d.maxDurationMs),d.totalDurationMs>g.representativeDurationMs&&(g.where=u,g.representativeDurationMs=d.totalDurationMs)};C.snapshot().forEach(c=>{c.attributes.forEach(u=>{n(`@${u.name}
7
+ return (${y});${g}`;try{return u=new Function(...n,A),this.EXPRESSION_CACHE.set(c,u),this.compileFailedExpressions.delete(e),{bindKeys:n,evaluator:u,compileFailed:!1}}catch(E){return o.length>0?(m.warn("[Haori]","Failed to shadow undeclared identifier(s): "+o.join(", ")+". Falling back to evaluation without shadowing.",e),this.prepareEvaluator(e,t,[])):(m.error("[Haori]","Failed to compile expression:",e,E),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,c=t[n-2]||null,u=t[n-3]||null;if(this.startsObjectKey(o,i,c,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 diagnoseStrictComparison(e,t={}){const r=R.splitStrictComparison(e);if(r===null)return null;R.evaluatingForDiagnosis=!0;let i,n;try{i=R.evaluateDetailed(r.left,t),n=R.evaluateDetailed(r.right,t)}finally{R.evaluatingForDiagnosis=!1}if(i.unresolvedReference||n.unresolvedReference)return null;const s=i.value,a=n.value;return typeof s==typeof a||!R.isLooselyEqual(s,a)?null:{left:typeof s,right:typeof a}}static isLooselyEqual(e,t){return e==t}static splitStrictComparison(e){const t=R.strictComparisonSplits.get(e);if(t!==void 0)return t;const r=R.computeStrictComparisonSplit(e);return R.strictComparisonSplits.set(e,r),r}static computeStrictComparisonSplit(e){const t=R.tokenizeExpression(e);if(t===null)return null;let r=0,i=null;for(const a of t)if(a.type==="operator"){if(a.value==="("||a.value==="["||a.value==="{"){r+=1;continue}if(a.value===")"||a.value==="]"||a.value==="}"){r-=1;continue}if(r===0){if(a.value==="&&")return R.splitStrictComparison(e.slice(0,a.position));if(a.value==="==="){if(i!==null)return null;i=a;continue}if(R.COMPOSING_OPERATORS.has(a.value))return null}}if(i===null)return null;const n=e.slice(0,i.position).trim(),s=e.slice(i.position+i.value.length).trim();return n===""||s===""?null:{left:n,right:s}}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==="/"&&this.startsRegexpLiteral(t)){const o=this.readRegexpToken(e,n);if(o===null)return null;t.push(o.token),n=o.nextIndex;continue}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 startsRegexpLiteral(e){const t=e[e.length-1];if(t===void 0)return!0;if(t.type!=="operator"||t.value===")"||t.value==="]"||t.value==="}")return!1;const r=e[e.length-2];return!((t.value==="+"||t.value==="-")&&r?.value===t.value)}static readRegexpToken(e,t){let r=t+1,i=!1;for(;r<e.length;){const n=e[r];if(n==="\\"){r+=2;continue}if(n==="[")i=!0;else if(n==="]")i=!1;else if(n==="/"&&!i){for(r+=1;r<e.length&&/[A-Za-z]/.test(e[r]);)r+=1;return{token:{type:"regexp",value:e.slice(t,r),position:t},nextIndex:r}}r+=1}return null}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"||e.type==="regexp"?!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;if(this.WRAPPED_VALUES.has(r))return r;const 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 c=Reflect.get(s,a,o);return typeof a=="symbol"?c:this.wrapBoundValue(c,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 c=Reflect.apply(s,a,o);return this.isIteratorLike(c)?c:this.wrapBoundValue(c,t)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),t)});return this.WRAPPED_VALUES.add(n),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}};R.MAX_IDENTIFIER_RECOVERY_COUNT=8,R.BUILTIN_NAMESPACE="haori",R.BUILTIN_HELPERS={...Ft},R.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,R.BUILTIN_DATA_PROPERTY="data",R.BUILTIN_DATA_REFERENCE_PATTERN=/(^|[^\w$.])haori\s*(\.\s*data(?![\w$])|\[)/,R.IDENTIFIER_NAME_PATTERN=/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u,R.usableBindingKeyCache=new Map,R.loggedUnusableBindingKeys=new Set,R.compileFailedExpressions=new Set,R.forbiddenBindingValueCache=new WeakMap,R.forbiddenBindingValueCacheResetScheduled=!1,R.loggedForbiddenKeySignatures=new Set,R.loggedForbiddenKeyResetScheduled=!1,R.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"],R.STRICT_FORBIDDEN_NAMES=["eval","arguments"],R.REBINDABLE_FORBIDDEN_NAMES=new Set(["location","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),R.FORBIDDEN_BINDING_NAMES=new Set([...R.FORBIDDEN_NAMES.filter(e=>!R.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...R.STRICT_FORBIDDEN_NAMES]),R.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),R.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),R.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"]),R.NON_SHADOWABLE_IDENTIFIERS=new Set(["true","false","null","undefined","NaN","Infinity","enum","implements","interface","package","private","protected","public","static","super"]),R.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"]),R.EXPRESSION_CACHE=new Map,R.FREE_IDENTIFIER_CACHE=new Map,R.BOUND_IDENTIFIER_CACHE=new Map,R.OPTIONAL_CHAIN_CACHE=new Map,R.GUARDED_MEMBER_CACHE=new Map,R.MEMBER_KEY_GUARD_OPEN="(_hk=>_hk==='constructor'||_hk==='__proto__'||_hk==='prototype'?undefined:_hk)(",R.FORBIDDEN_NAME_PATTERNS=R.FORBIDDEN_NAMES.map(e=>({name:e,pattern:new RegExp(`(^|[^\\w$.])${e}(?![\\w$])`)})),R.FORBIDDEN_IDENTIFIER_CACHE=new Map,R.pendingUnresolvedIdentifiers=new Set,R.evaluatingForDiagnosis=!1,R.unresolvedReportScheduled=!1,R.suppliedIdentifiers=new Set,R.pendingScopeMissingIdentifiers=new Map,R.scopeMissingReportScheduled=!1,R.rowScopeIdentifiers=new Set,R.loggedScopeMissingIdentifiers=new Set,R.loggedBlockedIdentifierExpressions=new Set,R.COMPOSING_OPERATORS=new Set(["||","?",":","==","!=",">=","<=",">","<","=>",",","!","+","-","*","/","%","..."]),R.strictComparisonSplits=new Map,R.WRAPPED_VALUES=new WeakSet;let re=R;const fe="data-haori-if-disabled",ut="input, select, textarea, button, fieldset",C=class C{static reset(){C.ELEMENT_STORES.clear(),C.ensureGlobalAccess()}static start(){C.collecting=!0}static stop(){C.collecting=!1}static isCollecting(){return C.collecting&&q.isEnabled()}static snapshot(){return C.ensureGlobalAccess(),[...C.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:C.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:C.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 report(e=C.DEFAULT_REPORT_LIMIT){const t=new Map;let r=0,i=0;const n=(c,u,d)=>{r+=d.totalDurationMs,i+=d.calls;const g=t.get(c);if(g===void 0){t.set(c,{where:u,template:d.template,elements:1,calls:d.calls,totalDurationMs:d.totalDurationMs,maxDurationMs:d.maxDurationMs,sharePercent:0,representativeDurationMs:d.totalDurationMs});return}g.elements+=1,g.calls+=d.calls,g.totalDurationMs+=d.totalDurationMs,g.maxDurationMs=Math.max(g.maxDurationMs,d.maxDurationMs),d.totalDurationMs>g.representativeDurationMs&&(g.where=u,g.representativeDurationMs=d.totalDurationMs)};C.snapshot().forEach(c=>{c.attributes.forEach(u=>{n(`@${u.name}
9
9
  ${u.template}`,`${c.elementId} @${u.name}`,u)}),c.texts.forEach(u=>{n(`#${u.childIndex}
10
10
  ${u.template}`,`${c.elementId} #${u.childIndex}`,u)})});const s=[...t.values()].map(({representativeDurationMs:c,...u})=>u);s.sort((c,u)=>u.totalDurationMs-c.totalDurationMs);const a=s.slice(0,e).map(c=>({...c,sharePercent:r>0?Math.round(c.totalDurationMs/r*1e3)/10:0})),o={totalDurationMs:r,totalCalls:i,entryCount:s.length,top:a};return C.logReport(o),o}static logReport(e){const t=e.top.map((r,i)=>{const n=String(i+1).padStart(2),s=r.totalDurationMs.toFixed(1).padStart(9),a=`${r.sharePercent.toFixed(1)}%`.padStart(6),o=String(r.calls).padStart(6),c=String(r.elements).padStart(4),u=r.maxDurationMs.toFixed(1).padStart(8);return`${n}. ${s}ms ${a} calls=${o} elements=${c} max=${u}ms ${r.where} ${r.template}`});m.info("[Haori][evaluation-profile]",`total=${e.totalDurationMs.toFixed(1)}ms calls=${e.totalCalls} declarations=${e.entryCount}
11
11
  `+t.join(`
12
- `))}static record(e,t,r){if(!q.isEnabled()||!e||t.length===0||(C.ensureGlobalAccess(),!C.isCollecting()))return;const i=C.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const s=C.getOrCreateCounter(i.attributes,e.rawName,e.template);C.updateCounter(s,t,r);return}const n=C.getOrCreateCounter(i.texts,String(e.childIndex),e.template);C.updateCounter(n,t,r)}static ensureGlobalAccess(){if(!q.isEnabled())return;const e=globalThis;e[C.GLOBAL_KEY]===void 0&&(e[C.GLOBAL_KEY]={start:()=>C.start(),stop:()=>C.stop(),reset:()=>C.reset(),snapshot:()=>C.snapshot(),report:t=>C.report(t)})}static getOrCreateElementStore(e){const t=C.createElementId(e),r=C.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return C.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=C.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){if(!C.isCollecting())return{value:e(),durationMs:0};const t=C.now();return{value:e(),durationMs:C.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(`${l.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${l.prefix}derive-name="${s.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};C.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",C.ELEMENT_STORES=new Map,C.collecting=!1,C.DEFAULT_REPORT_LIMIT=20;let $e=C;const de=class de{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.skipMutationNodeSet=new Set,this.target=e,de.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(de.FRAGMENT_CACHE.has(e))return de.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new w(e);break;case Node.TEXT_NODE:t=new ne(e);break;case Node.COMMENT_NODE:t=new He(e);break;default:return m.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}static peek(e){return de.FRAGMENT_CACHE.get(e)??null}isSkipMutationNode(e){return this.skipMutationNodeSet.has(e)}holdSkipMutationNode(e){this.skipMutationNodeSet.add(e)}releaseSkipMutationNode(e){this.skipMutationNodeSet.delete(e)}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return e.holdSkipMutationNode(this.target),K.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode===e.getTarget()&&e.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{e.skipMutationNodes=t,e.releaseSkipMutationNode(this.target)})}else{const e=this.target.parentNode;if(e)return K.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 e.holdSkipMutationNode(this.target),K.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode!==e.getTarget()&&e.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{e.skipMutationNodes=t,e.releaseSkipMutationNode(this.target)})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(e){this.mounted=e}remove(e=!0){return this.parent&&this.parent.removeChild(this),de.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};de.FRAGMENT_CACHE=new WeakMap;let D=de;const S=class S extends D{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.initialized=!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,S.dropFollowUpArtifacts(e),this.syncValue(),this.initialBindAttribute=e.getAttribute(`${l.prefix}bind`),e.getAttributeNames().forEach(i=>{const n=e.getAttribute(i);if(n!==null&&!this.attributeMap.has(i)){const s=new Ce(i,n);this.attributeMap.set(i,s)}});let t=null;const r=[];e.childNodes.forEach(i=>{if(S.isOwnedWithinExternal(i))return;const n=D.peek(i)?.getParent()??null,s=D.get(i);n!==null&&n!==this&&(t=t??n,n===t&&r.push(s)),s.setParent(this),this.children.push(s)}),t!==null&&this.takeOverPlaceOf(t,r)}takeOverPlaceOf(e,t){const r=e.children,i=t.map(s=>r.indexOf(s)).filter(s=>s>=0).sort((s,a)=>s-a);if(i.length===0)return;const n=i[0];i.slice().reverse().forEach(s=>r.splice(s,1)),r.splice(n,0,this),this.setParent(e)}static isOwnedWithinExternal(e){const r=D.peek(e)?.getParent()??null;if(r===null)return!1;const i=r.getTarget().closest(`[${l.prefix}external]`);return i!==null&&i.contains(e)}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof S)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){m.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new S(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.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}static dropFollowUpArtifacts(e){S.dropIfVisibilityArtifacts(e),e.removeAttribute(`${l.prefix}each-done`),e.removeAttribute(`${l.prefix}importing`)}static dropIfVisibilityArtifacts(e){e.hasAttribute(`${l.prefix}if-false`)&&(e.style.removeProperty("display"),e.getAttribute("style")?.trim()===""&&e.removeAttribute("style"),e.removeAttribute(`${l.prefix}if-false`),S.forEachFormControlInBranch(e,t=>{t.hasAttribute(fe)&&(t.removeAttribute(fe),t.removeAttribute("disabled"))}))}remove(e=!0){const t=[];return e&&te.destroySubtree(this.getTarget()),this.getTarget().hasAttribute(`${l.prefix}external`)?this.detachPreservingSubtree(e):(this.children.slice().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(()=>{}))}detachPreservingSubtree(e){const t=this.getParent();return t&&t.removeChild(this),e?this.unmount():Promise.resolve()}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=this.withRetainedReservedKeys(e),this.clearBindingDataCache()}withRetainedReservedKeys(e){const t=this.bindingData;if(t===null)return e;const r={};for(const i of Object.keys(t))S.isReservedBindingKey(i)&&(r[i]=t[i]);return{...r,...e}}static isReservedBindingKey(e){return e.startsWith("_")}isExecutingBindingWork(){return this.bindingWorkActive>0}static isExecutingAnyBindingWork(){return S.bindingWorkActiveCount>0}markBindingWorkStart(){this.bindingWorkActive++,S.bindingWorkActiveCount++}markBindingWorkEnd(){this.bindingWorkActive>0&&(this.bindingWorkActive--,S.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 S&&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}isInitialized(){return this.initialized}markInitialized(){this.initialized=!0}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():K.enqueue(()=>{i.value=""})):(m.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):(m.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(()=>{if(this.isSupersededByUserEdit(s)||r&&!this.canApplyValue(r))return;const a=i.value;i.value=n,this.recordValueWriteResult(i.value===n),i.value!==a&&S.notifyValueToEnhancers(i),t&&((i instanceof HTMLInputElement&&S.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 c=e.includes(o.value);o.selected!==c&&(o.selected=c,s=!0),c&&a.add(o.value)}),this.recordValueWriteResult(e.every(o=>a.has(o))),s&&S.notifyValueToEnhancers(i),s&&t&&i.dispatchEvent(new Event("change",{bubbles:!0}))})}enqueueValueWrite(e){this.skipChangeValue=!0;const t=K.enqueue(e).finally(()=>{this.skipChangeValue=!1});return this.pendingValueWrite=t,t}isSupersededByUserEdit(e){return this.userEditSequence!==e}static retryUnappliedValueWrites(e,t){if(S.UNAPPLIED_VALUE_WRITES.size===0)return Promise.resolve();const r=[];for(const i of Array.from(S.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()}static notifyValueToEnhancers(e){te.isApplied(e)&&te.refreshSubtree(e)}clearUnappliedValueWrite(){this.valueWriteUnapplied=!1,S.UNAPPLIED_VALUE_WRITES.delete(this)}getValue(){return this.value}static currentSequence(){return S.sequenceCounter}static nextSequence(){return S.sequenceCounter+=1,S.sequenceCounter}static setPendingMutationFlusher(e){S.pendingMutationFlusher=e}static nextOperationSequence(){return S.pendingMutationFlusher&&!S.isExecutingAnyBindingWork()&&S.pendingMutationFlusher(),S.nextSequence()}canApplyValue(e){return e.kind==="nonSupply"&&e.editedPaths!==void 0&&this.userEditSequence>0&&this.wasResetAfter(this.userEditSequence)?!1:S.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 S.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=S.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=S.currentSequence()){e>this.authoritativeValueSequence&&(this.authoritativeValueSequence=e),this.lastValueKind==="edit"&&this.lastValueSequence<=e&&(this.lastValueKind="supply")}static warnUnresolvedAttribute(e,t,r,i){if(!q.isEnabled())return;const n=`${e} ${r}`;S.loggedUnresolvedAttributes.has(n)||(S.loggedUnresolvedAttributes.add(n),m.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))}static warnTypeMismatchedComparison(e,t,r,i){const n=`${e} ${t}`;S.loggedTypeMismatchedComparisons.has(n)||(S.loggedTypeMismatchedComparisons.add(n),m.warn("[Haori]",`The strict comparison compares different types (${r.left} vs ${r.right}), so it is always false even though the values match. Align the types (for example with ${l.prefix}value-type) or compare converted values: ${e}="${t}"`,i))}hasPendingCheckableUserEdit(e){if(!e)return this.hasPendingUserEdit();const t=this.getTarget().closest("select");if(!t)return!1;const r=D.get(t);return r instanceof S?r.hasPendingUserEdit():!1}clearValue(){this.value=null,this.clearUnappliedValueWrite()}normalizeValueForElement(e,t){const r=S.resolveDeclaredValueType(e);return r==="boolean"?S.normalizeBooleanValue(t):r==="string"?t===null?null:String(t):r==="number"||r===null&&e instanceof HTMLInputElement&&e.type==="number"?S.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"||!S.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(`${l.prefix}value-type`);if(t===null)return null;const r=t.trim().toLowerCase();return S.VALUE_TYPE_NAMES.has(r)?S.acceptsDeclaredValueType(e)?r:(S.warnValueTypeDeclaration(e,t,"値を持つ入力(checkbox / radio / file と複数選択の select を除く)にのみ指定できます"),null):(S.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(!q.isEnabled())return;const i=e instanceof HTMLInputElement?`[type=${e.type}]`:"",n=`${e.tagName}${i} ${t} ${r}`;S.loggedValueTypeDeclarations.has(n)||(S.loggedValueTypeDeclarations.add(n),m.warn("Haori",`${l.prefix}value-type="${t}" を無視しました(${r}):`,e))}static isValuePropertyTarget(e){return e instanceof HTMLInputElement?S.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(S.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,S.UNAPPLIED_VALUE_WRITES.add(this);return}this.clearUnappliedValueWrite()}getValueForCollection(){return this.skipChangeValue||this.valueWriteUnapplied?this.value:S.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=D.get(t);r instanceof S&&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=K.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 Ce(e,r);if(n){const Se=this.attributeMap.get(e);if(Se&&(Se.isEvaluate||Se.isForceEvaluation())&&!o.isEvaluate&&!o.isForceEvaluation()){const ke=K.enqueue(()=>{}).finally(()=>{this.releaseSelfWritingAttributes(s)});return this.holdSelfWritingAttributes(s,ke),ke}}this.attributeMap.set(e,o);const c=this.getTarget(),u=o.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:c,rawName:e,template:r}),d=o.isEvaluate||o.isRawEvaluate,g=e===t&&S.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),y=o.isSingleExpression(),E=ue.joinEvaluateResults(u.results),A=u.results.length===1?u.results[0]:E,I=t==="value"&&S.resolveDeclaredValueType(c)==="boolean",x=A===!1&&!I,H=!o.isForceEvaluation()&&(t!==e?u.hasUnresolvedReference||A===null||A===void 0||x:g?u.hasUnresolvedReference||A===null||A===void 0||A===!1:y?u.hasUnresolvedReference||A===null||A===void 0||x:d&&E==="");if(H&&u.hasUnresolvedReference&&S.warnUnresolvedAttribute(e,t,r,c),q.isEnabled()&&A===!1&&y){const Se=o.getSingleExpression(),ke=Se===null?null:re.diagnoseStrictComparison(Se,this.getBindingData());ke!==null&&S.warnTypeMismatchedComparison(e,r,ke,c)}const k=o.isForceEvaluation()?r:y?A:E,j=i&&o.isEvaluate&&t==="value"&&S.isValuePropertyTarget(c),Z=c.getRootNode(),ee=j&&S.isUserEditableValue(c)&&(c===Z.activeElement||this.hasPendingUserEdit()),L=H||k===null||k===!1&&!I?null:String(k),ae=e!==t&&c.getAttribute(e)!==r,G=L===null?c.hasAttribute(t):c.getAttribute(t)!==L,T=L===null?"":L,O=j&&!ee&&c.value!==T,Y=t==="checked"&&c instanceof HTMLInputElement&&(c.type==="checkbox"||c.type==="radio"),Q=t==="selected"&&c instanceof HTMLOptionElement,ye=Z.activeElement,le=ye!==null&&(Y&&c===ye||Q&&c.closest("select")===ye)||(Y||Q)&&this.hasPendingCheckableUserEdit(Q),W=L!==null,z=Y&&o.isEvaluate&&!le&&c.checked!==W,X=Q&&o.isEvaluate&&!le&&c.selected!==W;if(!ae&&!G&&!O&&!z&&!X)return j&&!ee&&(this.value=this.normalizeValueForElement(c,T),this.clearUnappliedValueWrite()),(Y||Q)&&!le&&this.syncCheckableValueFromDom(Q),Promise.resolve();const Ie=K.enqueue(()=>{ae&&c.setAttribute(e,r),L===null?c.removeAttribute(t):G&&(c.setAttribute(t,L),t===`${l.prefix}bind`&&this.recordSelfWrittenBind(L)),t==="style"&&this.captureAndHideDisplay(),j&&!ee&&(this.value=this.normalizeValueForElement(c,T),O&&(c.value=T),this.recordValueWriteResult(c.value===T)),z&&(c.checked=W),X&&(c.selected=W),(z||X)&&this.syncCheckableValueFromDom(X)}).finally(()=>{this.releaseSelfWritingAttributes(s)});return this.holdSelfWritingAttributes(s,Ie),Ie}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=K.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:ue.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=D.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.isSkipMutationNode(e.getTarget()))return Promise.resolve();if(e===this)return m.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let n=this.parent;for(;n;)i.add(n),n=n.getParent();if(i.has(e))return m.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=e.getParent()===this;let a=-1,o=-1;s&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const c=e.getParent();c!==null&&c.removeChild(e);let u=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let g;if(s?a!==-1&&a<o?g=o-1:g=o:g=this.children.indexOf(t),g===-1){const y=this.resolveInsertionPointFromDom(t,!1);y===null?(m.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(y.index,0,e),u=y.referenceNode)}else this.children.splice(g,0,e)}e.setParent(this),e.setMounted(this.mounted);const d=this.skipMutationNodes;return this.skipMutationNodes=!0,this.holdSkipMutationNode(e.getTarget()),K.enqueue(()=>{this.target.insertBefore(e.getTarget(),u)}).finally(()=>{this.skipMutationNodes=d,this.releaseSkipMutationNode(e.getTarget())})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(m.warn("[Haori]","Reference child not found in children.",t),this.insertBefore(e,null)):this.insertBefore(e,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(e,this.children[r+1]||null)}getPrevious(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<=0?null:t[r-1]}getNext(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<0||r+1>=t.length?null:t[r+1]}isVisible(){return this.visible}captureAndHideDisplay(){if(this.visible)return;const e=this.getTarget().style;this.display=e.getPropertyValue("display"),this.displayPriority=e.getPropertyPriority("display"),e.setProperty("display","none","important")}hideDisplayWithoutCapture(){if(this.visible)return;const e=this.getTarget().style;e.getPropertyValue("display")==="none"&&e.getPropertyPriority("display")==="important"||e.setProperty("display","none","important")}static reassertHiddenDisplay(e){const t=D.get(e);t instanceof S&&t.hideDisplayWithoutCapture()}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const e=this.getTarget();return this.captureAndHideDisplay(),e.setAttribute(`${l.prefix}if-false`,""),S.disableFormControlsInBranch(e),Promise.resolve()}static forEachFormControlInBranch(e,t){e.matches(ut)&&t(e);const r=i=>{Array.from(i.children).forEach(n=>{n.hasAttribute(`${l.prefix}if-false`)||(n instanceof HTMLElement&&n.matches(ut)&&t(n),r(n))})};r(e)}static disableFormControlsInBranch(e){S.forEachFormControlInBranch(e,t=>{t.hasAttribute("disabled")||(t.setAttribute(fe,""),t.setAttribute("disabled",""))})}restoreFormControlsDisabledByIf(){S.forEachFormControlInBranch(this.getTarget(),e=>{e.hasAttribute(fe)&&(e.removeAttribute(fe),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(`${l.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)}};S.NUMBER_INPUT_PATTERN=/^-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/,S.VALUE_TYPE_NAMES=new Set(["boolean","number","string"]),S.loggedValueTypeDeclarations=new Set,S.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"]),S.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],S.UNAPPLIED_VALUE_WRITES=new Set,S.sequenceCounter=0,S.bindingWorkActiveCount=0,S.pendingMutationFlusher=null,S.loggedUnresolvedAttributes=new Set,S.loggedTypeMismatchedComparisons=new Set;let w=S;class ne extends D{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new ue(this.text)}clone(){const e=new ne(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 ue(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):K.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=ue.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 He extends D{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new He(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,K.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const Le=class Le{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(Le.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)}getSingleExpression(){return this.isSingleExpression()?this.contents[0].text:null}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(m.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const n=[],s=[];let a=0,o=!1;return this.contents.forEach(c=>{try{if(r(c)){const u=$e.measure(()=>re.evaluateDetailed(c.text,e)),d=u.value;a+=u.durationMs,s.push({expression:c.text,durationMs:u.durationMs}),o=o||d.unresolvedReference,n.push(d.value)}else n.push(c.text)}catch(u){m.error("[Haori]",`Error evaluating ${i} expression: ${c.text}`,u),s.push({expression:c.text,durationMs:0}),n.push("")}}),$e.record(t,s,a),{results:n,hasUnresolvedReference:o}}};Le.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let ue=Le;const ie=class ie extends ue{constructor(e,t){super(t),this.forceEvaluation=ie.needsForceEvaluation(e)}static needsForceEvaluation(e){if(ie.forceEvaluationNames===null||ie.forceEvaluationPrefix!==l.prefix){const t=new Set;for(const r of[l.prefix,...ie.FORCE_EVALUATION_PREFIXES])for(const i of ie.FORCE_EVALUATION_SUFFIXES)t.add(`${r}${i}`);ie.forceEvaluationNames=t,ie.forceEvaluationPrefix=l.prefix}return ie.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?(m.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};ie.FORCE_EVALUATION_SUFFIXES=["if","each","derive"],ie.FORCE_EVALUATION_PREFIXES=["data-","hor-"],ie.forceEvaluationNames=null,ie.forceEvaluationPrefix=null;let Ce=ie;const ve=class ve{static get runtime(){return l.runtime}static setRuntime(e){l.setRuntime(e)}static waitForRenders(){return K.waitForIdle()}static dialog(e){return K.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 K.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return K.enqueue(()=>{e instanceof HTMLDialogElement?(ve.clearMessagesSync(e),e.showModal()):m.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return K.enqueue(()=>{e instanceof HTMLDialogElement?e.close():m.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return ve.addMessage(e,t,"error")}static addMessage(e,t,r){return K.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 K.enqueue(()=>{ve.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 Ne(e,t,r)}static now(e,t){return Qe(e,t)}static today(e,t,r){return _e(e,t,r)}static number(e,t){return et(e,t)}static range(e,t,r){return tt(e,t,r)}static pages(e,t,r){return rt(e,t,r)}static monthAdd(e,t){return Me(e,t)}static monthRange(e,t){return it(e,t)}static pageSummary(e,t){return nt(e,t)}static findBy(e,t,r){return st(e,t,r)}static sum(e,t){return at(e,t)}static distinct(e,t){return lt(e,t)}static groupBy(e,t){return ct(e,t)}};ve.enhancers={register(e,t){te.register(e,t)},has(e){return te.has(e)}};let oe=ve;const It="入力内容を確認してください",kt=["addErrorMessage","clearMessages"],dt="data-haori-group-name";function ft(){const e=globalThis.window?.Haori;return kt.every(r=>typeof e?.[r]=="function")?e:oe}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(`${l.prefix}form-name`);return t||e.getAttribute("name")}static clearRowUserEditMarksForChangedKeys(e,t){const r=h.getValues(e),i=new Set;for(const n of new Set([...Object.keys(r),...Object.keys(t)]))h.isSameCollectedValue(r[n],t[n])||i.add(n);i.size!==0&&h.clearUserEditMarksForKeys(e,e,i)}static isSameCollectedValue(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}static clearUserEditMarksForKeys(e,t,r){const i=h.resolveRowTopLevelKey(e,t);i!==null&&r.has(i)&&e.clearUserEditMark(),e.getChildElementFragments().forEach(n=>{h.clearUserEditMarksForKeys(n,t,r)})}static resolveRowTopLevelKey(e,t){let r=null,i=e;for(;i!==null&&i!==t;){const n=i.getAttribute(`${l.prefix}form-object`)||i.getAttribute(`${l.prefix}form-list`)||h.resolveFieldName(i);n!=null&&String(n)!==""&&(r=String(n)),i=i.getParent()}return r}static prepareFormName(e){if(!e.hasAttribute(`${l.prefix}form-name`))return;const t=e.getAttribute(`${l.prefix}form-name`);if(!t){m.warn("Haori",`${l.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(dt))return;const i=h.resolveGroupScope(e),n=`${String(t)}--haori${h.resolveGroupScopeId(i)}`;if(r.getAttribute("name")!==n)return e.setAttribute(dt,"").then(()=>e.setAttribute("name",n))}static resolveGroupScope(e){let t=e,r=t.getParent();for(;r!==null;){if(r.hasAttribute(`${l.prefix}form-list`))return t;if(r.getTarget()instanceof HTMLFormElement||r.hasAttribute(`${l.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=D.get(r);if(i instanceof w&&h.hasDeclarativeBinding(i,"selected")&&!h.isDeclarationResolved(i,"selected"))return!1}return!0}return!1}static isDeclarationResolved(e,t){for(const r of[`${l.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"):w.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 w&&h.clearDeclarativeStateFromDom(t)})}static hasDeclarativeBinding(e,t){if(e.hasAttribute(`${l.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=D.get(t);if(r instanceof w&&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 c of o)n.has(c)||n.set(c,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 isResettingInternally(){return h.internalResetDepth>0}static getPartValues(e,t,r=null,i=null){if(e.hasAttribute(`${l.prefix}form-detach`))return t;if(e.getTarget().hasAttribute(`${l.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(`${l.prefix}form-object`),a=e.getAttribute(`${l.prefix}form-list`),o=e.hasAttribute(`${l.prefix}form-list`),c=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]=[]),!c&&d.checked&&(Array.isArray(t[u])||(t[u]=[]),t[u].push(d.value))}else if(o&&c)Array.isArray(t[String(n)])?t[String(n)].push(null):t[String(n)]=[null];else if(!c)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,g=u instanceof HTMLInputElement?u.value:e.getValue(),y=d?g:null,E=String(n);y===null?E in t||(t[E]=null):t[E]===null||t[E]===void 0?t[E]=y:Array.isArray(t[E])?t[E].push(y):t[E]=[t[E],y]}else t[String(n)]=h.resolveCollectedValue(e);s&&m.warn("Haori",`Element cannot have both ${l.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 g of e.getChildElementFragments())h.getPartValues(g,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&&m.warn("Haori",`Element cannot have both ${l.prefix}form-list and ${l.prefix}form-object attributes.`)}else if(a){const u=[],d=[];let g=!1;for(const y of e.getChildElementFragments()){const E={},A=i===null?null:new Set;h.getPartValues(y,E,r,A),A!==null&&h.registerCollectedExcludedKeys(E,A),Object.keys(E).length>0?(g=!0,u.push(E),d.push(y.getListKey())):r!==null&&(u.push({}),d.push(y.getListKey()))}if(r===null){const y=e.getAttribute(`${l.prefix}each-key`);h.registerCollectedRowIdentity(u,y==null?null:String(y),d,h.isCollectedListFromEachSource(e)),h.warnDerivedRowsWithoutKey(e),t[String(a)]=u}else g&&(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(`${l.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 resolveAncestorKeyOwner(e,t){let r=e.getParent();for(;r;){const i=r.getRawBindingData();if(i&&Object.prototype.hasOwnProperty.call(i,t))return r.getListKey()!==null?null:{owner:r,value:i[t]};r=r.getParent()}return null}static resolveAncestorArgOwner(e,t){const r=h.resolveAncestorKeyOwner(e,t);if(r===null)return null;const i=h.asPlainRecord(r.value);return i===null?(h.warnArgOwnerIsNotRecord(e,t,r.value),null):{owner:r.owner,value:i}}static ancestorBaseResolver(e){return t=>h.resolveAncestorKeyOwner(e,t)?.value}static warnArgOwnerIsNotRecord(e,t,r){if(!q.isEnabled()||r==null)return;const i=e.getTarget(),n=h.warnedArgOwnerNotRecord.get(i);n?.has(t)||(n?n.add(t):h.warnedArgOwnerNotRecord.set(i,new Set([t])),m.warn("[Haori]",`${l.prefix}form-arg="${t}" のキーを祖先が${Array.isArray(r)?"配列":`${typeof r} 型の値`}で持っています。${l.prefix}form-arg はそのキーの配下に入力欄が対応することを宣言するため、値はレコード(オブジェクト)である必要があります。このままでは収集値がそのキーへ直接入り、値の型が変わります。`))}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(`${l.prefix}each`)&&i.hasAttribute(`${l.prefix}form-list`)){const n=i.getRawAttribute(`${l.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(`${l.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=`${l.prefix}form-object`,s=`${l.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],[${l.prefix}form-name],[${n}],[${s}]`;return r.querySelectorAll(o).forEach(c=>{if(!(c instanceof HTMLElement))return;let u=null,d=!1,g=c;for(;g&&g!==r;)g.hasAttribute(`${l.prefix}form-detach`)&&(d=!0),(g.hasAttribute(n)||g.hasAttribute(s))&&(u=g),g=g.parentElement;if(d)return;const y=u??c,E=y.getAttribute(n)||y.getAttribute(s)||y.getAttribute(`${l.prefix}form-name`)||y.getAttribute("name");E&&t.add(E)}),t}static applyCustomValidity(e){const t=`${l.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)){m.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=re.evaluateDetailed(h.unwrapConditionExpression(i),n);if(s.unresolvedReference){m.warn("Haori",`${t} の参照が解決できないため無効として扱います: ${i}`),r.setCustomValidity(h.resolveValidityMessage(e));return}r.setCustomValidity(s.value?"":h.resolveValidityMessage(e))}static resolveValidityMessage(e){const t=e.getAttribute(`${l.prefix}validity-message`);return typeof t=="string"&&t.trim()!==""?t:It}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(!q.isEnabled()||!e)return;const r=`${l.prefix}validity`;(e.hasAttribute(r)||e.getTarget().querySelector(`[${r}]`)!==null)&&m.warn("Haori",`${r} は指定されていますが検証は行われません(${t})。${l.prefix}{event}-validate を指定するか、${l.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){!q.isEnabled()||h.warnedPositionalRowFallbacks.has(e)||(h.warnedPositionalRowFallbacks.add(e),m.warn("[Haori]",`${l.prefix}form-list の行を出現順で対応付けます(${e})。配列と画面の行数・並びが一致していない場合、行の値を取り違えます。`))}static warnDerivedRowsWithoutKey(e){if(!q.isEnabled()||e.getRawAttribute(`${l.prefix}each-key`)!==null)return;const t=e.getRawAttribute(`${l.prefix}each`);t===null||h.resolveLeadingPath(t)!==null||h.warnedDerivedRowsWithoutKey.has(t)||(h.warnedDerivedRowsWithoutKey.add(t),m.warn("[Haori]",`${l.prefix}each="${t}" の一覧を ${l.prefix}form-list で収集していますが、${l.prefix}each-key がありません。行と配列要素を出現順で対応付けるため、画面に出ていない要素があると行の値を取り違えます。${l.prefix}each-key を宣言してください。`))}static mergeCollectedValues(e,t,r=null){const i={...e??{}};for(const[s,a]of Object.entries(t)){if(h.UNSAFE_MERGE_KEYS.has(s))continue;const o=e&&Object.prototype.hasOwnProperty.call(e,s)?e[s]:r?.(s);i[s]=h.overlayCollectedValue(o,a)}const n=h.COLLECTED_EXCLUDED_KEYS.get(t);if(n)for(const s of n)s in t||delete i[s];return i}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(`${l.prefix}form-list`);if(t==null||t==="")return!0;const r=e.getRawAttribute(`${l.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=$.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=e.slice();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 c=o.shift();n[c]=h.overlayCollectedValue(e[c],t[s])}return n}static syncAncestorArgForms(e,t,r=null,i=null){const n=[];for(const{form:a,key:o}of h.collectArgForms(e)){if(a.wasResetAfter(t))continue;const c=h.resolveAncestorArgOwner(a,o);!c||c.owner!==e||n.push(h.pushAncestorArgValue(a,o,c.value,r))}const s=e.getRawBindingData();for(const{form:a,keys:o}of h.collectShadowingContainers(e)){if(a.wasResetAfter(t))continue;const c=o.filter(u=>h.createArgValueSignature(i?.[u])!==h.createArgValueSignature(s?.[u]));c.length!==0&&n.push(h.releaseOwnCopy(a,c,r))}return Promise.all(n).then(()=>{})}static collectShadowingContainers(e){const t=`${l.prefix}form-arg`,r=[];return e.getTarget().querySelectorAll(`form:not([${t}]), [${l.prefix}form]`).forEach(i=>{const n=D.get(i);if(!(n instanceof w))return;const s=n.getRawBindingData();if(s===null)return;const a=h.getInitialBindingData(n),o=Object.keys(s).filter(c=>Object.prototype.hasOwnProperty.call(a??{},c)?!1:h.resolveAncestorKeyOwner(n,c)?.owner===e);o.length>0&&r.push({form:n,keys:o})}),r}static releaseOwnCopy(e,t,r=null){const i=e.getRawBindingData();if(i===null)return Promise.resolve();const n={...i};for(const s of t)delete n[s];return $.setBindingData(e.getTarget(),n,{kind:r?.kind??"supply",sequence:r?.sequence??w.nextSequence()})}static collectArgForms(e){const t=`${l.prefix}form-arg`,r=e.getTarget().querySelectorAll(`form[${t}]`),i=[];return r.forEach(n=>{const s=D.get(n);if(!(s instanceof w))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();return a&&Object.prototype.hasOwnProperty.call(a,t)?h.releaseOwnCopy(e,[t],i):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=D.get(i);if(!(n instanceof w))continue;const s=n.getRawBindingData(),a=n.getAttribute(`${l.prefix}form-arg`),o=a?String(a):null,c=o!==null&&!(s&&Object.prototype.hasOwnProperty.call(s,o))?h.resolveAncestorArgOwner(n,o):null;if(!(!s&&!c)){if(h.INITIAL_RESTORED_FORMS.add(i),c){r.push(h.pushAncestorArgValue(n,o,c.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(`${l.prefix}form-object`)||e.getAttribute(`${l.prefix}form-list`))}static resolveCollectionScope(e){let t=e,r=t.getParent();for(;r!==null;){if(h.startsCollectionLevel(r))return r.getAttribute(`${l.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(`${l.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(`${l.prefix}form-detach`)||i.getTarget().hasAttribute(`${l.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(`${l.prefix}form-detach`)&&!r)return Promise.resolve();const c=h.resolveFieldName(e),u=e.getAttribute(`${l.prefix}form-object`),d=e.getAttribute(`${l.prefix}form-list`),g=e.hasAttribute(`${l.prefix}form-list`);if(c){const y=t[String(c)],E=n&&h.hasResolvedDeclarativeState(e),A=n&&typeof y>"u"&&!h.isDeclarativeStateBound(e);let I=y;if(E?I=void 0:A&&(I=null),h.isFileInput(e))return(I===null||I==="")&&o.push(h.applyFragmentValue(e,null,i,a)),Promise.all(o).then(()=>{});if(g&&Array.isArray(I)&&!h.isGroupedCheckable(e)&&!h.isMultipleSelect(e)){const x=String(c),H=s.get(x)??0;s.set(x,H+1),o.push(h.applyFragmentValue(e,I[H]??null,i,a))}else typeof I>"u"||(Array.isArray(I)&&h.isGroupedCheckable(e)||Array.isArray(I)&&h.isMultipleSelect(e)||typeof I=="string"||typeof I=="number"||typeof I=="boolean"||I===null?o.push(h.applyFragmentValue(e,I,i,a)):o.push(h.applyFragmentValue(e,String(I),i,a)))}else if(u){const y=t[String(u)];if(y&&typeof y=="object"){const E=new Map;for(const A of e.getChildElementFragments())o.push(h.setPartValues(A,y,r,i,n,E,a))}}else if(d){const y=t[String(d)];if(Array.isArray(y)){const E=e.getChildElementFragments(),A=e.getAttribute(`${l.prefix}each-key`),I=h.isCollectedListFromEachSource(e)?h.pairRowsWithItems(E,y,A==null?null:String(A)):null;for(let x=0;x<E.length;x++){const H=E[x],k=I?I[x]:y.length>x?y[x]:null;o.push(h.setPartValues(H,h.asPlainRecord(k)??{},r,i,n,new Map,a))}}}else for(const y of e.getChildElementFragments())o.push(h.setPartValues(y,t,r,i,n,s,a));return Promise.all(o).then(()=>{})}static async reset(e,t=w.nextSequence()){const r=h.collectBindingTargetForms(e);if(r.length>0&&r.every(n=>n.isSupplyStale(t)))return;h.markResetSubtree(e,t),$.clearUserEditMarks(e,t),h.clearValues(e),await Promise.all([h.clearMessages(e),h.clearEachClones(e)]),await K.enqueue(()=>{const n=h.collectEditsAfter(e,t),s=e.getTarget();h.internalResetDepth+=1;try{s instanceof HTMLFormElement?s.reset():(s.querySelectorAll("form").forEach(a=>a.reset()),h.restoreDefaultValues(s))}finally{h.internalResetDepth-=1}h.clearDeclarativeStateFromDom(e),$.invalidateDerivedSubtreeSignatures(e),h.restoreEdits(n)});const i=r;for(const n of i){const s=h.getInitialBindingData(n);s===null&&n.getRawBindingData()===null||await $.setBindingData(n.getTarget(),s??{},{sequence:t})}h.syncValuesFromDom(e),await $.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(`${l.prefix}form-arg`);let c={...s||{}};if(o){const u=String(o);!Object.prototype.hasOwnProperty.call(s??{},u)&&h.resolveAncestorArgOwner(n,u)!==null||(c[u]=h.mergeCollectedValues(c[u]??null,a))}else c=h.mergeCollectedValues(c,a),h.deleteAncestorOwnedKeys(n,s,c);await $.setBindingData(n.getTarget(),c,{sequence:t})}te.refreshSubtree(e.getTarget())}static deleteAncestorOwnedKeys(e,t,r){for(const i of Object.keys(r))Object.prototype.hasOwnProperty.call(t??{},i)||h.resolveAncestorKeyOwner(e,i)!==null&&delete r[i]}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:$.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=D.get(n);s instanceof w&&i.push(s)}return i}static clearEachClones(e){const t=[],r=n=>{if(n.hasAttribute(`${l.prefix}each`)){for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${l.prefix}each-before`),o=s.hasAttribute(`${l.prefix}each-after`);!a&&!o&&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(`${l.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 ft().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return h.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=ft(),a=s.addMessage,o=u=>typeof a=="function"?a.call(s,u,r,i):s.addErrorMessage(u,r),c=h.findFragmentsByKey(e,t);return c.forEach(u=>{n.push(o(u.getTarget()))}),c.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(`${l.prefix}form-object`))t.length>1&&e.getAttribute(`${l.prefix}form-object`)===i&&e.getChildElementFragments().forEach(s=>{r.push(...h.findFragmentByKeyParts(s,t.slice(1)))});else if(e.hasAttribute(`${l.prefix}form-list`)){if(t.length>1){const n=e.getAttribute(`${l.prefix}form-list`),s=i.lastIndexOf("["),a=i.lastIndexOf("]");if(s!==-1&&a!==-1&&s<a){const o=i.substring(0,s);if(n===o){const c=i.substring(s+1,a),u=Number(c);if(isNaN(u))m.error("Haori",`Invalid index: ${i}`);else{const d=e.getChildElementFragments().filter(g=>g.hasAttribute(`${l.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(`${l.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.internalResetDepth=0,h.warnedArgOwnerNotRecord=new WeakMap,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.warnedDerivedRowsWithoutKey=new Set,h.LEADING_PATH_PATTERN=/^\s*([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*)\s*([\s\S]*)$/;let F=h;class B{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){B.dispatch(document,"ready",{version:e})}static importStart(e,t){B.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){B.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){B.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 c of o){const u=t?.[c],d=r[c];u!==d&&n.push(c)}B.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){B.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){B.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){B.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){B.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){B.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){B.dispatch(e,"show",{visible:!0})}static hide(e){B.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){B.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){B.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){B.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:n?performance.now()-n:void 0})}static pollTimeout(e,t,r){B.dispatch(e,"polltimeout",{count:t,elapsedMs:r})}static pollStop(e,t,r,i){B.dispatch(e,"pollstop",{reason:t,count:r,elapsedMs:i})}}const Nt={401:"unauthorized-redirect",403:"forbidden-redirect"};function xt(b,e){return b.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=re.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function Mt(b,e){const t=b.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=D.get(b),i=r instanceof w?r.getBindingData():{},n=xt(t,i);return n===""?null:n}function $t(b,e,t){const r=b.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):"",c=a>=0?t.slice(0,a):t,u=c.includes("?")?"&":"?";return`${c}${u}${s}${o}`}function ht(b){const e=Nt[b];if(e===void 0||typeof document>"u")return!1;const t=`${l.prefix}${e}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=Mt(i,t);if(n===null)continue;const s=$t(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 J{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 m.error("Haori",`Invalid selector: ${e} (${t})`,i),[]}}static query(e,t,r=document.body){try{return r.querySelector(e)}catch(i){return m.error("Haori",`Invalid selector: ${e} (${t})`,i),null}}}const N=class N{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 N.WARNED_KINDS.has(e)||(N.WARNED_KINDS.add(e),m.warn("Haori",`${e}Storage が利用できないため ${l.prefix}store を無効にします:`,t)),null}}static isReservedKey(e){return w.isReservedBindingKey(e)}static isPlainRecord(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}static warnOnce(e,t,r){let i=N.WARNED_ELEMENTS.get(e);i||(i=new Set,N.WARNED_ELEMENTS.set(e,i)),!i.has(t)&&(i.add(t),m.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(`${l.prefix}store`);if(r===null)return null;const i=r.trim();if(i==="")return N.warnOnce(t,"key",`${l.prefix}store にストレージキーが指定されていません。`),null;if(i.includes("{{"))return N.warnOnce(t,"expression",`${l.prefix}store に式は使用できません(静的な文字列を指定してください): ${i}`),null;const n=e.getRawAttribute(`${l.prefix}store-type`);let s="session";if(n!==null){const d=n.trim();d==="local"||d==="session"?s=d:N.warnOnce(t,"type",`${l.prefix}store-type は session または local を指定してください(session として扱います): ${d}`)}const a=e.getRawAttribute(`${l.prefix}store-arg`),o=a===null||a.trim()===""?null:a.trim(),c=e.getRawAttribute(`${l.prefix}store-params`);let u=null;if(c!==null){const d=c.split("&").map(y=>y.trim()).filter(y=>y!==""),g=d.filter(y=>!N.isReservedKey(y));g.length!==d.length&&N.warnOnce(t,"reserved",`${l.prefix}store-params の予約キー(先頭が _ のキー)は対象外です。`),u=g.length>0?g:null}return u===null&&o===null?(N.warnOnce(t,"target",`${l.prefix}store には ${l.prefix}store-params または ${l.prefix}store-arg のいずれかが必要です。`),null):{key:i,kind:s,params:u,arg:o}}static readRecord(e){const t=N.resolveStorage(e.kind);if(!t)return null;let r;try{r=t.getItem(e.key)}catch(n){return m.warn("Haori",`ストレージの読み取りに失敗しました: ${e.key}`,n),null}if(r===null)return null;let i;try{i=JSON.parse(r)}catch(n){return m.warn("Haori",`保存済みデータが JSON として解釈できません: ${e.key}`,n),null}return N.isPlainRecord(i)?i:(m.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(!N.isPlainRecord(s))return m.warn("Haori",`保存済みデータの ${e.arg} がオブジェクトではありません: `+e.key),{};r=s}const i=e.params??Object.keys(r),n={};for(const s of i)N.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(N.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=N.stringify(t);if(r===null){N.SIGNATURES.delete(e);return}N.SIGNATURES.set(e,{json:r,refs:N.createRefs(t)})}static writeRecord(e,t){const r=N.resolveStorage(e.kind);if(!r)return!1;const i=N.readRecord(e)??{};if(e.arg!==null){const n=i[e.arg],s=N.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 m.warn("Haori",`ストレージへの保存に失敗しました: ${e.key}`,n),!1}}static restore(e){const t=N.readDeclaration(e);if(!t)return Promise.resolve();const r=e.getTarget();if(N.isInsideEachRow(e))return N.warnOnce(r,"each-row",`${l.prefix}each の行の内側では ${l.prefix}store を使用できません(行データは親要素側で配列キーを指定してください)。`),Promise.resolve();N.RESTORED_ELEMENTS.add(r);const i=N.readRecord(t),n=i?N.extractFromRecord(t,i):{},s={...e.getRawBindingData()??{},...n};return N.seedSignature(r,N.selectFromData(t,s)),Object.keys(n).length===0?Promise.resolve():$.setBindingData(r,s,{reentrant:!0,kind:"nonSupply",sequence:w.nextSequence()})}static mirror(e){const t=N.readDeclaration(e);if(!t||N.isInsideEachRow(e))return;const r=e.getTarget();if(!N.RESTORED_ELEMENTS.has(r))return;const i=e.getRawBindingData();if(!i)return;const n=N.selectFromData(t,i);if(Object.keys(n).length===0)return;const s=N.SIGNATURES.get(r);if(s&&N.hasSameRefs(s,n))return;const a=N.stringify(n);if(a===null){m.warn("Haori",`保存対象を直列化できないためミラーを行いません: ${t.key}`);return}if(s&&s.json===a){s.refs=N.createRefs(n);return}N.writeRecord(t,n)&&N.SIGNATURES.set(r,{json:a,refs:N.createRefs(n)})}static clear(e,t){const r=N.resolveStorage(t);if(r){try{r.removeItem(e)}catch(i){m.warn("Haori",`ストレージの破棄に失敗しました: ${e}`,i);return}N.reseedDeclaringElements(e,t)}}static reseedDeclaringElements(e,t){document.querySelectorAll(`[${l.prefix}store]`).forEach(i=>{if(!N.RESTORED_ELEMENTS.has(i))return;const n=D.get(i);if(!(n instanceof w))return;const s=N.readDeclaration(n);if(!s||s.key!==e||s.kind!==t)return;const a=n.getRawBindingData();N.seedSignature(i,a?N.selectFromData(s,a):{})})}};N.SIGNATURES=new WeakMap,N.RESTORED_ELEMENTS=new WeakSet,N.WARNED_ELEMENTS=new WeakMap,N.WARNED_KINDS=new Set;let Re=N;class pt{static readParams(){const e={},t=new URLSearchParams(window.location.search);for(const r of new Set(t.keys())){if(r==="__proto__")continue;const i=t.getAll(r);e[r]=i.length===1?i[0]:i}return 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 Ct=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],Pt="__haoriHistoryState__",Ue="data-haori-click-lock",gt="ファイルを保存できませんでした",Lt=100;let Te=null;const Ot=["info","warning","error","success"],Bt=/^(\d{3})-(click|click-await|close|toast|toast-level|no-message)$/;function he(){const e=globalThis.window?.Haori;return Ct.every(r=>typeof e?.[r]=="function")?e:oe}const Ht=new Set(["GET","HEAD","OPTIONS"]);function Ve(b){return Ht.has(b.toUpperCase())}function Ut(b,e){for(const[t,r]of Object.entries(e))r!==void 0&&(Array.isArray(r)?r.forEach(i=>{b.append(t,be(i))}):b.append(t,be(r)))}function be(b){if(b==null)return"";if(typeof b=="object"||typeof b=="function")try{return JSON.stringify(b)??""}catch{return""}return String(b)}function mt(b,e){const t=new URL(b,window.location.href),r=new URLSearchParams(t.search);return Ut(r,e),t.search=r.toString(),t.toString()}function Vt(b){if(b==null)return{payload:{},dropped:!1};if(typeof b=="string"){const e=b.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:yt(new URLSearchParams(e)),dropped:!1}:{payload:{},dropped:!0}}if(b instanceof URLSearchParams)return{payload:yt(b),dropped:!1};if(typeof FormData<"u"&&b instanceof FormData){const e={};let t=!1;for(const[r,i]of b.entries()){if(typeof i!="string"){t=!0;continue}bt(e,r,i)}return{payload:e,dropped:t}}return{payload:{},dropped:!0}}function yt(b){const e={};for(const[t,r]of b.entries())bt(e,t,r);return e}function bt(b,e,t){const r=b[e];r===void 0?b[e]=t:Array.isArray(r)?r.push(t):b[e]=[r,t]}function pe(b,e){if(F.isCompleteSetValue(e))return e;if(Array.isArray(e)){const t=Array.isArray(b)?b.slice():[];let r=!1;return e.forEach((i,n)=>{i!=null&&(typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0||(t[n]=pe(t[n],i),r=!0))}),r?t:b}if(e!==null&&typeof e=="object"){const t=b!==null&&typeof b=="object"&&!Array.isArray(b)?{...b}:{};for(const[r,i]of Object.entries(e))t[r]=pe(t[r],i);return t}return e}function qt(b){const e=b?.body;return e==null?!1:typeof e=="string"?e!=="":!0}function Wt(b,e){const t={...e||{}},r=(t.method||"GET").toUpperCase();if(l.runtime!=="demo"||Ve(r))return{url:b,options:t,requestedMethod:r,effectiveMethod:r,normalized:!1};const{payload:i,dropped:n}=Vt(t.body);let s=b;Object.keys(i).length>0&&(s=mt(s,i)),n&&m.warn("Haori",`The ${r} body cannot be converted into a query string and is dropped by the demo runtime normalization. Send the values with ${l.prefix}{event}-data / ${l.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 jt(b){return b==null?null:typeof b=="string"?b:b instanceof URLSearchParams?b.toString():b instanceof FormData?Array.from(b.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(b)}function De(b){return b instanceof Blob?!0:Array.isArray(b)?b.some(De):b!==null&&typeof b=="object"?Object.values(b).some(De):!1}function Kt(b){return Object.values(b).some(e=>e instanceof Blob?!1:Array.isArray(e)?e.some(t=>!(t instanceof Blob)&&De(t)):De(e))}function Pe(b){return qe(F.getValues(b))}function qe(b){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 F.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 F.carryCollectedRowIdentity(r,i),i}return r},t={};for(const[r,i]of Object.entries(b))t[r]=e(i);return F.carryCollectedRowIdentity(b,t),t}function zt(b,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:b,method:String(e.method||"GET").toUpperCase(),headers:r,body:jt(e.body||null)})}const p=class p{constructor(e,t=null,r=null){this.reentrantBind=!1,this.suppressEmptyReplaceBind=!1,this.requestUserEditSequence=null,this.downloadReceivedBytes=0,this.downloadTotalBytes=null,this.downloadFolder=null,this.twoWayCommitBind=!1,this.skipped=!1,this.operationSequence=r!=null?w.nextOperationSequence():w.nextSequence(),p.isElementFragment(e)?(this.options=p.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static recordClickOutcome(e,t){p.CLICK_OUTCOMES.set(e,t)}static takeClickOutcome(e){const t=p.CLICK_OUTCOMES.get(e);return t?(p.CLICK_OUTCOMES.delete(e),t):null}static attrName(e,t,r=!1){return e?`${l.prefix}${e}-${t}`:r?`${l.prefix}fetch-${t}`:`${l.prefix}${t}`}static resolveSelectorTargets(e,t,r){const i=J.read(e,t),n=[];if(i)J.queryAll(i,t).forEach(a=>{const o=D.get(a);o&&n.push(o)}),n.length===0&&m.error("Haori",`Element not found: ${i} (${t})`);else if(r==="error-click")m.error("Haori",`${t} にはクリックする要素のセレクタが必要です。`);else if(r==="open"||r==="close"||r==="error-close"){const s=e.getTarget().closest("dialog");s?n.push(D.get(s)):m.error("Haori",`Ancestor <dialog> not found (${t})`)}else n.push(e);return n}static readToastLevel(e,t,r,i){return p.toToastLevel(p.readLateAttribute(e,t,r,i))}static readErrorStatusActions(e,t,r){const i=p.attrName(r,"error-"),n=new Set;for(const a of e.getAttributeNames()){if(!a.startsWith(i))continue;const o=Bt.exec(a.slice(i.length));o&&n.add(o[1])}const s=new Map;return n.forEach(a=>{const o=`error-${a}`,c=u=>p.attrName(r,`${o}-${u}`);s.set(Number(a),{key:o,clickFragments:e.hasAttribute(c("click"))?p.resolveSelectorTargets(e,c("click"),"error-click"):null,clickAwait:e.hasAttribute(c("click-await")),closeFragments:e.hasAttribute(c("close"))?p.resolveSelectorTargets(e,c("close"),"error-close"):null,toastMessage:p.readLateAttribute(e,t,`${o}-toast`,c("toast")),toastLevel:p.readToastLevel(e,t,`${o}-toast-level`,c("toast-level")),noMessage:e.hasAttribute(c("no-message"))})}),s}static toToastLevel(e){return Ot.includes(e)?e:null}static parseErrorStatuses(e,t){const r=[];for(const i of(e??"").split("&")){const n=i.trim();/^\d{3}$/.test(n)?r.push(Number(n)):m.warn("Haori",`${t} の "${n}" は 3 桁のステータスではないため無視します。`)}return r}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 normalizeAttributeText(e){return e?String(e):null}static readFetchHeaders(e,t){if(!e.hasAttribute(t))return null;const r=e.getRawAttribute(t);let i;try{i=$.parseDataBind(r)}catch(n){return m.error("Haori",`Invalid fetch headers: ${n}`),null}return i===null||typeof i!="object"||Array.isArray(i)?(m.warn("Haori",`${t} はヘッダー名と値のオブジェクトで指定してください(${Array.isArray(i)?"配列":`${typeof i} 型の値`}が指定されたため、ヘッダーは設定しません)。`),null):i}static hasDeclaredContentType(e){return!e||typeof e!="object"?!1:Object.keys(e).some(t=>t.toLowerCase()==="content-type")}static withContentType(e,t){const r={};return e&&typeof e=="object"&&Object.entries(e).forEach(([i,n])=>{i.toLowerCase()!=="content-type"&&(r[i]=n)}),r["Content-Type"]=t,r}static invokeFetch(e,t){try{return fetch(e,t)}catch(r){return Promise.reject(r)}}static unescapeNewlines(e){return typeof e=="string"?e.replace(/\\n/g,`
12
+ `))}static record(e,t,r){if(!q.isEnabled()||!e||t.length===0||(C.ensureGlobalAccess(),!C.isCollecting()))return;const i=C.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const s=C.getOrCreateCounter(i.attributes,e.rawName,e.template);C.updateCounter(s,t,r);return}const n=C.getOrCreateCounter(i.texts,String(e.childIndex),e.template);C.updateCounter(n,t,r)}static ensureGlobalAccess(){if(!q.isEnabled())return;const e=globalThis;e[C.GLOBAL_KEY]===void 0&&(e[C.GLOBAL_KEY]={start:()=>C.start(),stop:()=>C.stop(),reset:()=>C.reset(),snapshot:()=>C.snapshot(),report:t=>C.report(t)})}static getOrCreateElementStore(e){const t=C.createElementId(e),r=C.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return C.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=C.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){if(!C.isCollecting())return{value:e(),durationMs:0};const t=C.now();return{value:e(),durationMs:C.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(`${l.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${l.prefix}derive-name="${s.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};C.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",C.ELEMENT_STORES=new Map,C.collecting=!1,C.DEFAULT_REPORT_LIMIT=20;let $e=C;const de=class de{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.skipMutationNodeSet=new Set,this.target=e,de.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(de.FRAGMENT_CACHE.has(e))return de.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new w(e);break;case Node.TEXT_NODE:t=new ne(e);break;case Node.COMMENT_NODE:t=new He(e);break;default:return m.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}static peek(e){return de.FRAGMENT_CACHE.get(e)??null}isSkipMutationNode(e){return this.skipMutationNodeSet.has(e)}holdSkipMutationNode(e){this.skipMutationNodeSet.add(e)}releaseSkipMutationNode(e){this.skipMutationNodeSet.delete(e)}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return e.holdSkipMutationNode(this.target),K.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode===e.getTarget()&&e.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{e.skipMutationNodes=t,e.releaseSkipMutationNode(this.target)})}else{const e=this.target.parentNode;if(e)return K.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 e.holdSkipMutationNode(this.target),K.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode!==e.getTarget()&&e.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{e.skipMutationNodes=t,e.releaseSkipMutationNode(this.target)})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(e){this.mounted=e}remove(e=!0){return this.parent&&this.parent.removeChild(this),de.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};de.FRAGMENT_CACHE=new WeakMap;let D=de;const S=class S extends D{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.initialized=!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,S.dropFollowUpArtifacts(e),this.syncValue(),this.initialBindAttribute=e.getAttribute(`${l.prefix}bind`),e.getAttributeNames().forEach(i=>{const n=e.getAttribute(i);if(n!==null&&!this.attributeMap.has(i)){const s=new Ce(i,n);this.attributeMap.set(i,s)}});let t=null;const r=[];e.childNodes.forEach(i=>{if(S.isOwnedWithinExternal(i))return;const n=D.peek(i)?.getParent()??null,s=D.get(i);n!==null&&n!==this&&(t=t??n,n===t&&r.push(s)),s.setParent(this),this.children.push(s)}),t!==null&&this.takeOverPlaceOf(t,r)}takeOverPlaceOf(e,t){const r=e.children,i=t.map(s=>r.indexOf(s)).filter(s=>s>=0).sort((s,a)=>s-a);if(i.length===0)return;const n=i[0];i.slice().reverse().forEach(s=>r.splice(s,1)),r.splice(n,0,this),this.setParent(e)}static isOwnedWithinExternal(e){const r=D.peek(e)?.getParent()??null;if(r===null)return!1;const i=r.getTarget().closest(`[${l.prefix}external]`);return i!==null&&i.contains(e)}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof S)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){m.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new S(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.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}static dropFollowUpArtifacts(e){S.dropIfVisibilityArtifacts(e),e.removeAttribute(`${l.prefix}each-done`),e.removeAttribute(`${l.prefix}importing`)}static dropIfVisibilityArtifacts(e){e.hasAttribute(`${l.prefix}if-false`)&&(e.style.removeProperty("display"),e.getAttribute("style")?.trim()===""&&e.removeAttribute("style"),e.removeAttribute(`${l.prefix}if-false`),S.forEachFormControlInBranch(e,t=>{t.hasAttribute(fe)&&(t.removeAttribute(fe),t.removeAttribute("disabled"))}))}remove(e=!0){const t=[];return e&&te.destroySubtree(this.getTarget()),this.getTarget().hasAttribute(`${l.prefix}external`)?this.detachPreservingSubtree(e):(this.children.slice().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(()=>{}))}detachPreservingSubtree(e){const t=this.getParent();return t&&t.removeChild(this),e?this.unmount():Promise.resolve()}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=this.withRetainedReservedKeys(e),this.clearBindingDataCache()}withRetainedReservedKeys(e){const t=this.bindingData;if(t===null)return e;const r={};for(const i of Object.keys(t))S.isReservedBindingKey(i)&&(r[i]=t[i]);return{...r,...e}}static isReservedBindingKey(e){return e.startsWith("_")}isExecutingBindingWork(){return this.bindingWorkActive>0}static isExecutingAnyBindingWork(){return S.bindingWorkActiveCount>0}markBindingWorkStart(){this.bindingWorkActive++,S.bindingWorkActiveCount++}markBindingWorkEnd(){this.bindingWorkActive>0&&(this.bindingWorkActive--,S.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 S&&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}isInitialized(){return this.initialized}markInitialized(){this.initialized=!0}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():K.enqueue(()=>{i.value=""})):(m.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):(m.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(()=>{if(this.isSupersededByUserEdit(s)||r&&!this.canApplyValue(r))return;const a=i.value;i.value=n,this.recordValueWriteResult(i.value===n),i.value!==a&&S.notifyValueToEnhancers(i),t&&((i instanceof HTMLInputElement&&S.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 c=e.includes(o.value);o.selected!==c&&(o.selected=c,s=!0),c&&a.add(o.value)}),this.recordValueWriteResult(e.every(o=>a.has(o))),s&&S.notifyValueToEnhancers(i),s&&t&&i.dispatchEvent(new Event("change",{bubbles:!0}))})}enqueueValueWrite(e){this.skipChangeValue=!0;const t=K.enqueue(e).finally(()=>{this.skipChangeValue=!1});return this.pendingValueWrite=t,t}isSupersededByUserEdit(e){return this.userEditSequence!==e}static retryUnappliedValueWrites(e,t){if(S.UNAPPLIED_VALUE_WRITES.size===0)return Promise.resolve();const r=[];for(const i of Array.from(S.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()}static notifyValueToEnhancers(e){te.isApplied(e)&&te.refreshSubtree(e)}clearUnappliedValueWrite(){this.valueWriteUnapplied=!1,S.UNAPPLIED_VALUE_WRITES.delete(this)}getValue(){return this.value}static currentSequence(){return S.sequenceCounter}static nextSequence(){return S.sequenceCounter+=1,S.sequenceCounter}static setPendingMutationFlusher(e){S.pendingMutationFlusher=e}static nextOperationSequence(){return S.pendingMutationFlusher&&!S.isExecutingAnyBindingWork()&&S.pendingMutationFlusher(),S.nextSequence()}canApplyValue(e){return e.kind==="nonSupply"&&e.editedPaths!==void 0&&this.userEditSequence>0&&this.wasResetAfter(this.userEditSequence)?!1:S.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 S.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=S.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=S.currentSequence()){e>this.authoritativeValueSequence&&(this.authoritativeValueSequence=e),this.lastValueKind==="edit"&&this.lastValueSequence<=e&&(this.lastValueKind="supply")}static warnUnresolvedAttribute(e,t,r,i){if(!q.isEnabled())return;const n=`${e} ${r}`;S.loggedUnresolvedAttributes.has(n)||(S.loggedUnresolvedAttributes.add(n),m.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))}static warnTypeMismatchedComparison(e,t,r,i){const n=`${e} ${t}`;S.loggedTypeMismatchedComparisons.has(n)||(S.loggedTypeMismatchedComparisons.add(n),m.warn("[Haori]",`The strict comparison compares different types (${r.left} vs ${r.right}), so it is always false even though the values match. Align the types (for example with ${l.prefix}value-type) or compare converted values: ${e}="${t}"`,i))}hasPendingCheckableUserEdit(e){if(!e)return this.hasPendingUserEdit();const t=this.getTarget().closest("select");if(!t)return!1;const r=D.get(t);return r instanceof S?r.hasPendingUserEdit():!1}clearValue(){this.value=null,this.clearUnappliedValueWrite()}normalizeValueForElement(e,t){const r=S.resolveDeclaredValueType(e);return r==="boolean"?S.normalizeBooleanValue(t):r==="string"?t===null?null:String(t):r==="number"||r===null&&e instanceof HTMLInputElement&&e.type==="number"?S.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"||!S.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(`${l.prefix}value-type`);if(t===null)return null;const r=t.trim().toLowerCase();return S.VALUE_TYPE_NAMES.has(r)?S.acceptsDeclaredValueType(e)?r:(S.warnValueTypeDeclaration(e,t,"値を持つ入力(checkbox / radio / file と複数選択の select を除く)にのみ指定できます"),null):(S.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(!q.isEnabled())return;const i=e instanceof HTMLInputElement?`[type=${e.type}]`:"",n=`${e.tagName}${i} ${t} ${r}`;S.loggedValueTypeDeclarations.has(n)||(S.loggedValueTypeDeclarations.add(n),m.warn("Haori",`${l.prefix}value-type="${t}" を無視しました(${r}):`,e))}static isValuePropertyTarget(e){return e instanceof HTMLInputElement?S.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(S.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,S.UNAPPLIED_VALUE_WRITES.add(this);return}this.clearUnappliedValueWrite()}getValueForCollection(){return this.skipChangeValue||this.valueWriteUnapplied?this.value:S.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=D.get(t);r instanceof S&&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=K.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 Ce(e,r);if(n){const Se=this.attributeMap.get(e);if(Se&&(Se.isEvaluate||Se.isForceEvaluation())&&!o.isEvaluate&&!o.isForceEvaluation()){const ke=K.enqueue(()=>{}).finally(()=>{this.releaseSelfWritingAttributes(s)});return this.holdSelfWritingAttributes(s,ke),ke}}this.attributeMap.set(e,o);const c=this.getTarget(),u=o.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:c,rawName:e,template:r}),d=o.isEvaluate||o.isRawEvaluate,g=e===t&&S.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),y=o.isSingleExpression(),A=ue.joinEvaluateResults(u.results),E=u.results.length===1?u.results[0]:A,I=t==="value"&&S.resolveDeclaredValueType(c)==="boolean",x=E===!1&&!I,H=!o.isForceEvaluation()&&(t!==e?u.hasUnresolvedReference||E===null||E===void 0||x:g?u.hasUnresolvedReference||E===null||E===void 0||E===!1:y?u.hasUnresolvedReference||E===null||E===void 0||x:d&&A==="");if(H&&u.hasUnresolvedReference&&S.warnUnresolvedAttribute(e,t,r,c),q.isEnabled()&&E===!1&&y){const Se=o.getSingleExpression(),ke=Se===null?null:re.diagnoseStrictComparison(Se,this.getBindingData());ke!==null&&S.warnTypeMismatchedComparison(e,r,ke,c)}const k=o.isForceEvaluation()?r:y?E:A,j=i&&o.isEvaluate&&t==="value"&&S.isValuePropertyTarget(c),Z=c.getRootNode(),ee=j&&S.isUserEditableValue(c)&&(c===Z.activeElement||this.hasPendingUserEdit()),L=H||k===null||k===!1&&!I?null:String(k),ae=e!==t&&c.getAttribute(e)!==r,G=L===null?c.hasAttribute(t):c.getAttribute(t)!==L,T=L===null?"":L,O=j&&!ee&&c.value!==T,Y=t==="checked"&&c instanceof HTMLInputElement&&(c.type==="checkbox"||c.type==="radio"),Q=t==="selected"&&c instanceof HTMLOptionElement,ye=Z.activeElement,le=ye!==null&&(Y&&c===ye||Q&&c.closest("select")===ye)||(Y||Q)&&this.hasPendingCheckableUserEdit(Q),W=L!==null,z=Y&&o.isEvaluate&&!le&&c.checked!==W,X=Q&&o.isEvaluate&&!le&&c.selected!==W;if(!ae&&!G&&!O&&!z&&!X)return j&&!ee&&(this.value=this.normalizeValueForElement(c,T),this.clearUnappliedValueWrite()),(Y||Q)&&!le&&this.syncCheckableValueFromDom(Q),Promise.resolve();const Ie=K.enqueue(()=>{ae&&c.setAttribute(e,r),L===null?c.removeAttribute(t):G&&(c.setAttribute(t,L),t===`${l.prefix}bind`&&this.recordSelfWrittenBind(L)),t==="style"&&this.captureAndHideDisplay(),j&&!ee&&(this.value=this.normalizeValueForElement(c,T),O&&(c.value=T),this.recordValueWriteResult(c.value===T)),z&&(c.checked=W),X&&(c.selected=W),(z||X)&&this.syncCheckableValueFromDom(X)}).finally(()=>{this.releaseSelfWritingAttributes(s)});return this.holdSelfWritingAttributes(s,Ie),Ie}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=K.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:ue.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=D.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.isSkipMutationNode(e.getTarget()))return Promise.resolve();if(e===this)return m.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let n=this.parent;for(;n;)i.add(n),n=n.getParent();if(i.has(e))return m.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=e.getParent()===this;let a=-1,o=-1;s&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const c=e.getParent();c!==null&&c.removeChild(e);let u=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let g;if(s?a!==-1&&a<o?g=o-1:g=o:g=this.children.indexOf(t),g===-1){const y=this.resolveInsertionPointFromDom(t,!1);y===null?(m.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(y.index,0,e),u=y.referenceNode)}else this.children.splice(g,0,e)}e.setParent(this),e.setMounted(this.mounted);const d=this.skipMutationNodes;return this.skipMutationNodes=!0,this.holdSkipMutationNode(e.getTarget()),K.enqueue(()=>{this.target.insertBefore(e.getTarget(),u)}).finally(()=>{this.skipMutationNodes=d,this.releaseSkipMutationNode(e.getTarget())})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(m.warn("[Haori]","Reference child not found in children.",t),this.insertBefore(e,null)):this.insertBefore(e,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(e,this.children[r+1]||null)}getPrevious(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<=0?null:t[r-1]}getNext(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<0||r+1>=t.length?null:t[r+1]}isVisible(){return this.visible}captureAndHideDisplay(){if(this.visible)return;const e=this.getTarget().style;this.display=e.getPropertyValue("display"),this.displayPriority=e.getPropertyPriority("display"),e.setProperty("display","none","important")}hideDisplayWithoutCapture(){if(this.visible)return;const e=this.getTarget().style;e.getPropertyValue("display")==="none"&&e.getPropertyPriority("display")==="important"||e.setProperty("display","none","important")}static reassertHiddenDisplay(e){const t=D.get(e);t instanceof S&&t.hideDisplayWithoutCapture()}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const e=this.getTarget();return this.captureAndHideDisplay(),e.setAttribute(`${l.prefix}if-false`,""),S.disableFormControlsInBranch(e),Promise.resolve()}static forEachFormControlInBranch(e,t){e.matches(ut)&&t(e);const r=i=>{Array.from(i.children).forEach(n=>{n.hasAttribute(`${l.prefix}if-false`)||(n instanceof HTMLElement&&n.matches(ut)&&t(n),r(n))})};r(e)}static disableFormControlsInBranch(e){S.forEachFormControlInBranch(e,t=>{t.hasAttribute("disabled")||(t.setAttribute(fe,""),t.setAttribute("disabled",""))})}restoreFormControlsDisabledByIf(){S.forEachFormControlInBranch(this.getTarget(),e=>{e.hasAttribute(fe)&&(e.removeAttribute(fe),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(`${l.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)}};S.NUMBER_INPUT_PATTERN=/^-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/,S.VALUE_TYPE_NAMES=new Set(["boolean","number","string"]),S.loggedValueTypeDeclarations=new Set,S.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"]),S.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],S.UNAPPLIED_VALUE_WRITES=new Set,S.sequenceCounter=0,S.bindingWorkActiveCount=0,S.pendingMutationFlusher=null,S.loggedUnresolvedAttributes=new Set,S.loggedTypeMismatchedComparisons=new Set;let w=S;class ne extends D{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new ue(this.text)}clone(){const e=new ne(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 ue(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):K.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=ue.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 He extends D{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new He(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,K.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const Le=class Le{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(Le.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)}getSingleExpression(){return this.isSingleExpression()?this.contents[0].text:null}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(m.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const n=[],s=[];let a=0,o=!1;return this.contents.forEach(c=>{try{if(r(c)){const u=$e.measure(()=>re.evaluateDetailed(c.text,e)),d=u.value;a+=u.durationMs,s.push({expression:c.text,durationMs:u.durationMs}),o=o||d.unresolvedReference,n.push(d.value)}else n.push(c.text)}catch(u){m.error("[Haori]",`Error evaluating ${i} expression: ${c.text}`,u),s.push({expression:c.text,durationMs:0}),n.push("")}}),$e.record(t,s,a),{results:n,hasUnresolvedReference:o}}};Le.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let ue=Le;const ie=class ie extends ue{constructor(e,t){super(t),this.forceEvaluation=ie.needsForceEvaluation(e)}static needsForceEvaluation(e){if(ie.forceEvaluationNames===null||ie.forceEvaluationPrefix!==l.prefix){const t=new Set;for(const r of[l.prefix,...ie.FORCE_EVALUATION_PREFIXES])for(const i of ie.FORCE_EVALUATION_SUFFIXES)t.add(`${r}${i}`);ie.forceEvaluationNames=t,ie.forceEvaluationPrefix=l.prefix}return ie.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?(m.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};ie.FORCE_EVALUATION_SUFFIXES=["if","each","derive"],ie.FORCE_EVALUATION_PREFIXES=["data-","hor-"],ie.forceEvaluationNames=null,ie.forceEvaluationPrefix=null;let Ce=ie;const ve=class ve{static get runtime(){return l.runtime}static setRuntime(e){l.setRuntime(e)}static waitForRenders(){return K.waitForIdle()}static dialog(e){return K.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 K.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return K.enqueue(()=>{e instanceof HTMLDialogElement?(ve.clearMessagesSync(e),e.showModal()):m.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return K.enqueue(()=>{e instanceof HTMLDialogElement?e.close():m.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return ve.addMessage(e,t,"error")}static addMessage(e,t,r){return K.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 K.enqueue(()=>{ve.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 Ne(e,t,r)}static now(e,t){return Qe(e,t)}static today(e,t,r){return _e(e,t,r)}static number(e,t){return et(e,t)}static range(e,t,r){return tt(e,t,r)}static pages(e,t,r){return rt(e,t,r)}static monthAdd(e,t){return Me(e,t)}static monthRange(e,t){return it(e,t)}static pageSummary(e,t){return nt(e,t)}static findBy(e,t,r){return st(e,t,r)}static sum(e,t){return at(e,t)}static distinct(e,t){return lt(e,t)}static groupBy(e,t){return ct(e,t)}};ve.enhancers={register(e,t){te.register(e,t)},has(e){return te.has(e)}};let oe=ve;const It="入力内容を確認してください",kt=["addErrorMessage","clearMessages"],dt="data-haori-group-name";function ft(){const e=globalThis.window?.Haori;return kt.every(r=>typeof e?.[r]=="function")?e:oe}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(`${l.prefix}form-name`);return t||e.getAttribute("name")}static clearRowUserEditMarksForChangedKeys(e,t){const r=h.getValues(e),i=new Set;for(const n of new Set([...Object.keys(r),...Object.keys(t)]))h.isSameCollectedValue(r[n],t[n])||i.add(n);i.size!==0&&h.clearUserEditMarksForKeys(e,e,i)}static isSameCollectedValue(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}static clearUserEditMarksForKeys(e,t,r){const i=h.resolveRowTopLevelKey(e,t);i!==null&&r.has(i)&&e.clearUserEditMark(),e.getChildElementFragments().forEach(n=>{h.clearUserEditMarksForKeys(n,t,r)})}static resolveRowTopLevelKey(e,t){let r=null,i=e;for(;i!==null&&i!==t;){const n=i.getAttribute(`${l.prefix}form-object`)||i.getAttribute(`${l.prefix}form-list`)||h.resolveFieldName(i);n!=null&&String(n)!==""&&(r=String(n)),i=i.getParent()}return r}static prepareFormName(e){if(!e.hasAttribute(`${l.prefix}form-name`))return;const t=e.getAttribute(`${l.prefix}form-name`);if(!t){m.warn("Haori",`${l.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(dt))return;const i=h.resolveGroupScope(e),n=`${String(t)}--haori${h.resolveGroupScopeId(i)}`;if(r.getAttribute("name")!==n)return e.setAttribute(dt,"").then(()=>e.setAttribute("name",n))}static resolveGroupScope(e){let t=e,r=t.getParent();for(;r!==null;){if(r.hasAttribute(`${l.prefix}form-list`))return t;if(r.getTarget()instanceof HTMLFormElement||r.hasAttribute(`${l.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=D.get(r);if(i instanceof w&&h.hasDeclarativeBinding(i,"selected")&&!h.isDeclarationResolved(i,"selected"))return!1}return!0}return!1}static isDeclarationResolved(e,t){for(const r of[`${l.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"):w.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 w&&h.clearDeclarativeStateFromDom(t)})}static hasDeclarativeBinding(e,t){if(e.hasAttribute(`${l.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=D.get(t);if(r instanceof w&&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 c of o)n.has(c)||n.set(c,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 isResettingInternally(){return h.internalResetDepth>0}static getPartValues(e,t,r=null,i=null){if(e.hasAttribute(`${l.prefix}form-detach`))return t;if(e.getTarget().hasAttribute(`${l.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(`${l.prefix}form-object`),a=e.getAttribute(`${l.prefix}form-list`),o=e.hasAttribute(`${l.prefix}form-list`),c=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]=[]),!c&&d.checked&&(Array.isArray(t[u])||(t[u]=[]),t[u].push(d.value))}else if(o&&c)Array.isArray(t[String(n)])?t[String(n)].push(null):t[String(n)]=[null];else if(!c)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,g=u instanceof HTMLInputElement?u.value:e.getValue(),y=d?g:null,A=String(n);y===null?A in t||(t[A]=null):t[A]===null||t[A]===void 0?t[A]=y:Array.isArray(t[A])?t[A].push(y):t[A]=[t[A],y]}else t[String(n)]=h.resolveCollectedValue(e);s&&m.warn("Haori",`Element cannot have both ${l.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 g of e.getChildElementFragments())h.getPartValues(g,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&&m.warn("Haori",`Element cannot have both ${l.prefix}form-list and ${l.prefix}form-object attributes.`)}else if(a){const u=[],d=[];let g=!1;for(const y of e.getChildElementFragments()){const A={},E=i===null?null:new Set;h.getPartValues(y,A,r,E),E!==null&&h.registerCollectedExcludedKeys(A,E),Object.keys(A).length>0?(g=!0,u.push(A),d.push(y.getListKey())):r!==null&&(u.push({}),d.push(y.getListKey()))}if(r===null){const y=e.getAttribute(`${l.prefix}each-key`);h.registerCollectedRowIdentity(u,y==null?null:String(y),d,h.isCollectedListFromEachSource(e)),h.warnDerivedRowsWithoutKey(e),t[String(a)]=u}else g&&(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(`${l.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 resolveAncestorKeyOwner(e,t){let r=e.getParent();for(;r;){const i=r.getRawBindingData();if(i&&Object.prototype.hasOwnProperty.call(i,t))return r.getListKey()!==null?null:{owner:r,value:i[t]};r=r.getParent()}return null}static resolveAncestorArgOwner(e,t){const r=h.resolveAncestorKeyOwner(e,t);if(r===null)return null;const i=h.asPlainRecord(r.value);return i===null?(h.warnArgOwnerIsNotRecord(e,t,r.value),null):{owner:r.owner,value:i}}static ancestorBaseResolver(e){return t=>h.resolveAncestorKeyOwner(e,t)?.value}static warnArgOwnerIsNotRecord(e,t,r){if(!q.isEnabled()||r==null)return;const i=e.getTarget(),n=h.warnedArgOwnerNotRecord.get(i);n?.has(t)||(n?n.add(t):h.warnedArgOwnerNotRecord.set(i,new Set([t])),m.warn("[Haori]",`${l.prefix}form-arg="${t}" のキーを祖先が${Array.isArray(r)?"配列":`${typeof r} 型の値`}で持っています。${l.prefix}form-arg はそのキーの配下に入力欄が対応することを宣言するため、値はレコード(オブジェクト)である必要があります。このままでは収集値がそのキーへ直接入り、値の型が変わります。`))}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(`${l.prefix}each`)&&i.hasAttribute(`${l.prefix}form-list`)){const n=i.getRawAttribute(`${l.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(`${l.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=`${l.prefix}form-object`,s=`${l.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],[${l.prefix}form-name],[${n}],[${s}]`;return r.querySelectorAll(o).forEach(c=>{if(!(c instanceof HTMLElement))return;let u=null,d=!1,g=c;for(;g&&g!==r;)g.hasAttribute(`${l.prefix}form-detach`)&&(d=!0),(g.hasAttribute(n)||g.hasAttribute(s))&&(u=g),g=g.parentElement;if(d)return;const y=u??c,A=y.getAttribute(n)||y.getAttribute(s)||y.getAttribute(`${l.prefix}form-name`)||y.getAttribute("name");A&&t.add(A)}),t}static applyCustomValidity(e){const t=`${l.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)){m.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=re.evaluateDetailed(h.unwrapConditionExpression(i),n);if(s.unresolvedReference){m.warn("Haori",`${t} の参照が解決できないため無効として扱います: ${i}`),r.setCustomValidity(h.resolveValidityMessage(e));return}r.setCustomValidity(s.value?"":h.resolveValidityMessage(e))}static resolveValidityMessage(e){const t=e.getAttribute(`${l.prefix}validity-message`);return typeof t=="string"&&t.trim()!==""?t:It}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(!q.isEnabled()||!e)return;const r=`${l.prefix}validity`;(e.hasAttribute(r)||e.getTarget().querySelector(`[${r}]`)!==null)&&m.warn("Haori",`${r} は指定されていますが検証は行われません(${t})。${l.prefix}{event}-validate を指定するか、${l.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){!q.isEnabled()||h.warnedPositionalRowFallbacks.has(e)||(h.warnedPositionalRowFallbacks.add(e),m.warn("[Haori]",`${l.prefix}form-list の行を出現順で対応付けます(${e})。配列と画面の行数・並びが一致していない場合、行の値を取り違えます。`))}static warnDerivedRowsWithoutKey(e){if(!q.isEnabled()||e.getRawAttribute(`${l.prefix}each-key`)!==null)return;const t=e.getRawAttribute(`${l.prefix}each`);t===null||h.resolveLeadingPath(t)!==null||h.warnedDerivedRowsWithoutKey.has(t)||(h.warnedDerivedRowsWithoutKey.add(t),m.warn("[Haori]",`${l.prefix}each="${t}" の一覧を ${l.prefix}form-list で収集していますが、${l.prefix}each-key がありません。行と配列要素を出現順で対応付けるため、画面に出ていない要素があると行の値を取り違えます。${l.prefix}each-key を宣言してください。`))}static mergeCollectedValues(e,t,r=null){const i={...e??{}};for(const[s,a]of Object.entries(t)){if(h.UNSAFE_MERGE_KEYS.has(s))continue;const o=e&&Object.prototype.hasOwnProperty.call(e,s)?e[s]:r?.(s);i[s]=h.overlayCollectedValue(o,a)}const n=h.COLLECTED_EXCLUDED_KEYS.get(t);if(n)for(const s of n)s in t||delete i[s];return i}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(`${l.prefix}form-list`);if(t==null||t==="")return!0;const r=e.getRawAttribute(`${l.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=$.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=e.slice();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 c=o.shift();n[c]=h.overlayCollectedValue(e[c],t[s])}return n}static syncAncestorArgForms(e,t,r=null,i=null){const n=[];for(const{form:a,key:o}of h.collectArgForms(e)){if(a.wasResetAfter(t))continue;const c=h.resolveAncestorArgOwner(a,o);!c||c.owner!==e||n.push(h.pushAncestorArgValue(a,o,c.value,r))}const s=e.getRawBindingData();for(const{form:a,keys:o}of h.collectShadowingContainers(e)){if(a.wasResetAfter(t))continue;const c=o.filter(u=>h.createArgValueSignature(i?.[u])!==h.createArgValueSignature(s?.[u]));c.length!==0&&n.push(h.releaseOwnCopy(a,c,r))}return Promise.all(n).then(()=>{})}static collectShadowingContainers(e){const t=`${l.prefix}form-arg`,r=[];return e.getTarget().querySelectorAll(`form:not([${t}]), [${l.prefix}form]`).forEach(i=>{const n=D.get(i);if(!(n instanceof w))return;const s=n.getRawBindingData();if(s===null)return;const a=h.getInitialBindingData(n),o=Object.keys(s).filter(c=>Object.prototype.hasOwnProperty.call(a??{},c)?!1:h.resolveAncestorKeyOwner(n,c)?.owner===e);o.length>0&&r.push({form:n,keys:o})}),r}static releaseOwnCopy(e,t,r=null){const i=e.getRawBindingData();if(i===null)return Promise.resolve();const n={...i};for(const s of t)delete n[s];return $.setBindingData(e.getTarget(),n,{kind:r?.kind??"supply",sequence:r?.sequence??w.nextSequence()})}static collectArgForms(e){const t=`${l.prefix}form-arg`,r=e.getTarget().querySelectorAll(`form[${t}]`),i=[];return r.forEach(n=>{const s=D.get(n);if(!(s instanceof w))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();return a&&Object.prototype.hasOwnProperty.call(a,t)?h.releaseOwnCopy(e,[t],i):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=D.get(i);if(!(n instanceof w))continue;const s=n.getRawBindingData(),a=n.getAttribute(`${l.prefix}form-arg`),o=a?String(a):null,c=o!==null&&!(s&&Object.prototype.hasOwnProperty.call(s,o))?h.resolveAncestorArgOwner(n,o):null;if(!(!s&&!c)){if(h.INITIAL_RESTORED_FORMS.add(i),c){r.push(h.pushAncestorArgValue(n,o,c.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(`${l.prefix}form-object`)||e.getAttribute(`${l.prefix}form-list`))}static resolveCollectionScope(e){let t=e,r=t.getParent();for(;r!==null;){if(h.startsCollectionLevel(r))return r.getAttribute(`${l.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(`${l.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(`${l.prefix}form-detach`)||i.getTarget().hasAttribute(`${l.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(`${l.prefix}form-detach`)&&!r)return Promise.resolve();const c=h.resolveFieldName(e),u=e.getAttribute(`${l.prefix}form-object`),d=e.getAttribute(`${l.prefix}form-list`),g=e.hasAttribute(`${l.prefix}form-list`);if(c){const y=t[String(c)],A=n&&h.hasResolvedDeclarativeState(e),E=n&&typeof y>"u"&&!h.isDeclarativeStateBound(e);let I=y;if(A?I=void 0:E&&(I=null),h.isFileInput(e))return(I===null||I==="")&&o.push(h.applyFragmentValue(e,null,i,a)),Promise.all(o).then(()=>{});if(g&&Array.isArray(I)&&!h.isGroupedCheckable(e)&&!h.isMultipleSelect(e)){const x=String(c),H=s.get(x)??0;s.set(x,H+1),o.push(h.applyFragmentValue(e,I[H]??null,i,a))}else typeof I>"u"||(Array.isArray(I)&&h.isGroupedCheckable(e)||Array.isArray(I)&&h.isMultipleSelect(e)||typeof I=="string"||typeof I=="number"||typeof I=="boolean"||I===null?o.push(h.applyFragmentValue(e,I,i,a)):o.push(h.applyFragmentValue(e,String(I),i,a)))}else if(u){const y=t[String(u)];if(y&&typeof y=="object"){const A=new Map;for(const E of e.getChildElementFragments())o.push(h.setPartValues(E,y,r,i,n,A,a))}}else if(d){const y=t[String(d)];if(Array.isArray(y)){const A=e.getChildElementFragments(),E=e.getAttribute(`${l.prefix}each-key`),I=h.isCollectedListFromEachSource(e)?h.pairRowsWithItems(A,y,E==null?null:String(E)):null;for(let x=0;x<A.length;x++){const H=A[x],k=I?I[x]:y.length>x?y[x]:null;o.push(h.setPartValues(H,h.asPlainRecord(k)??{},r,i,n,new Map,a))}}}else for(const y of e.getChildElementFragments())o.push(h.setPartValues(y,t,r,i,n,s,a));return Promise.all(o).then(()=>{})}static async reset(e,t=w.nextSequence()){const r=h.collectBindingTargetForms(e);if(r.length>0&&r.every(n=>n.isSupplyStale(t)))return;h.markResetSubtree(e,t),$.clearUserEditMarks(e,t),h.clearValues(e),await Promise.all([h.clearMessages(e),h.clearEachClones(e)]),await K.enqueue(()=>{const n=h.collectEditsAfter(e,t),s=e.getTarget();h.internalResetDepth+=1;try{s instanceof HTMLFormElement?s.reset():(s.querySelectorAll("form").forEach(a=>a.reset()),h.restoreDefaultValues(s))}finally{h.internalResetDepth-=1}h.clearDeclarativeStateFromDom(e),$.invalidateDerivedSubtreeSignatures(e),h.restoreEdits(n)});const i=r;for(const n of i){const s=h.getInitialBindingData(n);s===null&&n.getRawBindingData()===null||await $.setBindingData(n.getTarget(),s??{},{sequence:t})}h.syncValuesFromDom(e),await $.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(`${l.prefix}form-arg`);let c={...s||{}};if(o){const u=String(o);!Object.prototype.hasOwnProperty.call(s??{},u)&&h.resolveAncestorArgOwner(n,u)!==null||(c[u]=h.mergeCollectedValues(c[u]??null,a))}else c=h.mergeCollectedValues(c,a),h.deleteAncestorOwnedKeys(n,s,c);await $.setBindingData(n.getTarget(),c,{sequence:t})}te.refreshSubtree(e.getTarget())}static deleteAncestorOwnedKeys(e,t,r){for(const i of Object.keys(r))Object.prototype.hasOwnProperty.call(t??{},i)||h.resolveAncestorKeyOwner(e,i)!==null&&delete r[i]}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:$.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=D.get(n);s instanceof w&&i.push(s)}return i}static clearEachClones(e){const t=[],r=n=>{if(n.hasAttribute(`${l.prefix}each`)){for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${l.prefix}each-before`),o=s.hasAttribute(`${l.prefix}each-after`);!a&&!o&&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(`${l.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 ft().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return h.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=ft(),a=s.addMessage,o=u=>typeof a=="function"?a.call(s,u,r,i):s.addErrorMessage(u,r),c=h.findFragmentsByKey(e,t);return c.forEach(u=>{n.push(o(u.getTarget()))}),c.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(`${l.prefix}form-object`))t.length>1&&e.getAttribute(`${l.prefix}form-object`)===i&&e.getChildElementFragments().forEach(s=>{r.push(...h.findFragmentByKeyParts(s,t.slice(1)))});else if(e.hasAttribute(`${l.prefix}form-list`)){if(t.length>1){const n=e.getAttribute(`${l.prefix}form-list`),s=i.lastIndexOf("["),a=i.lastIndexOf("]");if(s!==-1&&a!==-1&&s<a){const o=i.substring(0,s);if(n===o){const c=i.substring(s+1,a),u=Number(c);if(isNaN(u))m.error("Haori",`Invalid index: ${i}`);else{const d=e.getChildElementFragments().filter(g=>g.hasAttribute(`${l.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(`${l.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.internalResetDepth=0,h.warnedArgOwnerNotRecord=new WeakMap,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.warnedDerivedRowsWithoutKey=new Set,h.LEADING_PATH_PATTERN=/^\s*([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*)\s*([\s\S]*)$/;let F=h;class B{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){B.dispatch(document,"ready",{version:e})}static importStart(e,t){B.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){B.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){B.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 c of o){const u=t?.[c],d=r[c];u!==d&&n.push(c)}B.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){B.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){B.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){B.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){B.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){B.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){B.dispatch(e,"show",{visible:!0})}static hide(e){B.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){B.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){B.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){B.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:n?performance.now()-n:void 0})}static pollTimeout(e,t,r){B.dispatch(e,"polltimeout",{count:t,elapsedMs:r})}static pollStop(e,t,r,i){B.dispatch(e,"pollstop",{reason:t,count:r,elapsedMs:i})}}const Nt={401:"unauthorized-redirect",403:"forbidden-redirect"};function xt(b,e){return b.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=re.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function Mt(b,e){const t=b.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=D.get(b),i=r instanceof w?r.getBindingData():{},n=xt(t,i);return n===""?null:n}function $t(b,e,t){const r=b.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):"",c=a>=0?t.slice(0,a):t,u=c.includes("?")?"&":"?";return`${c}${u}${s}${o}`}function ht(b){const e=Nt[b];if(e===void 0||typeof document>"u")return!1;const t=`${l.prefix}${e}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=Mt(i,t);if(n===null)continue;const s=$t(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 J{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 m.error("Haori",`Invalid selector: ${e} (${t})`,i),[]}}static query(e,t,r=document.body){try{return r.querySelector(e)}catch(i){return m.error("Haori",`Invalid selector: ${e} (${t})`,i),null}}}const N=class N{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 N.WARNED_KINDS.has(e)||(N.WARNED_KINDS.add(e),m.warn("Haori",`${e}Storage が利用できないため ${l.prefix}store を無効にします:`,t)),null}}static isReservedKey(e){return w.isReservedBindingKey(e)}static isPlainRecord(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}static warnOnce(e,t,r){let i=N.WARNED_ELEMENTS.get(e);i||(i=new Set,N.WARNED_ELEMENTS.set(e,i)),!i.has(t)&&(i.add(t),m.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(`${l.prefix}store`);if(r===null)return null;const i=r.trim();if(i==="")return N.warnOnce(t,"key",`${l.prefix}store にストレージキーが指定されていません。`),null;if(i.includes("{{"))return N.warnOnce(t,"expression",`${l.prefix}store に式は使用できません(静的な文字列を指定してください): ${i}`),null;const n=e.getRawAttribute(`${l.prefix}store-type`);let s="session";if(n!==null){const d=n.trim();d==="local"||d==="session"?s=d:N.warnOnce(t,"type",`${l.prefix}store-type は session または local を指定してください(session として扱います): ${d}`)}const a=e.getRawAttribute(`${l.prefix}store-arg`),o=a===null||a.trim()===""?null:a.trim(),c=e.getRawAttribute(`${l.prefix}store-params`);let u=null;if(c!==null){const d=c.split("&").map(y=>y.trim()).filter(y=>y!==""),g=d.filter(y=>!N.isReservedKey(y));g.length!==d.length&&N.warnOnce(t,"reserved",`${l.prefix}store-params の予約キー(先頭が _ のキー)は対象外です。`),u=g.length>0?g:null}return u===null&&o===null?(N.warnOnce(t,"target",`${l.prefix}store には ${l.prefix}store-params または ${l.prefix}store-arg のいずれかが必要です。`),null):{key:i,kind:s,params:u,arg:o}}static readRecord(e){const t=N.resolveStorage(e.kind);if(!t)return null;let r;try{r=t.getItem(e.key)}catch(n){return m.warn("Haori",`ストレージの読み取りに失敗しました: ${e.key}`,n),null}if(r===null)return null;let i;try{i=JSON.parse(r)}catch(n){return m.warn("Haori",`保存済みデータが JSON として解釈できません: ${e.key}`,n),null}return N.isPlainRecord(i)?i:(m.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(!N.isPlainRecord(s))return m.warn("Haori",`保存済みデータの ${e.arg} がオブジェクトではありません: `+e.key),{};r=s}const i=e.params??Object.keys(r),n={};for(const s of i)N.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(N.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=N.stringify(t);if(r===null){N.SIGNATURES.delete(e);return}N.SIGNATURES.set(e,{json:r,refs:N.createRefs(t)})}static writeRecord(e,t){const r=N.resolveStorage(e.kind);if(!r)return!1;const i=N.readRecord(e)??{};if(e.arg!==null){const n=i[e.arg],s=N.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 m.warn("Haori",`ストレージへの保存に失敗しました: ${e.key}`,n),!1}}static restore(e){const t=N.readDeclaration(e);if(!t)return Promise.resolve();const r=e.getTarget();if(N.isInsideEachRow(e))return N.warnOnce(r,"each-row",`${l.prefix}each の行の内側では ${l.prefix}store を使用できません(行データは親要素側で配列キーを指定してください)。`),Promise.resolve();N.RESTORED_ELEMENTS.add(r);const i=N.readRecord(t),n=i?N.extractFromRecord(t,i):{},s={...e.getRawBindingData()??{},...n};return N.seedSignature(r,N.selectFromData(t,s)),Object.keys(n).length===0?Promise.resolve():$.setBindingData(r,s,{reentrant:!0,kind:"nonSupply",sequence:w.nextSequence()})}static mirror(e){const t=N.readDeclaration(e);if(!t||N.isInsideEachRow(e))return;const r=e.getTarget();if(!N.RESTORED_ELEMENTS.has(r))return;const i=e.getRawBindingData();if(!i)return;const n=N.selectFromData(t,i);if(Object.keys(n).length===0)return;const s=N.SIGNATURES.get(r);if(s&&N.hasSameRefs(s,n))return;const a=N.stringify(n);if(a===null){m.warn("Haori",`保存対象を直列化できないためミラーを行いません: ${t.key}`);return}if(s&&s.json===a){s.refs=N.createRefs(n);return}N.writeRecord(t,n)&&N.SIGNATURES.set(r,{json:a,refs:N.createRefs(n)})}static clear(e,t){const r=N.resolveStorage(t);if(r){try{r.removeItem(e)}catch(i){m.warn("Haori",`ストレージの破棄に失敗しました: ${e}`,i);return}N.reseedDeclaringElements(e,t)}}static reseedDeclaringElements(e,t){document.querySelectorAll(`[${l.prefix}store]`).forEach(i=>{if(!N.RESTORED_ELEMENTS.has(i))return;const n=D.get(i);if(!(n instanceof w))return;const s=N.readDeclaration(n);if(!s||s.key!==e||s.kind!==t)return;const a=n.getRawBindingData();N.seedSignature(i,a?N.selectFromData(s,a):{})})}};N.SIGNATURES=new WeakMap,N.RESTORED_ELEMENTS=new WeakSet,N.WARNED_ELEMENTS=new WeakMap,N.WARNED_KINDS=new Set;let Re=N;class pt{static readParams(){const e={},t=new URLSearchParams(window.location.search);for(const r of new Set(t.keys())){if(r==="__proto__")continue;const i=t.getAll(r);e[r]=i.length===1?i[0]:i}return 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 Ct=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],Pt="__haoriHistoryState__",Ue="data-haori-click-lock",gt="ファイルを保存できませんでした",Lt=100;let Te=null;const Ot=["info","warning","error","success"],Bt=/^(\d{3})-(click|click-await|close|toast|toast-level|no-message)$/;function he(){const e=globalThis.window?.Haori;return Ct.every(r=>typeof e?.[r]=="function")?e:oe}const Ht=new Set(["GET","HEAD","OPTIONS"]);function Ve(b){return Ht.has(b.toUpperCase())}function Ut(b,e){for(const[t,r]of Object.entries(e))r!==void 0&&(Array.isArray(r)?r.forEach(i=>{b.append(t,be(i))}):b.append(t,be(r)))}function be(b){if(b==null)return"";if(typeof b=="object"||typeof b=="function")try{return JSON.stringify(b)??""}catch{return""}return String(b)}function mt(b,e){const t=new URL(b,window.location.href),r=new URLSearchParams(t.search);return Ut(r,e),t.search=r.toString(),t.toString()}function Vt(b){if(b==null)return{payload:{},dropped:!1};if(typeof b=="string"){const e=b.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:yt(new URLSearchParams(e)),dropped:!1}:{payload:{},dropped:!0}}if(b instanceof URLSearchParams)return{payload:yt(b),dropped:!1};if(typeof FormData<"u"&&b instanceof FormData){const e={};let t=!1;for(const[r,i]of b.entries()){if(typeof i!="string"){t=!0;continue}bt(e,r,i)}return{payload:e,dropped:t}}return{payload:{},dropped:!0}}function yt(b){const e={};for(const[t,r]of b.entries())bt(e,t,r);return e}function bt(b,e,t){const r=b[e];r===void 0?b[e]=t:Array.isArray(r)?r.push(t):b[e]=[r,t]}function pe(b,e){if(F.isCompleteSetValue(e))return e;if(Array.isArray(e)){const t=Array.isArray(b)?b.slice():[];let r=!1;return e.forEach((i,n)=>{i!=null&&(typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0||(t[n]=pe(t[n],i),r=!0))}),r?t:b}if(e!==null&&typeof e=="object"){const t=b!==null&&typeof b=="object"&&!Array.isArray(b)?{...b}:{};for(const[r,i]of Object.entries(e))t[r]=pe(t[r],i);return t}return e}function qt(b){const e=b?.body;return e==null?!1:typeof e=="string"?e!=="":!0}function Wt(b,e){const t={...e||{}},r=(t.method||"GET").toUpperCase();if(l.runtime!=="demo"||Ve(r))return{url:b,options:t,requestedMethod:r,effectiveMethod:r,normalized:!1};const{payload:i,dropped:n}=Vt(t.body);let s=b;Object.keys(i).length>0&&(s=mt(s,i)),n&&m.warn("Haori",`The ${r} body cannot be converted into a query string and is dropped by the demo runtime normalization. Send the values with ${l.prefix}{event}-data / ${l.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 jt(b){return b==null?null:typeof b=="string"?b:b instanceof URLSearchParams?b.toString():b instanceof FormData?Array.from(b.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(b)}function De(b){return b instanceof Blob?!0:Array.isArray(b)?b.some(De):b!==null&&typeof b=="object"?Object.values(b).some(De):!1}function Kt(b){return Object.values(b).some(e=>e instanceof Blob?!1:Array.isArray(e)?e.some(t=>!(t instanceof Blob)&&De(t)):De(e))}function Pe(b){return qe(F.getValues(b))}function qe(b){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 F.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 F.carryCollectedRowIdentity(r,i),i}return r},t={};for(const[r,i]of Object.entries(b))t[r]=e(i);return F.carryCollectedRowIdentity(b,t),t}function zt(b,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:b,method:String(e.method||"GET").toUpperCase(),headers:r,body:jt(e.body||null)})}const p=class p{constructor(e,t=null,r=null){this.reentrantBind=!1,this.suppressEmptyReplaceBind=!1,this.requestUserEditSequence=null,this.downloadReceivedBytes=0,this.downloadTotalBytes=null,this.downloadFolder=null,this.twoWayCommitBind=!1,this.skipped=!1,this.operationSequence=r!=null?w.nextOperationSequence():w.nextSequence(),p.isElementFragment(e)?(this.options=p.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static recordClickOutcome(e,t){p.CLICK_OUTCOMES.set(e,t)}static takeClickOutcome(e){const t=p.CLICK_OUTCOMES.get(e);return t?(p.CLICK_OUTCOMES.delete(e),t):null}static attrName(e,t,r=!1){return e?`${l.prefix}${e}-${t}`:r?`${l.prefix}fetch-${t}`:`${l.prefix}${t}`}static resolveSelectorTargets(e,t,r){const i=J.read(e,t),n=[];if(i)J.queryAll(i,t).forEach(a=>{const o=D.get(a);o&&n.push(o)}),n.length===0&&m.error("Haori",`Element not found: ${i} (${t})`);else if(r==="error-click")m.error("Haori",`${t} にはクリックする要素のセレクタが必要です。`);else if(r==="open"||r==="close"||r==="error-close"){const s=e.getTarget().closest("dialog");s?n.push(D.get(s)):m.error("Haori",`Ancestor <dialog> not found (${t})`)}else n.push(e);return n}static readToastLevel(e,t,r,i){return p.toToastLevel(p.readLateAttribute(e,t,r,i))}static readErrorStatusActions(e,t,r){const i=p.attrName(r,"error-"),n=new Set;for(const a of e.getAttributeNames()){if(!a.startsWith(i))continue;const o=Bt.exec(a.slice(i.length));o&&n.add(o[1])}const s=new Map;return n.forEach(a=>{const o=`error-${a}`,c=u=>p.attrName(r,`${o}-${u}`);s.set(Number(a),{key:o,clickFragments:e.hasAttribute(c("click"))?p.resolveSelectorTargets(e,c("click"),"error-click"):null,clickAwait:e.hasAttribute(c("click-await")),closeFragments:e.hasAttribute(c("close"))?p.resolveSelectorTargets(e,c("close"),"error-close"):null,toastMessage:p.readLateAttribute(e,t,`${o}-toast`,c("toast")),toastLevel:p.readToastLevel(e,t,`${o}-toast-level`,c("toast-level")),noMessage:e.hasAttribute(c("no-message"))})}),s}static toToastLevel(e){return Ot.includes(e)?e:null}static parseErrorStatuses(e,t){const r=[];for(const i of(e??"").split("&")){const n=i.trim();/^\d{3}$/.test(n)?r.push(Number(n)):m.warn("Haori",`${t} の "${n}" は 3 桁のステータスではないため無視します。`)}return r}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 normalizeAttributeText(e){return e?String(e):null}static readFetchHeaders(e,t){if(!e.hasAttribute(t))return null;const r=e.getRawAttribute(t);let i;try{i=$.parseDataBind(r)}catch(n){return m.error("Haori",`Invalid fetch headers: ${n}`),null}return i===null||typeof i!="object"||Array.isArray(i)?(m.warn("Haori",`${t} はヘッダー名と値のオブジェクトで指定してください(${Array.isArray(i)?"配列":`${typeof i} 型の値`}が指定されたため、ヘッダーは設定しません)。`),null):i}static hasDeclaredContentType(e){return!e||typeof e!="object"?!1:Object.keys(e).some(t=>t.toLowerCase()==="content-type")}static withContentType(e,t){const r={};return e&&typeof e=="object"&&Object.entries(e).forEach(([i,n])=>{i.toLowerCase()!=="content-type"&&(r[i]=n)}),r["Content-Type"]=t,r}static invokeFetch(e,t){try{return fetch(e,t)}catch(r){return Promise.reject(r)}}static unescapeNewlines(e){return typeof e=="string"?e.replace(/\\n/g,`
13
13
  `):e}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(p.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=re.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"?p.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(p.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const c=re.evaluateDetailed(s??a??"",t);return r=r||c.unresolvedReference,p.isJsonStringContext(e,o)?p.stringifyJsonTemplateStringContent(c.value):p.stringifyJsonTemplateValue(c.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return p.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(p.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:$.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const c=p.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:$.parseDataBind(c.value),hasUnresolvedReference:s||c.hasUnresolvedReference}}const o=p.resolveDataParamStringDetailed(r,e.getBindingData());return{value:$.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e},i=t?p.attrName(t,"if"):p.attrName(null,"if",!0);if(e.hasAttribute(i)){const T=e.getRawAttribute(i);typeof T=="string"&&T.trim()!==""?(r.conditionExpression=F.unwrapConditionExpression(T),r.conditionAttributeName=i):m.warn("Haori",`${i} に条件式が指定されていません。`)}if(t){if(e.hasAttribute(p.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(p.attrName(t,"confirm"))&&(r.confirmMessage=p.unescapeNewlines(p.normalizeAttributeText(e.getAttribute(p.attrName(t,"confirm"))))),e.hasAttribute(p.attrName(t,"data"))&&(r.dataAttrName=p.attrName(t,"data")),e.hasAttribute(p.attrName(t,"form"))){const O=J.read(e,p.attrName(t,"form"));if(O){const Y=J.query(O,p.attrName(t,"form"));Y!==null?r.formFragment=F.getFormFragment(D.get(Y)):m.error("Haori",`Form element not found: ${O} (${p.attrName(t,"form")})`)}else r.formFragment=F.getFormFragment(e)}else(t==="change"||t==="input")&&(r.formFragment=F.getFormFragment(e),r.formFragment===null&&p.isNamedInputFragment(e)&&(r.selfValueFragment=e));if(e.hasAttribute(`${l.prefix}${t}-before-run`)){const O=e.getRawAttribute(`${l.prefix}${t}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
14
14
  "use strict";
15
15
  ${O}
@@ -17,17 +17,17 @@ ${O}
17
17
  ${O}
18
18
  );`)}catch{try{Y=new Function("event",`"use strict";
19
19
  ${O}
20
- `)}catch(Q){m.error("Haori",`Invalid run script: ${Q}`)}}Y&&(r.runScript=Y)}}const n=p.attrName(t,"fetch"),s=e.hasAttribute(n);if(s){const T=e.getAttributeEvaluation(n);T&&(r.fetchHasUnresolvedReference=T.hasUnresolvedReference,r.fetchUrl=T.hasUnresolvedReference?null:T.value)}const a={},o=t?p.attrName(t,"fetch-method"):p.attrName(null,"method",!0);if(e.hasAttribute(o)){const T=e.getAttributeEvaluation(o);T?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:a.method=p.normalizeAttributeText(T?.value)??void 0}const c=t?p.attrName(t,"fetch-headers"):p.attrName(null,"headers",!0),u=p.readFetchHeaders(e,c);u!==null&&(a.headers=u);const d=t?p.attrName(t,"fetch-content-type"):p.attrName(null,"content-type",!0);let g=null;if(e.hasAttribute(d)){const T=e.getAttributeEvaluation(d);T?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),g=p.normalizeAttributeText(T?.value)}if(g!==null)a.headers=p.withContentType(a.headers,g);else if(a.method&&!p.hasDeclaredContentType(a.headers)){const T=a.method.toUpperCase();a.headers=p.withContentType(a.headers,T==="GET"||T==="HEAD"||T==="OPTIONS"?"application/x-www-form-urlencoded":"application/json")}Object.keys(a).length>0&&(r.fetchOptions=a);const y=t?p.attrName(t,"fetch-download"):p.attrName(null,"download",!0);if(e.hasAttribute(y)&&!s)m.warn("Haori",`${y} は ${n} と併せて指定してください(保存する応答が無いため、この宣言は無視します)。`);else if(e.hasAttribute(y)){r.download=!0;const T=e.getAttributeEvaluation(y);r.downloadFileName=T?.hasUnresolvedReference?null:p.normalizeAttributeText(T?.value)}const E=t?p.attrName(t,"fetch-download-folder"):p.attrName(null,"download-folder",!0);e.hasAttribute(E)&&(r.download?r.downloadFolder=!0:m.warn("Haori",`${E} は ${y} と併せて指定してください(書き出す応答が無いため、この宣言は無視します)。`));const A=t?p.attrName(t,"bind"):p.attrName(null,"bind",!0);if(e.hasAttribute(A)){const T=J.read(e,A);if(T){const O=J.queryAll(T,A);O.length>0?(r.bindFragments=[],O.forEach(Y=>{const Q=D.get(Y);Q&&r.bindFragments.push(Q)})):m.error("Haori",`Bind element not found: ${T} (${A})`)}}const I=p.attrName(t,"bind-arg"),x=p.attrName(null,"arg",!0),H=p.attrName(null,"bind-arg",!0);t?e.hasAttribute(I)&&(r.bindArg=e.getRawAttribute(I)):e.hasAttribute(x)?r.bindArg=e.getRawAttribute(x):e.hasAttribute(H)&&(r.bindArg=e.getRawAttribute(H));const k=t?p.attrName(t,"bind-params"):p.attrName(null,"bind-params",!0);if(e.hasAttribute(k)){const T=e.getRawAttribute(k);r.bindParams=T.split("&").map(O=>O.trim())}const j=t?p.attrName(t,"bind-append"):p.attrName(null,"bind-append",!0);if(e.hasAttribute(j)){const T=e.getRawAttribute(j);r.bindAppendParams=T.split("&").map(O=>O.trim()).filter(Boolean)}const Z=t?p.attrName(t,"bind-merge"):p.attrName(null,"bind-merge",!0);e.hasAttribute(Z)&&(r.bindMerge=!0);const ee=t?p.attrName(t,"bind-transform"):p.attrName(null,"bind-transform",!0);e.hasAttribute(ee)&&(r.bindTransform=e.getRawAttribute(ee));const L=t?p.attrName(t,"copy-params"):null;if(L&&e.hasAttribute(L)){const T=e.getRawAttribute(L);r.copyParams=T.split("&").map(O=>O.trim()).filter(Boolean)}if(t){if(e.hasAttribute(p.attrName(t,"adjust"))){const W=J.read(e,p.attrName(t,"adjust"));if(W){const z=J.queryAll(W,p.attrName(t,"adjust"));z.length>0?(r.adjustFragments=[],z.forEach(X=>{const Ie=D.get(X);Ie&&r.adjustFragments.push(Ie)})):m.error("Haori",`Adjust element not found: ${W} (${p.attrName(t,"adjust")})`)}if(e.hasAttribute(p.attrName(t,"adjust-value"))){const z=e.getRawAttribute(p.attrName(t,"adjust-value")),X=Number(z);isNaN(X)||(r.adjustValue=X)}}if(e.hasAttribute(p.attrName(t,"row-add"))&&(r.rowAdd=!0),e.hasAttribute(p.attrName(t,"row-remove"))&&(r.rowRemove=!0),e.hasAttribute(p.attrName(t,"row-prev"))&&(r.rowMovePrev=!0),e.hasAttribute(p.attrName(t,"row-next"))&&(r.rowMoveNext=!0),e.hasAttribute(`${l.prefix}${t}-after-run`)){const W=e.getRawAttribute(`${l.prefix}${t}-after-run`);try{r.afterCallback=new Function("response",`
20
+ `)}catch(Q){m.error("Haori",`Invalid run script: ${Q}`)}}Y&&(r.runScript=Y)}}const n=p.attrName(t,"fetch"),s=e.hasAttribute(n);if(s){const T=e.getAttributeEvaluation(n);T&&(r.fetchHasUnresolvedReference=T.hasUnresolvedReference,r.fetchUrl=T.hasUnresolvedReference?null:T.value)}const a={},o=t?p.attrName(t,"fetch-method"):p.attrName(null,"method",!0);if(e.hasAttribute(o)){const T=e.getAttributeEvaluation(o);T?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:a.method=p.normalizeAttributeText(T?.value)??void 0}const c=t?p.attrName(t,"fetch-headers"):p.attrName(null,"headers",!0),u=p.readFetchHeaders(e,c);u!==null&&(a.headers=u);const d=t?p.attrName(t,"fetch-content-type"):p.attrName(null,"content-type",!0);let g=null;if(e.hasAttribute(d)){const T=e.getAttributeEvaluation(d);T?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),g=p.normalizeAttributeText(T?.value)}if(g!==null)a.headers=p.withContentType(a.headers,g);else if(a.method&&!p.hasDeclaredContentType(a.headers)){const T=a.method.toUpperCase();a.headers=p.withContentType(a.headers,T==="GET"||T==="HEAD"||T==="OPTIONS"?"application/x-www-form-urlencoded":"application/json")}Object.keys(a).length>0&&(r.fetchOptions=a);const y=t?p.attrName(t,"fetch-download"):p.attrName(null,"download",!0);if(e.hasAttribute(y)&&!s)m.warn("Haori",`${y} は ${n} と併せて指定してください(保存する応答が無いため、この宣言は無視します)。`);else if(e.hasAttribute(y)){r.download=!0;const T=e.getAttributeEvaluation(y);r.downloadFileName=T?.hasUnresolvedReference?null:p.normalizeAttributeText(T?.value)}const A=t?p.attrName(t,"fetch-download-folder"):p.attrName(null,"download-folder",!0);e.hasAttribute(A)&&(r.download?r.downloadFolder=!0:m.warn("Haori",`${A} は ${y} と併せて指定してください(書き出す応答が無いため、この宣言は無視します)。`));const E=t?p.attrName(t,"bind"):p.attrName(null,"bind",!0);if(e.hasAttribute(E)){const T=J.read(e,E);if(T){const O=J.queryAll(T,E);O.length>0?(r.bindFragments=[],O.forEach(Y=>{const Q=D.get(Y);Q&&r.bindFragments.push(Q)})):m.error("Haori",`Bind element not found: ${T} (${E})`)}}const I=p.attrName(t,"bind-arg"),x=p.attrName(null,"arg",!0),H=p.attrName(null,"bind-arg",!0);t?e.hasAttribute(I)&&(r.bindArg=e.getRawAttribute(I)):e.hasAttribute(x)?r.bindArg=e.getRawAttribute(x):e.hasAttribute(H)&&(r.bindArg=e.getRawAttribute(H));const k=t?p.attrName(t,"bind-params"):p.attrName(null,"bind-params",!0);if(e.hasAttribute(k)){const T=e.getRawAttribute(k);r.bindParams=T.split("&").map(O=>O.trim())}const j=t?p.attrName(t,"bind-append"):p.attrName(null,"bind-append",!0);if(e.hasAttribute(j)){const T=e.getRawAttribute(j);r.bindAppendParams=T.split("&").map(O=>O.trim()).filter(Boolean)}const Z=t?p.attrName(t,"bind-merge"):p.attrName(null,"bind-merge",!0);e.hasAttribute(Z)&&(r.bindMerge=!0);const ee=t?p.attrName(t,"bind-transform"):p.attrName(null,"bind-transform",!0);e.hasAttribute(ee)&&(r.bindTransform=e.getRawAttribute(ee));const L=t?p.attrName(t,"copy-params"):null;if(L&&e.hasAttribute(L)){const T=e.getRawAttribute(L);r.copyParams=T.split("&").map(O=>O.trim()).filter(Boolean)}if(t){if(e.hasAttribute(p.attrName(t,"adjust"))){const W=J.read(e,p.attrName(t,"adjust"));if(W){const z=J.queryAll(W,p.attrName(t,"adjust"));z.length>0?(r.adjustFragments=[],z.forEach(X=>{const Ie=D.get(X);Ie&&r.adjustFragments.push(Ie)})):m.error("Haori",`Adjust element not found: ${W} (${p.attrName(t,"adjust")})`)}if(e.hasAttribute(p.attrName(t,"adjust-value"))){const z=e.getRawAttribute(p.attrName(t,"adjust-value")),X=Number(z);isNaN(X)||(r.adjustValue=X)}}if(e.hasAttribute(p.attrName(t,"row-add"))&&(r.rowAdd=!0),e.hasAttribute(p.attrName(t,"row-remove"))&&(r.rowRemove=!0),e.hasAttribute(p.attrName(t,"row-prev"))&&(r.rowMovePrev=!0),e.hasAttribute(p.attrName(t,"row-next"))&&(r.rowMoveNext=!0),e.hasAttribute(`${l.prefix}${t}-after-run`)){const W=e.getRawAttribute(`${l.prefix}${t}-after-run`);try{r.afterCallback=new Function("response",`
21
21
  "use strict";
22
22
  ${W}
23
- `)}catch(z){m.error("Haori",`Invalid after script: ${z}`)}}if(e.hasAttribute(p.attrName(t,"dialog"))&&(r.dialogMessage=p.unescapeNewlines(p.readLateAttribute(e,r,"dialog",p.attrName(t,"dialog")))),e.hasAttribute(p.attrName(t,"toast"))&&(r.toastMessage=p.readLateAttribute(e,r,"toast",p.attrName(t,"toast")),r.toastLevel=p.readToastLevel(e,r,"toast-level",p.attrName(t,"toast-level"))),t!=="poll"){const W=p.attrName(t,"error-toast");e.hasAttribute(W)&&(r.errorToastMessage=p.readLateAttribute(e,r,"error-toast",W),r.errorToastLevel=p.readToastLevel(e,r,"error-toast-level",p.attrName(t,"error-toast-level")));const z=p.attrName(t,"error-status");e.hasAttribute(z)&&(r.errorStatuses=p.parseErrorStatuses(e.getRawAttribute(z),z)),r.errorNoMessage=e.hasAttribute(p.attrName(t,"error-no-message"))}const T=p.attrName(t,"redirect"),O=p.attrName(t,"redirect-replace"),Y=e.hasAttribute(T),Q=e.hasAttribute(O);if(Y&&(r.redirectUrl=p.readLateAttribute(e,r,"redirect",T)),Q&&(r.redirectReplaceUrl=p.readLateAttribute(e,r,"redirect-replace",O)),Y||Q){const W=p.attrName(t,"redirect-return-param");e.hasAttribute(W)&&(r.redirectReturnParam=p.readLateAttribute(e,r,"redirect-return-param",W))}if(e.hasAttribute(p.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(p.attrName(t,"scroll"))&&(r.scrollTarget=p.readLateAttribute(e,r,"scroll",p.attrName(t,"scroll"))),e.hasAttribute(p.attrName(t,"history"))&&(r.historyUrl=p.readLateAttribute(e,r,"history",p.attrName(t,"history"))),e.hasAttribute(p.attrName(t,"history-data"))&&(r.historyDataAttrName=p.attrName(t,"history-data")),e.hasAttribute(p.attrName(t,"history-form"))){const W=J.read(e,p.attrName(t,"history-form"));if(W){const z=J.query(W,p.attrName(t,"history-form"));z!==null?r.historyFormFragment=F.getFormFragment(D.get(z)):m.error("Haori",`Form element not found: ${W} (${p.attrName(t,"history-form")})`)}else r.historyFormFragment=F.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close","error-click","error-close"].forEach(W=>{if(W.startsWith("error-")&&t==="poll")return;const z=p.attrName(t,W);if(!e.hasAttribute(z))return;const X=p.resolveSelectorTargets(e,z,W);if(X.length>0)switch(W){case"reset-before":r.resetBeforeFragments=X;break;case"reset":r.resetFragments=X;break;case"refetch":r.refetchFragments=X;break;case"click":r.clickFragments=X,r.clickAwait=e.hasAttribute(`${z}-await`);break;case"copy":r.copyFragments=X;break;case"open":r.openFragments=X;break;case"close":r.closeFragments=X;break;case"error-click":r.errorClickFragments=X,r.errorClickAwait=e.hasAttribute(`${z}-await`);break;case"error-close":r.errorCloseFragments=X;break}}),t!=="poll"&&(r.errorStatusActions=p.readErrorStatusActions(e,r,t));const le=p.attrName(t,"copy-source");if(e.hasAttribute(le)){const W=J.read(e,le);if(W){const z=J.query(W,le);if(z!==null){const X=D.get(z);X?r.copySourceFragment=X:m.error("Haori",`Element is not managed by Haori: ${W} (${le})`)}else m.error("Haori",`Element not found: ${W} (${le})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(p.attrName(null,"data",!0))&&(r.dataAttrName=p.attrName(null,"data",!0)),e.hasAttribute(p.attrName(null,"form",!0)))){const T=J.read(e,p.attrName(null,"form",!0));if(T){const O=J.query(T,p.attrName(null,"form",!0));O!==null?r.formFragment=F.getFormFragment(D.get(O)):m.error("Haori",`Form element not found: ${T} (${p.attrName(null,"fetch-form",!0)})`)}else r.formFragment=F.getFormFragment(e)}const ae=t?p.attrName(t,"fetch-state"):p.attrName(null,"state",!0);if(e.hasAttribute(ae)){const T=J.read(e,ae),O=[];T?(J.queryAll(T,ae).forEach(Q=>{const ye=D.get(Q);ye&&O.push(ye)}),O.length===0&&m.error("Haori",`Element not found: ${T} (${ae})`)):O.push(e),O.length>0&&(r.fetchStateFragments=O)}const G=t?p.attrName(t,"store-clear"):p.attrName(null,"store-clear",!0);if(e.hasAttribute(G)){const T=e.getRawAttribute(G),O=T===null?"":T.trim();if(O==="")m.error("Haori",`ストレージキーが指定されていません (${G})`);else{r.storeClearKey=O;const Y=e.getRawAttribute(`${G}-type`),Q=Y===null?"session":Y.trim();Q==="local"||Q==="session"?r.storeClearKind=Q:(m.warn("Haori",`${G}-type は session または local を指定してください(session として扱います): ${Q}`),r.storeClearKind="session")}}return s&&!r.download&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),r.download&&r.bindFragments&&r.bindFragments.length>0&&(m.warn("Haori",`${y} と同時にバインド先が指定されています(応答はファイルとして保存し、バインドは行いません)。`),r.bindFragments=null),p.recordRowWriteTargets(r),r}static recordRowWriteTargets(e){const t=new Map,r=[...e.bindFragments??[],...e.copyFragments??[]];for(const i of r){const n=i.getParent();!n||!n.hasAttribute(`${l.prefix}each`)||!n.hasAttribute(`${l.prefix}form-list`)||t.set(i,p.getRowFragments(n).includes(i)?n:null)}t.size>0&&(e.rowWriteTargets=t)}static isNamedInputFragment(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.getAttribute("name")!==null||e.hasAttribute(`${l.prefix}form-name`):!1}static isElementFragment(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.getTarget=="function"&&typeof t.getChildElementFragments=="function"}static resolveAutoFetchSignature(e){return new p(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}markReentrantBind(){this.reentrantBind=!0}runWithResult(){return this.execute()}async runWithOutcome(){return await this.execute()?"success":this.skipped?"skipped":"failure"}async execute(){const e=this.acquireExecutionLock();if(e===!1)return!1;try{if(Object.keys(this.options).length===0)return this.skipped=!0,!1;if(this.options.formFragment&&this.validate(this.options.formFragment)===!1)return!1;if(!this.options.formFragment&&this.options.targetFragment&&F.warnUnvalidatedCustomValidity(F.getFormFragment(this.options.targetFragment),`${l.prefix}${this.eventType??"fetch"}-form が解決できません`),!this.evaluateExecutionCondition())return this.skipped=!0,!1;if(this.options.runScript){const g=this.options.targetFragment?.getTarget()??null;try{const y=this.options.runScript.call(g,this.domEvent);y===!1&&this.domEvent&&this.domEvent.preventDefault(),y!=null&&typeof y.then=="function"&&await y}catch(y){m.error("Haori",`Run script execution error: ${y}`)}}if(!await this.confirm()||this.options.downloadFolder&&await this.prepareDownloadFolder()==="cancelled")return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(g=>F.reset(g,this.operationSequence))),this.captureHistorySnapshots());const r=this.prepareFetchRequest();this.requestUserEditSequence=w.currentSequence();const i=r.payload;let n=r.url,s=r.options,a=!1,o=!1;if(this.options.beforeCallback){const g=this.options.beforeCallback(n||null,s||null);if(g!=null){if(g===!1||typeof g=="object"&&g.stop)return!1;typeof g=="object"&&(a="fetchUrl"in g,o="fetchOptions"in g,n=a?g.fetchUrl:n,s=o?g.fetchOptions:s)}}const c=Object.keys(i).length>0;if(n){const g=(s?.method||"GET").toUpperCase(),E=!a&&o&&r.transportMode==="query-get"&&qt(s)&&!Ve(g)?r.baseUrl??n:n,A=Wt(E,s);n=A.url;const I={...A.options},x=A.normalized?A.requestedMethod:r.requestedMethod,H=A.effectiveMethod,k=r.transportMode==="query-get"||A.normalized,j=A.queryString??r.queryString;if(k&&m.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:x,effectiveMethod:H,transportMode:"query-get",url:n,payload:c?i:void 0,queryString:j}),this.options.targetFragment&&n){const Z=performance.now(),ee={runtime:l.runtime,requestedMethod:x,effectiveMethod:H,transportMode:k?"query-get":"http",...k?{queryString:j}:{}};return B.fetchStart(this.options.targetFragment.getTarget(),n,I,c?i:void 0,ee),await this.injectFetchState("loading"),await p.invokeFetch(n,I).then(L=>this.handleFetchResult(L,n||void 0,Z)).catch(async L=>{throw n&&B.fetchError(this.options.targetFragment.getTarget(),n,L),await this.injectFetchState("error",null,L instanceof Error?L.message:String(L)),await this.runErrorActions(null),L})}return await fetch(n,I).then(Z=>this.handleFetchResult(Z,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&c){const g=this.options.formFragment,y=g.getTarget(),E=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&E.add(this.options.targetFragment);const A=g.getRawBindingData(),I=qe(i),x=g.getAttribute(`${l.prefix}form-arg`);let H;if(x){H={...A??{}};const k=String(x),j=F.resolveAncestorArgOwner(g,k);H[k]=F.mergeCollectedValues((j?j.value:H[k])??null,I)}else H=F.mergeCollectedValues(A,I,F.ancestorBaseResolver(g));await $.setBindingData(y,H,{skipFragments:E,kind:"nonSupply",sequence:this.operationSequence,editedPaths:F.collectEditedPaths(g,this.operationSequence,x?String(x):"",I)})}this.suppressEmptyReplaceBind=!c&&!this.options.formFragment&&(this.eventType==="change"||this.eventType==="input"),this.twoWayCommitBind=this.eventType==="change"||this.eventType==="input";const u=c?qe(i):{},d=new Response(JSON.stringify(u),{headers:{"Content-Type":"application/json"}});return await this.handleFetchResult(d)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const e=this.options.targetFragment,t=e.getTarget();if(p.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(Ue))return!1;const r=t.hasAttribute(`${l.prefix}click-no-disabled`);return p.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(Ue,""),r||t.setAttribute("disabled",""),{target:t,fragment:e,appliedDisabledAttribute:!r}}static findDisabledDeclaration(e){const t=`${l.prefix}attr-disabled`,r=e.getRawAttribute(t);if(r!==null)return{name:t,value:r};const i=e.getRawAttribute("disabled");return i!==null&&i.includes("{{")?{name:"disabled",value:i}:null}releaseExecutionLock(e){if(!e)return;const t=e.target;if(p.RUNNING_CLICK_TARGETS.delete(t),t.removeAttribute(Ue),!e.appliedDisabledAttribute)return;const r=p.findDisabledDeclaration(e.fragment);if(r===null){t.removeAttribute("disabled");return}$.setAttribute(t,r.name,r.value).catch(i=>{m.error("Haori",`ロックの解除で ${r.name} を適用し直せませんでした: ${i}`)})}static forgetDownloadFolder(){Te=null}async prepareDownloadFolder(){if(Te)return this.downloadFolder=Te,"ready";const e=globalThis.showDirectoryPicker;if(typeof e!="function")return m.info("Haori","この環境では保存先のフォルダを選ばせられないため、今までどおり保存します。"),"fallback";try{const t=await e.call(globalThis,{mode:"readwrite"});return Te=t,this.downloadFolder=t,"ready"}catch(t){return t?.name==="AbortError"?"cancelled":(m.info("Haori",`保存先のフォルダを選ばせられなかったため、今までどおり保存します: ${t}`),"fallback")}}async readResponseBody(e){const t=e.headers.get("Content-Type")??"",r=e.body;if(!r||typeof r.getReader!="function")try{const s=await e.blob();return this.downloadReceivedBytes=s.size,this.dropTotalBytesIfExceeded(),await this.injectFetchState("loading"),s}catch(s){return m.error("Haori",`応答をファイルとして読み取れませんでした: ${s}`),null}const i=[];return await this.pumpResponseBody(r,s=>{i.push(new Blob([s]))})?new Blob(i,t!==""?{type:t}:void 0):null}async pumpResponseBody(e,t){await this.injectFetchState("loading");let r=Date.now();const i=e.getReader();try{for(;;){const{done:n,value:s}=await i.read();if(n)break;await t(s),this.downloadReceivedBytes+=s.byteLength,this.dropTotalBytesIfExceeded();const a=Date.now();a-r>=Lt&&(r=a,await this.injectFetchState("loading"))}}catch(n){return m.error("Haori",`応答をファイルとして読み取れませんでした: ${n}`),!1}return!0}dropTotalBytesIfExceeded(){this.downloadTotalBytes!==null&&this.downloadReceivedBytes>this.downloadTotalBytes&&(this.downloadTotalBytes=null)}static resolveDownloadTotalBytes(e){const t=e.headers.get("Content-Encoding");if(t!==null){const s=t.trim().toLowerCase();if(s!==""&&s!=="identity")return null}const r=e.headers.get("Content-Length");if(r===null)return null;const i=r.trim();if(i==="")return null;const n=Number(i);return!Number.isSafeInteger(n)||n<0?null:n}async saveResponseToFolder(e,t,r){const i=t.body;if(!i||typeof i.getReader!="function")return"fallback";const n=p.resolveDownloadFileName(t,this.options.downloadFileName??null,r??this.options.fetchUrl??null);let s=!0;try{await e.getFileHandle(n)}catch(c){if(c?.name==="NotFoundError")s=!1;else return m.info("Haori",`保存先のフォルダを確かめられなかったため、今までどおり保存します: ${c}`),"fallback"}if(s&&!await he().confirm(`${n} は既にあります。上書きしますか?`))return"cancelled";let a;try{a=await(await e.getFileHandle(n,{create:!0})).createWritable()}catch(c){return m.info("Haori",`保存先のファイルを作れなかったため、今までどおり保存します: ${c}`),"fallback"}if(await this.pumpResponseBody(i,c=>a.write(c)))try{return await a.close(),"saved"}catch(c){m.error("Haori",`ファイルを書き終えられませんでした: ${c}`)}try{await a.abort()}catch(c){m.error("Haori",`書きかけを取り消せませんでした: ${c}`)}if(!s)try{await e.removeEntry(n)}catch(c){m.error("Haori",`作りかけのファイルを取り除けませんでした: ${c}`)}return"failed"}async saveResponseAsFile(e,t){if(this.downloadTotalBytes=p.resolveDownloadTotalBytes(e),this.downloadFolder){const a=await this.saveResponseToFolder(this.downloadFolder,e,t);if(a!=="fallback")return a;this.downloadFolder=null,Te=null}const r=await this.readResponseBody(e);if(r===null)return"failed";const i=p.resolveDownloadFileName(e,this.options.downloadFileName??null,t??this.options.fetchUrl??null);if(typeof URL>"u"||typeof URL.createObjectURL!="function")return m.error("Haori","この環境では Blob の URL を生成できないため、ファイルを保存できません。"),"failed";const n=URL.createObjectURL(r),s=document.createElement("a");return s.href=n,s.download=i,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(n),0),"saved"}async showDownloadFailure(){const e=this.options.formFragment??(this.options.targetFragment?F.getFormFragment(this.options.targetFragment)||this.options.targetFragment:null),t=e?e.getTarget():document.body,r=he();await r.clearMessages(t),await r.addErrorMessage(t,gt)}static resolveDownloadFileName(e,t,r){const n=[p.readContentDispositionFileName(e.headers.get("Content-Disposition")),t,p.readUrlFileName(r)];for(const s of n){const a=p.sanitizeFileName(s);if(a!==null)return a}return"download"}static readContentDispositionFileName(e){if(!e)return null;const t=/filename\*\s*=\s*([^;]+)/i.exec(e);if(t){const n=t[1].trim(),s=n.split("'"),a=s.length>=3?s.slice(2).join("'"):n;try{return decodeURIComponent(a)}catch(o){m.warn("Haori",`Content-Disposition を解釈できません: ${o}`)}}const r=/filename\s*=\s*"((?:[^"\\]|\\.)*)"/i.exec(e);if(r)return r[1].replace(/\\(.)/g,"$1");const i=/filename\s*=\s*([^;]+)/i.exec(e);return i?i[1].trim():null}static readUrlFileName(e){if(!e)return null;const r=e.split("#")[0].split("?")[0].split("/"),i=r[r.length-1];return i===""?null:i}static sanitizeFileName(e){if(e===null)return null;const t=e.replace(/[\u0000-\u001f\u007f/\\]/g,"").trim();return t===""?null:t}async handleFetchResult(e,t,r){const i=he();if(!e.ok){if(ht(e.status))return!1;this.options.targetFragment&&t&&B.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r);const E=await this.handleFetchError(e,this.selectErrorActions(e.status)?.noMessage!==!0);return await this.injectFetchState("error",e.status,e.statusText||null,E),await this.runErrorActions(e.status),!1}if(this.options.targetFragment&&t&&r&&B.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const E=this.options.afterCallback(e);if(E!=null){if(E===!1||typeof E=="object"&&E.stop)return!1;typeof E=="object"&&"response"in E&&(e="response"in E?E.response:e)}}if(this.options.download){const E=await this.saveResponseAsFile(e,t);if(E==="cancelled")return await this.injectFetchState("success",e.status,null),!1;if(E==="failed")return await this.showDownloadFailure(),await this.injectFetchState("error",e.status,gt),!1}const n=[];n.push(this.bindResult(e)),n.push(this.adjust()),n.push(this.addRow()),n.push(this.removeRow()),n.push(this.movePrevRow()),n.push(this.moveNextRow()),await Promise.all(n),await this.injectFetchState("success",e.status,null),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(E=>F.reset(E,this.operationSequence))),await this.copy();const s=[];this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(E=>{s.push(new p(E,null).run())});const a=await this.clickTargets(this.options.clickFragments,this.options.clickAwait===!0,"click-await");if(!a&&this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(E=>{const A=E.getTarget();A instanceof HTMLElement?s.push(i.openDialog(A)):m.error("Haori","Element is not an HTML element: ",A)}),!a&&this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(E=>{const A=E.getTarget();A instanceof HTMLElement?s.push(i.closeDialog(A)):m.error("Haori","Element is not an HTML element: ",A)}),await Promise.all(s),a)return!1;const o=p.unescapeNewlines(p.normalizeAttributeText(this.resolveLateAttribute("dialog",this.options.dialogMessage)));o&&await i.dialog(o);const c=p.normalizeAttributeText(this.resolveLateAttribute("toast",this.options.toastMessage));if(c){const E=p.toToastLevel(this.resolveLateAttribute("toast-level",this.options.toastLevel));await i.toast(c,E??"info")}this.clearStore(),this.pushHistory();const u=this.resolveLateAttribute("scroll",this.options.scrollTarget);u&&J.query(u,p.attrName(this.eventType,"scroll"),document)?.scrollIntoView({behavior:"smooth",block:"nearest"});const d=this.resolveLateAttribute("redirect",this.options.redirectUrl),g=this.resolveLateAttribute("redirect-replace",this.options.redirectReplaceUrl);d&&g&&m.warn("Haori",`${p.attrName(this.eventType,"redirect")} と ${p.attrName(this.eventType,"redirect-replace")} の両方が指定されています。履歴を置き換える方を採用します。`);const y=g||d;if(y){let E=y;const A=this.resolveLateAttribute("redirect-return-param",this.options.redirectReturnParam);if(A){const x=new URLSearchParams(window.location.search).get(A);if(x!==null){const H=x.trim();pt.isSafeLocalPath(H)?E=H:m.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${x}`)}}g?window.location.replace(E):window.location.href=E}return!0}clearStore(){const e=this.options.storeClearKey;e&&Re.clear(e,this.options.storeClearKind??"session")}async clickTargets(e,t,r){if(!e||e.length===0)return!1;for(const i of e){await $.evaluateAll(i);const n=i.getTarget();if(t&&p.takeClickOutcome(n),typeof n.click=="function"?n.click():n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0})),!t)continue;const s=p.takeClickOutcome(n);if(s===null){m.warn("Haori",`${l.prefix}${this.eventType??"fetch"}-${r} はこの対象の完了を待てません(手続きが同期に起動していません)。`);continue}if(await s==="failure")return!0}return!1}async runErrorActions(e){const t=this.selectErrorActions(e);if(!t||await this.clickTargets(t.clickFragments,t.clickAwait,`${t.key}-click-await`))return;const i=he(),n=[];t.closeFragments?.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?n.push(i.closeDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(n);const s=p.normalizeAttributeText(this.resolveLateAttribute(`${t.key}-toast`,t.toastMessage));if(s){const a=p.toToastLevel(this.resolveLateAttribute(`${t.key}-toast-level`,t.toastLevel));await i.toast(s,a??"info")}}selectErrorActions(e){const t=e===null?void 0:this.options.errorStatusActions?.get(e);return t||(this.appliesErrorActions(e)?{key:"error",clickFragments:this.options.errorClickFragments??null,clickAwait:this.options.errorClickAwait===!0,closeFragments:this.options.errorCloseFragments??null,toastMessage:this.options.errorToastMessage??null,toastLevel:this.options.errorToastLevel??null,noMessage:this.options.errorNoMessage===!0}:null)}appliesErrorActions(e){const t=this.options.errorStatuses;return t===void 0||e!==null&&t.includes(e)}resolveLateAttribute(e,t){const r=t??null,i=this.options.lateAttributes?.get(e)??null,n=this.options.targetFragment??null;if(!i||!n||!n.hasAttribute(i.attributeName))return r;const s=n.getAttributeEvaluation(i.attributeName);return s===null?r:s.hasUnresolvedReference&&!i.hasUnresolvedReference?(q.isEnabled()&&m.warn("Haori",`${i.attributeName} の参照が手続きの途中で解決できなくなったため、手続き開始時の値を使います`),r):s.value??null}pushHistory(){const e=this.resolveLateAttribute("history",this.options.historyUrl),t=e!=null,r=this.resolveHistoryDataValues(),i=this.resolveHistoryFormValues(),n=r!=null,s=i!=null;if(!(!t&&!n&&!s))try{const a=t?e:window.location.pathname,o=new URL(a,window.location.href);if(o.origin!==window.location.origin){const u="history.pushState: cross-origin URL is not allowed: "+o.toString();m.error("Haori",u);return}const c=u=>{for(const[d,g]of Object.entries(u))g!=null&&(Array.isArray(g)?(o.searchParams.delete(d),g.forEach(y=>o.searchParams.append(d,String(y)))):typeof g=="object"?o.searchParams.set(d,JSON.stringify(g)):o.searchParams.set(d,String(g)))};n&&c(r),s&&c(i),history.pushState({[Pt]:!0},"",o.toString()),$.refreshUrlParams()}catch(a){m.error("Haori",`history.pushState failed: ${a}`)}}async handleFetchError(e,t){let r=null;this.options.formFragment?r=this.options.formFragment:this.options.targetFragment&&(r=F.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const i=r?r.getTarget():document.body;await he().clearMessages(i);const n=async u=>{const d=r?r.getTarget():document.body;await he().addErrorMessage(d,u)},s=()=>{if(!this.options.scrollOnError)return;const u=r?r.getTarget():document.body;(u.getAttribute("data-message-level")==="error"?u:u.parentElement?.getAttribute("data-message-level")==="error"?u.parentElement:u.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})},a=async u=>{if(t){u.length===0&&await n(`${e.status} ${e.statusText}`);for(const d of u)d.key&&r?await F.addErrorMessage(r,d.key,d.message):await n(d.message);s()}return u.length===0?null:u.map(d=>d.message).join(`
24
- `)};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const u=await e.json(),d=[];if(Array.isArray(u)){const g=new Map,y=[];for(const E of u)if(E&&typeof E=="object"&&!Array.isArray(E)){const A=E.key,I=E.message,x=typeof A=="string"&&A.length>0?A:null,H=typeof I=="string"?I:I!=null?String(I):"";if(H.length===0)continue;if(x!==null){const k=g.get(x)??[];k.push(H),g.set(x,k)}else y.push(H)}else typeof E=="string"&&E.length>0&&y.push(E);for(const[E,A]of g)d.push({key:E,message:A.join(`
25
- `)});for(const E of y)d.push({message:E})}else if(u&&typeof u=="object"){if(typeof u.message=="string"&&d.push({message:u.message}),Array.isArray(u.messages))for(const g of u.messages)typeof g=="string"&&d.push({message:g});if(u.errors&&typeof u.errors=="object")for(const[g,y]of Object.entries(u.errors))Array.isArray(y)?d.push({key:g,message:y.join(`
23
+ `)}catch(z){m.error("Haori",`Invalid after script: ${z}`)}}if(e.hasAttribute(p.attrName(t,"dialog"))&&(r.dialogMessage=p.unescapeNewlines(p.readLateAttribute(e,r,"dialog",p.attrName(t,"dialog")))),e.hasAttribute(p.attrName(t,"toast"))&&(r.toastMessage=p.readLateAttribute(e,r,"toast",p.attrName(t,"toast")),r.toastLevel=p.readToastLevel(e,r,"toast-level",p.attrName(t,"toast-level"))),t!=="poll"){const W=p.attrName(t,"error-toast");e.hasAttribute(W)&&(r.errorToastMessage=p.readLateAttribute(e,r,"error-toast",W),r.errorToastLevel=p.readToastLevel(e,r,"error-toast-level",p.attrName(t,"error-toast-level")));const z=p.attrName(t,"error-status");e.hasAttribute(z)&&(r.errorStatuses=p.parseErrorStatuses(e.getRawAttribute(z),z)),r.errorNoMessage=e.hasAttribute(p.attrName(t,"error-no-message"))}const T=p.attrName(t,"redirect"),O=p.attrName(t,"redirect-replace"),Y=e.hasAttribute(T),Q=e.hasAttribute(O);if(Y&&(r.redirectUrl=p.readLateAttribute(e,r,"redirect",T)),Q&&(r.redirectReplaceUrl=p.readLateAttribute(e,r,"redirect-replace",O)),Y||Q){const W=p.attrName(t,"redirect-return-param");e.hasAttribute(W)&&(r.redirectReturnParam=p.readLateAttribute(e,r,"redirect-return-param",W))}if(e.hasAttribute(p.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(p.attrName(t,"scroll"))&&(r.scrollTarget=p.readLateAttribute(e,r,"scroll",p.attrName(t,"scroll"))),e.hasAttribute(p.attrName(t,"history"))&&(r.historyUrl=p.readLateAttribute(e,r,"history",p.attrName(t,"history"))),e.hasAttribute(p.attrName(t,"history-data"))&&(r.historyDataAttrName=p.attrName(t,"history-data")),e.hasAttribute(p.attrName(t,"history-form"))){const W=J.read(e,p.attrName(t,"history-form"));if(W){const z=J.query(W,p.attrName(t,"history-form"));z!==null?r.historyFormFragment=F.getFormFragment(D.get(z)):m.error("Haori",`Form element not found: ${W} (${p.attrName(t,"history-form")})`)}else r.historyFormFragment=F.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close","error-click","error-close"].forEach(W=>{if(W.startsWith("error-")&&t==="poll")return;const z=p.attrName(t,W);if(!e.hasAttribute(z))return;const X=p.resolveSelectorTargets(e,z,W);if(X.length>0)switch(W){case"reset-before":r.resetBeforeFragments=X;break;case"reset":r.resetFragments=X;break;case"refetch":r.refetchFragments=X;break;case"click":r.clickFragments=X,r.clickAwait=e.hasAttribute(`${z}-await`);break;case"copy":r.copyFragments=X;break;case"open":r.openFragments=X;break;case"close":r.closeFragments=X;break;case"error-click":r.errorClickFragments=X,r.errorClickAwait=e.hasAttribute(`${z}-await`);break;case"error-close":r.errorCloseFragments=X;break}}),t!=="poll"&&(r.errorStatusActions=p.readErrorStatusActions(e,r,t));const le=p.attrName(t,"copy-source");if(e.hasAttribute(le)){const W=J.read(e,le);if(W){const z=J.query(W,le);if(z!==null){const X=D.get(z);X?r.copySourceFragment=X:m.error("Haori",`Element is not managed by Haori: ${W} (${le})`)}else m.error("Haori",`Element not found: ${W} (${le})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(p.attrName(null,"data",!0))&&(r.dataAttrName=p.attrName(null,"data",!0)),e.hasAttribute(p.attrName(null,"form",!0)))){const T=J.read(e,p.attrName(null,"form",!0));if(T){const O=J.query(T,p.attrName(null,"form",!0));O!==null?r.formFragment=F.getFormFragment(D.get(O)):m.error("Haori",`Form element not found: ${T} (${p.attrName(null,"fetch-form",!0)})`)}else r.formFragment=F.getFormFragment(e)}const ae=t?p.attrName(t,"fetch-state"):p.attrName(null,"state",!0);if(e.hasAttribute(ae)){const T=J.read(e,ae),O=[];T?(J.queryAll(T,ae).forEach(Q=>{const ye=D.get(Q);ye&&O.push(ye)}),O.length===0&&m.error("Haori",`Element not found: ${T} (${ae})`)):O.push(e),O.length>0&&(r.fetchStateFragments=O)}const G=t?p.attrName(t,"store-clear"):p.attrName(null,"store-clear",!0);if(e.hasAttribute(G)){const T=e.getRawAttribute(G),O=T===null?"":T.trim();if(O==="")m.error("Haori",`ストレージキーが指定されていません (${G})`);else{r.storeClearKey=O;const Y=e.getRawAttribute(`${G}-type`),Q=Y===null?"session":Y.trim();Q==="local"||Q==="session"?r.storeClearKind=Q:(m.warn("Haori",`${G}-type は session または local を指定してください(session として扱います): ${Q}`),r.storeClearKind="session")}}return s&&!r.download&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),r.download&&r.bindFragments&&r.bindFragments.length>0&&(m.warn("Haori",`${y} と同時にバインド先が指定されています(応答はファイルとして保存し、バインドは行いません)。`),r.bindFragments=null),p.recordRowWriteTargets(r),r}static recordRowWriteTargets(e){const t=new Map,r=[...e.bindFragments??[],...e.copyFragments??[]];for(const i of r){const n=i.getParent();!n||!n.hasAttribute(`${l.prefix}each`)||!n.hasAttribute(`${l.prefix}form-list`)||t.set(i,p.getRowFragments(n).includes(i)?n:null)}t.size>0&&(e.rowWriteTargets=t)}static isNamedInputFragment(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.getAttribute("name")!==null||e.hasAttribute(`${l.prefix}form-name`):!1}static isElementFragment(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.getTarget=="function"&&typeof t.getChildElementFragments=="function"}static resolveAutoFetchSignature(e){return new p(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}markReentrantBind(){this.reentrantBind=!0}runWithResult(){return this.execute()}async runWithOutcome(){return await this.execute()?"success":this.skipped?"skipped":"failure"}async execute(){const e=this.acquireExecutionLock();if(e===!1)return!1;try{if(Object.keys(this.options).length===0)return this.skipped=!0,!1;if(this.options.formFragment&&this.validate(this.options.formFragment)===!1)return!1;if(!this.options.formFragment&&this.options.targetFragment&&F.warnUnvalidatedCustomValidity(F.getFormFragment(this.options.targetFragment),`${l.prefix}${this.eventType??"fetch"}-form が解決できません`),!this.evaluateExecutionCondition())return this.skipped=!0,!1;if(this.options.runScript){const g=this.options.targetFragment?.getTarget()??null;try{const y=this.options.runScript.call(g,this.domEvent);y===!1&&this.domEvent&&this.domEvent.preventDefault(),y!=null&&typeof y.then=="function"&&await y}catch(y){m.error("Haori",`Run script execution error: ${y}`)}}if(!await this.confirm()||this.options.downloadFolder&&await this.prepareDownloadFolder()==="cancelled")return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(g=>F.reset(g,this.operationSequence))),this.captureHistorySnapshots());const r=this.prepareFetchRequest();this.requestUserEditSequence=w.currentSequence();const i=r.payload;let n=r.url,s=r.options,a=!1,o=!1;if(this.options.beforeCallback){const g=this.options.beforeCallback(n||null,s||null);if(g!=null){if(g===!1||typeof g=="object"&&g.stop)return!1;typeof g=="object"&&(a="fetchUrl"in g,o="fetchOptions"in g,n=a?g.fetchUrl:n,s=o?g.fetchOptions:s)}}const c=Object.keys(i).length>0;if(n){const g=(s?.method||"GET").toUpperCase(),A=!a&&o&&r.transportMode==="query-get"&&qt(s)&&!Ve(g)?r.baseUrl??n:n,E=Wt(A,s);n=E.url;const I={...E.options},x=E.normalized?E.requestedMethod:r.requestedMethod,H=E.effectiveMethod,k=r.transportMode==="query-get"||E.normalized,j=E.queryString??r.queryString;if(k&&m.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:x,effectiveMethod:H,transportMode:"query-get",url:n,payload:c?i:void 0,queryString:j}),this.options.targetFragment&&n){const Z=performance.now(),ee={runtime:l.runtime,requestedMethod:x,effectiveMethod:H,transportMode:k?"query-get":"http",...k?{queryString:j}:{}};return B.fetchStart(this.options.targetFragment.getTarget(),n,I,c?i:void 0,ee),await this.injectFetchState("loading"),await p.invokeFetch(n,I).then(L=>this.handleFetchResult(L,n||void 0,Z)).catch(async L=>{throw n&&B.fetchError(this.options.targetFragment.getTarget(),n,L),await this.injectFetchState("error",null,L instanceof Error?L.message:String(L)),await this.runErrorActions(null),L})}return await fetch(n,I).then(Z=>this.handleFetchResult(Z,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&c){const g=this.options.formFragment,y=g.getTarget(),A=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&A.add(this.options.targetFragment);const E=g.getRawBindingData(),I=qe(i),x=g.getAttribute(`${l.prefix}form-arg`);let H;if(x){H={...E??{}};const k=String(x),j=F.resolveAncestorArgOwner(g,k);H[k]=F.mergeCollectedValues((j?j.value:H[k])??null,I)}else H=F.mergeCollectedValues(E,I,F.ancestorBaseResolver(g));await $.setBindingData(y,H,{skipFragments:A,kind:"nonSupply",sequence:this.operationSequence,editedPaths:F.collectEditedPaths(g,this.operationSequence,x?String(x):"",I)})}this.suppressEmptyReplaceBind=!c&&!this.options.formFragment&&(this.eventType==="change"||this.eventType==="input"),this.twoWayCommitBind=this.eventType==="change"||this.eventType==="input";const u=c?qe(i):{},d=new Response(JSON.stringify(u),{headers:{"Content-Type":"application/json"}});return await this.handleFetchResult(d)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const e=this.options.targetFragment,t=e.getTarget();if(p.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(Ue))return!1;const r=t.hasAttribute(`${l.prefix}click-no-disabled`);return p.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(Ue,""),r||t.setAttribute("disabled",""),{target:t,fragment:e,appliedDisabledAttribute:!r}}static findDisabledDeclaration(e){const t=`${l.prefix}attr-disabled`,r=e.getRawAttribute(t);if(r!==null)return{name:t,value:r};const i=e.getRawAttribute("disabled");return i!==null&&i.includes("{{")?{name:"disabled",value:i}:null}releaseExecutionLock(e){if(!e)return;const t=e.target;if(p.RUNNING_CLICK_TARGETS.delete(t),t.removeAttribute(Ue),!e.appliedDisabledAttribute)return;const r=p.findDisabledDeclaration(e.fragment);if(r===null){t.removeAttribute("disabled");return}$.setAttribute(t,r.name,r.value).catch(i=>{m.error("Haori",`ロックの解除で ${r.name} を適用し直せませんでした: ${i}`)})}static forgetDownloadFolder(){Te=null}async prepareDownloadFolder(){if(Te)return this.downloadFolder=Te,"ready";const e=globalThis.showDirectoryPicker;if(typeof e!="function")return m.info("Haori","この環境では保存先のフォルダを選ばせられないため、今までどおり保存します。"),"fallback";try{const t=await e.call(globalThis,{mode:"readwrite"});return Te=t,this.downloadFolder=t,"ready"}catch(t){return t?.name==="AbortError"?"cancelled":(m.info("Haori",`保存先のフォルダを選ばせられなかったため、今までどおり保存します: ${t}`),"fallback")}}async readResponseBody(e){const t=e.headers.get("Content-Type")??"",r=e.body;if(!r||typeof r.getReader!="function")try{const s=await e.blob();return this.downloadReceivedBytes=s.size,this.dropTotalBytesIfExceeded(),await this.injectFetchState("loading"),s}catch(s){return m.error("Haori",`応答をファイルとして読み取れませんでした: ${s}`),null}const i=[];return await this.pumpResponseBody(r,s=>{i.push(new Blob([s]))})?new Blob(i,t!==""?{type:t}:void 0):null}async pumpResponseBody(e,t){await this.injectFetchState("loading");let r=Date.now();const i=e.getReader();try{for(;;){const{done:n,value:s}=await i.read();if(n)break;await t(s),this.downloadReceivedBytes+=s.byteLength,this.dropTotalBytesIfExceeded();const a=Date.now();a-r>=Lt&&(r=a,await this.injectFetchState("loading"))}}catch(n){return m.error("Haori",`応答をファイルとして読み取れませんでした: ${n}`),!1}return!0}dropTotalBytesIfExceeded(){this.downloadTotalBytes!==null&&this.downloadReceivedBytes>this.downloadTotalBytes&&(this.downloadTotalBytes=null)}static resolveDownloadTotalBytes(e){const t=e.headers.get("Content-Encoding");if(t!==null){const s=t.trim().toLowerCase();if(s!==""&&s!=="identity")return null}const r=e.headers.get("Content-Length");if(r===null)return null;const i=r.trim();if(i==="")return null;const n=Number(i);return!Number.isSafeInteger(n)||n<0?null:n}async saveResponseToFolder(e,t,r){const i=t.body;if(!i||typeof i.getReader!="function")return"fallback";const n=p.resolveDownloadFileName(t,this.options.downloadFileName??null,r??this.options.fetchUrl??null);let s=!0;try{await e.getFileHandle(n)}catch(c){if(c?.name==="NotFoundError")s=!1;else return m.info("Haori",`保存先のフォルダを確かめられなかったため、今までどおり保存します: ${c}`),"fallback"}if(s&&!await he().confirm(`${n} は既にあります。上書きしますか?`))return"cancelled";let a;try{a=await(await e.getFileHandle(n,{create:!0})).createWritable()}catch(c){return m.info("Haori",`保存先のファイルを作れなかったため、今までどおり保存します: ${c}`),"fallback"}if(await this.pumpResponseBody(i,c=>a.write(c)))try{return await a.close(),"saved"}catch(c){m.error("Haori",`ファイルを書き終えられませんでした: ${c}`)}try{await a.abort()}catch(c){m.error("Haori",`書きかけを取り消せませんでした: ${c}`)}if(!s)try{await e.removeEntry(n)}catch(c){m.error("Haori",`作りかけのファイルを取り除けませんでした: ${c}`)}return"failed"}async saveResponseAsFile(e,t){if(this.downloadTotalBytes=p.resolveDownloadTotalBytes(e),this.downloadFolder){const a=await this.saveResponseToFolder(this.downloadFolder,e,t);if(a!=="fallback")return a;this.downloadFolder=null,Te=null}const r=await this.readResponseBody(e);if(r===null)return"failed";const i=p.resolveDownloadFileName(e,this.options.downloadFileName??null,t??this.options.fetchUrl??null);if(typeof URL>"u"||typeof URL.createObjectURL!="function")return m.error("Haori","この環境では Blob の URL を生成できないため、ファイルを保存できません。"),"failed";const n=URL.createObjectURL(r),s=document.createElement("a");return s.href=n,s.download=i,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(n),0),"saved"}async showDownloadFailure(){const e=this.options.formFragment??(this.options.targetFragment?F.getFormFragment(this.options.targetFragment)||this.options.targetFragment:null),t=e?e.getTarget():document.body,r=he();await r.clearMessages(t),await r.addErrorMessage(t,gt)}static resolveDownloadFileName(e,t,r){const n=[p.readContentDispositionFileName(e.headers.get("Content-Disposition")),t,p.readUrlFileName(r)];for(const s of n){const a=p.sanitizeFileName(s);if(a!==null)return a}return"download"}static readContentDispositionFileName(e){if(!e)return null;const t=/filename\*\s*=\s*([^;]+)/i.exec(e);if(t){const n=t[1].trim(),s=n.split("'"),a=s.length>=3?s.slice(2).join("'"):n;try{return decodeURIComponent(a)}catch(o){m.warn("Haori",`Content-Disposition を解釈できません: ${o}`)}}const r=/filename\s*=\s*"((?:[^"\\]|\\.)*)"/i.exec(e);if(r)return r[1].replace(/\\(.)/g,"$1");const i=/filename\s*=\s*([^;]+)/i.exec(e);return i?i[1].trim():null}static readUrlFileName(e){if(!e)return null;const r=e.split("#")[0].split("?")[0].split("/"),i=r[r.length-1];return i===""?null:i}static sanitizeFileName(e){if(e===null)return null;const t=e.replace(/[\u0000-\u001f\u007f/\\]/g,"").trim();return t===""?null:t}async handleFetchResult(e,t,r){const i=he();if(!e.ok){if(ht(e.status))return!1;this.options.targetFragment&&t&&B.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r);const A=await this.handleFetchError(e,this.selectErrorActions(e.status)?.noMessage!==!0);return await this.injectFetchState("error",e.status,e.statusText||null,A),await this.runErrorActions(e.status),!1}if(this.options.targetFragment&&t&&r&&B.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const A=this.options.afterCallback(e);if(A!=null){if(A===!1||typeof A=="object"&&A.stop)return!1;typeof A=="object"&&"response"in A&&(e="response"in A?A.response:e)}}if(this.options.download){const A=await this.saveResponseAsFile(e,t);if(A==="cancelled")return await this.injectFetchState("success",e.status,null),!1;if(A==="failed")return await this.showDownloadFailure(),await this.injectFetchState("error",e.status,gt),!1}const n=[];n.push(this.bindResult(e)),n.push(this.adjust()),n.push(this.addRow()),n.push(this.removeRow()),n.push(this.movePrevRow()),n.push(this.moveNextRow()),await Promise.all(n),await this.injectFetchState("success",e.status,null),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(A=>F.reset(A,this.operationSequence))),await this.copy();const s=[];this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(A=>{s.push(new p(A,null).run())});const a=await this.clickTargets(this.options.clickFragments,this.options.clickAwait===!0,"click-await");if(!a&&this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(A=>{const E=A.getTarget();E instanceof HTMLElement?s.push(i.openDialog(E)):m.error("Haori","Element is not an HTML element: ",E)}),!a&&this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(A=>{const E=A.getTarget();E instanceof HTMLElement?s.push(i.closeDialog(E)):m.error("Haori","Element is not an HTML element: ",E)}),await Promise.all(s),a)return!1;const o=p.unescapeNewlines(p.normalizeAttributeText(this.resolveLateAttribute("dialog",this.options.dialogMessage)));o&&await i.dialog(o);const c=p.normalizeAttributeText(this.resolveLateAttribute("toast",this.options.toastMessage));if(c){const A=p.toToastLevel(this.resolveLateAttribute("toast-level",this.options.toastLevel));await i.toast(c,A??"info")}this.clearStore(),this.pushHistory();const u=this.resolveLateAttribute("scroll",this.options.scrollTarget);u&&J.query(u,p.attrName(this.eventType,"scroll"),document)?.scrollIntoView({behavior:"smooth",block:"nearest"});const d=this.resolveLateAttribute("redirect",this.options.redirectUrl),g=this.resolveLateAttribute("redirect-replace",this.options.redirectReplaceUrl);d&&g&&m.warn("Haori",`${p.attrName(this.eventType,"redirect")} と ${p.attrName(this.eventType,"redirect-replace")} の両方が指定されています。履歴を置き換える方を採用します。`);const y=g||d;if(y){let A=y;const E=this.resolveLateAttribute("redirect-return-param",this.options.redirectReturnParam);if(E){const x=new URLSearchParams(window.location.search).get(E);if(x!==null){const H=x.trim();pt.isSafeLocalPath(H)?A=H:m.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${x}`)}}g?window.location.replace(A):window.location.href=A}return!0}clearStore(){const e=this.options.storeClearKey;e&&Re.clear(e,this.options.storeClearKind??"session")}async clickTargets(e,t,r){if(!e||e.length===0)return!1;for(const i of e){await $.evaluateAll(i);const n=i.getTarget();if(t&&p.takeClickOutcome(n),typeof n.click=="function"?n.click():n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0})),!t)continue;const s=p.takeClickOutcome(n);if(s===null){m.warn("Haori",`${l.prefix}${this.eventType??"fetch"}-${r} はこの対象の完了を待てません(手続きが同期に起動していません)。`);continue}if(await s==="failure")return!0}return!1}async runErrorActions(e){const t=this.selectErrorActions(e);if(!t||await this.clickTargets(t.clickFragments,t.clickAwait,`${t.key}-click-await`))return;const i=he(),n=[];t.closeFragments?.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?n.push(i.closeDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(n);const s=p.normalizeAttributeText(this.resolveLateAttribute(`${t.key}-toast`,t.toastMessage));if(s){const a=p.toToastLevel(this.resolveLateAttribute(`${t.key}-toast-level`,t.toastLevel));await i.toast(s,a??"info")}}selectErrorActions(e){const t=e===null?void 0:this.options.errorStatusActions?.get(e);return t||(this.appliesErrorActions(e)?{key:"error",clickFragments:this.options.errorClickFragments??null,clickAwait:this.options.errorClickAwait===!0,closeFragments:this.options.errorCloseFragments??null,toastMessage:this.options.errorToastMessage??null,toastLevel:this.options.errorToastLevel??null,noMessage:this.options.errorNoMessage===!0}:null)}appliesErrorActions(e){const t=this.options.errorStatuses;return t===void 0||e!==null&&t.includes(e)}resolveLateAttribute(e,t){const r=t??null,i=this.options.lateAttributes?.get(e)??null,n=this.options.targetFragment??null;if(!i||!n||!n.hasAttribute(i.attributeName))return r;const s=n.getAttributeEvaluation(i.attributeName);return s===null?r:s.hasUnresolvedReference&&!i.hasUnresolvedReference?(q.isEnabled()&&m.warn("Haori",`${i.attributeName} の参照が手続きの途中で解決できなくなったため、手続き開始時の値を使います`),r):s.value??null}pushHistory(){const e=this.resolveLateAttribute("history",this.options.historyUrl),t=e!=null,r=this.resolveHistoryDataValues(),i=this.resolveHistoryFormValues(),n=r!=null,s=i!=null;if(!(!t&&!n&&!s))try{const a=t?e:window.location.pathname,o=new URL(a,window.location.href);if(o.origin!==window.location.origin){const u="history.pushState: cross-origin URL is not allowed: "+o.toString();m.error("Haori",u);return}const c=u=>{for(const[d,g]of Object.entries(u))g!=null&&(Array.isArray(g)?(o.searchParams.delete(d),g.forEach(y=>o.searchParams.append(d,String(y)))):typeof g=="object"?o.searchParams.set(d,JSON.stringify(g)):o.searchParams.set(d,String(g)))};n&&c(r),s&&c(i),history.pushState({[Pt]:!0},"",o.toString()),$.refreshUrlParams()}catch(a){m.error("Haori",`history.pushState failed: ${a}`)}}async handleFetchError(e,t){let r=null;this.options.formFragment?r=this.options.formFragment:this.options.targetFragment&&(r=F.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const i=r?r.getTarget():document.body;await he().clearMessages(i);const n=async u=>{const d=r?r.getTarget():document.body;await he().addErrorMessage(d,u)},s=()=>{if(!this.options.scrollOnError)return;const u=r?r.getTarget():document.body;(u.getAttribute("data-message-level")==="error"?u:u.parentElement?.getAttribute("data-message-level")==="error"?u.parentElement:u.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})},a=async u=>{if(t){u.length===0&&await n(`${e.status} ${e.statusText}`);for(const d of u)d.key&&r?await F.addErrorMessage(r,d.key,d.message):await n(d.message);s()}return u.length===0?null:u.map(d=>d.message).join(`
24
+ `)};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const u=await e.json(),d=[];if(Array.isArray(u)){const g=new Map,y=[];for(const A of u)if(A&&typeof A=="object"&&!Array.isArray(A)){const E=A.key,I=A.message,x=typeof E=="string"&&E.length>0?E:null,H=typeof I=="string"?I:I!=null?String(I):"";if(H.length===0)continue;if(x!==null){const k=g.get(x)??[];k.push(H),g.set(x,k)}else y.push(H)}else typeof A=="string"&&A.length>0&&y.push(A);for(const[A,E]of g)d.push({key:A,message:E.join(`
25
+ `)});for(const A of y)d.push({message:A})}else if(u&&typeof u=="object"){if(typeof u.message=="string"&&d.push({message:u.message}),Array.isArray(u.messages))for(const g of u.messages)typeof g=="string"&&d.push({message:g});if(u.errors&&typeof u.errors=="object")for(const[g,y]of Object.entries(u.errors))Array.isArray(y)?d.push({key:g,message:y.join(`
26
26
  `)}):typeof y=="string"?d.push({key:g,message:y}):y!=null&&d.push({key:g,message:String(y)});if(d.length===0)for(const[g,y]of Object.entries(u))g==="message"||g==="messages"||g==="errors"||(Array.isArray(y)?d.push({key:g,message:y.join(`
27
- `)}):typeof y=="string"&&d.push({key:g,message:y}))}return await a(d)}catch{}let c="";try{c=(await e.text()).trim()}catch{}return await a(c.length>0?[{message:c}]:[])}validate(e){if(this.options.valid!==!0)return F.warnUnvalidatedCustomValidity(e,`${l.prefix}${this.eventType??"fetch"}-validate の指定がありません`),!0;F.applyCustomValidity(e);const t=this.findFirstInvalid(e);if(t===null)return!0;const r=t;return p.isRectFullyVisible(t.getBoundingClientRect())?(r.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1):(t.focus({preventScroll:!0}),t.scrollIntoView({behavior:"smooth",block:"nearest"}),p.reportValidityAfterScroll(r),!1)}static reportValidityAfterScroll(e){const t=++p.validationReportGeneration,r=performance.now();let i=null,n=0;const s=()=>{if(t!==p.validationReportGeneration||!e.isConnected)return;const a=e.getBoundingClientRect(),o=`${Math.round(a.top)}:${Math.round(a.left)}`;if(n=o===i?n+1:0,i=o,n>=p.VALIDATION_SCROLL_STABLE_FRAMES&&p.isRectPartlyVisible(a)||performance.now()-r>=p.VALIDATION_SCROLL_TIMEOUT_MS){e.reportValidity();return}requestAnimationFrame(s)};requestAnimationFrame(s)}static getViewportSize(){return{width:window.innerWidth||document.documentElement.clientWidth,height:window.innerHeight||document.documentElement.clientHeight}}static isRectFullyVisible(e){const{width:t,height:r}=p.getViewportSize();return e.top>=0&&e.left>=0&&e.bottom<=r&&e.right<=t}static isRectPartlyVisible(e){const{width:t,height:r}=p.getViewportSize();return e.top<r&&e.bottom>0&&e.left<t&&e.right>0}evaluateExecutionCondition(e=!1){const t=this.options.conditionExpression;if(!t)return!0;const r=this.options.targetFragment;if(!r)return!0;const i=this.options.conditionAttributeName??`${l.prefix}if`,n=F.buildConditionScope(r,this.options.formFragment??null),s=re.evaluateDetailed(t,n);return s.unresolvedReference?(e||m.warn("Haori",`${i} の参照が解決できないため実行しません: ${t}`),!1):s.value?!0:(!e&&q.isEnabled()&&m.warn("Haori",`${i} の条件が偽のため手続きを中断しました: ${t}`),!1)}findFirstInvalid(e){if(e.getTarget().hasAttribute(`${l.prefix}if-false`))return null;let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):he().confirm(e)}bindResult(e){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const t=e.headers.get("Content-Type")?.includes("application/json");return e.text().then(r=>{if(r==="")return;let i=t?JSON.parse(r):r;if(this.options.bindTransform)try{i=re.evaluate(this.options.bindTransform,{response:i})}catch(o){m.error("Haori",`Invalid bind-transform: ${o}`)}if(this.options.bindParams){const o={};this.options.bindParams.forEach(c=>{i&&typeof i=="object"&&c in i&&(o[c]=i[c])}),i=o}if(this.suppressEmptyReplaceBind&&!this.options.bindArg&&!this.options.bindMerge&&i!==null&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0){m.warn("Haori",`Skipped binding because the input has no value to collect; the bind target would be replaced with an empty object. Add a name attribute to the input, or specify ${l.prefix}${this.eventType}-form.`);return}const n=[],s=this.eventType?p.attrName(this.eventType,"bind"):p.attrName(null,"bind",!0),a=[];if(this.options.bindArg)this.options.bindFragments.forEach(o=>{const c=this.resolveRowWrite(o,s);if(c.kind==="skip")return;if(c.kind==="row"){const g=this.options.bindArg;a.push({container:c.container,row:o,attributeName:s,syncWhenUnchanged:"reflect",apply:y=>{const E=this.resolveCurrentRowItem(o,y),A={...E};if(i&&typeof i=="object"&&!Array.isArray(i)){const I=E[g],x=I!==null&&typeof I=="object"&&!Array.isArray(I)?I:{};A[g]=this.mergeAppendBindingData(o,i,x)}else A[g]=i;return this.reconcileRowUserEdits(o,A)}});return}const u={...o.getRawBindingData()??{}},d=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const g=u[d],y=g&&typeof g=="object"&&!Array.isArray(g)?g:{};u[d]=this.mergeAppendBindingData(o,i,y)}else u[d]=i;n.push($.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,u),{reentrant:this.reentrantBind&&o.isExecutingBindingWork(),sequence:this.operationSequence,clearUserEdits:!1}))});else if(typeof i=="string"){if(this.options.defaultSelfBind){m.warn("Haori","string data is not bound because no bind target was specified.");return}return m.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(o=>{const c=this.resolveRowWrite(o,s);if(c.kind==="skip")return;if(c.kind==="row"){a.push({container:c.container,row:o,attributeName:s,syncWhenUnchanged:"reflect",apply:g=>{const y=this.options.bindMerge?this.resolveCurrentRowItem(o,g):g,E=this.mergeAppendBindingData(o,i,y),A=this.options.bindMerge?{...y,...E}:E;return this.reconcileRowUserEdits(o,A)}});return}const u=this.mergeAppendBindingData(o,i),d=this.options.bindMerge?{...o.getRawBindingData()??{},...u}:u;n.push($.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,d),{reentrant:this.reentrantBind&&o.isExecutingBindingWork(),sequence:this.operationSequence,clearUserEdits:!1}))});return n.push(this.applyRowWrites(a)),Promise.all(n).then(()=>{const o=this.options.bindArg??null;this.options.bindFragments.forEach(c=>{B.bindComplete(c.getTarget(),o)})})})}reconcileUserEditsForBind(e,t){const r=this.requestUserEditSequence;if(r===null)return t;const i=this.eventType==="poll";if(!i&&!this.twoWayCommitBind&&$.clearUserEditMarks(e,r),!(e.getTarget()instanceof HTMLFormElement))return this.reconcileAncestorArgFormEdits(e,t,i?0:r);const n=F.getValuesEditedAfter(e,i?0:r);if(Object.keys(n).length===0)return t;const s=e.getAttribute(`${l.prefix}form-arg`);if(s){const a=String(s),o=t[a],c=o&&typeof o=="object"&&!Array.isArray(o)?o:{};return{...t,[a]:pe(c,n)}}return pe(t,n)}reconcileRowUserEdits(e,t){const r=this.requestUserEditSequence;if(r===null)return t;const i=this.eventType==="poll";!i&&!this.twoWayCommitBind&&$.clearUserEditMarks(e,r);const n=F.getValuesEditedAfter(e,i?0:r);return Object.keys(n).length===0?t:pe(t,n)}reconcileAncestorArgFormEdits(e,t,r){let i=t;for(const{form:n,key:s}of F.collectArgForms(e)){if(!Object.prototype.hasOwnProperty.call(i,s))continue;const a=F.getValuesEditedAfter(n,r);if(Object.keys(a).length===0)continue;const o=i[s],c=o&&typeof o=="object"&&!Array.isArray(o)?o:{};i={...i,[s]:pe(c,a)}}return i}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},n=r;for(const s of this.options.bindAppendParams){const a=i[s],o=n[s];Array.isArray(o)&&Array.isArray(a)&&(i[s]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=p.attrName(this.eventType,"copy"),i=[],n=[];return this.options.copyFragments.forEach(s=>{const a=this.resolveRowWrite(s,r);if(a.kind==="skip")return;if(a.kind==="row"){i.push({container:a.container,row:s,attributeName:r,syncWhenUnchanged:"supply",apply:c=>this.applyCopyToRowItem(s,c,t)});return}const o={...s.getRawBindingData()??{},...t};n.push($.setBindingData(s.getTarget(),o,{sequence:this.operationSequence}))}),n.push(this.applyRowWrites(i)),Promise.all(n).then(()=>{})}resolveCurrentRowItem(e,t){const r=F.getValuesEditedAfter(e,0);return Object.keys(r).length===0?t:pe(t,r)}applyCopyToRowItem(e,t,r){return{...this.resolveCurrentRowItem(e,t),...r}}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?Pe(this.options.copySourceFragment):$.withoutReservedBindingKeys(this.options.copySourceFragment.getRawBindingData()??{}):this.options.formFragment?Pe(this.options.formFragment):this.options.targetFragment?$.withoutReservedBindingKeys(this.options.targetFragment.getRawBindingData()??{}):{}}buildPayloadResolution(){const e={};let t=!1;const r=this.options.formFragment??this.options.selfValueFragment;if(r){const i=F.getValues(r);Object.assign(e,i),F.carryCollectedRowIdentity(i,e)}if(this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const i=p.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||i.hasUnresolvedReference,i.value&&Object.assign(e,i.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return e.signature===null||!this.options.conditionExpression?{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}:{signature:`${e.signature}|if=${String(this.evaluateExecutionCondition(!0))}`,hasUnresolvedReference:e.hasUnresolvedReference}}prepareFetchRequest(){const e=this.buildPayloadResolution(),t=e.payload,r=!!this.options.fetchHasUnresolvedReference||e.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,baseUrl:null,options:null,payload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const n={...this.options.fetchOptions||{}},s=new Headers(n.headers||void 0),a=(n.method||"GET").toUpperCase(),o=l.runtime==="demo"&&!Ve(a),c=o?"GET":a;if(n.method=c,Object.keys(t).length>0&&De(t)){const d=s.get("Content-Type")||"";c!=="GET"&&c!=="HEAD"&&c!=="OPTIONS"&&/multipart\/form-data/i.test(d)?Kt(t)&&m.warn("Haori",`A File value nested under ${l.prefix}form-object / ${l.prefix}form-list cannot be sent. Place file inputs at the top level of the collected form values.`):m.warn("Haori",`A File value cannot be sent without ${l.prefix}fetch-content-type="multipart/form-data" and a body method such as POST.`)}if(c==="GET"||c==="HEAD"||c==="OPTIONS")Object.keys(t).length>0&&(i=mt(i,t));else if(Object.keys(t).length>0){const d=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(d)){s.delete("Content-Type");const g=new FormData;for(const[y,E]of Object.entries(t))E==null?g.append(y,""):E instanceof Blob?g.append(y,E):Array.isArray(E)?E.forEach(A=>{A instanceof Blob?g.append(y,A):g.append(y,be(A))}):g.append(y,be(E));n.body=g}else if(/application\/x-www-form-urlencoded/i.test(d)){const g=new URLSearchParams;for(const[y,E]of Object.entries(t))E!==void 0&&(Array.isArray(E)?E.forEach(A=>g.append(y,be(A))):g.append(y,be(E)));n.body=g}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}n.headers=s;let u;return o&&(u=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,baseUrl:this.options.fetchUrl,options:n,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:c,queryString:u,transportMode:o?"query-get":"http",signature:zt(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=p.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?Pe(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?p.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return Pe(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(s=>{s in e&&(r.has(s)||(i[s]=e[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=e,t.push(r.setValue(String(n)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return m.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return e||(m.error("Haori","Row fragment not found."),null)}resolveRowContainer(e){const t=this.options.targetFragment;if(!t)return m.error("Haori","Target fragment is not specified for row operation."),null;const r=p.attrName(this.eventType,e),i=J.read(t,r);if(i!==null&&i.trim()!==""){const s=J.query(i,r,document);if(s===null)return m.error("Haori",`Row container not found: ${i} (${r})`),null;const a=D.get(s);return a instanceof w?a.hasAttribute(`${l.prefix}each`)?a:(m.error("Haori",`Row container must have ${l.prefix}each: ${i} (${r})`),null):(m.error("Haori",`Row container is not initialized: ${i} (${r})`),null)}const n=this.getRowFragment();return n?n.getParent():null}static resolveEachArray(e,t=!1){const r=e.getRawAttribute(`${l.prefix}each`);if(r===null)return t||m.error("Haori",`Row container has no ${l.prefix}each expression.`),null;const i=e.getRawAttribute(`${l.prefix}each-array`),n=i!==null,s=n?`${l.prefix}each-array`:`${l.prefix}each`,a=n?i:r,o=a.trim().split(".");if(!(o.length>0&&o.every(A=>/^[A-Za-z_$][\w$]*$/.test(A))))return t||m.error("Haori",`Row operations require a plain identifier path for ${s} (got: ${a}).`+(n?"":` Declare ${l.prefix}each-array to specify the array to write back to.`)),null;if(n&&e.getRawAttribute(`${l.prefix}each-key`)===null)return t||m.error("Haori",`${l.prefix}each-array requires ${l.prefix}each-key (${l.prefix}each-array="${a}").`),null;const u=p.resolveRowScopeBase(e,o[0]);if(u==="unresolvable")return null;let d,g,y;if(u)d=u.owner,g=u.ownerData,y=[...u.path,...o.slice(1)];else{for(d=e,g=null;d;){const A=d.getRawBindingData();if(A&&o[0]in A&&!p.isRowScopeKey(d,o[0])){g=A;break}d=d.getParent()}y=o}if(!d||!g)return t||m.error("Haori",`Binding data owner not found for ${s}="${a}".`),null;const E=p.readPathValue(g,y);return Array.isArray(E)?{owner:d,ownerData:g,array:E,path:y,mapped:n}:(t||m.error("Haori",`${s}="${a}" does not resolve to an array.`),null)}static resolveRowScopeBase(e,t){let r=e;for(;r;){const i=r.closestByAttribute(`${l.prefix}row`);if(!i)return null;const n=i.getParent();if(!n)return null;if(n.getAttribute(`${l.prefix}each-arg`)===t){const s=p.resolveEachArray(n,!0);if(!s)return m.error("Haori",`Row operations cannot resolve the write-back array for ${l.prefix}each="${e.getRawAttribute(`${l.prefix}each`)}": the ancestor container that supplies "${t}" (${l.prefix}each="${n.getRawAttribute(`${l.prefix}each`)}") does not resolve to a writable array. Build the outer list with ${l.prefix}derive and declare ${l.prefix}each-array on this ${l.prefix}each.`),"unresolvable";const a=p.resolveRowIndex(n,i,s.array,`${l.prefix}each="${n.getRawAttribute(`${l.prefix}each`)}"`);return a===null?null:{owner:s.owner,ownerData:s.ownerData,path:[...s.path,String(a)]}}r=n}return null}static isRowScopeKey(e,t){if(!e.hasAttribute(`${l.prefix}row`))return!1;const r=e.getParent();return r?r.getAttribute(`${l.prefix}each-arg`)===t||r.getAttribute(`${l.prefix}each-index`)===t:!1}static readPathValue(e,t){let r=e;for(const i of t){if(r===null||typeof r!="object")return;r=r[i]}return r}static withPathValue(e,t,r){const i={...e};let n=i;for(let s=0;s<t.length-1;s+=1){const a=t[s],o=n[a],c=Array.isArray(o)?o.slice():{...o};n[a]=c,n=c}return n[t[t.length-1]]=r,i}static getRowFragments(e){return e.getChildElementFragments().filter(t=>!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`))}resolveRowWrite(e,t){const r=this.options.rowWriteTargets;if(!r||!r.has(e))return{kind:"plain"};const i=r.get(e)??null;return i===null?(m.warn("Haori",`Target is not a row of the ${l.prefix}each container (${t}).`),{kind:"skip"}):p.getRowFragments(i).includes(e)?{kind:"row",container:i}:(m.warn("Haori",`The target row is no longer in the ${l.prefix}each container; the write was skipped (${t}).`),{kind:"skip"})}applyRowWrites(e){if(e.length===0)return Promise.resolve();const t=new Map;for(const i of e){const n=t.get(i.container);n?n.push(i):t.set(i.container,[i])}const r=[];return t.forEach((i,n)=>{const s=p.resolveEachArray(n);if(!s)return;const a=s.array.slice();let o=!1;for(const u of i){const d=p.resolveRowArrayIndex(u,a);if(d===null)continue;const g=a[d];if(g===null||typeof g!="object"||Array.isArray(g)){m.warn("Haori",`Row data is not an object; the write was skipped (${u.attributeName}).`);continue}const y=u.apply(g);if(p.isSameRowItem(g,y)){u.syncWhenUnchanged&&r.push(p.syncUnchangedRowValues(u.row,y,u.syncWhenUnchanged));continue}a[d]=y,o=!0,u.syncWhenUnchanged==="supply"&&F.clearRowUserEditMarksForChangedKeys(u.row,y)}if(!o)return;const c=$.setBindingData(s.owner.getTarget(),p.withPathValue(s.ownerData,s.path,a),{reentrant:this.reentrantBind&&s.owner.isExecutingBindingWork(),kind:"nonSupply",sequence:this.operationSequence});if($.isEachUpdateRunning(n)){c.catch(u=>{m.error("Haori","Failed to write row data.",u)});return}r.push(c)}),Promise.all(r).then(()=>{})}static syncUnchangedRowValues(e,t,r){return r==="supply"&&F.clearRowUserEditMarksForChangedKeys(e,t),F.syncRowValues(e,t)}static isSameRowItem(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}static resolveRowArrayIndex(e,t){return p.resolveRowIndex(e.container,e.row,t,e.attributeName)}static resolveRowIndex(e,t,r,i){const n=p.getRowFragments(e),s=n.indexOf(t);if(s===-1)return m.warn("Haori",`The target row is no longer in the ${l.prefix}each container; the write was skipped (${i}).`),null;const a=e.getAttribute(`${l.prefix}each-key`),o=t.getListKey();if(a&&o!==null){const c=[];r.forEach((g,y)=>{$.createListKey(g,String(a),y)===o&&c.push(y)});const u=n.slice(0,s).filter(g=>g.getListKey()===o).length,d=c[u]??-1;return d===-1?(m.warn("Haori",`No array element corresponds to the target row (key "${o}"); the write was skipped (${i}).`),null):d}return s>=r.length?(m.warn("Haori",`The target row index is out of range; the write was skipped (${i}).`),null):s}addRow(){return this.options.rowAdd!==!0?Promise.resolve():this.spliceRows("row-add",(e,t)=>(e.splice(t+1,0,{}),!0))}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.options.targetFragment?.hasAttribute(p.attrName(this.eventType,"row-remove-empty"));return this.spliceRows("row-remove",(t,r)=>r<0||r>=t.length||!e&&t.length<=1?!1:(t.splice(r,1),!0))}movePrevRow(){return this.options.rowMovePrev!==!0?Promise.resolve():this.spliceRows("row-prev",(e,t,r)=>{const i=r();if(i===null||t<=0||t>=e.length)return!1;const[n]=e.splice(t,1);return e.splice(i,0,n),!0})}moveNextRow(){return this.options.rowMoveNext!==!0?Promise.resolve():this.spliceRows("row-next",(e,t,r,i)=>{const n=i();if(n===null||t<0||t>=e.length-1)return!1;const[s]=e.splice(t,1);return e.splice(n,0,s),!0})}spliceRows(e,t){const r=this.resolveRowContainer(e);if(!r)return Promise.reject(new Error("Row container not found."));const i=p.resolveEachArray(r);if(!i)return Promise.reject(new Error("Row array not resolved."));const n=this.options.targetFragment,s=n?n.closestByAttribute(`${l.prefix}row`):null,a=p.getRowFragments(r),o=s?a.indexOf(s):a.length-1,c=y=>y<0||y>=a.length?null:i.mapped?p.resolveRowIndex(r,a[y],i.array,p.attrName(this.eventType,e)):y,u=o>=0?c(o):i.mapped?i.array.length-1:o;if(u===null)return Promise.resolve();const d=i.array.slice();if(!t(d,u,()=>c(o-1),()=>c(o+1)))return Promise.resolve();const g=new Map;return a.forEach(y=>{const E=y.getListKey();E!==null&&!g.has(String(E))&&g.set(String(E),y)}),d.forEach((y,E)=>{if(p.isSameRowItem(i.array[E],y))return;const A=g.get($.createListKey(y,null,E));A&&$.clearUserEditMarks(A)}),$.setBindingData(i.owner.getTarget(),p.withPathValue(i.ownerData,i.path,d),{kind:"nonSupply",sequence:this.operationSequence})}async injectFetchState(e,t=null,r=null,i=null){const n=this.options.fetchStateFragments;if(!n||n.length===0)return;const s={status:e,loading:e==="loading",success:e==="success",error:e==="error",statusCode:t,message:r,responseMessage:i};this.options.download&&(s.receivedBytes=this.downloadReceivedBytes,s.totalBytes=this.downloadTotalBytes),await Promise.all(n.map(a=>{const o=a.getTarget(),c={...a.getRawBindingData()??{},_fetch:s};return $.setBindingData(o,c,{reflectToAttribute:!1,kind:"nonSupply",sequence:this.operationSequence})}))}};p.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,p.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,p.RUNNING_CLICK_TARGETS=new WeakSet,p.CLICK_OUTCOMES=new WeakMap,p.validationReportGeneration=0,p.VALIDATION_SCROLL_TIMEOUT_MS=1e3,p.VALIDATION_SCROLL_STABLE_FRAMES=2;let se=p;class Gt{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw m.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){ht(r.status);const n=`${r.status} ${r.statusText}`;throw m.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw m.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(m.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return m.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const f=class f{static isDeferredAttributeName(e){return f.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return f.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!f.isEvaluateAllExcludedAttributeName(e)&&f.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${l.prefix}${f.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=D.get(e);return r instanceof w?r.hasAttribute(`${l.prefix}${f.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);f.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>f.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof w?t.push(f.evaluateAll(r)):r instanceof ne&&t.push(f.evaluateText(r))}),Promise.all(t).then(()=>{})}static clearUserEditMarks(e,t=w.currentSequence()){e.clearUserEditMark(t),e.getChildren().forEach(r=>{r instanceof w&&f.clearUserEditMarks(r,t)})}static getReactiveFetchState(e){const t=f.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return f.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=f.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return f.REACTIVE_IMPORT_STATES.set(e,r),r}static reevaluateReactiveSpecialAttributes(e,t=new Set){if(t.has(e)||!e.isInitialized())return Promise.resolve();const r=[];return e.hasAttribute(`${l.prefix}validity`)&&F.applyCustomValidity(e),e.hasAttribute(`${l.prefix}fetch`)&&r.push(f.executeManagedFetch(e)),e.hasAttribute(`${l.prefix}import`)&&r.push(f.executeManagedImport(e)),e.isVisible()?(e.getChildren().forEach(i=>{i instanceof w&&r.push(f.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})):Promise.all(r).then(()=>{})}static executeManagedFetch(e,t=!1){const r=e.getTarget(),i=f.initialValueRestore;if(!t&&i!==null&&e.hasAttribute(`${l.prefix}fetch-form`))return i.then(()=>f.executeManagedFetch(e,!0)).catch(o=>{m.error("Haori",`初期表示の取得に失敗しました: ${o}`)}),Promise.resolve();const n=f.getReactiveFetchState(r),s=se.resolveAutoFetchSignature(e);if(n.running)return(s.hasUnresolvedReference||s.signature!==n.lastSignature)&&(n.rerunRequested=!0),Promise.resolve();if(s.hasUnresolvedReference||s.signature===null)return n.lastSignature=null,Promise.resolve();if(n.lastSignature===s.signature)return Promise.resolve();n.lastSignature=s.signature,n.running=!0;const a=new se(e,null);return a.markReentrantBind(),a.runWithResult().then(()=>{}).finally(()=>{if(n.running=!1,n.rerunRequested)return n.rerunRequested=!1,f.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=f.getReactiveImportState(t),i=e.getAttributeEvaluation(`${l.prefix}import`),n=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return n!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(n===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===n)return Promise.resolve();r.lastUrl=n,r.running=!0;const s=performance.now();return t.setAttribute(`${l.prefix}importing`,""),B.importStart(t,n),Gt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return K.enqueue(()=>{t.innerHTML=a}).then(()=>{t.removeAttribute(`${l.prefix}importing`),B.importEnd(t,n,o,s),f.adoptImportedChildren(e);const c=[];return e.getChildren().forEach(u=>{u instanceof w?c.push(f.scan(u.getTarget())):u instanceof ne&&c.push(f.evaluateText(u))}),Promise.all(c).then(()=>{})})}).catch(a=>{t.removeAttribute(`${l.prefix}importing`),B.importError(t,n,a),m.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,f.executeManagedImport(e)})}static adoptImportedChildren(e){const t=e.getTarget();e.getChildren().filter(r=>r.getTarget().parentNode!==t).forEach(r=>{r.remove(!1)}),t.childNodes.forEach(r=>{const i=D.get(r);i!==null&&i.getParent()!==e&&e.pushChild(i)})}static scan(e){return f.scanElement(e,!0)}static scanElement(e,t){const r=D.get(e);if(!r)return Promise.resolve();const i=f.initializeElementFragment(r,!1).then(()=>F.restoreInitialValues(e)),n=f.initialValueRestore;return f.initialValueRestore=i,i.then(()=>{f.initialValueRestore=n,t&&te.applySubtree(e)})}static applyEnhancersOnShow(e,t){const r=e.getTarget();return w.retryUnappliedValueWrites(r,t).then(()=>{te.applySubtree(r)})}static initializeFreshEachRow(e){return f.initializeElementFragment(e,!0).then(()=>{f.needsScheduledEvaluateAll(e)&&f.scheduleEvaluateAll(e),te.applySubtree(e.getTarget())})}static initializeElementFragment(e,t){return f.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():f.initializeElementAttributes(e).then(()=>{if(f.shouldSkipChildInitialization(e,t)){f.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof w?r.push(f.initializeElementFragment(i,t)):i instanceof ne&&r.push(f.evaluateText(i))}),Promise.all(r).then(()=>{f.refreshDerivedSubtreeSignature(e)})})}static syncMountedState(e){if(e.getParent()?.isMounted()){e.setMounted(!0);return}const r=e.getTarget();if(r.parentNode&&document.body.contains(r)){e.setMounted(!0);return}e.setMounted(!1)}static initializeElementAttributes(e){let t=Promise.resolve();const r=new Set;for(const i of f.PRIORITY_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>f.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||f.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>(e.markInitialized(),f.setAttribute(e.getTarget(),i,n))))}for(const i of f.DEFERRED_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>(e.markInitialized(),f.setAttribute(e.getTarget(),n,e.getRawAttribute(n)))),r.add(n))}return t.then(()=>(e.markInitialized(),F.prepareFormName(e)))}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${l.prefix}if`);return e.hasAttribute(`${l.prefix}if`)&&f.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${l.prefix}each`)}static setAttribute(e,t,r,i=!1,n){const s=D.get(e),a=f.getAliasedAttributeName(t);if(a!==null)return r===null?s.removeAliasedAttribute(t,a):s.setAliasedAttribute(t,a,r,i);const o=[];let c=null,u=null,d=null;switch(t){case`${l.prefix}bind`:{if(r!==null&&i&&s instanceof w&&s.consumeSelfWrittenBind(r))break;const g=r===null?{}:f.parseDataBind(r);if(i){const y=n??w.nextSequence();return r===null?(o.push(f.setBindingData(e,g,{reflectToAttribute:!1,sequence:y})),o.push(s.removeAttribute(t))):o.push(f.setBindingData(e,g,{sequence:y})),Promise.all(o).then(()=>{})}r===null&&s.clearBindingDataCache(),s.setBindingData(g);break}case`${l.prefix}derive`:u=f.createDeriveInputSignature(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),c=f.evaluateDerive(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),o.push(c.then(()=>{}));break;case`${l.prefix}derive-name`:u=f.createDeriveInputSignature(s,s.getRawAttribute(`${l.prefix}derive`),r),c=f.evaluateDerive(s,s.getRawAttribute(`${l.prefix}derive`),r),o.push(c.then(()=>{}));break;case`${l.prefix}if`:d=()=>f.evaluateIfOnAttributeWrite(s);break;case`${l.prefix}each`:d=()=>f.evaluateEach(s);break;case`${l.prefix}fetch`:d=()=>f.executeManagedFetch(s);break;case`${l.prefix}import`:typeof r=="string"&&(d=()=>f.executeManagedImport(s));break;case`${l.prefix}store`:r!==null&&o.push(Re.restore(s));break;case`${l.prefix}validity`:case`${l.prefix}validity-message`:return r!==null&&F.applyCustomValidity(s),Promise.all(o).then(()=>{});case`${l.prefix}url-param`:{const g=s.getAttribute(`${l.prefix}url-arg`),y=pt.readParams();g===null&&s.hasAttribute(`${l.prefix}store`)&&m.warn("Haori",`${l.prefix}url-param を ${l.prefix}url-arg なしで ${l.prefix}store と併用すると復元した値が消えます(${l.prefix}url-arg を指定してください)。`);const E={reentrant:!0,kind:"nonSupply",sequence:w.nextSequence()};if(g===null)o.push(f.setBindingData(e,y,E));else{const A=s.getRawBindingData()||{};A[String(g)]=y,o.push(f.setBindingData(e,A,E))}break}}return r===null?o.push(s.removeAttribute(t)):o.push(s.setAttribute(t,r,i)),Promise.all(o).then(()=>d===null?void 0:d()).then(()=>{if(c!==null)return s.setDeriveInputSignature(u),c.then(g=>{if(g)return f.reevaluateChildren(s)})}).then(()=>{})}static setBindingData(e,t,r={}){const i=D.get(e),n=r.skipFragments??new Set,s=r.reentrant??!1,a=r.reflectToAttribute??!0,o=r.kind??"supply",c=r.sequence??w.nextOperationSequence(),u={sequence:c,kind:o,...r.editedPaths===void 0?{}:{editedPaths:r.editedPaths}},d=o==="supply";d&&i.markSupplyApplied(c);const g=w.currentSequence(),y=i.getRawBindingData();d&&(r.clearUserEdits??!0)&&f.clearUserEditMarks(i,c);const E=a?f.resolveByPathAuthority(i,y,t,u):t;i.setBindingData(E),a&&(B.bindChange(e,y,E,"manual"),Re.mirror(i));const A=()=>{i.markBindingWorkStart();const I=i.getRawBindingData()??E;let x=a?i.setAttribute(`${l.prefix}bind`,JSON.stringify(f.withoutReservedBindingKeys(I))):Promise.resolve();return e.tagName==="FORM"&&(x=x.then(()=>{if(i.wasResetAfter(g))return;const H=i.getRawBindingData()??E;return F.syncValues(i,F.resolveSyncValues(i,H),!1,u)})),x=x.then(()=>F.syncAncestorArgForms(i,g,u,y)),x=x.then(()=>f.evaluateAll(i,n)),x=x.then(()=>w.retryUnappliedValueWrites(e,g)),x=x.then(()=>f.reevaluateReactiveSpecialAttributes(i,n)),x.then(()=>i.markBindingWorkEnd(),H=>{throw i.markBindingWorkEnd(),H})};return s?A():i.enqueueBindingWork(A)}static withoutReservedBindingKeys(e){const t={};for(const r of Object.keys(e))w.isReservedBindingKey(r)||(t[r]=e[r]);return t}static resolveByPathAuthority(e,t,r,i){const n=f.mergePathAuthority(e,t??{},r,i,"");return n===f.ABSENT_PATH?r:n}static mergePathAuthority(e,t,r,i,n){if(f.isPlainRecord(t)&&f.isPlainRecord(r)){const u=t,d=r,g={};let y=Object.keys(u).some(A=>!Object.prototype.hasOwnProperty.call(d,A));const E=new Set([...Object.keys(u),...Object.keys(d)]);for(const A of E){const I=n===""?A:`${n}.${A}`,x=f.mergePathAuthority(e,Object.prototype.hasOwnProperty.call(u,A)?u[A]:f.ABSENT_PATH,Object.prototype.hasOwnProperty.call(d,A)?d[A]:f.ABSENT_PATH,i,I);x!==f.ABSENT_PATH&&(g[A]=x),x!==(Object.prototype.hasOwnProperty.call(d,A)?d[A]:f.ABSENT_PATH)&&(y=!0)}return y?g:d}const s=f.resolveArrayPairing(e,t,r,n);if(s!==null){const u=t,d=r,g=d.map((y,E)=>f.mergePathAuthority(e,u[E],y,i,`${n}[${s[E]}]`));return g.some((y,E)=>y!==d[E])?g:d}if(f.isSameBindingValue(t,r))return r;const a=i.editedPaths?.get(n),o=a===void 0?i.kind:"edit",c={sequence:a??i.sequence,kind:o};return e.canApplyPath(n,c)?(e.markPathApplied(n,c),r):t}static resolveArrayPairing(e,t,r,i){if(!Array.isArray(t)||!Array.isArray(r)||t.length!==r.length||r.length===0)return null;const n=r.some(o=>f.isPlainRecord(o))?f.resolveEachKeyArg(e,i):null,s=t.map((o,c)=>f.createListKey(o,n,c)),a=r.map((o,c)=>f.createListKey(o,n,c));return s.some((o,c)=>o!==a[c])?null:a}static resolveEachKeyArg(e,t){const r=`${l.prefix}each`,i=e.getTarget(),n=t.replace(/\[[^\]]*\]/g,""),s=i.querySelectorAll(`[${r}]`);for(const a of Array.from(s)){const o=f.resolveEachDeclarationPath(a,i);if(o===null||o!==n)continue;const c=a.getAttribute(`${r}-key`);return c===null?null:c.trim()}return null}static resolveEachDeclarationPath(e,t){const r=`${l.prefix}each`;let i=e.getAttribute(r)?.trim()??"";if(i==="")return null;let n=e.parentElement;for(;n!==null&&n!==t;){const s=n.getAttribute(r)?.trim();if(s!=null){if(s==="")return null;const a=n.getAttribute(`${r}-arg`)?.trim();if(a!=null&&a!==""){if(i!==a&&!i.startsWith(`${a}.`))return null;i=i===a?s:`${s}.${i.slice(a.length+1)}`}else i=`${s}.${i}`}n=n.parentElement}return i}static isPlainRecord(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}static isSameBindingValue(e,t){if(e===t)return!0;if(e===f.ABSENT_PATH||t===f.ABSENT_PATH)return!1;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}static getBindingData(e,t={}){const r=D.get(e);return r instanceof w?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=f.collectScope(e);return q.isEnabled()&&m.info("[Haori]","scope dump for",e,t),t}static collectScope(e){const t=D.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=c=>{const u=c.getTarget(),d=f.resolveElementId(u);return d!==""?`#${d}`:u.tagName.toLowerCase()},s=(c,u,d,g)=>{if(c)for(const y of Object.keys(c))y in i||(i[y]={value:c[y],source:n(u),kind:d,depth:g})};let a=t,o=0;for(;a;)a!==t&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return m.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,n]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(e,t){const r=D.get(e);if(r.isSkipMutationNode(t))return Promise.resolve();const i=D.get(t.nextSibling),n=D.get(t);if(n){if(n.getParent()===r)return Promise.resolve();if(r.insertBefore(n,i),n instanceof w)return f.scan(n.getTarget());if(n instanceof ne)return f.evaluateText(n)}return Promise.resolve()}static removeNode(e){const t=D.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNode(e))return;t.remove()}}static changeText(e,t){const r=D.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=D.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=f.getFormFragment(r);if(n){const s=F.getValues(n),a=n.getAttribute(`${l.prefix}form-arg`),o=n.getRawBindingData();let c;if(a){c={...o??{}};const u=String(a),d=F.resolveAncestorArgOwner(n,u);c[u]=F.mergeCollectedValues((d?d.value:c[u])??null,s)}else c=F.mergeCollectedValues(o,s,F.ancestorBaseResolver(n));i.push(f.setBindingData(n.getTarget(),c,{kind:"nonSupply",sequence:w.nextSequence()}))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?f.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=f.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${l.prefix}derive`),n=e.hasAttribute(`${l.prefix}if`),s=e.hasAttribute(`${l.prefix}each`),a=e.getRawAttribute(`${l.prefix}derive`),o=e.getRawAttribute(`${l.prefix}derive-name`);let c=!1,u=!1,d=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const E=f.createDeriveInputSignature(e,a,o);E===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>f.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==E&&(r=r.then(()=>f.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(E)})))}let g=!1,y=0;return n&&(r=r.then(()=>{const E=e.isVisible();return y=w.currentSequence(),f.evaluateIf(e).then(()=>{g=!E&&e.isVisible()})})),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>f.evaluateEachFixedChildren(e)).then(()=>f.evaluateEach(e)).then(()=>{if(g)return f.applyEnhancersOnShow(e,y)})):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!f.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),f.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}d=f.createDescendantBindingSignature(e,"evaluateAll"),u=!0,c=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===d,f.logDerivedSubtreeProfileSnapshot(e,c?"skip-hit":"skip-miss")})),r.then(()=>{if(c)return;const E=[];return e.getChildren().forEach(A=>{if(A instanceof w){if(f.canSkipUnchangedNestedEach(A))return;E.push(f.evaluateAll(A,t))}else A instanceof ne&&E.push(f.evaluateText(A))}),Promise.all(E).then(()=>{})}).then(()=>{u&&d!==null&&e.setDeriveSubtreeSignature(d)}))}static evaluateDerive(e,t=e.getRawAttribute(`${l.prefix}derive`),r=e.getRawAttribute(`${l.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!t||n==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const s=re.evaluateDetailed(t,e.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return f.createBindingSignature(i)===f.createBindingSignature(a)?Promise.resolve(!1):(e.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(e){return e.evaluate()}static isHiddenIfCondition(e){return!e}static logFalsyIfDiagnostics(e){const t=e.getRawAttribute(`${l.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;if(re.hasCompileFailure(t)){m.warn("[Haori]","data-if is hidden because the expression could not be compiled (see the preceding compile error):",t);return}const{sources:r}=f.collectScope(e.getTarget()),i=new Set,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const c=t.indexOf(o,s);s=c+o.length,!(c>0&&t[c-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),m.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static isEachFixedChild(e){return e.hasAttribute(`${l.prefix}each-before`)||e.hasAttribute(`${l.prefix}each-after`)}static hasEachFixedChildren(e){return e.getChildren().some(t=>t instanceof w&&f.isEachFixedChild(t))}static evaluateEachFixedChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof w?f.isEachFixedChild(r)&&t.push(f.evaluateAll(r)):r instanceof ne&&t.push(f.evaluateText(r))}),Promise.all(t).then(()=>{})}static evaluateIfOnAttributeWrite(e){if(!e.hasAttribute(`${l.prefix}each`))return f.evaluateIf(e);const t=e.isVisible(),r=w.currentSequence();return f.evaluateIf(e).then(()=>{if(!t)return f.evaluateEach(e).then(()=>f.reevaluateReactiveSpecialAttributes(e)).then(()=>f.applyEnhancersOnShow(e,r))})}static evaluateIf(e){const t=[],r=e.getAttribute(`${l.prefix}if`);if(f.isHiddenIfCondition(r))q.isEnabled()&&e.isVisible()&&f.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{B.hide(e.getTarget())}));else{e.restoreFormControlsDisabledByIf();const i=e.isVisible(),n=w.currentSequence(),s=[],a=e.hasAttribute(`${l.prefix}each`);e.getChildren().forEach(o=>{if(o instanceof w){if(a&&!f.isEachFixedChild(o))return;o.isMounted()?i?s.push(f.evaluateAll(o)):s.push(f.evaluateAll(o).then(()=>f.reevaluateReactiveSpecialAttributes(o))):s.push(f.scanElement(o.getTarget(),!1))}else o instanceof ne&&s.push(f.evaluateText(o))}),t.push(e.show().then(()=>{B.show(e.getTarget()),i||(f.triggerLoadOnShow(e),te.refreshSubtree(e.getTarget(),!1))})),t.push(Promise.all(s).then(()=>{if(!(i||a))return f.applyEnhancersOnShow(e,n)}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${l.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new se(e,"load").run().catch(i=>{m.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=f.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},f.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(q.isEnabled()&&re.recordRowScopeIdentifiers([f.getRowScopeName(e,"each-arg"),f.getRowScopeName(e,"each-index")]),e.isMounted()||f.syncMountedState(e),!e.isVisible()||!e.isMounted())return e.getTarget().removeAttribute(`${l.prefix}each-done`),Promise.resolve();const t=f.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):f.runEachUpdateLoop(e,t)}static getRowScopeName(e,t){const r=e.getAttribute(`${l.prefix}${t}`);return typeof r!="string"||r===""?null:r}static isEachUpdateRunning(e){return f.getEachUpdateState(e).running}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${l.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await f.performEachUpdate(e);while(t.rerunRequested);const i=e.getTarget();i.setAttribute(`${l.prefix}each-done`,""),te.refreshSubtree(i,!1),f.runEachRenderedScript(i)}finally{t.running=!1,t.settled=null}f.runEachRenderedChange(e)})();return t.settled=r,r}static runEachRenderedScript(e){const t=`${l.prefix}each-rendered-run`;if(!e.hasAttribute(t))return;const r=String(e.getAttribute(t)??"");let i=null;try{i=new Function(`"use strict"; return (
27
+ `)}):typeof y=="string"&&d.push({key:g,message:y}))}return await a(d)}catch{}let c="";try{c=(await e.text()).trim()}catch{}return await a(c.length>0?[{message:c}]:[])}validate(e){if(this.options.valid!==!0)return F.warnUnvalidatedCustomValidity(e,`${l.prefix}${this.eventType??"fetch"}-validate の指定がありません`),!0;F.applyCustomValidity(e);const t=this.findFirstInvalid(e);if(t===null)return!0;const r=t;return p.isRectFullyVisible(t.getBoundingClientRect())?(r.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1):(t.focus({preventScroll:!0}),t.scrollIntoView({behavior:"smooth",block:"nearest"}),p.reportValidityAfterScroll(r),!1)}static reportValidityAfterScroll(e){const t=++p.validationReportGeneration,r=performance.now();let i=null,n=0;const s=()=>{if(t!==p.validationReportGeneration||!e.isConnected)return;const a=e.getBoundingClientRect(),o=`${Math.round(a.top)}:${Math.round(a.left)}`;if(n=o===i?n+1:0,i=o,n>=p.VALIDATION_SCROLL_STABLE_FRAMES&&p.isRectPartlyVisible(a)||performance.now()-r>=p.VALIDATION_SCROLL_TIMEOUT_MS){e.reportValidity();return}requestAnimationFrame(s)};requestAnimationFrame(s)}static getViewportSize(){return{width:window.innerWidth||document.documentElement.clientWidth,height:window.innerHeight||document.documentElement.clientHeight}}static isRectFullyVisible(e){const{width:t,height:r}=p.getViewportSize();return e.top>=0&&e.left>=0&&e.bottom<=r&&e.right<=t}static isRectPartlyVisible(e){const{width:t,height:r}=p.getViewportSize();return e.top<r&&e.bottom>0&&e.left<t&&e.right>0}evaluateExecutionCondition(e=!1){const t=this.options.conditionExpression;if(!t)return!0;const r=this.options.targetFragment;if(!r)return!0;const i=this.options.conditionAttributeName??`${l.prefix}if`,n=F.buildConditionScope(r,this.options.formFragment??null),s=re.evaluateDetailed(t,n);return s.unresolvedReference?(e||m.warn("Haori",`${i} の参照が解決できないため実行しません: ${t}`),!1):s.value?!0:(!e&&q.isEnabled()&&m.warn("Haori",`${i} の条件が偽のため手続きを中断しました: ${t}`),!1)}findFirstInvalid(e){if(e.getTarget().hasAttribute(`${l.prefix}if-false`))return null;let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):he().confirm(e)}bindResult(e){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const t=e.headers.get("Content-Type")?.includes("application/json");return e.text().then(r=>{if(r==="")return;let i=t?JSON.parse(r):r;if(this.options.bindTransform)try{i=re.evaluate(this.options.bindTransform,{response:i})}catch(o){m.error("Haori",`Invalid bind-transform: ${o}`)}if(this.options.bindParams){const o={};this.options.bindParams.forEach(c=>{i&&typeof i=="object"&&c in i&&(o[c]=i[c])}),i=o}if(this.suppressEmptyReplaceBind&&!this.options.bindArg&&!this.options.bindMerge&&i!==null&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0){m.warn("Haori",`Skipped binding because the input has no value to collect; the bind target would be replaced with an empty object. Add a name attribute to the input, or specify ${l.prefix}${this.eventType}-form.`);return}const n=[],s=this.eventType?p.attrName(this.eventType,"bind"):p.attrName(null,"bind",!0),a=[];if(this.options.bindArg)this.options.bindFragments.forEach(o=>{const c=this.resolveRowWrite(o,s);if(c.kind==="skip")return;if(c.kind==="row"){const g=this.options.bindArg;a.push({container:c.container,row:o,attributeName:s,syncWhenUnchanged:"reflect",apply:y=>{const A=this.resolveCurrentRowItem(o,y),E={...A};if(i&&typeof i=="object"&&!Array.isArray(i)){const I=A[g],x=I!==null&&typeof I=="object"&&!Array.isArray(I)?I:{};E[g]=this.mergeAppendBindingData(o,i,x)}else E[g]=i;return this.reconcileRowUserEdits(o,E)}});return}const u={...o.getRawBindingData()??{}},d=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const g=u[d],y=g&&typeof g=="object"&&!Array.isArray(g)?g:{};u[d]=this.mergeAppendBindingData(o,i,y)}else u[d]=i;n.push($.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,u),{reentrant:this.reentrantBind&&o.isExecutingBindingWork(),sequence:this.operationSequence,clearUserEdits:!1}))});else if(typeof i=="string"){if(this.options.defaultSelfBind){m.warn("Haori","string data is not bound because no bind target was specified.");return}return m.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(o=>{const c=this.resolveRowWrite(o,s);if(c.kind==="skip")return;if(c.kind==="row"){a.push({container:c.container,row:o,attributeName:s,syncWhenUnchanged:"reflect",apply:g=>{const y=this.options.bindMerge?this.resolveCurrentRowItem(o,g):g,A=this.mergeAppendBindingData(o,i,y),E=this.options.bindMerge?{...y,...A}:A;return this.reconcileRowUserEdits(o,E)}});return}const u=this.mergeAppendBindingData(o,i),d=this.options.bindMerge?{...o.getRawBindingData()??{},...u}:u;n.push($.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,d),{reentrant:this.reentrantBind&&o.isExecutingBindingWork(),sequence:this.operationSequence,clearUserEdits:!1}))});return n.push(this.applyRowWrites(a)),Promise.all(n).then(()=>{const o=this.options.bindArg??null;this.options.bindFragments.forEach(c=>{B.bindComplete(c.getTarget(),o)})})})}reconcileUserEditsForBind(e,t){const r=this.requestUserEditSequence;if(r===null)return t;const i=this.eventType==="poll";if(!i&&!this.twoWayCommitBind&&$.clearUserEditMarks(e,r),!(e.getTarget()instanceof HTMLFormElement))return this.reconcileAncestorArgFormEdits(e,t,i?0:r);const n=F.getValuesEditedAfter(e,i?0:r);if(Object.keys(n).length===0)return t;const s=e.getAttribute(`${l.prefix}form-arg`);if(s){const a=String(s),o=t[a],c=o&&typeof o=="object"&&!Array.isArray(o)?o:{};return{...t,[a]:pe(c,n)}}return pe(t,n)}reconcileRowUserEdits(e,t){const r=this.requestUserEditSequence;if(r===null)return t;const i=this.eventType==="poll";!i&&!this.twoWayCommitBind&&$.clearUserEditMarks(e,r);const n=F.getValuesEditedAfter(e,i?0:r);return Object.keys(n).length===0?t:pe(t,n)}reconcileAncestorArgFormEdits(e,t,r){let i=t;for(const{form:n,key:s}of F.collectArgForms(e)){if(!Object.prototype.hasOwnProperty.call(i,s))continue;const a=F.getValuesEditedAfter(n,r);if(Object.keys(a).length===0)continue;const o=i[s],c=o&&typeof o=="object"&&!Array.isArray(o)?o:{};i={...i,[s]:pe(c,a)}}return i}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},n=r;for(const s of this.options.bindAppendParams){const a=i[s],o=n[s];Array.isArray(o)&&Array.isArray(a)&&(i[s]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=p.attrName(this.eventType,"copy"),i=[],n=[];return this.options.copyFragments.forEach(s=>{const a=this.resolveRowWrite(s,r);if(a.kind==="skip")return;if(a.kind==="row"){i.push({container:a.container,row:s,attributeName:r,syncWhenUnchanged:"supply",apply:c=>this.applyCopyToRowItem(s,c,t)});return}const o={...s.getRawBindingData()??{},...t};n.push($.setBindingData(s.getTarget(),o,{sequence:this.operationSequence}))}),n.push(this.applyRowWrites(i)),Promise.all(n).then(()=>{})}resolveCurrentRowItem(e,t){const r=F.getValuesEditedAfter(e,0);return Object.keys(r).length===0?t:pe(t,r)}applyCopyToRowItem(e,t,r){return{...this.resolveCurrentRowItem(e,t),...r}}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?Pe(this.options.copySourceFragment):$.withoutReservedBindingKeys(this.options.copySourceFragment.getRawBindingData()??{}):this.options.formFragment?Pe(this.options.formFragment):this.options.targetFragment?$.withoutReservedBindingKeys(this.options.targetFragment.getRawBindingData()??{}):{}}buildPayloadResolution(){const e={};let t=!1;const r=this.options.formFragment??this.options.selfValueFragment;if(r){const i=F.getValues(r);Object.assign(e,i),F.carryCollectedRowIdentity(i,e)}if(this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const i=p.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||i.hasUnresolvedReference,i.value&&Object.assign(e,i.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return e.signature===null||!this.options.conditionExpression?{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}:{signature:`${e.signature}|if=${String(this.evaluateExecutionCondition(!0))}`,hasUnresolvedReference:e.hasUnresolvedReference}}prepareFetchRequest(){const e=this.buildPayloadResolution(),t=e.payload,r=!!this.options.fetchHasUnresolvedReference||e.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,baseUrl:null,options:null,payload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const n={...this.options.fetchOptions||{}},s=new Headers(n.headers||void 0),a=(n.method||"GET").toUpperCase(),o=l.runtime==="demo"&&!Ve(a),c=o?"GET":a;if(n.method=c,Object.keys(t).length>0&&De(t)){const d=s.get("Content-Type")||"";c!=="GET"&&c!=="HEAD"&&c!=="OPTIONS"&&/multipart\/form-data/i.test(d)?Kt(t)&&m.warn("Haori",`A File value nested under ${l.prefix}form-object / ${l.prefix}form-list cannot be sent. Place file inputs at the top level of the collected form values.`):m.warn("Haori",`A File value cannot be sent without ${l.prefix}fetch-content-type="multipart/form-data" and a body method such as POST.`)}if(c==="GET"||c==="HEAD"||c==="OPTIONS")Object.keys(t).length>0&&(i=mt(i,t));else if(Object.keys(t).length>0){const d=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(d)){s.delete("Content-Type");const g=new FormData;for(const[y,A]of Object.entries(t))A==null?g.append(y,""):A instanceof Blob?g.append(y,A):Array.isArray(A)?A.forEach(E=>{E instanceof Blob?g.append(y,E):g.append(y,be(E))}):g.append(y,be(A));n.body=g}else if(/application\/x-www-form-urlencoded/i.test(d)){const g=new URLSearchParams;for(const[y,A]of Object.entries(t))A!==void 0&&(Array.isArray(A)?A.forEach(E=>g.append(y,be(E))):g.append(y,be(A)));n.body=g}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}n.headers=s;let u;return o&&(u=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,baseUrl:this.options.fetchUrl,options:n,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:c,queryString:u,transportMode:o?"query-get":"http",signature:zt(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=p.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?Pe(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?p.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return Pe(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(s=>{s in e&&(r.has(s)||(i[s]=e[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=e,t.push(r.setValue(String(n)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return m.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return e||(m.error("Haori","Row fragment not found."),null)}resolveRowContainer(e){const t=this.options.targetFragment;if(!t)return m.error("Haori","Target fragment is not specified for row operation."),null;const r=p.attrName(this.eventType,e),i=J.read(t,r);if(i!==null&&i.trim()!==""){const s=J.query(i,r,document);if(s===null)return m.error("Haori",`Row container not found: ${i} (${r})`),null;const a=D.get(s);return a instanceof w?a.hasAttribute(`${l.prefix}each`)?a:(m.error("Haori",`Row container must have ${l.prefix}each: ${i} (${r})`),null):(m.error("Haori",`Row container is not initialized: ${i} (${r})`),null)}const n=this.getRowFragment();return n?n.getParent():null}static resolveEachArray(e,t=!1){const r=e.getRawAttribute(`${l.prefix}each`);if(r===null)return t||m.error("Haori",`Row container has no ${l.prefix}each expression.`),null;const i=e.getRawAttribute(`${l.prefix}each-array`),n=i!==null,s=n?`${l.prefix}each-array`:`${l.prefix}each`,a=n?i:r,o=a.trim().split(".");if(!(o.length>0&&o.every(E=>/^[A-Za-z_$][\w$]*$/.test(E))))return t||m.error("Haori",`Row operations require a plain identifier path for ${s} (got: ${a}).`+(n?"":` Declare ${l.prefix}each-array to specify the array to write back to.`)),null;if(n&&e.getRawAttribute(`${l.prefix}each-key`)===null)return t||m.error("Haori",`${l.prefix}each-array requires ${l.prefix}each-key (${l.prefix}each-array="${a}").`),null;const u=p.resolveRowScopeBase(e,o[0]);if(u==="unresolvable")return null;let d,g,y;if(u)d=u.owner,g=u.ownerData,y=[...u.path,...o.slice(1)];else{for(d=e,g=null;d;){const E=d.getRawBindingData();if(E&&o[0]in E&&!p.isRowScopeKey(d,o[0])){g=E;break}d=d.getParent()}y=o}if(!d||!g)return t||m.error("Haori",`Binding data owner not found for ${s}="${a}".`),null;const A=p.readPathValue(g,y);return Array.isArray(A)?{owner:d,ownerData:g,array:A,path:y,mapped:n}:(t||m.error("Haori",`${s}="${a}" does not resolve to an array.`),null)}static resolveRowScopeBase(e,t){let r=e;for(;r;){const i=r.closestByAttribute(`${l.prefix}row`);if(!i)return null;const n=i.getParent();if(!n)return null;if(n.getAttribute(`${l.prefix}each-arg`)===t){const s=p.resolveEachArray(n,!0);if(!s)return m.error("Haori",`Row operations cannot resolve the write-back array for ${l.prefix}each="${e.getRawAttribute(`${l.prefix}each`)}": the ancestor container that supplies "${t}" (${l.prefix}each="${n.getRawAttribute(`${l.prefix}each`)}") does not resolve to a writable array. Build the outer list with ${l.prefix}derive and declare ${l.prefix}each-array on this ${l.prefix}each.`),"unresolvable";const a=p.resolveRowIndex(n,i,s.array,`${l.prefix}each="${n.getRawAttribute(`${l.prefix}each`)}"`);return a===null?null:{owner:s.owner,ownerData:s.ownerData,path:[...s.path,String(a)]}}r=n}return null}static isRowScopeKey(e,t){if(!e.hasAttribute(`${l.prefix}row`))return!1;const r=e.getParent();return r?r.getAttribute(`${l.prefix}each-arg`)===t||r.getAttribute(`${l.prefix}each-index`)===t:!1}static readPathValue(e,t){let r=e;for(const i of t){if(r===null||typeof r!="object")return;r=r[i]}return r}static withPathValue(e,t,r){const i={...e};let n=i;for(let s=0;s<t.length-1;s+=1){const a=t[s],o=n[a],c=Array.isArray(o)?o.slice():{...o};n[a]=c,n=c}return n[t[t.length-1]]=r,i}static getRowFragments(e){return e.getChildElementFragments().filter(t=>!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`))}resolveRowWrite(e,t){const r=this.options.rowWriteTargets;if(!r||!r.has(e))return{kind:"plain"};const i=r.get(e)??null;return i===null?(m.warn("Haori",`Target is not a row of the ${l.prefix}each container (${t}).`),{kind:"skip"}):p.getRowFragments(i).includes(e)?{kind:"row",container:i}:(m.warn("Haori",`The target row is no longer in the ${l.prefix}each container; the write was skipped (${t}).`),{kind:"skip"})}applyRowWrites(e){if(e.length===0)return Promise.resolve();const t=new Map;for(const i of e){const n=t.get(i.container);n?n.push(i):t.set(i.container,[i])}const r=[];return t.forEach((i,n)=>{const s=p.resolveEachArray(n);if(!s)return;const a=s.array.slice();let o=!1;for(const u of i){const d=p.resolveRowArrayIndex(u,a);if(d===null)continue;const g=a[d];if(g===null||typeof g!="object"||Array.isArray(g)){m.warn("Haori",`Row data is not an object; the write was skipped (${u.attributeName}).`);continue}const y=u.apply(g);if(p.isSameRowItem(g,y)){u.syncWhenUnchanged&&r.push(p.syncUnchangedRowValues(u.row,y,u.syncWhenUnchanged));continue}a[d]=y,o=!0,u.syncWhenUnchanged==="supply"&&F.clearRowUserEditMarksForChangedKeys(u.row,y)}if(!o)return;const c=$.setBindingData(s.owner.getTarget(),p.withPathValue(s.ownerData,s.path,a),{reentrant:this.reentrantBind&&s.owner.isExecutingBindingWork(),kind:"nonSupply",sequence:this.operationSequence});if($.isEachUpdateRunning(n)){c.catch(u=>{m.error("Haori","Failed to write row data.",u)});return}r.push(c)}),Promise.all(r).then(()=>{})}static syncUnchangedRowValues(e,t,r){return r==="supply"&&F.clearRowUserEditMarksForChangedKeys(e,t),F.syncRowValues(e,t)}static isSameRowItem(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}static resolveRowArrayIndex(e,t){return p.resolveRowIndex(e.container,e.row,t,e.attributeName)}static resolveRowIndex(e,t,r,i){const n=p.getRowFragments(e),s=n.indexOf(t);if(s===-1)return m.warn("Haori",`The target row is no longer in the ${l.prefix}each container; the write was skipped (${i}).`),null;const a=e.getAttribute(`${l.prefix}each-key`),o=t.getListKey();if(a&&o!==null){const c=[];r.forEach((g,y)=>{$.createListKey(g,String(a),y)===o&&c.push(y)});const u=n.slice(0,s).filter(g=>g.getListKey()===o).length,d=c[u]??-1;return d===-1?(m.warn("Haori",`No array element corresponds to the target row (key "${o}"); the write was skipped (${i}).`),null):d}return s>=r.length?(m.warn("Haori",`The target row index is out of range; the write was skipped (${i}).`),null):s}addRow(){return this.options.rowAdd!==!0?Promise.resolve():this.spliceRows("row-add",(e,t)=>(e.splice(t+1,0,{}),!0))}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.options.targetFragment?.hasAttribute(p.attrName(this.eventType,"row-remove-empty"));return this.spliceRows("row-remove",(t,r)=>r<0||r>=t.length||!e&&t.length<=1?!1:(t.splice(r,1),!0))}movePrevRow(){return this.options.rowMovePrev!==!0?Promise.resolve():this.spliceRows("row-prev",(e,t,r)=>{const i=r();if(i===null||t<=0||t>=e.length)return!1;const[n]=e.splice(t,1);return e.splice(i,0,n),!0})}moveNextRow(){return this.options.rowMoveNext!==!0?Promise.resolve():this.spliceRows("row-next",(e,t,r,i)=>{const n=i();if(n===null||t<0||t>=e.length-1)return!1;const[s]=e.splice(t,1);return e.splice(n,0,s),!0})}spliceRows(e,t){const r=this.resolveRowContainer(e);if(!r)return Promise.reject(new Error("Row container not found."));const i=p.resolveEachArray(r);if(!i)return Promise.reject(new Error("Row array not resolved."));const n=this.options.targetFragment,s=n?n.closestByAttribute(`${l.prefix}row`):null,a=p.getRowFragments(r),o=s?a.indexOf(s):a.length-1,c=y=>y<0||y>=a.length?null:i.mapped?p.resolveRowIndex(r,a[y],i.array,p.attrName(this.eventType,e)):y,u=o>=0?c(o):i.mapped?i.array.length-1:o;if(u===null)return Promise.resolve();const d=i.array.slice();if(!t(d,u,()=>c(o-1),()=>c(o+1)))return Promise.resolve();const g=new Map;return a.forEach(y=>{const A=y.getListKey();A!==null&&!g.has(String(A))&&g.set(String(A),y)}),d.forEach((y,A)=>{if(p.isSameRowItem(i.array[A],y))return;const E=g.get($.createListKey(y,null,A));E&&$.clearUserEditMarks(E)}),$.setBindingData(i.owner.getTarget(),p.withPathValue(i.ownerData,i.path,d),{kind:"nonSupply",sequence:this.operationSequence})}async injectFetchState(e,t=null,r=null,i=null){const n=this.options.fetchStateFragments;if(!n||n.length===0)return;const s={status:e,loading:e==="loading",success:e==="success",error:e==="error",statusCode:t,message:r,responseMessage:i};this.options.download&&(s.receivedBytes=this.downloadReceivedBytes,s.totalBytes=this.downloadTotalBytes),await Promise.all(n.map(a=>{const o=a.getTarget(),c={...a.getRawBindingData()??{},_fetch:s};return $.setBindingData(o,c,{reflectToAttribute:!1,kind:"nonSupply",sequence:this.operationSequence})}))}};p.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,p.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,p.RUNNING_CLICK_TARGETS=new WeakSet,p.CLICK_OUTCOMES=new WeakMap,p.validationReportGeneration=0,p.VALIDATION_SCROLL_TIMEOUT_MS=1e3,p.VALIDATION_SCROLL_STABLE_FRAMES=2;let se=p;class Gt{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw m.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){ht(r.status);const n=`${r.status} ${r.statusText}`;throw m.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw m.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(m.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return m.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const f=class f{static isDeferredAttributeName(e){return f.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return f.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!f.isEvaluateAllExcludedAttributeName(e)&&f.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${l.prefix}${f.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=D.get(e);return r instanceof w?r.hasAttribute(`${l.prefix}${f.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);f.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>f.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof w?t.push(f.evaluateAll(r)):r instanceof ne&&t.push(f.evaluateText(r))}),Promise.all(t).then(()=>{})}static clearUserEditMarks(e,t=w.currentSequence()){e.clearUserEditMark(t),e.getChildren().forEach(r=>{r instanceof w&&f.clearUserEditMarks(r,t)})}static getReactiveFetchState(e){const t=f.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return f.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=f.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return f.REACTIVE_IMPORT_STATES.set(e,r),r}static reevaluateReactiveSpecialAttributes(e,t=new Set){if(t.has(e)||!e.isInitialized())return Promise.resolve();const r=[];return e.hasAttribute(`${l.prefix}validity`)&&F.applyCustomValidity(e),e.hasAttribute(`${l.prefix}fetch`)&&r.push(f.executeManagedFetch(e)),e.hasAttribute(`${l.prefix}import`)&&r.push(f.executeManagedImport(e)),e.isVisible()?(e.getChildren().forEach(i=>{i instanceof w&&r.push(f.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})):Promise.all(r).then(()=>{})}static executeManagedFetch(e,t=!1){const r=e.getTarget(),i=f.initialValueRestore;if(!t&&i!==null&&e.hasAttribute(`${l.prefix}fetch-form`))return i.then(()=>f.executeManagedFetch(e,!0)).catch(o=>{m.error("Haori",`初期表示の取得に失敗しました: ${o}`)}),Promise.resolve();const n=f.getReactiveFetchState(r),s=se.resolveAutoFetchSignature(e);if(n.running)return(s.hasUnresolvedReference||s.signature!==n.lastSignature)&&(n.rerunRequested=!0),Promise.resolve();if(s.hasUnresolvedReference||s.signature===null)return n.lastSignature=null,Promise.resolve();if(n.lastSignature===s.signature)return Promise.resolve();n.lastSignature=s.signature,n.running=!0;const a=new se(e,null);return a.markReentrantBind(),a.runWithResult().then(()=>{}).finally(()=>{if(n.running=!1,n.rerunRequested)return n.rerunRequested=!1,f.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=f.getReactiveImportState(t),i=e.getAttributeEvaluation(`${l.prefix}import`),n=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return n!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(n===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===n)return Promise.resolve();r.lastUrl=n,r.running=!0;const s=performance.now();return t.setAttribute(`${l.prefix}importing`,""),B.importStart(t,n),Gt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return K.enqueue(()=>{t.innerHTML=a}).then(()=>{t.removeAttribute(`${l.prefix}importing`),B.importEnd(t,n,o,s),f.adoptImportedChildren(e);const c=[];return e.getChildren().forEach(u=>{u instanceof w?c.push(f.scan(u.getTarget())):u instanceof ne&&c.push(f.evaluateText(u))}),Promise.all(c).then(()=>{})})}).catch(a=>{t.removeAttribute(`${l.prefix}importing`),B.importError(t,n,a),m.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,f.executeManagedImport(e)})}static adoptImportedChildren(e){const t=e.getTarget();e.getChildren().filter(r=>r.getTarget().parentNode!==t).forEach(r=>{r.remove(!1)}),t.childNodes.forEach(r=>{const i=D.get(r);i!==null&&i.getParent()!==e&&e.pushChild(i)})}static scan(e){return f.scanElement(e,!0)}static scanElement(e,t){const r=D.get(e);if(!r)return Promise.resolve();const i=f.initializeElementFragment(r,!1).then(()=>F.restoreInitialValues(e)),n=f.initialValueRestore;return f.initialValueRestore=i,i.then(()=>{f.initialValueRestore=n,t&&te.applySubtree(e)})}static applyEnhancersOnShow(e,t){const r=e.getTarget();return w.retryUnappliedValueWrites(r,t).then(()=>{te.applySubtree(r)})}static initializeFreshEachRow(e){return f.initializeElementFragment(e,!0).then(()=>{f.needsScheduledEvaluateAll(e)&&f.scheduleEvaluateAll(e),te.applySubtree(e.getTarget())})}static initializeElementFragment(e,t){return f.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():f.initializeElementAttributes(e).then(()=>{if(f.shouldSkipChildInitialization(e,t)){f.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof w?r.push(f.initializeElementFragment(i,t)):i instanceof ne&&r.push(f.evaluateText(i))}),Promise.all(r).then(()=>{f.refreshDerivedSubtreeSignature(e)})})}static syncMountedState(e){if(e.getParent()?.isMounted()){e.setMounted(!0);return}const r=e.getTarget();if(r.parentNode&&document.body.contains(r)){e.setMounted(!0);return}e.setMounted(!1)}static initializeElementAttributes(e){let t=Promise.resolve();const r=new Set;for(const i of f.PRIORITY_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>f.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||f.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>(e.markInitialized(),f.setAttribute(e.getTarget(),i,n))))}for(const i of f.DEFERRED_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>(e.markInitialized(),f.setAttribute(e.getTarget(),n,e.getRawAttribute(n)))),r.add(n))}return t.then(()=>(e.markInitialized(),F.prepareFormName(e)))}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${l.prefix}if`);return e.hasAttribute(`${l.prefix}if`)&&f.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${l.prefix}each`)}static setAttribute(e,t,r,i=!1,n){const s=D.get(e),a=f.getAliasedAttributeName(t);if(a!==null)return r===null?s.removeAliasedAttribute(t,a):s.setAliasedAttribute(t,a,r,i);const o=[];let c=null,u=null,d=null;switch(t){case`${l.prefix}bind`:{if(r!==null&&i&&s instanceof w&&s.consumeSelfWrittenBind(r))break;const g=r===null?{}:f.parseDataBind(r);if(i){const y=n??w.nextSequence();return r===null?(o.push(f.setBindingData(e,g,{reflectToAttribute:!1,sequence:y})),o.push(s.removeAttribute(t))):o.push(f.setBindingData(e,g,{sequence:y})),Promise.all(o).then(()=>{})}r===null&&s.clearBindingDataCache(),s.setBindingData(g);break}case`${l.prefix}derive`:u=f.createDeriveInputSignature(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),c=f.evaluateDerive(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),o.push(c.then(()=>{}));break;case`${l.prefix}derive-name`:u=f.createDeriveInputSignature(s,s.getRawAttribute(`${l.prefix}derive`),r),c=f.evaluateDerive(s,s.getRawAttribute(`${l.prefix}derive`),r),o.push(c.then(()=>{}));break;case`${l.prefix}if`:d=()=>f.evaluateIfOnAttributeWrite(s);break;case`${l.prefix}each`:d=()=>f.evaluateEach(s);break;case`${l.prefix}fetch`:d=()=>f.executeManagedFetch(s);break;case`${l.prefix}import`:typeof r=="string"&&(d=()=>f.executeManagedImport(s));break;case`${l.prefix}store`:r!==null&&o.push(Re.restore(s));break;case`${l.prefix}validity`:case`${l.prefix}validity-message`:return r!==null&&F.applyCustomValidity(s),Promise.all(o).then(()=>{});case`${l.prefix}url-param`:{const g=s.getAttribute(`${l.prefix}url-arg`),y=pt.readParams();g===null&&s.hasAttribute(`${l.prefix}store`)&&m.warn("Haori",`${l.prefix}url-param を ${l.prefix}url-arg なしで ${l.prefix}store と併用すると復元した値が消えます(${l.prefix}url-arg を指定してください)。`);const A={reentrant:!0,kind:"nonSupply",sequence:w.nextSequence()};if(g===null)o.push(f.setBindingData(e,y,A));else{const E=s.getRawBindingData()||{};E[String(g)]=y,o.push(f.setBindingData(e,E,A))}break}}return r===null?o.push(s.removeAttribute(t)):o.push(s.setAttribute(t,r,i)),Promise.all(o).then(()=>d===null?void 0:d()).then(()=>{if(c!==null)return s.setDeriveInputSignature(u),c.then(g=>{if(g)return f.reevaluateChildren(s)})}).then(()=>{})}static setBindingData(e,t,r={}){const i=D.get(e),n=r.skipFragments??new Set,s=r.reentrant??!1,a=r.reflectToAttribute??!0,o=r.kind??"supply",c=r.sequence??w.nextOperationSequence(),u={sequence:c,kind:o,...r.editedPaths===void 0?{}:{editedPaths:r.editedPaths}},d=o==="supply";d&&i.markSupplyApplied(c);const g=w.currentSequence(),y=i.getRawBindingData();d&&(r.clearUserEdits??!0)&&f.clearUserEditMarks(i,c);const A=a?f.resolveByPathAuthority(i,y,t,u):t;i.setBindingData(A),a&&(B.bindChange(e,y,A,"manual"),Re.mirror(i));const E=()=>{i.markBindingWorkStart();const I=i.getRawBindingData()??A;let x=a?i.setAttribute(`${l.prefix}bind`,JSON.stringify(f.withoutReservedBindingKeys(I))):Promise.resolve();return e.tagName==="FORM"&&(x=x.then(()=>{if(i.wasResetAfter(g))return;const H=i.getRawBindingData()??A;return F.syncValues(i,F.resolveSyncValues(i,H),!1,u)})),x=x.then(()=>F.syncAncestorArgForms(i,g,u,y)),x=x.then(()=>f.evaluateAll(i,n)),x=x.then(()=>w.retryUnappliedValueWrites(e,g)),x=x.then(()=>f.reevaluateReactiveSpecialAttributes(i,n)),x.then(()=>i.markBindingWorkEnd(),H=>{throw i.markBindingWorkEnd(),H})};return s?E():i.enqueueBindingWork(E)}static withoutReservedBindingKeys(e){const t={};for(const r of Object.keys(e))w.isReservedBindingKey(r)||(t[r]=e[r]);return t}static resolveByPathAuthority(e,t,r,i){const n=f.mergePathAuthority(e,t??{},r,i,"");return n===f.ABSENT_PATH?r:n}static mergePathAuthority(e,t,r,i,n){if(f.isPlainRecord(t)&&f.isPlainRecord(r)){const u=t,d=r,g={};let y=Object.keys(u).some(E=>!Object.prototype.hasOwnProperty.call(d,E));const A=new Set([...Object.keys(u),...Object.keys(d)]);for(const E of A){const I=n===""?E:`${n}.${E}`,x=f.mergePathAuthority(e,Object.prototype.hasOwnProperty.call(u,E)?u[E]:f.ABSENT_PATH,Object.prototype.hasOwnProperty.call(d,E)?d[E]:f.ABSENT_PATH,i,I);x!==f.ABSENT_PATH&&(g[E]=x),x!==(Object.prototype.hasOwnProperty.call(d,E)?d[E]:f.ABSENT_PATH)&&(y=!0)}return y?g:d}const s=f.resolveArrayPairing(e,t,r,n);if(s!==null){const u=t,d=r,g=d.map((y,A)=>f.mergePathAuthority(e,u[A],y,i,`${n}[${s[A]}]`));return g.some((y,A)=>y!==d[A])?g:d}if(f.isSameBindingValue(t,r))return r;const a=i.editedPaths?.get(n),o=a===void 0?i.kind:"edit",c={sequence:a??i.sequence,kind:o};return e.canApplyPath(n,c)?(e.markPathApplied(n,c),r):t}static resolveArrayPairing(e,t,r,i){if(!Array.isArray(t)||!Array.isArray(r)||t.length!==r.length||r.length===0)return null;const n=r.some(o=>f.isPlainRecord(o))?f.resolveEachKeyArg(e,i):null,s=t.map((o,c)=>f.createListKey(o,n,c)),a=r.map((o,c)=>f.createListKey(o,n,c));return s.some((o,c)=>o!==a[c])?null:a}static resolveEachKeyArg(e,t){const r=`${l.prefix}each`,i=e.getTarget(),n=t.replace(/\[[^\]]*\]/g,""),s=i.querySelectorAll(`[${r}]`);for(const a of Array.from(s)){const o=f.resolveEachDeclarationPath(a,i);if(o===null||o!==n)continue;const c=a.getAttribute(`${r}-key`);return c===null?null:c.trim()}return null}static resolveEachDeclarationPath(e,t){const r=`${l.prefix}each`;let i=e.getAttribute(r)?.trim()??"";if(i==="")return null;let n=e.parentElement;for(;n!==null&&n!==t;){const s=n.getAttribute(r)?.trim();if(s!=null){if(s==="")return null;const a=n.getAttribute(`${r}-arg`)?.trim();if(a!=null&&a!==""){if(i!==a&&!i.startsWith(`${a}.`))return null;i=i===a?s:`${s}.${i.slice(a.length+1)}`}else i=`${s}.${i}`}n=n.parentElement}return i}static isPlainRecord(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}static isSameBindingValue(e,t){if(e===t)return!0;if(e===f.ABSENT_PATH||t===f.ABSENT_PATH)return!1;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}static getBindingData(e,t={}){const r=D.get(e);return r instanceof w?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=f.collectScope(e);return q.isEnabled()&&m.info("[Haori]","scope dump for",e,t),t}static collectScope(e){const t=D.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=c=>{const u=c.getTarget(),d=f.resolveElementId(u);return d!==""?`#${d}`:u.tagName.toLowerCase()},s=(c,u,d,g)=>{if(c)for(const y of Object.keys(c))y in i||(i[y]={value:c[y],source:n(u),kind:d,depth:g})};let a=t,o=0;for(;a;)a!==t&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return m.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,n]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(e,t){const r=D.get(e);if(r.isSkipMutationNode(t))return Promise.resolve();const i=D.get(t.nextSibling),n=D.get(t);if(n){if(n.getParent()===r)return Promise.resolve();if(r.insertBefore(n,i),n instanceof w)return f.scan(n.getTarget());if(n instanceof ne)return f.evaluateText(n)}return Promise.resolve()}static removeNode(e){const t=D.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNode(e))return;t.remove()}}static changeText(e,t){const r=D.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=D.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=f.getFormFragment(r);if(n){const s=F.getValues(n),a=n.getAttribute(`${l.prefix}form-arg`),o=n.getRawBindingData();let c;if(a){c={...o??{}};const u=String(a),d=F.resolveAncestorArgOwner(n,u);c[u]=F.mergeCollectedValues((d?d.value:c[u])??null,s)}else c=F.mergeCollectedValues(o,s,F.ancestorBaseResolver(n));i.push(f.setBindingData(n.getTarget(),c,{kind:"nonSupply",sequence:w.nextSequence()}))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?f.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=f.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${l.prefix}derive`),n=e.hasAttribute(`${l.prefix}if`),s=e.hasAttribute(`${l.prefix}each`),a=e.getRawAttribute(`${l.prefix}derive`),o=e.getRawAttribute(`${l.prefix}derive-name`);let c=!1,u=!1,d=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const A=f.createDeriveInputSignature(e,a,o);A===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>f.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==A&&(r=r.then(()=>f.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(A)})))}let g=!1,y=0;return n&&(r=r.then(()=>{const A=e.isVisible();return y=w.currentSequence(),f.evaluateIf(e).then(()=>{g=!A&&e.isVisible()})})),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>f.evaluateEachFixedChildren(e)).then(()=>f.evaluateEach(e)).then(()=>{if(g)return f.applyEnhancersOnShow(e,y)})):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!f.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),f.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}d=f.createDescendantBindingSignature(e,"evaluateAll"),u=!0,c=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===d,f.logDerivedSubtreeProfileSnapshot(e,c?"skip-hit":"skip-miss")})),r.then(()=>{if(c)return;const A=[];return e.getChildren().forEach(E=>{if(E instanceof w){if(f.canSkipUnchangedNestedEach(E))return;A.push(f.evaluateAll(E,t))}else E instanceof ne&&A.push(f.evaluateText(E))}),Promise.all(A).then(()=>{})}).then(()=>{u&&d!==null&&e.setDeriveSubtreeSignature(d)}))}static evaluateDerive(e,t=e.getRawAttribute(`${l.prefix}derive`),r=e.getRawAttribute(`${l.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!t||n==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const s=re.evaluateDetailed(t,e.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return f.createBindingSignature(i)===f.createBindingSignature(a)?Promise.resolve(!1):(e.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(e){return e.evaluate()}static isHiddenIfCondition(e){return!e}static logFalsyIfDiagnostics(e){const t=e.getRawAttribute(`${l.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;if(re.hasCompileFailure(t)){m.warn("[Haori]","data-if is hidden because the expression could not be compiled (see the preceding compile error):",t);return}const{sources:r}=f.collectScope(e.getTarget()),i=new Set,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const c=t.indexOf(o,s);s=c+o.length,!(c>0&&t[c-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),m.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static isEachFixedChild(e){return e.hasAttribute(`${l.prefix}each-before`)||e.hasAttribute(`${l.prefix}each-after`)}static hasEachFixedChildren(e){return e.getChildren().some(t=>t instanceof w&&f.isEachFixedChild(t))}static evaluateEachFixedChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof w?f.isEachFixedChild(r)&&t.push(f.evaluateAll(r)):r instanceof ne&&t.push(f.evaluateText(r))}),Promise.all(t).then(()=>{})}static evaluateIfOnAttributeWrite(e){if(!e.hasAttribute(`${l.prefix}each`))return f.evaluateIf(e);const t=e.isVisible(),r=w.currentSequence();return f.evaluateIf(e).then(()=>{if(!t)return f.evaluateEach(e).then(()=>f.reevaluateReactiveSpecialAttributes(e)).then(()=>f.applyEnhancersOnShow(e,r))})}static evaluateIf(e){const t=[],r=e.getAttribute(`${l.prefix}if`);if(f.isHiddenIfCondition(r))q.isEnabled()&&e.isVisible()&&f.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{B.hide(e.getTarget())}));else{e.restoreFormControlsDisabledByIf();const i=e.isVisible(),n=w.currentSequence(),s=[],a=e.hasAttribute(`${l.prefix}each`);e.getChildren().forEach(o=>{if(o instanceof w){if(a&&!f.isEachFixedChild(o))return;o.isMounted()?i?s.push(f.evaluateAll(o)):s.push(f.evaluateAll(o).then(()=>f.reevaluateReactiveSpecialAttributes(o))):s.push(f.scanElement(o.getTarget(),!1))}else o instanceof ne&&s.push(f.evaluateText(o))}),t.push(e.show().then(()=>{B.show(e.getTarget()),i||(f.triggerLoadOnShow(e),te.refreshSubtree(e.getTarget(),!1))})),t.push(Promise.all(s).then(()=>{if(!(i||a))return f.applyEnhancersOnShow(e,n)}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${l.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new se(e,"load").run().catch(i=>{m.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=f.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},f.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(q.isEnabled()&&re.recordRowScopeIdentifiers([f.getRowScopeName(e,"each-arg"),f.getRowScopeName(e,"each-index")]),e.isMounted()||f.syncMountedState(e),!e.isVisible()||!e.isMounted())return e.getTarget().removeAttribute(`${l.prefix}each-done`),Promise.resolve();const t=f.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):f.runEachUpdateLoop(e,t)}static getRowScopeName(e,t){const r=e.getAttribute(`${l.prefix}${t}`);return typeof r!="string"||r===""?null:r}static isEachUpdateRunning(e){return f.getEachUpdateState(e).running}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${l.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await f.performEachUpdate(e);while(t.rerunRequested);const i=e.getTarget();i.setAttribute(`${l.prefix}each-done`,""),te.refreshSubtree(i,!1),f.runEachRenderedScript(i)}finally{t.running=!1,t.settled=null}f.runEachRenderedChange(e)})();return t.settled=r,r}static runEachRenderedScript(e){const t=`${l.prefix}each-rendered-run`;if(!e.hasAttribute(t))return;const r=String(e.getAttribute(t)??"");let i=null;try{i=new Function(`"use strict"; return (
28
28
  ${r}
29
29
  );`)}catch{try{i=new Function(`"use strict";
30
30
  ${r}
31
- `)}catch(n){m.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(i)try{i.call(e)}catch(n){m.error("[Haori]",`each-rendered-run execution error: ${n}`)}}static runEachRenderedChange(e){const t=`${l.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),m.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){m.error("[Haori]",`each-rendered-change dispatch error: ${s}`)}}}static countEachRenderedRows(e){let t=0;for(const r of e.getChildElementFragments())r.getTarget().hasAttribute(`${l.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(`${l.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 w){if(a.hasAttribute(`${l.prefix}each-before`)||a.hasAttribute(`${l.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&&f.warnExtraEachChildren(e),!s){const a=e.getTarget();Array.from(a.children).filter(c=>!c.hasAttribute(`${l.prefix}each-before`)&&!c.hasAttribute(`${l.prefix}each-after`)).forEach(c=>{if(!s){const d=D.get(c);d instanceof w&&(r=d.clone(),f.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const u=D.get(c);u instanceof w&&e.getChildren().includes(u)&&(e.removeChild(u),u.setMounted(!1)),c.parentNode&&c.parentNode.removeChild(c)})}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(`${l.prefix}each-before`)&&!r.hasAttribute(`${l.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(`${l.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(m.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${l.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${l.prefix}derive`)||t?.closestByAttribute(`${l.prefix}derive-name`)||t?.closestByAttribute(`${l.prefix}if`)||t?.closestByAttribute(`${l.prefix}fetch`)||t?.closestByAttribute(`${l.prefix}import`)||f.hasNonEachDynamicElementState(e)||!f.isRowLocalEachTemplate(e)||f.hasEachFixedChildren(e))return!1;const r=f.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${l.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(`${l.prefix}each-arg`);if(r===null||!i)return e.setRowLocalTemplate(!1),!1;const n=new Set([String(i)]),s=e.getAttribute(`${l.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(l.prefix))continue;const a=i.slice(l.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))continue;const o=a.indexOf("-");if(!(o!==-1&&f.ROW_LOCAL_ROW_OPERATIONS.has(a.slice(o+1))))return!1}let r=t;if(e.hasAttribute(`${l.prefix}each`)){const i=e.getRawAttribute(`${l.prefix}each-arg`);if(typeof i!="string"||i==="")return!1;const n=new Set(t);n.add(i);const s=e.getRawAttribute(`${l.prefix}each-index`);typeof s=="string"&&s!==""&&n.add(s),r=n}for(const i of e.getChildren())if(i instanceof w){if(!f.isRowLocalSubtree(i,r))return!1}else if(i instanceof ne){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=re.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(`${l.prefix}derive`)||e.hasAttribute(`${l.prefix}if`)||e.hasAttribute(`${l.prefix}each`)||e.hasAttribute(`${l.prefix}fetch`)||e.hasAttribute(`${l.prefix}import`)?!1:!f.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof w?t.hasAttribute(`${l.prefix}derive`)||t.hasAttribute(`${l.prefix}derive-name`)||t.hasAttribute(`${l.prefix}fetch`)||t.hasAttribute(`${l.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 refreshUrlParams(){const e=`${l.prefix}url-param`,r=Array.from(document.querySelectorAll(`[${e}]`)).map(i=>{const n=D.peek(i);return n instanceof w?f.setAttribute(i,e,n.getRawAttribute(e)??""):Promise.resolve()});return Promise.all(r).then(()=>{}).catch(i=>{m.error("Haori",`${e} を読み直せませんでした: ${i}`)})}static invalidateDerivedSubtreeSignatures(e){for(let r=e.getParent();r!==null;r=r.getParent())r.setDeriveSubtreeSignature(null);const t=r=>{r.setDeriveSubtreeSignature(null),r.getChildren().forEach(i=>{i instanceof w&&t(i)})};t(e)}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(!q.isEnabled()||!e.hasAttribute(`${l.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(`${l.prefix}derive-name`);typeof a=="string"&&a.trim()!==""&&(n+=`[${l.prefix}derive-name="${a.trim()}"]`);const o=r.getParent();if(o){const c=o.getChildren().filter(u=>u instanceof w).findIndex(u=>u===r);n+=`:nth-child(${c+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),m.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${l.prefix}each`,`${l.prefix}each-key`,`${l.prefix}each-arg`,`${l.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${l.prefix}attr-`)||i.startsWith(l.prefix))return!0;const n=e.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:e.getChildren().some(i=>i instanceof ne&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>f.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof w?!f.markFreshInitializationSkippable(n):n instanceof ne?n.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${l.prefix}attr-`)||t.startsWith(l.prefix))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static updateDiff(e,t){const r=e.getTemplate();if(r===null)return m.error("[Haori]",`Template is not set for ${l.prefix}each="${e.getRawAttribute(`${l.prefix}each`)}". The container needs one element child as the row template.`,e.getTarget()),Promise.resolve();let i=e.getAttribute(`${l.prefix}each-index`);i&&(i=String(i));const n=e.getAttribute(`${l.prefix}each-key`),s=e.getAttribute(`${l.prefix}each-arg`),a=t.map((k,j)=>f.createListKey(k,n?String(n):null,j)),o=new Set(a),c=new Map;a.forEach(k=>{c.set(k,(c.get(k)??0)+1)}),n&&o.size!==a.length&&f.warnDuplicateEachKey(String(n));const u=[];let d=e.getChildren().filter(k=>k instanceof w).filter(k=>!k.hasAttribute(`${l.prefix}each-before`)&&!k.hasAttribute(`${l.prefix}each-after`));const g=d.map(k=>k.getListKey()),y=new Set;d=d.filter((k,j)=>{const Z=String(k.getListKey()),ee=c.get(Z)??0;if(ee===0){y.add(k);const L=k.getListKey();return L!==null&&B.rowRemove(k.getTarget(),L,j),u.push(k.remove()),!1}return c.set(Z,ee-1),!0});const E=d.map(k=>k.getListKey()),A=new Map;d.forEach(k=>{const j=k.getListKey();if(j===null)return;const Z=A.get(j);Z?Z.push(k):A.set(j,[k])});const I=e.getChildElementFragments().filter(k=>!y.has(k)),x=I.filter(k=>k.hasAttribute(`${l.prefix}each-before`)).length;let H=Promise.resolve();return a.forEach((k,j)=>{const Z=t[j],ee=j;let L;const ae=A.get(k)?.shift();if(ae){L=ae;const G=x+j;H=H.then(()=>f.updateRowFragment(L,Z,i,ee,s?String(s):null,k).then(T=>f.repositionEachRow(e,L,I,G).then(O=>{if(O!==null&&B.rowMove(L.getTarget(),k,O-x,j),!(!T&&f.isRowLocalEachTemplate(e)))return f.evaluateAll(L).then(()=>f.applyRowFormValues(e,L,Z))})))}else{L=r.clone();const G=x+j;H=H.then(()=>f.updateRowFragment(L,Z,i,ee,s?String(s):null,k).then(()=>{const T=I[G]??null;return e.insertBefore(L,T).then(()=>{I.splice(G,0,L)}).then(()=>f.initializeFreshEachRow(L)).then(()=>f.applyRowFormValues(e,L,Z)).then(()=>{B.rowAdd(L.getTarget(),k,ee,Z)})}))}}),Promise.all(u).then(()=>H).then(()=>{const k=a.filter(G=>G!==null),j=E.filter(G=>G!==null),Z=new Set(j),ee=k.filter(G=>!Z.has(G)),ae=g.filter(G=>G!==null).filter(G=>!o.has(G));B.eachUpdate(e.getTarget(),ee,ae,k)})}static warnExtraEachChildren(e){const t=e.getChildren().filter(r=>r instanceof w).filter(r=>!r.hasAttribute(`${l.prefix}each-before`)&&!r.hasAttribute(`${l.prefix}each-after`));t.length!==0&&m.warn("[Haori]",`${l.prefix}each="${e.getRawAttribute(`${l.prefix}each`)}" のコンテナに要素の子が 2 つ以上あります。テンプレートになるのは最初の子だけで、残り ${t.length} 個は行に入りません(${t.map(r=>r.getTarget().tagName.toLowerCase()).join(", ")})。行の中身は 1 つの要素で包んでください。`,e.getTarget())}static warnDuplicateEachKey(e){!q.isEnabled()||f.WARNED_DUPLICATE_EACH_KEYS.has(e)||(f.WARNED_DUPLICATE_EACH_KEYS.add(e),m.warn("[Haori]",`${l.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(`${l.prefix}form-list`)||!F.isCollectedListFromEachSource(e)||typeof r!="object"||r===null||Array.isArray(r)?Promise.resolve():F.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 m.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);r&&(a[r]=i);const o=a,c=f.createBindingSignature({listKey:s,bindingData:o});return e.getListKey()===s&&e.getRenderSignature()===c?Promise.resolve(!1):(e.setListKey(s),e.setRenderSignature(c),e.setBindingData(o),e.setAttribute(`${l.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(`${l.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.initialValueRestore=null,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.ROW_LOCAL_ROW_OPERATIONS=new Set(["row-add","row-remove","row-prev","row-next"]),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 $=f;const we=class we{constructor(e=document){this.customEventHandlers=new Map,this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures=[],this.onClick=t=>this.delegate(t,"click"),this.onReset=t=>{if(t.defaultPrevented||F.isResettingInternally())return;const r=t.target;r instanceof HTMLElement&&setTimeout(()=>te.refreshSubtree(r),0)},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;if(!r||r[we.HISTORY_STATE_KEY]!==!0){$.refreshUrlParams();return}location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=D.get(e);t&&new se(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){m.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("reset",this.onReset),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("reset",this.onReset),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`${l.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(we.BUILTIN_EVENT_NAMES.has(e)){m.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){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=D.get(i);n instanceof w&&new se(n,"on",t).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const e=this.root instanceof Document?this.root:this.root.ownerDocument??document,t=this.root instanceof Document?e.body:this.root;t&&(this.customEventObserver=new MutationObserver(r=>{for(const i of r)i.addedNodes.forEach(n=>{n instanceof HTMLElement&&(n.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(n.getAttribute(this.onAttributeName)),n.querySelectorAll(`[${this.onAttributeName}]`).forEach(s=>this.subscribeCustomEvent(s.getAttribute(this.onAttributeName))))})}),this.customEventObserver.observe(t,{childList:!0,subtree:!0}))}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(r){if(t==="input"){const i=`${l.prefix}input-`;if(!r.getAttributeNames().some(s=>s.startsWith(i))){this.recordUserEdit(r);return}}if(r.hasAttribute(`${l.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=D.get(e);if(!i)return;(t==="change"||t==="input")&&this.syncUserEdit(e,t==="change");const n=()=>{const s=new se(i,t,r).runWithOutcome().catch(a=>(m.error("[Haori]","Procedure execution error:",a),"failure"));if(t==="click"){se.recordClickOutcome(e,s);const a=r.target;a instanceof HTMLElement&&a!==e&&se.recordClickOutcome(a,s)}};if(t==="click"&&e.hasAttribute(`${l.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=D.get(e);t instanceof w&&t.markUserEdit()}syncUserEdit(e,t){const r=D.get(e);if(r instanceof w&&(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=D.get(n);s instanceof w&&(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=`${l.prefix}click-`,r=`${l.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}};we.HISTORY_STATE_KEY="__haoriHistoryState__",we.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let We=we;const V=class V{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)&&(V.isHtmlElement(e)&&V.syncElement(e),e.querySelectorAll("*").forEach(t=>{V.syncElement(t)}))}static syncElement(e){const t=V.registrations.get(e),r=D.get(e);if(!r||!V.shouldObserve(r)){t&&(t.observer.disconnect(),V.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=V.resolveRoot(r),n=V.resolveRootMargin(r),s=V.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(t&&t.root===i&&t.rootMargin===n&&t.threshold===s&&t.once===a){t.fragment=r,V.runPendingIntersect(e,t);return}t&&(t.observer.disconnect(),V.registrations.delete(e));const o=new IntersectionObserver(c=>{const u=V.registrations.get(e);u&&c.forEach(d=>{if(u.intersecting=d.isIntersecting,!!d.isIntersecting){if(u.running||V.isDisabled(u.fragment)){u.pending=!0;return}V.runProcedure(e,u)}})},{root:i,rootMargin:n,threshold:s});o.observe(e),V.registrations.set(e,{fragment:r,observer:o,once:a,running:t?.running??!1,intersecting:!1,pending:!1,root:i,rootMargin:n,threshold:s})}static runProcedure(e,t){t.pending=!1,t.running=!0;let r=!1;new se(t.fragment,"intersect").runWithResult().then(i=>{r=i}).catch(i=>{m.error("[Haori]","Intersect procedure execution error:",i)}).finally(()=>{const i=V.registrations.get(e);if(i){if(i.running=!1,r&&i.once){i.observer.disconnect(),V.registrations.delete(e);return}V.runPendingIntersect(e,i)}})}static runPendingIntersect(e,t){!t.pending||!t.intersecting||t.running||V.isDisabled(t.fragment)||V.runProcedure(e,t)}static cleanupTree(e){if(V.isHtmlElement(e)){const t=V.registrations.get(e);t&&(t.observer.disconnect(),V.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=V.registrations.get(t);r&&(r.observer.disconnect(),V.registrations.delete(t))})}static disconnectAll(){V.registrations.forEach(e=>{e.observer.disconnect()}),V.registrations.clear()}static shouldObserve(e){return e.getAttributeNames().some(t=>{if(!t.startsWith(`${l.prefix}intersect-`))return!1;const r=t.slice(`${l.prefix}intersect-`.length);return!V.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${l.prefix}intersect-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=J.query(r,t,document);return V.isHtmlElement(i)?i:(m.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${l.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${l.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=`${l.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"}};V.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),V.registrations=new Map;let Ee=V;const v=class v{static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(v.isHtmlElement(e)&&v.syncElement(e),e.querySelectorAll("*").forEach(t=>{v.syncElement(t)}))}static syncElement(e){const t=v.registrations.get(e);if(!t&&!v.hasPollAttribute(e))return;const r=D.get(e);if(!(r instanceof w)||!v.shouldObserve(r)){t&&v.teardown(e,t);return}const i=v.buildConfigKey(r);if(t){if(t.configKey===i){t.fragment=r;return}v.teardown(e,t)}v.startPolling(e,r,i)}static cleanupTree(e){if(v.isHtmlElement(e)){const t=v.registrations.get(e);t&&v.teardown(e,t)}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=v.registrations.get(t);r&&v.teardown(t,r)})}static disconnectAll(){v.registrations.forEach(e=>{v.clearTimers(e)}),v.registrations.clear(),v.visibilityListener&&typeof document<"u"&&document.removeEventListener("visibilitychange",v.visibilityListener),v.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=`${l.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=`${l.prefix}poll-`;return e.getAttributeNames().some(r=>r.startsWith(t)?!v.CONFIG_KEYS.has(r.slice(t.length)):!1)}static buildConfigKey(e){const t=`${l.prefix}poll-`;return e.getAttributeNames().filter(r=>r.startsWith(t)).sort().map(r=>`${r}=${e.getRawAttribute(r)??""}`).join(`
32
- `)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:v.resolveInterval(t),timeoutMs:v.resolveTimeout(t),errorLimit:v.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};v.registrations.set(e,i),v.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{v.handleTimeout(e)},i.timeoutMs)),v.injectState(i),v.tick(e)}static async tick(e){const t=v.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await v.stop(e,t,"detached");return}const r=v.isHidden(e)||v.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await v.injectState(t)),r){v.schedule(e,t);return}if(v.isUntilSatisfied(t.fragment)){await v.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new se(t.fragment,"poll").runWithResult()}catch(n){m.error("[Haori]","Poll procedure execution error:",n)}finally{t.fetching=!1}if(!(v.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await v.stop(e,t,"error");return}if(i&&v.isUntilSatisfied(t.fragment)){await v.stop(e,t,"until");return}v.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{v.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=v.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&B.pollTimeout(e,t.count,v.elapsed(t)),await v.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,v.clearTimers(t),r==="detached"){v.registrations.delete(e);return}await v.injectState(t),e.isConnected&&B.pollStop(e,r,t.count,v.elapsed(t))}}static teardown(e,t){v.clearTimers(t),v.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(v.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(v.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),v.tick(t))})};v.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=v.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:v.elapsed(e)};return Promise.all(t.map(i=>{const n=i.getTarget(),s={...i.getRawBindingData()??{},_poll:r};return $.setBindingData(n,s,{reflectToAttribute:!1,kind:"nonSupply",sequence:w.nextSequence()})})).then(()=>{})}static resolveStateFragments(e){const t=`${l.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=J.queryAll(i,t,document);if(n.length===0)return m.error("[Haori]",`Poll state element not found: ${i}`),[];const s=[];return n.forEach(a=>{if(!a.isConnected)return;const o=D.get(a);o instanceof w&&s.push(o)}),s}static resolveInterval(e){const t=`${l.prefix}poll-interval`;if(!e.hasAttribute(t))return v.DEFAULT_INTERVAL_MS;const r=v.toNumber(e.getAttribute(t));return r===null?(m.warn("[Haori]",`${t} は数値で指定してください。既定値 ${v.DEFAULT_INTERVAL_MS}ms を使用します。`),v.DEFAULT_INTERVAL_MS):r<v.MIN_INTERVAL_MS?(m.warn("[Haori]",`${t} の下限は ${v.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),v.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${l.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=v.toNumber(e.getAttribute(t));return r===null||r<=0?(m.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${l.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=v.toNumber(e.getAttribute(t));return r===null||r<1?(m.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(`[${l.prefix}if-false]`)!==null}static isDisabled(e){const t=`${l.prefix}poll-disabled`;return e.hasAttribute(t)?v.isTruthy(e.getAttribute(t)):!1}static isUntilSatisfied(e){const t=`${l.prefix}poll-until`;if(!e.hasAttribute(t))return!1;const r=e.getAttributeEvaluation(t);return r?r.hasUnresolvedReference?(m.warn("[Haori]",`${t} に未解決の参照が含まれています(停止条件は成立扱いにしません):`,e.getRawAttribute(t),e.getTarget()),!1):v.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}};v.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),v.DEFAULT_INTERVAL_MS=5e3,v.MIN_INTERVAL_MS=100,v.registrations=new Map,v.visibilityListener=null;let Ae=v;const Et="0.57.0";function Yt(b){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>b()):Promise.resolve().then(b)}const P=class P{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)&&(P.isHtmlElement(e)&&P.syncElement(e),e.querySelectorAll("*").forEach(t=>{P.syncElement(t)}))}static syncElement(e){const t=P.registrations.get(e),r=D.get(e);if(!(r instanceof w)||!P.shouldObserve(r)){t&&(t.observer.disconnect(),P.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=P.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),P.registrations.delete(e)),m.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=P.resolveRoot(r),s=P.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,P.refreshRows(t);return}t&&(t.observer.disconnect(),P.registrations.delete(e));const a=new IntersectionObserver(c=>{const u=P.registrations.get(e);if(!u)return;let d=!1;c.forEach(g=>{const y=g.target;u.observedRows.has(y)&&(g.isIntersecting?u.visibleRows.has(y)||(u.visibleRows.add(y),d=!0):u.visibleRows.delete(y)&&(d=!0))}),d&&P.scheduleCompute(u)},{root:n,rootMargin:s,threshold:P.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};P.registrations.set(e,o),P.refreshRows(o)}static cleanupTree(e){if(P.isHtmlElement(e)){const t=P.registrations.get(e);t&&(t.observer.disconnect(),P.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=P.registrations.get(t);r&&(r.observer.disconnect(),P.registrations.delete(t))})}static disconnectAll(){P.registrations.forEach(e=>{e.observer.disconnect()}),P.registrations.clear()}static shouldObserve(e){return e.hasAttribute(`${l.prefix}each`)&&e.hasAttribute(`${l.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${l.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${l.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=J.query(r,t,document);return P.isHtmlElement(i)?i:(m.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${l.prefix}each-visible-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?P.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof w&&!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=P.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));P.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,Yt(()=>{e.scheduled=!1;const t=e.fragment.getTarget();P.registrations.get(t)===e&&P.computeAndPublish(e)}))}static computeAndPublish(e){const t=P.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 c of i)c<a&&(a=c),c>o&&(o=c);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,P.publish(e,n))}static publish(e,t){const r=P.resolveBindOwner(e.fragment);if(!r){m.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);$.setBindingData(i,n,{skipFragments:a,reflectToAttribute:!1,kind:"nonSupply",sequence:w.nextSequence()}).catch(o=>{m.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${l.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};P.THRESHOLD=0,P.DEFAULT_ROOT_MARGIN="0px",P.registrations=new Map;let ge=P;const U=class U{static disconnectMutationObservers(){U._mutationObservers.forEach(e=>{e.disconnect()}),U._mutationObservers.length=0}static async init(){if(U._initialized)return;U._initialized=!0,U.disconnectMutationObservers(),w.setPendingMutationFlusher(()=>{U.flushPendingMutations()});const e=new We;U._dispatcher=e,e.startDeferred(),U._initialIntakes=[];try{const t=await Promise.allSettled([$.scan(document.head),$.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&m.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&m.error("[Haori]","Failed to build body fragment:",i.reason),await U.waitInitialIntakes(),await K.wait(),document.body.setAttribute("data-haori-ready",""),U.observe(document.head),U.observe(document.body),Ee.syncTree(document.body),Ae.syncTree(document.body),ge.syncTree(document.body)}finally{U._initialIntakes=null,e.release()}B.ready(Et)}static getDispatcher(){return U._dispatcher}static async waitInitialIntakes(){const e=U._initialIntakes;for(;e!==null&&e.length>0;)await Promise.allSettled(e.splice(0))}static captureMutations(e){if(U._mutationObservers.length>0){e();return}const t=new MutationObserver(()=>{});t.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0});try{e()}finally{const r=t.takeRecords().map(i=>U.toCapturedRecord(i));t.disconnect(),U.processMutations(r)}}static toCapturedRecord(e){return e.type!=="childList"?e:{type:e.type,target:e.target,addedNodes:Array.from(e.addedNodes).filter(t=>!U.hasKnownDescendant(t)),removedNodes:[]}}static hasKnownDescendant(e){return e instanceof Element&&Array.from(e.querySelectorAll("*")).some(t=>w.peek(t)!==null)}static isStaleExternalRemoval(e,t){const r=w.peek(t)?.getParent()??null;return r===null||r.getTarget()===e.target?!1:r.getTarget().closest(`[${l.prefix}external]`)!==null}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${l.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(r=>{U.processMutations(r)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),U._mutationObservers.push(t)}static flushPendingMutations(){for(const e of U._mutationObservers){const t=e.takeRecords();if(t.length===0)continue;const r=t.filter(U.isBindAttributeRecord),i=t.filter(n=>!U.isBindAttributeRecord(n));r.length>0&&U.processMutations(r,w.nextSequence()),i.length>0&&Promise.resolve().then(()=>{U.processMutations(i)})}}static isBindAttributeRecord(e){return e.type==="attributes"&&e.attributeName===`${l.prefix}bind`}static processMutations(e,t){for(const r of e)try{if(U.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(fe)&&(r.attributeName==="disabled"||r.attributeName===fe))break;if(r.attributeName&&(r.attributeName===`${l.prefix}if-false`||r.attributeName==="style"&&i.hasAttribute(`${l.prefix}if-false`))){r.attributeName==="style"&&w.reassertHiddenDisplay(i);break}if(r.attributeName&&$.isAliasedAttributeReflection(i,r.attributeName))break;const n=$.setAttribute(i,r.attributeName,i.getAttribute(r.attributeName),!0,t);U._initialIntakes?.push(n),Ee.syncElement(i),Ae.syncElement(i),ge.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{U.isStaleExternalRemoval(r,i)||(Ee.cleanupTree(i),Ae.cleanupTree(i),ge.cleanupTree(i),$.removeNode(i))}),Array.from(r.addedNodes).forEach(i=>{if(!(i.parentElement instanceof Element))return;const n=$.addNode(i.parentElement,i);U._initialIntakes?.push(n),Ee.syncTree(i),Ae.syncTree(i),ge.syncTree(i)}),r.target instanceof Element&&ge.syncElement(r.target);break}case"characterData":{r.target instanceof Text||r.target instanceof Comment?$.changeText(r.target,r.target.textContent):m.warn("[Haori]","Unsupported character data type:",r.target);break}default:m.warn("[Haori]","Unknown mutation type:",r.type);continue}}catch(i){m.error("[Haori]","Error processing mutation:",i)}}};U._initialized=!1,U._mutationObservers=[],U._dispatcher=null,U._initialIntakes=null;let Fe=U;te.setMutationCapture(b=>Fe.captureMutations(b)),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Fe.init):Fe.init();const Xt=()=>oe.waitForRenders(),Jt=oe.enhancers,Zt=Object.freeze(Object.defineProperty({__proto__:null,Core:$,Enhance:te,Env:l,Form:F,Fragment:D,Haori:oe,Log:m,Queue:K,default:oe,enhancers:Jt,version:Et,waitForRenders:Xt},Symbol.toStringTag,{value:"Module"})),je=oe;for(const[b,e]of Object.entries(Zt))b in je||Object.defineProperty(je,b,{value:e,writable:!0,enumerable:!0,configurable:!0});return je}();
31
+ `)}catch(n){m.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(i)try{i.call(e)}catch(n){m.error("[Haori]",`each-rendered-run execution error: ${n}`)}}static runEachRenderedChange(e){const t=`${l.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),m.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){m.error("[Haori]",`each-rendered-change dispatch error: ${s}`)}}}static countEachRenderedRows(e){let t=0;for(const r of e.getChildElementFragments())r.getTarget().hasAttribute(`${l.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(`${l.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 w){if(a.hasAttribute(`${l.prefix}each-before`)||a.hasAttribute(`${l.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&&f.warnExtraEachChildren(e),!s){const a=e.getTarget();Array.from(a.children).filter(c=>!c.hasAttribute(`${l.prefix}each-before`)&&!c.hasAttribute(`${l.prefix}each-after`)).forEach(c=>{if(!s){const d=D.get(c);d instanceof w&&(r=d.clone(),f.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const u=D.get(c);u instanceof w&&e.getChildren().includes(u)&&(e.removeChild(u),u.setMounted(!1)),c.parentNode&&c.parentNode.removeChild(c)})}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(`${l.prefix}each-before`)&&!r.hasAttribute(`${l.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(`${l.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(m.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${l.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${l.prefix}derive`)||t?.closestByAttribute(`${l.prefix}derive-name`)||t?.closestByAttribute(`${l.prefix}if`)||t?.closestByAttribute(`${l.prefix}fetch`)||t?.closestByAttribute(`${l.prefix}import`)||f.hasNonEachDynamicElementState(e)||!f.isRowLocalEachTemplate(e)||f.hasEachFixedChildren(e))return!1;const r=f.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${l.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(`${l.prefix}each-arg`);if(r===null||!i)return e.setRowLocalTemplate(!1),!1;const n=new Set([String(i)]),s=e.getAttribute(`${l.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(l.prefix))continue;const a=i.slice(l.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))continue;const o=a.indexOf("-");if(!(o!==-1&&f.ROW_LOCAL_ROW_OPERATIONS.has(a.slice(o+1))))return!1}let r=t;if(e.hasAttribute(`${l.prefix}each`)){const i=e.getRawAttribute(`${l.prefix}each-arg`);if(typeof i!="string"||i==="")return!1;const n=new Set(t);n.add(i);const s=e.getRawAttribute(`${l.prefix}each-index`);typeof s=="string"&&s!==""&&n.add(s),r=n}for(const i of e.getChildren())if(i instanceof w){if(!f.isRowLocalSubtree(i,r))return!1}else if(i instanceof ne){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=re.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(`${l.prefix}derive`)||e.hasAttribute(`${l.prefix}if`)||e.hasAttribute(`${l.prefix}each`)||e.hasAttribute(`${l.prefix}fetch`)||e.hasAttribute(`${l.prefix}import`)?!1:!f.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof w?t.hasAttribute(`${l.prefix}derive`)||t.hasAttribute(`${l.prefix}derive-name`)||t.hasAttribute(`${l.prefix}fetch`)||t.hasAttribute(`${l.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 refreshUrlParams(){const e=`${l.prefix}url-param`,r=Array.from(document.querySelectorAll(`[${e}]`)).map(i=>{const n=D.peek(i);return n instanceof w?f.setAttribute(i,e,n.getRawAttribute(e)??""):Promise.resolve()});return Promise.all(r).then(()=>{}).catch(i=>{m.error("Haori",`${e} を読み直せませんでした: ${i}`)})}static invalidateDerivedSubtreeSignatures(e){for(let r=e.getParent();r!==null;r=r.getParent())r.setDeriveSubtreeSignature(null);const t=r=>{r.setDeriveSubtreeSignature(null),r.getChildren().forEach(i=>{i instanceof w&&t(i)})};t(e)}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(!q.isEnabled()||!e.hasAttribute(`${l.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(`${l.prefix}derive-name`);typeof a=="string"&&a.trim()!==""&&(n+=`[${l.prefix}derive-name="${a.trim()}"]`);const o=r.getParent();if(o){const c=o.getChildren().filter(u=>u instanceof w).findIndex(u=>u===r);n+=`:nth-child(${c+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),m.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${l.prefix}each`,`${l.prefix}each-key`,`${l.prefix}each-arg`,`${l.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${l.prefix}attr-`)||i.startsWith(l.prefix))return!0;const n=e.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:e.getChildren().some(i=>i instanceof ne&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>f.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof w?!f.markFreshInitializationSkippable(n):n instanceof ne?n.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${l.prefix}attr-`)||t.startsWith(l.prefix))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static updateDiff(e,t){const r=e.getTemplate();if(r===null)return m.error("[Haori]",`Template is not set for ${l.prefix}each="${e.getRawAttribute(`${l.prefix}each`)}". The container needs one element child as the row template.`,e.getTarget()),Promise.resolve();let i=e.getAttribute(`${l.prefix}each-index`);i&&(i=String(i));const n=e.getAttribute(`${l.prefix}each-key`),s=e.getAttribute(`${l.prefix}each-arg`),a=t.map((k,j)=>f.createListKey(k,n?String(n):null,j)),o=new Set(a),c=new Map;a.forEach(k=>{c.set(k,(c.get(k)??0)+1)}),n&&o.size!==a.length&&f.warnDuplicateEachKey(String(n));const u=[];let d=e.getChildren().filter(k=>k instanceof w).filter(k=>!k.hasAttribute(`${l.prefix}each-before`)&&!k.hasAttribute(`${l.prefix}each-after`));const g=d.map(k=>k.getListKey()),y=new Set;d=d.filter((k,j)=>{const Z=String(k.getListKey()),ee=c.get(Z)??0;if(ee===0){y.add(k);const L=k.getListKey();return L!==null&&B.rowRemove(k.getTarget(),L,j),u.push(k.remove()),!1}return c.set(Z,ee-1),!0});const A=d.map(k=>k.getListKey()),E=new Map;d.forEach(k=>{const j=k.getListKey();if(j===null)return;const Z=E.get(j);Z?Z.push(k):E.set(j,[k])});const I=e.getChildElementFragments().filter(k=>!y.has(k)),x=I.filter(k=>k.hasAttribute(`${l.prefix}each-before`)).length;let H=Promise.resolve();return a.forEach((k,j)=>{const Z=t[j],ee=j;let L;const ae=E.get(k)?.shift();if(ae){L=ae;const G=x+j;H=H.then(()=>f.updateRowFragment(L,Z,i,ee,s?String(s):null,k).then(T=>f.repositionEachRow(e,L,I,G).then(O=>{if(O!==null&&B.rowMove(L.getTarget(),k,O-x,j),!(!T&&f.isRowLocalEachTemplate(e)))return f.evaluateAll(L).then(()=>f.applyRowFormValues(e,L,Z))})))}else{L=r.clone();const G=x+j;H=H.then(()=>f.updateRowFragment(L,Z,i,ee,s?String(s):null,k).then(()=>{const T=I[G]??null;return e.insertBefore(L,T).then(()=>{I.splice(G,0,L)}).then(()=>f.initializeFreshEachRow(L)).then(()=>f.applyRowFormValues(e,L,Z)).then(()=>{B.rowAdd(L.getTarget(),k,ee,Z)})}))}}),Promise.all(u).then(()=>H).then(()=>{const k=a.filter(G=>G!==null),j=A.filter(G=>G!==null),Z=new Set(j),ee=k.filter(G=>!Z.has(G)),ae=g.filter(G=>G!==null).filter(G=>!o.has(G));B.eachUpdate(e.getTarget(),ee,ae,k)})}static warnExtraEachChildren(e){const t=e.getChildren().filter(r=>r instanceof w).filter(r=>!r.hasAttribute(`${l.prefix}each-before`)&&!r.hasAttribute(`${l.prefix}each-after`));t.length!==0&&m.warn("[Haori]",`${l.prefix}each="${e.getRawAttribute(`${l.prefix}each`)}" のコンテナに要素の子が 2 つ以上あります。テンプレートになるのは最初の子だけで、残り ${t.length} 個は行に入りません(${t.map(r=>r.getTarget().tagName.toLowerCase()).join(", ")})。行の中身は 1 つの要素で包んでください。`,e.getTarget())}static warnDuplicateEachKey(e){!q.isEnabled()||f.WARNED_DUPLICATE_EACH_KEYS.has(e)||(f.WARNED_DUPLICATE_EACH_KEYS.add(e),m.warn("[Haori]",`${l.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(`${l.prefix}form-list`)||!F.isCollectedListFromEachSource(e)||typeof r!="object"||r===null||Array.isArray(r)?Promise.resolve():F.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 m.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);r&&(a[r]=i);const o=a,c=f.createBindingSignature({listKey:s,bindingData:o});return e.getListKey()===s&&e.getRenderSignature()===c?Promise.resolve(!1):(e.setListKey(s),e.setRenderSignature(c),e.setBindingData(o),e.setAttribute(`${l.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(`${l.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.initialValueRestore=null,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.ROW_LOCAL_ROW_OPERATIONS=new Set(["row-add","row-remove","row-prev","row-next"]),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 $=f;const we=class we{constructor(e=document){this.customEventHandlers=new Map,this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures=[],this.onClick=t=>this.delegate(t,"click"),this.onReset=t=>{if(t.defaultPrevented||F.isResettingInternally())return;const r=t.target;r instanceof HTMLElement&&setTimeout(()=>te.refreshSubtree(r),0)},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;if(!r||r[we.HISTORY_STATE_KEY]!==!0){$.refreshUrlParams();return}location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=D.get(e);t&&new se(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){m.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("reset",this.onReset),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("reset",this.onReset),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`${l.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(we.BUILTIN_EVENT_NAMES.has(e)){m.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){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=D.get(i);n instanceof w&&new se(n,"on",t).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const e=this.root instanceof Document?this.root:this.root.ownerDocument??document,t=this.root instanceof Document?e.body:this.root;t&&(this.customEventObserver=new MutationObserver(r=>{for(const i of r)i.addedNodes.forEach(n=>{n instanceof HTMLElement&&(n.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(n.getAttribute(this.onAttributeName)),n.querySelectorAll(`[${this.onAttributeName}]`).forEach(s=>this.subscribeCustomEvent(s.getAttribute(this.onAttributeName))))})}),this.customEventObserver.observe(t,{childList:!0,subtree:!0}))}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(r){if(t==="input"){const i=`${l.prefix}input-`;if(!r.getAttributeNames().some(s=>s.startsWith(i))){this.recordUserEdit(r);return}}if(r.hasAttribute(`${l.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=D.get(e);if(!i)return;(t==="change"||t==="input")&&this.syncUserEdit(e,t==="change");const n=()=>{const s=new se(i,t,r).runWithOutcome().catch(a=>(m.error("[Haori]","Procedure execution error:",a),"failure"));if(t==="click"){se.recordClickOutcome(e,s);const a=r.target;a instanceof HTMLElement&&a!==e&&se.recordClickOutcome(a,s)}};if(t==="click"&&e.hasAttribute(`${l.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=D.get(e);t instanceof w&&t.markUserEdit()}syncUserEdit(e,t){const r=D.get(e);if(r instanceof w&&(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=D.get(n);s instanceof w&&(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=`${l.prefix}click-`,r=`${l.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}};we.HISTORY_STATE_KEY="__haoriHistoryState__",we.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let We=we;const V=class V{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)&&(V.isHtmlElement(e)&&V.syncElement(e),e.querySelectorAll("*").forEach(t=>{V.syncElement(t)}))}static syncElement(e){const t=V.registrations.get(e),r=D.get(e);if(!r||!V.shouldObserve(r)){t&&(t.observer.disconnect(),V.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=V.resolveRoot(r),n=V.resolveRootMargin(r),s=V.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(t&&t.root===i&&t.rootMargin===n&&t.threshold===s&&t.once===a){t.fragment=r,V.runPendingIntersect(e,t);return}t&&(t.observer.disconnect(),V.registrations.delete(e));const o=new IntersectionObserver(c=>{const u=V.registrations.get(e);u&&c.forEach(d=>{if(u.intersecting=d.isIntersecting,!!d.isIntersecting){if(u.running||V.isDisabled(u.fragment)){u.pending=!0;return}V.runProcedure(e,u)}})},{root:i,rootMargin:n,threshold:s});o.observe(e),V.registrations.set(e,{fragment:r,observer:o,once:a,running:t?.running??!1,intersecting:!1,pending:!1,root:i,rootMargin:n,threshold:s})}static runProcedure(e,t){t.pending=!1,t.running=!0;let r=!1;new se(t.fragment,"intersect").runWithResult().then(i=>{r=i}).catch(i=>{m.error("[Haori]","Intersect procedure execution error:",i)}).finally(()=>{const i=V.registrations.get(e);if(i){if(i.running=!1,r&&i.once){i.observer.disconnect(),V.registrations.delete(e);return}V.runPendingIntersect(e,i)}})}static runPendingIntersect(e,t){!t.pending||!t.intersecting||t.running||V.isDisabled(t.fragment)||V.runProcedure(e,t)}static cleanupTree(e){if(V.isHtmlElement(e)){const t=V.registrations.get(e);t&&(t.observer.disconnect(),V.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=V.registrations.get(t);r&&(r.observer.disconnect(),V.registrations.delete(t))})}static disconnectAll(){V.registrations.forEach(e=>{e.observer.disconnect()}),V.registrations.clear()}static shouldObserve(e){return e.getAttributeNames().some(t=>{if(!t.startsWith(`${l.prefix}intersect-`))return!1;const r=t.slice(`${l.prefix}intersect-`.length);return!V.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${l.prefix}intersect-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=J.query(r,t,document);return V.isHtmlElement(i)?i:(m.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${l.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${l.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=`${l.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"}};V.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),V.registrations=new Map;let Ae=V;const v=class v{static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(v.isHtmlElement(e)&&v.syncElement(e),e.querySelectorAll("*").forEach(t=>{v.syncElement(t)}))}static syncElement(e){const t=v.registrations.get(e);if(!t&&!v.hasPollAttribute(e))return;const r=D.get(e);if(!(r instanceof w)||!v.shouldObserve(r)){t&&v.teardown(e,t);return}const i=v.buildConfigKey(r);if(t){if(t.configKey===i){t.fragment=r;return}v.teardown(e,t)}v.startPolling(e,r,i)}static cleanupTree(e){if(v.isHtmlElement(e)){const t=v.registrations.get(e);t&&v.teardown(e,t)}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=v.registrations.get(t);r&&v.teardown(t,r)})}static disconnectAll(){v.registrations.forEach(e=>{v.clearTimers(e)}),v.registrations.clear(),v.visibilityListener&&typeof document<"u"&&document.removeEventListener("visibilitychange",v.visibilityListener),v.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=`${l.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=`${l.prefix}poll-`;return e.getAttributeNames().some(r=>r.startsWith(t)?!v.CONFIG_KEYS.has(r.slice(t.length)):!1)}static buildConfigKey(e){const t=`${l.prefix}poll-`;return e.getAttributeNames().filter(r=>r.startsWith(t)).sort().map(r=>`${r}=${e.getRawAttribute(r)??""}`).join(`
32
+ `)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:v.resolveInterval(t),timeoutMs:v.resolveTimeout(t),errorLimit:v.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};v.registrations.set(e,i),v.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{v.handleTimeout(e)},i.timeoutMs)),v.injectState(i),v.tick(e)}static async tick(e){const t=v.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await v.stop(e,t,"detached");return}const r=v.isHidden(e)||v.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await v.injectState(t)),r){v.schedule(e,t);return}if(v.isUntilSatisfied(t.fragment)){await v.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new se(t.fragment,"poll").runWithResult()}catch(n){m.error("[Haori]","Poll procedure execution error:",n)}finally{t.fetching=!1}if(!(v.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await v.stop(e,t,"error");return}if(i&&v.isUntilSatisfied(t.fragment)){await v.stop(e,t,"until");return}v.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{v.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=v.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&B.pollTimeout(e,t.count,v.elapsed(t)),await v.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,v.clearTimers(t),r==="detached"){v.registrations.delete(e);return}await v.injectState(t),e.isConnected&&B.pollStop(e,r,t.count,v.elapsed(t))}}static teardown(e,t){v.clearTimers(t),v.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(v.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(v.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),v.tick(t))})};v.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=v.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:v.elapsed(e)};return Promise.all(t.map(i=>{const n=i.getTarget(),s={...i.getRawBindingData()??{},_poll:r};return $.setBindingData(n,s,{reflectToAttribute:!1,kind:"nonSupply",sequence:w.nextSequence()})})).then(()=>{})}static resolveStateFragments(e){const t=`${l.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=J.queryAll(i,t,document);if(n.length===0)return m.error("[Haori]",`Poll state element not found: ${i}`),[];const s=[];return n.forEach(a=>{if(!a.isConnected)return;const o=D.get(a);o instanceof w&&s.push(o)}),s}static resolveInterval(e){const t=`${l.prefix}poll-interval`;if(!e.hasAttribute(t))return v.DEFAULT_INTERVAL_MS;const r=v.toNumber(e.getAttribute(t));return r===null?(m.warn("[Haori]",`${t} は数値で指定してください。既定値 ${v.DEFAULT_INTERVAL_MS}ms を使用します。`),v.DEFAULT_INTERVAL_MS):r<v.MIN_INTERVAL_MS?(m.warn("[Haori]",`${t} の下限は ${v.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),v.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${l.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=v.toNumber(e.getAttribute(t));return r===null||r<=0?(m.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${l.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=v.toNumber(e.getAttribute(t));return r===null||r<1?(m.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(`[${l.prefix}if-false]`)!==null}static isDisabled(e){const t=`${l.prefix}poll-disabled`;return e.hasAttribute(t)?v.isTruthy(e.getAttribute(t)):!1}static isUntilSatisfied(e){const t=`${l.prefix}poll-until`;if(!e.hasAttribute(t))return!1;const r=e.getAttributeEvaluation(t);return r?r.hasUnresolvedReference?(m.warn("[Haori]",`${t} に未解決の参照が含まれています(停止条件は成立扱いにしません):`,e.getRawAttribute(t),e.getTarget()),!1):v.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}};v.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),v.DEFAULT_INTERVAL_MS=5e3,v.MIN_INTERVAL_MS=100,v.registrations=new Map,v.visibilityListener=null;let Ee=v;const At="0.57.1";function Yt(b){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>b()):Promise.resolve().then(b)}const P=class P{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)&&(P.isHtmlElement(e)&&P.syncElement(e),e.querySelectorAll("*").forEach(t=>{P.syncElement(t)}))}static syncElement(e){const t=P.registrations.get(e),r=D.get(e);if(!(r instanceof w)||!P.shouldObserve(r)){t&&(t.observer.disconnect(),P.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=P.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),P.registrations.delete(e)),m.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=P.resolveRoot(r),s=P.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,P.refreshRows(t);return}t&&(t.observer.disconnect(),P.registrations.delete(e));const a=new IntersectionObserver(c=>{const u=P.registrations.get(e);if(!u)return;let d=!1;c.forEach(g=>{const y=g.target;u.observedRows.has(y)&&(g.isIntersecting?u.visibleRows.has(y)||(u.visibleRows.add(y),d=!0):u.visibleRows.delete(y)&&(d=!0))}),d&&P.scheduleCompute(u)},{root:n,rootMargin:s,threshold:P.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};P.registrations.set(e,o),P.refreshRows(o)}static cleanupTree(e){if(P.isHtmlElement(e)){const t=P.registrations.get(e);t&&(t.observer.disconnect(),P.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=P.registrations.get(t);r&&(r.observer.disconnect(),P.registrations.delete(t))})}static disconnectAll(){P.registrations.forEach(e=>{e.observer.disconnect()}),P.registrations.clear()}static shouldObserve(e){return e.hasAttribute(`${l.prefix}each`)&&e.hasAttribute(`${l.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${l.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${l.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=J.query(r,t,document);return P.isHtmlElement(i)?i:(m.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${l.prefix}each-visible-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?P.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof w&&!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=P.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));P.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,Yt(()=>{e.scheduled=!1;const t=e.fragment.getTarget();P.registrations.get(t)===e&&P.computeAndPublish(e)}))}static computeAndPublish(e){const t=P.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 c of i)c<a&&(a=c),c>o&&(o=c);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,P.publish(e,n))}static publish(e,t){const r=P.resolveBindOwner(e.fragment);if(!r){m.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);$.setBindingData(i,n,{skipFragments:a,reflectToAttribute:!1,kind:"nonSupply",sequence:w.nextSequence()}).catch(o=>{m.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${l.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};P.THRESHOLD=0,P.DEFAULT_ROOT_MARGIN="0px",P.registrations=new Map;let ge=P;const U=class U{static disconnectMutationObservers(){U._mutationObservers.forEach(e=>{e.disconnect()}),U._mutationObservers.length=0}static async init(){if(U._initialized)return;U._initialized=!0,U.disconnectMutationObservers(),w.setPendingMutationFlusher(()=>{U.flushPendingMutations()});const e=new We;U._dispatcher=e,e.startDeferred(),U._initialIntakes=[];try{const t=await Promise.allSettled([$.scan(document.head),$.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&m.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&m.error("[Haori]","Failed to build body fragment:",i.reason),await U.waitInitialIntakes(),await K.wait(),document.body.setAttribute("data-haori-ready",""),U.observe(document.head),U.observe(document.body),Ae.syncTree(document.body),Ee.syncTree(document.body),ge.syncTree(document.body)}finally{U._initialIntakes=null,e.release()}B.ready(At)}static getDispatcher(){return U._dispatcher}static async waitInitialIntakes(){const e=U._initialIntakes;for(;e!==null&&e.length>0;)await Promise.allSettled(e.splice(0))}static captureMutations(e){if(U._mutationObservers.length>0){e();return}const t=new MutationObserver(()=>{});t.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0});try{e()}finally{const r=t.takeRecords().map(i=>U.toCapturedRecord(i));t.disconnect(),U.processMutations(r)}}static toCapturedRecord(e){return e.type!=="childList"?e:{type:e.type,target:e.target,addedNodes:Array.from(e.addedNodes).filter(t=>!U.hasKnownDescendant(t)),removedNodes:[]}}static hasKnownDescendant(e){return e instanceof Element&&Array.from(e.querySelectorAll("*")).some(t=>w.peek(t)!==null)}static isStaleExternalRemoval(e,t){const r=w.peek(t)?.getParent()??null;return r===null||r.getTarget()===e.target?!1:r.getTarget().closest(`[${l.prefix}external]`)!==null}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${l.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(r=>{U.processMutations(r)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),U._mutationObservers.push(t)}static flushPendingMutations(){for(const e of U._mutationObservers){const t=e.takeRecords();if(t.length===0)continue;const r=t.filter(U.isBindAttributeRecord),i=t.filter(n=>!U.isBindAttributeRecord(n));r.length>0&&U.processMutations(r,w.nextSequence()),i.length>0&&Promise.resolve().then(()=>{U.processMutations(i)})}}static isBindAttributeRecord(e){return e.type==="attributes"&&e.attributeName===`${l.prefix}bind`}static processMutations(e,t){for(const r of e)try{if(U.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(fe)&&(r.attributeName==="disabled"||r.attributeName===fe))break;if(r.attributeName&&(r.attributeName===`${l.prefix}if-false`||r.attributeName==="style"&&i.hasAttribute(`${l.prefix}if-false`))){r.attributeName==="style"&&w.reassertHiddenDisplay(i);break}if(r.attributeName&&$.isAliasedAttributeReflection(i,r.attributeName))break;const n=$.setAttribute(i,r.attributeName,i.getAttribute(r.attributeName),!0,t);U._initialIntakes?.push(n),Ae.syncElement(i),Ee.syncElement(i),ge.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{U.isStaleExternalRemoval(r,i)||(Ae.cleanupTree(i),Ee.cleanupTree(i),ge.cleanupTree(i),$.removeNode(i))}),Array.from(r.addedNodes).forEach(i=>{if(!(i.parentElement instanceof Element))return;const n=$.addNode(i.parentElement,i);U._initialIntakes?.push(n),Ae.syncTree(i),Ee.syncTree(i),ge.syncTree(i)}),r.target instanceof Element&&ge.syncElement(r.target);break}case"characterData":{r.target instanceof Text||r.target instanceof Comment?$.changeText(r.target,r.target.textContent):m.warn("[Haori]","Unsupported character data type:",r.target);break}default:m.warn("[Haori]","Unknown mutation type:",r.type);continue}}catch(i){m.error("[Haori]","Error processing mutation:",i)}}};U._initialized=!1,U._mutationObservers=[],U._dispatcher=null,U._initialIntakes=null;let Fe=U;te.setMutationCapture(b=>Fe.captureMutations(b)),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Fe.init):Fe.init();const Xt=()=>oe.waitForRenders(),Jt=oe.enhancers,Zt=Object.freeze(Object.defineProperty({__proto__:null,Core:$,Enhance:te,Env:l,Form:F,Fragment:D,Haori:oe,Log:m,Queue:K,default:oe,enhancers:Jt,version:At,waitForRenders:Xt},Symbol.toStringTag,{value:"Module"})),je=oe;for(const[b,e]of Object.entries(Zt))b in je||Object.defineProperty(je,b,{value:e,writable:!0,enumerable:!0,configurable:!0});return je}();
33
33
  //# sourceMappingURL=haori.iife.js.map