haori 0.59.0 → 0.59.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.ja.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Haori.js は、HTML 属性を中心にして動的な UI を実現する軽量なライブラリです。JavaScript をほとんど書かずに、データバインディング、条件分岐、繰り返し処理、フォームの双方向バインディング、サーバー通信などを HTML 属性で宣言できます。
4
4
 
5
- バージョン: 0.59.0
5
+ バージョン: 0.59.1
6
6
 
7
7
  ---
8
8
 
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Haori.js is a lightweight, HTML-first UI library that enables dynamic user interfaces primarily through HTML attributes. It lets you declare data bindings, conditional rendering, list rendering, form two-way binding, server fetches, and HTML imports without writing much JavaScript.
4
4
 
5
- Version: 0.59.0
5
+ Version: 0.59.1
6
6
 
7
7
  ---
8
8
 
package/dist/haori.cjs.js CHANGED
@@ -24,10 +24,10 @@ ${W}
24
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,T=A.message,k=typeof E=="string"&&E.length>0?E:null,B=typeof T=="string"?T:T!=null?String(T):"";if(B.length===0)continue;if(k!==null){const I=g.get(k)??[];I.push(B),g.set(k,I)}else y.push(B)}else typeof A=="string"&&A.length>0&&y.push(A);for(const[A,E]of g)d.push({key:A,message:E.join(`
25
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 N.warnUnvalidatedCustomValidity(e,`${l.prefix}${this.eventType??"fetch"}-validate の指定がありません`),!0;N.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=N.buildConditionScope(r,this.options.formFragment??null),s=ie.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=ie.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 T=A[g],k=T!==null&&typeof T=="object"&&!Array.isArray(T)?T:{};E[g]=this.mergeAppendBindingData(o,i,k)}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=>{H.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=N.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]:ge(c,n)}}return ge(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=N.getValuesEditedAfter(e,i?0:r);return Object.keys(n).length===0?t:ge(t,n)}reconcileAncestorArgFormEdits(e,t,r){let i=t;for(const{form:n,key:s}of N.collectArgForms(e)){if(!Object.prototype.hasOwnProperty.call(i,s))continue;const a=N.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]:ge(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=N.getValuesEditedAfter(e,0);return Object.keys(r).length===0?t:ge(t,r)}applyCopyToRowItem(e,t,r){return{...this.resolveCurrentRowItem(e,t),...r}}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?xe(this.options.copySourceFragment):$.withoutReservedBindingKeys(this.options.copySourceFragment.getRawBindingData()??{}):this.options.formFragment?xe(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=N.getValues(r);Object.assign(e,i),N.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"&&!He(a),c=o?"GET":a;if(n.method=c,Object.keys(t).length>0&&Ie(t)){const d=s.get("Content-Type")||"";c!=="GET"&&c!=="HEAD"&&c!=="OPTIONS"&&/multipart\/form-data/i.test(d)?jt(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=yt(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,Ae(E))}):g.append(y,Ae(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,Ae(E))):g.append(y,Ae(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:Kt(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?xe(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 xe(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=K.read(t,r);if(i!==null&&i.trim()!==""){const s=K.query(i,r,document);if(s===null)return m.error("Haori",`Row container not found: ${i} (${r})`),null;const a=F.get(s);return a instanceof S?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"&&N.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"&&N.clearRowUserEditMarksForChangedKeys(e,t),N.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 ae=p;class zt{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){gt(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=F.get(e);return r instanceof S?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 S?t.push(f.evaluateAll(r)):r instanceof ne&&t.push(f.evaluateText(r))}),Promise.all(t).then(()=>{})}static clearUserEditMarks(e,t=S.currentSequence()){e.clearUserEditMark(t),e.getChildren().forEach(r=>{r instanceof S&&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`)&&N.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 S&&r.push(f.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})):Promise.all(r).then(()=>{})}static executeManagedFetch(e,t=!1){const r=e.getTarget();if(!t&&f.initialValueRestores.size>0&&e.hasAttribute(`${l.prefix}fetch-form`))return Promise.all(f.initialValueRestores).then(()=>f.executeManagedFetch(e,!0)).catch(a=>{m.error("Haori",`初期表示の取得に失敗しました: ${a}`)}),Promise.resolve();const i=f.getReactiveFetchState(r),n=ae.resolveAutoFetchSignature(e);if(i.running)return(n.hasUnresolvedReference||n.signature!==i.lastSignature)&&(i.rerunRequested=!0),Promise.resolve();if(n.hasUnresolvedReference||n.signature===null)return i.lastSignature=null,Promise.resolve();if(i.lastSignature===n.signature)return Promise.resolve();i.lastSignature=n.signature,i.running=!0;const s=new ae(e,null);return s.markReentrantBind(),s.runWithResult().then(()=>{}).finally(()=>{if(i.running=!1,i.rerunRequested)return i.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`,""),H.importStart(t,n),zt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return z.enqueue(()=>{t.innerHTML=a}).then(()=>{t.removeAttribute(`${l.prefix}importing`),H.importEnd(t,n,o,s),f.adoptImportedChildren(e);const c=[];return e.getChildren().forEach(u=>{u instanceof S?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`),H.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=F.get(r);i!==null&&i.getParent()!==e&&e.pushChild(i)})}static scan(e){return f.scanElement(e,!0)}static scanElement(e,t){const r=F.get(e);if(!r)return Promise.resolve();const i=f.initializeElementFragment(r,!1).then(()=>N.restoreInitialValues(e));return f.initialValueRestores.add(i),i.then(()=>{f.initialValueRestores.delete(i),t&&te.applySubtree(e)})}static applyEnhancersOnShow(e,t){const r=e.getTarget();return S.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 S?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(),N.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=F.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 S&&s.consumeSelfWrittenBind(r))break;const g=r===null?{}:f.parseDataBind(r);if(i){const y=n??S.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(Fe.restore(s));break;case`${l.prefix}validity`:case`${l.prefix}validity-message`:return r!==null&&N.applyCustomValidity(s),Promise.all(o).then(()=>{});case`${l.prefix}url-param`:{const g=s.getAttribute(`${l.prefix}url-arg`),y=mt.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:S.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=F.get(e),n=r.skipFragments??new Set,s=r.reentrant??!1,a=r.reflectToAttribute??!0,o=r.kind??"supply",c=r.sequence??S.nextOperationSequence(),u={sequence:c,kind:o,...r.editedPaths===void 0?{}:{editedPaths:r.editedPaths}},d=o==="supply";d&&i.markSupplyApplied(c);const g=S.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&&(H.bindChange(e,y,A,"manual"),Fe.mirror(i));const E=()=>{i.markBindingWorkStart();const T=i.getRawBindingData()??A;let k=a?i.setAttribute(`${l.prefix}bind`,JSON.stringify(f.withoutReservedBindingKeys(T))):Promise.resolve();return e.tagName==="FORM"&&(k=k.then(()=>{if(i.wasResetAfter(g))return;const B=i.getRawBindingData()??A;return N.syncValues(i,N.resolveSyncValues(i,B),!1,u)})),k=k.then(()=>N.syncAncestorArgForms(i,g,u,y)),k=k.then(()=>f.evaluateAll(i,n)),k=k.then(()=>S.retryUnappliedValueWrites(e,g)),k=k.then(()=>f.reevaluateReactiveSpecialAttributes(i,n)),k.then(()=>i.markBindingWorkEnd(),B=>{throw i.markBindingWorkEnd(),B})};return s?E():i.enqueueBindingWork(E)}static withoutReservedBindingKeys(e){const t={};for(const r of Object.keys(e))S.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 T=n===""?E:`${n}.${E}`,k=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,T);k!==f.ABSENT_PATH&&(g[E]=k),k!==(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=F.get(e);return r instanceof S?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=F.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=F.get(e);if(r.isSkipMutationNode(t))return Promise.resolve();const i=F.get(t.nextSibling),n=F.get(t);if(n){if(n.getParent()===r)return Promise.resolve();if(r.insertBefore(n,i),n instanceof S)return f.scan(n.getTarget());if(n instanceof ne)return f.evaluateText(n)}return Promise.resolve()}static removeNode(e){const t=F.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNode(e))return;t.remove()}}static changeText(e,t){const r=F.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=F.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=N.getValues(n),a=n.getAttribute(`${l.prefix}form-arg`),o=n.getRawBindingData();let c;if(a){c={...o??{}};const u=String(a),d=N.resolveAncestorArgOwner(n,u);c[u]=N.mergeCollectedValues((d?d.value:c[u])??null,s)}else c=N.mergeCollectedValues(o,s,N.ancestorBaseResolver(n));i.push(f.setBindingData(n.getTarget(),c,{kind:"nonSupply",sequence:S.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=S.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 S){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=ie.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(ie.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 S&&f.isEachFixedChild(t))}static evaluateEachFixedChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof S?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=S.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(()=>{H.hide(e.getTarget())}));else{e.restoreFormControlsDisabledByIf();const i=e.isVisible(),n=S.currentSequence(),s=[],a=e.hasAttribute(`${l.prefix}each`);e.getChildren().forEach(o=>{if(o instanceof S){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(()=>{H.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 ae(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()&&ie.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 N.warnUnvalidatedCustomValidity(e,`${l.prefix}${this.eventType??"fetch"}-validate の指定がありません`),!0;N.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=N.buildConditionScope(r,this.options.formFragment??null),s=ie.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=ie.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 T=A[g],k=T!==null&&typeof T=="object"&&!Array.isArray(T)?T:{};E[g]=this.mergeAppendBindingData(o,i,k)}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,[d]),{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,Object.keys(u)),{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=>{H.bindComplete(c.getTarget(),o)})})})}reconcileUserEditsForBind(e,t,r){const i=this.requestUserEditSequence;if(i===null)return t;const n=this.eventType==="poll";if(!n&&!this.twoWayCommitBind&&$.clearUserEditMarks(e,i),!(e.getTarget()instanceof HTMLFormElement))return this.reconcileAncestorArgFormEdits(e,t,r,n?0:i);const s=N.getValuesEditedAfter(e,n?0:i);if(Object.keys(s).length===0)return t;const a=e.getAttribute(`${l.prefix}form-arg`);if(a){const o=String(a),c=t[o],u=c&&typeof c=="object"&&!Array.isArray(c)?c:{};return{...t,[o]:ge(u,s)}}return ge(t,s)}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=N.getValuesEditedAfter(e,i?0:r);return Object.keys(n).length===0?t:ge(t,n)}reconcileAncestorArgFormEdits(e,t,r,i){let n=t;for(const{form:s,key:a}of N.collectArgForms(e)){if(!r.includes(a))continue;const o=N.getValuesEditedAfter(s,i);if(Object.keys(o).length===0)continue;const c=n[a],u=c&&typeof c=="object"&&!Array.isArray(c)?c:{};n={...n,[a]:ge(u,o)}}return n}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=N.getValuesEditedAfter(e,0);return Object.keys(r).length===0?t:ge(t,r)}applyCopyToRowItem(e,t,r){return{...this.resolveCurrentRowItem(e,t),...r}}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?xe(this.options.copySourceFragment):$.withoutReservedBindingKeys(this.options.copySourceFragment.getRawBindingData()??{}):this.options.formFragment?xe(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=N.getValues(r);Object.assign(e,i),N.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"&&!He(a),c=o?"GET":a;if(n.method=c,Object.keys(t).length>0&&Ie(t)){const d=s.get("Content-Type")||"";c!=="GET"&&c!=="HEAD"&&c!=="OPTIONS"&&/multipart\/form-data/i.test(d)?jt(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=yt(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,Ae(E))}):g.append(y,Ae(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,Ae(E))):g.append(y,Ae(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:Kt(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?xe(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 xe(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=K.read(t,r);if(i!==null&&i.trim()!==""){const s=K.query(i,r,document);if(s===null)return m.error("Haori",`Row container not found: ${i} (${r})`),null;const a=F.get(s);return a instanceof S?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"&&N.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"&&N.clearRowUserEditMarksForChangedKeys(e,t),N.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 ae=p;class zt{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){gt(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=F.get(e);return r instanceof S?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 S?t.push(f.evaluateAll(r)):r instanceof ne&&t.push(f.evaluateText(r))}),Promise.all(t).then(()=>{})}static clearUserEditMarks(e,t=S.currentSequence()){e.clearUserEditMark(t),e.getChildren().forEach(r=>{r instanceof S&&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`)&&N.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 S&&r.push(f.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})):Promise.all(r).then(()=>{})}static executeManagedFetch(e,t=!1){const r=e.getTarget();if(!t&&f.initialValueRestores.size>0&&e.hasAttribute(`${l.prefix}fetch-form`))return Promise.all(f.initialValueRestores).then(()=>f.executeManagedFetch(e,!0)).catch(a=>{m.error("Haori",`初期表示の取得に失敗しました: ${a}`)}),Promise.resolve();const i=f.getReactiveFetchState(r),n=ae.resolveAutoFetchSignature(e);if(i.running)return(n.hasUnresolvedReference||n.signature!==i.lastSignature)&&(i.rerunRequested=!0),Promise.resolve();if(n.hasUnresolvedReference||n.signature===null)return i.lastSignature=null,Promise.resolve();if(i.lastSignature===n.signature)return Promise.resolve();i.lastSignature=n.signature,i.running=!0;const s=new ae(e,null);return s.markReentrantBind(),s.runWithResult().then(()=>{}).finally(()=>{if(i.running=!1,i.rerunRequested)return i.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`,""),H.importStart(t,n),zt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return z.enqueue(()=>{t.innerHTML=a}).then(()=>{t.removeAttribute(`${l.prefix}importing`),H.importEnd(t,n,o,s),f.adoptImportedChildren(e);const c=[];return e.getChildren().forEach(u=>{u instanceof S?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`),H.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=F.get(r);i!==null&&i.getParent()!==e&&e.pushChild(i)})}static scan(e){return f.scanElement(e,!0)}static scanElement(e,t){const r=F.get(e);if(!r)return Promise.resolve();const i=f.initializeElementFragment(r,!1).then(()=>N.restoreInitialValues(e));return f.initialValueRestores.add(i),i.then(()=>{f.initialValueRestores.delete(i),t&&te.applySubtree(e)})}static applyEnhancersOnShow(e,t){const r=e.getTarget();return S.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 S?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(),N.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=F.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 S&&s.consumeSelfWrittenBind(r))break;const g=r===null?{}:f.parseDataBind(r);if(i){const y=n??S.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(Fe.restore(s));break;case`${l.prefix}validity`:case`${l.prefix}validity-message`:return r!==null&&N.applyCustomValidity(s),Promise.all(o).then(()=>{});case`${l.prefix}url-param`:{const g=s.getAttribute(`${l.prefix}url-arg`),y=mt.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:S.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=F.get(e),n=r.skipFragments??new Set,s=r.reentrant??!1,a=r.reflectToAttribute??!0,o=r.kind??"supply",c=r.sequence??S.nextOperationSequence(),u={sequence:c,kind:o,...r.editedPaths===void 0?{}:{editedPaths:r.editedPaths}},d=o==="supply";d&&i.markSupplyApplied(c);const g=S.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&&(H.bindChange(e,y,A,"manual"),Fe.mirror(i));const E=()=>{i.markBindingWorkStart();const T=i.getRawBindingData()??A;let k=a?i.setAttribute(`${l.prefix}bind`,JSON.stringify(f.withoutReservedBindingKeys(T))):Promise.resolve();return e.tagName==="FORM"&&(k=k.then(()=>{if(i.wasResetAfter(g))return;const B=i.getRawBindingData()??A;return N.syncValues(i,N.resolveSyncValues(i,B),!1,u)})),k=k.then(()=>N.syncAncestorArgForms(i,g,u,y)),k=k.then(()=>f.evaluateAll(i,n)),k=k.then(()=>S.retryUnappliedValueWrites(e,g)),k=k.then(()=>f.reevaluateReactiveSpecialAttributes(i,n)),k.then(()=>i.markBindingWorkEnd(),B=>{throw i.markBindingWorkEnd(),B})};return s?E():i.enqueueBindingWork(E)}static withoutReservedBindingKeys(e){const t={};for(const r of Object.keys(e))S.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 T=n===""?E:`${n}.${E}`,k=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,T);k!==f.ABSENT_PATH&&(g[E]=k),k!==(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=F.get(e);return r instanceof S?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=F.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=F.get(e);if(r.isSkipMutationNode(t))return Promise.resolve();const i=F.get(t.nextSibling),n=F.get(t);if(n){if(n.getParent()===r)return Promise.resolve();if(r.insertBefore(n,i),n instanceof S)return f.scan(n.getTarget());if(n instanceof ne)return f.evaluateText(n)}return Promise.resolve()}static removeNode(e){const t=F.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNode(e))return;t.remove()}}static changeText(e,t){const r=F.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=F.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=N.getValues(n),a=n.getAttribute(`${l.prefix}form-arg`),o=n.getRawBindingData();let c;if(a){c={...o??{}};const u=String(a),d=N.resolveAncestorArgOwner(n,u);c[u]=N.mergeCollectedValues((d?d.value:c[u])??null,s)}else c=N.mergeCollectedValues(o,s,N.ancestorBaseResolver(n));i.push(f.setBindingData(n.getTarget(),c,{kind:"nonSupply",sequence:S.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=S.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 S){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=ie.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(ie.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 S&&f.isEachFixedChild(t))}static evaluateEachFixedChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof S?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=S.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(()=>{H.hide(e.getTarget())}));else{e.restoreFormControlsDisabledByIf();const i=e.isVisible(),n=S.currentSequence(),s=[],a=e.hasAttribute(`${l.prefix}each`);e.getChildren().forEach(o=>{if(o instanceof S){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(()=>{H.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 ae(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()&&ie.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
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 S){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=F.get(c);d instanceof S&&(r=d.clone(),f.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const u=F.get(c);u instanceof S&&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 S){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=ie.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 S?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=F.peek(i);return n instanceof S?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 S&&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 S).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 S?!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((I,j)=>f.createListKey(I,n?String(n):null,j)),o=new Set(a),c=new Map;a.forEach(I=>{c.set(I,(c.get(I)??0)+1)}),n&&o.size!==a.length&&f.warnDuplicateEachKey(String(n));const u=[];let d=e.getChildren().filter(I=>I instanceof S).filter(I=>!I.hasAttribute(`${l.prefix}each-before`)&&!I.hasAttribute(`${l.prefix}each-after`));const g=d.map(I=>I.getListKey()),y=new Set;d=d.filter((I,j)=>{const Z=String(I.getListKey()),_=c.get(Z)??0;if(_===0){y.add(I);const P=I.getListKey();return P!==null&&H.rowRemove(I.getTarget(),P,j),u.push(I.remove()),!1}return c.set(Z,_-1),!0});const A=d.map(I=>I.getListKey()),E=new Map;d.forEach(I=>{const j=I.getListKey();if(j===null)return;const Z=E.get(j);Z?Z.push(I):E.set(j,[I])});const T=e.getChildElementFragments().filter(I=>!y.has(I)),k=T.filter(I=>I.hasAttribute(`${l.prefix}each-before`)).length;let B=Promise.resolve();return a.forEach((I,j)=>{const Z=t[j],_=j;let P;const se=E.get(I)?.shift();if(se){P=se;const Y=k+j;B=B.then(()=>f.updateRowFragment(P,Z,i,_,s?String(s):null,I).then(D=>f.repositionEachRow(e,P,T,Y).then(L=>{if(L!==null&&H.rowMove(P.getTarget(),I,L-k,j),!(!D&&f.isRowLocalEachTemplate(e)))return f.evaluateAll(P).then(()=>f.applyRowFormValues(e,P,Z))})))}else{P=r.clone();const Y=k+j;B=B.then(()=>f.updateRowFragment(P,Z,i,_,s?String(s):null,I).then(()=>{const D=T[Y]??null;return e.insertBefore(P,D).then(()=>{T.splice(Y,0,P)}).then(()=>f.initializeFreshEachRow(P)).then(()=>f.applyRowFormValues(e,P,Z)).then(()=>{H.rowAdd(P.getTarget(),I,_,Z)})}))}}),Promise.all(u).then(()=>B).then(()=>{const I=a.filter(Y=>Y!==null),j=A.filter(Y=>Y!==null),Z=new Set(j),_=I.filter(Y=>!Z.has(Y)),se=g.filter(Y=>Y!==null).filter(Y=>!o.has(Y));H.eachUpdate(e.getTarget(),_,se,I)})}static warnExtraEachChildren(e){const t=e.getChildren().filter(r=>r instanceof S).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`)||!N.isCollectedListFromEachSource(e)||typeof r!="object"||r===null||Array.isArray(r)?Promise.resolve():N.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.initialValueRestores=new Set,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 Se=class Se{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||N.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[Se.HISTORY_STATE_KEY]!==!0){$.refreshUrlParams();return}location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=F.get(e);t&&new ae(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(Se.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=F.get(i);n instanceof S&&this.isFromTarget(n,t)&&new ae(n,"on",t).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})})}isFromTarget(e,t){const r=`${this.onAttributeName}-target`;if(!e.hasAttribute(r))return!0;const i=K.read(e,r),n=t.target;return i===null||!(n instanceof Node)?!1:K.queryAll(i,r).some(s=>s.contains(n))}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=F.get(e);if(!i)return;(t==="change"||t==="input")&&this.syncUserEdit(e,t==="change");const n=()=>{const s=new ae(i,t,r).runWithOutcome().catch(a=>(m.error("[Haori]","Procedure execution error:",a),"failure"));if(t==="click"){ae.recordClickOutcome(e,s);const a=r.target;a instanceof HTMLElement&&a!==e&&ae.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=F.get(e);t instanceof S&&t.markUserEdit()}syncUserEdit(e,t){const r=F.get(e);if(r instanceof S&&(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=F.get(n);s instanceof S&&(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}};Se.HISTORY_STATE_KEY="__haoriHistoryState__",Se.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let Ve=Se;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=F.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 ae(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=K.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=F.get(e);if(!(r instanceof S)||!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 ae(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&&H.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&&H.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:S.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=K.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=F.get(a);o instanceof S&&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 ve=v;const At="0.59.0";function Gt(b){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>b()):Promise.resolve().then(b)}const O=class O{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)&&(O.isHtmlElement(e)&&O.syncElement(e),e.querySelectorAll("*").forEach(t=>{O.syncElement(t)}))}static syncElement(e){const t=O.registrations.get(e),r=F.get(e);if(!(r instanceof S)||!O.shouldObserve(r)){t&&(t.observer.disconnect(),O.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=O.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),O.registrations.delete(e)),m.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=O.resolveRoot(r),s=O.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,O.refreshRows(t);return}t&&(t.observer.disconnect(),O.registrations.delete(e));const a=new IntersectionObserver(c=>{const u=O.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&&O.scheduleCompute(u)},{root:n,rootMargin:s,threshold:O.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};O.registrations.set(e,o),O.refreshRows(o)}static cleanupTree(e){if(O.isHtmlElement(e)){const t=O.registrations.get(e);t&&(t.observer.disconnect(),O.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=O.registrations.get(t);r&&(r.observer.disconnect(),O.registrations.delete(t))})}static disconnectAll(){O.registrations.forEach(e=>{e.observer.disconnect()}),O.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=K.query(r,t,document);return O.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===""?O.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof S&&!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=O.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));O.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,Gt(()=>{e.scheduled=!1;const t=e.fragment.getTarget();O.registrations.get(t)===e&&O.computeAndPublish(e)}))}static computeAndPublish(e){const t=O.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,O.publish(e,n))}static publish(e,t){const r=O.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:S.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}};O.THRESHOLD=0,O.DEFAULT_ROOT_MARGIN="0px",O.registrations=new Map;let me=O;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(),S.setPendingMutationFlusher(()=>{U.flushPendingMutations()});const e=new Ve;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 z.wait(),document.body.setAttribute("data-haori-ready",""),U.observe(document.head),U.observe(document.body),Ee.syncTree(document.body),ve.syncTree(document.body),me.syncTree(document.body)}finally{U._initialIntakes=null,e.release()}H.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=>S.peek(t)!==null)}static isStaleExternalRemoval(e,t){const r=S.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,S.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(pe)&&(r.attributeName==="disabled"||r.attributeName===pe))break;if(r.attributeName&&(r.attributeName===`${l.prefix}if-false`||r.attributeName==="style"&&i.hasAttribute(`${l.prefix}if-false`))){r.attributeName==="style"&&S.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),ve.syncElement(i),me.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{U.isStaleExternalRemoval(r,i)||(Ee.cleanupTree(i),ve.cleanupTree(i),me.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),ve.syncTree(i),me.syncTree(i)}),r.target instanceof Element&&me.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 Ne=U;te.setMutationCapture(b=>Ne.captureMutations(b));document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Ne.init):Ne.init();const Yt=()=>de.waitForRenders(),Xt=de.enhancers;exports.Core=$;exports.Enhance=te;exports.Env=l;exports.Form=N;exports.Fragment=F;exports.Haori=de;exports.Log=m;exports.Queue=z;exports.default=de;exports.enhancers=Xt;exports.version=At;exports.waitForRenders=Yt;
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 ae(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&&H.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&&H.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:S.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=K.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=F.get(a);o instanceof S&&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 ve=v;const At="0.59.1";function Gt(b){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>b()):Promise.resolve().then(b)}const O=class O{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)&&(O.isHtmlElement(e)&&O.syncElement(e),e.querySelectorAll("*").forEach(t=>{O.syncElement(t)}))}static syncElement(e){const t=O.registrations.get(e),r=F.get(e);if(!(r instanceof S)||!O.shouldObserve(r)){t&&(t.observer.disconnect(),O.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=O.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),O.registrations.delete(e)),m.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=O.resolveRoot(r),s=O.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,O.refreshRows(t);return}t&&(t.observer.disconnect(),O.registrations.delete(e));const a=new IntersectionObserver(c=>{const u=O.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&&O.scheduleCompute(u)},{root:n,rootMargin:s,threshold:O.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};O.registrations.set(e,o),O.refreshRows(o)}static cleanupTree(e){if(O.isHtmlElement(e)){const t=O.registrations.get(e);t&&(t.observer.disconnect(),O.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=O.registrations.get(t);r&&(r.observer.disconnect(),O.registrations.delete(t))})}static disconnectAll(){O.registrations.forEach(e=>{e.observer.disconnect()}),O.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=K.query(r,t,document);return O.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===""?O.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof S&&!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=O.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));O.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,Gt(()=>{e.scheduled=!1;const t=e.fragment.getTarget();O.registrations.get(t)===e&&O.computeAndPublish(e)}))}static computeAndPublish(e){const t=O.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,O.publish(e,n))}static publish(e,t){const r=O.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:S.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}};O.THRESHOLD=0,O.DEFAULT_ROOT_MARGIN="0px",O.registrations=new Map;let me=O;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(),S.setPendingMutationFlusher(()=>{U.flushPendingMutations()});const e=new Ve;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 z.wait(),document.body.setAttribute("data-haori-ready",""),U.observe(document.head),U.observe(document.body),Ee.syncTree(document.body),ve.syncTree(document.body),me.syncTree(document.body)}finally{U._initialIntakes=null,e.release()}H.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=>S.peek(t)!==null)}static isStaleExternalRemoval(e,t){const r=S.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,S.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(pe)&&(r.attributeName==="disabled"||r.attributeName===pe))break;if(r.attributeName&&(r.attributeName===`${l.prefix}if-false`||r.attributeName==="style"&&i.hasAttribute(`${l.prefix}if-false`))){r.attributeName==="style"&&S.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),ve.syncElement(i),me.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{U.isStaleExternalRemoval(r,i)||(Ee.cleanupTree(i),ve.cleanupTree(i),me.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),ve.syncTree(i),me.syncTree(i)}),r.target instanceof Element&&me.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 Ne=U;te.setMutationCapture(b=>Ne.captureMutations(b));document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Ne.init):Ne.init();const Yt=()=>de.waitForRenders(),Xt=de.enhancers;exports.Core=$;exports.Enhance=te;exports.Env=l;exports.Form=N;exports.Fragment=F;exports.Haori=de;exports.Log=m;exports.Queue=z;exports.default=de;exports.enhancers=Xt;exports.version=At;exports.waitForRenders=Yt;
33
33
  //# sourceMappingURL=haori.cjs.js.map
package/dist/haori.es.js CHANGED
@@ -11064,7 +11064,7 @@ ${W}
11064
11064
  n.push(
11065
11065
  $.setBindingData(
11066
11066
  o.getTarget(),
11067
- this.reconcileUserEditsForBind(o, u),
11067
+ this.reconcileUserEditsForBind(o, u, [d]),
11068
11068
  {
11069
11069
  // マネージド fetch の bind かつ、bind 先が実行中のバインドワークを
11070
11070
  // 持つ(= 自分自身を await している)ときだけ reentrant(即時実行)に
@@ -11122,7 +11122,11 @@ ${W}
11122
11122
  n.push(
11123
11123
  $.setBindingData(
11124
11124
  o.getTarget(),
11125
- this.reconcileUserEditsForBind(o, d),
11125
+ this.reconcileUserEditsForBind(
11126
+ o,
11127
+ d,
11128
+ Object.keys(u)
11129
+ ),
11126
11130
  {
11127
11131
  // いずれも上の bindArg 分岐と同じ扱い。
11128
11132
  reentrant: this.reentrantBind && o.isExecutingBindingWork(),
@@ -11169,31 +11173,34 @@ ${W}
11169
11173
  *
11170
11174
  * @param fragment バインド先のフラグメント
11171
11175
  * @param data バインドする応答データ
11176
+ * @param responseKeys 応答が持つキー。`-bind-merge` で既存データへ混ぜる前の
11177
+ * キーで、`-bind-arg` では指定したキーだけ
11172
11178
  * @return ユーザー編集分を上書きしたデータ
11173
11179
  */
11174
- reconcileUserEditsForBind(e, t) {
11175
- const r = this.requestUserEditSequence;
11176
- if (r === null)
11180
+ reconcileUserEditsForBind(e, t, r) {
11181
+ const i = this.requestUserEditSequence;
11182
+ if (i === null)
11177
11183
  return t;
11178
- const i = this.eventType === "poll";
11179
- if (!i && !this.twoWayCommitBind && $.clearUserEditMarks(e, r), !(e.getTarget() instanceof HTMLFormElement))
11184
+ const n = this.eventType === "poll";
11185
+ if (!n && !this.twoWayCommitBind && $.clearUserEditMarks(e, i), !(e.getTarget() instanceof HTMLFormElement))
11180
11186
  return this.reconcileAncestorArgFormEdits(
11181
11187
  e,
11182
11188
  t,
11183
- i ? 0 : r
11189
+ r,
11190
+ n ? 0 : i
11184
11191
  );
11185
- const n = k.getValuesEditedAfter(
11192
+ const s = k.getValuesEditedAfter(
11186
11193
  e,
11187
- i ? 0 : r
11194
+ n ? 0 : i
11188
11195
  );
11189
- if (Object.keys(n).length === 0)
11196
+ if (Object.keys(s).length === 0)
11190
11197
  return t;
11191
- const s = e.getAttribute(`${l.prefix}form-arg`);
11192
- if (s) {
11193
- const a = String(s), o = t[a], c = o && typeof o == "object" && !Array.isArray(o) ? o : {};
11194
- return { ...t, [a]: pe(c, n) };
11198
+ const a = e.getAttribute(`${l.prefix}form-arg`);
11199
+ if (a) {
11200
+ const o = String(a), c = t[o], u = c && typeof c == "object" && !Array.isArray(c) ? c : {};
11201
+ return { ...t, [o]: pe(u, s) };
11195
11202
  }
11196
- return pe(t, n);
11203
+ return pe(t, s);
11197
11204
  }
11198
11205
  /**
11199
11206
  * 編集可能な行へのバインドについて、送信後の編集を要素データへ上書きし直します。
@@ -11233,21 +11240,22 @@ ${W}
11233
11240
  *
11234
11241
  * @param fragment バインド先のフラグメント
11235
11242
  * @param data バインドする応答データ
11243
+ * @param responseKeys 応答が持つキー(既存データへ混ぜる前)
11236
11244
  * @param baseline この通し番号より後の編集を保護する
11237
11245
  * @return ユーザー編集分を上書きしたデータ
11238
11246
  */
11239
- reconcileAncestorArgFormEdits(e, t, r) {
11240
- let i = t;
11241
- for (const { form: n, key: s } of k.collectArgForms(e)) {
11242
- if (!Object.prototype.hasOwnProperty.call(i, s))
11247
+ reconcileAncestorArgFormEdits(e, t, r, i) {
11248
+ let n = t;
11249
+ for (const { form: s, key: a } of k.collectArgForms(e)) {
11250
+ if (!r.includes(a))
11243
11251
  continue;
11244
- const a = k.getValuesEditedAfter(n, r);
11245
- if (Object.keys(a).length === 0)
11252
+ const o = k.getValuesEditedAfter(s, i);
11253
+ if (Object.keys(o).length === 0)
11246
11254
  continue;
11247
- const o = i[s], c = o && typeof o == "object" && !Array.isArray(o) ? o : {};
11248
- i = { ...i, [s]: pe(c, a) };
11255
+ const c = n[a], u = c && typeof c == "object" && !Array.isArray(c) ? c : {};
11256
+ n = { ...n, [a]: pe(u, o) };
11249
11257
  }
11250
- return i;
11258
+ return n;
11251
11259
  }
11252
11260
  /**
11253
11261
  * bind-append 指定があるキーについて、既存配列と結合したデータを返します。
@@ -15638,7 +15646,7 @@ v.CONFIG_KEYS = /* @__PURE__ */ new Set([
15638
15646
  "state"
15639
15647
  ]), v.DEFAULT_INTERVAL_MS = 5e3, v.MIN_INTERVAL_MS = 100, v.registrations = /* @__PURE__ */ new Map(), v.visibilityListener = null;
15640
15648
  let Ee = v;
15641
- const zt = "0.59.0";
15649
+ const zt = "0.59.1";
15642
15650
  function Gt(b) {
15643
15651
  typeof requestAnimationFrame == "function" ? requestAnimationFrame(() => b()) : Promise.resolve().then(b);
15644
15652
  }
@@ -24,10 +24,10 @@ ${W}
24
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,T=A.message,k=typeof E=="string"&&E.length>0?E:null,H=typeof T=="string"?T:T!=null?String(T):"";if(H.length===0)continue;if(k!==null){const N=g.get(k)??[];N.push(H),g.set(k,N)}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
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 I.warnUnvalidatedCustomValidity(e,`${l.prefix}${this.eventType??"fetch"}-validate の指定がありません`),!0;I.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=I.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 T=A[g],k=T!==null&&typeof T=="object"&&!Array.isArray(T)?T:{};E[g]=this.mergeAppendBindingData(o,i,k)}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=I.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=I.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 I.collectArgForms(e)){if(!Object.prototype.hasOwnProperty.call(i,s))continue;const a=I.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=I.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=I.getValues(r);Object.assign(e,i),I.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=yt(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=F.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"&&I.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"&&I.clearRowUserEditMarksForChangedKeys(e,t),I.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=F.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`)&&I.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();if(!t&&f.initialValueRestores.size>0&&e.hasAttribute(`${l.prefix}fetch-form`))return Promise.all(f.initialValueRestores).then(()=>f.executeManagedFetch(e,!0)).catch(a=>{m.error("Haori",`初期表示の取得に失敗しました: ${a}`)}),Promise.resolve();const i=f.getReactiveFetchState(r),n=se.resolveAutoFetchSignature(e);if(i.running)return(n.hasUnresolvedReference||n.signature!==i.lastSignature)&&(i.rerunRequested=!0),Promise.resolve();if(n.hasUnresolvedReference||n.signature===null)return i.lastSignature=null,Promise.resolve();if(i.lastSignature===n.signature)return Promise.resolve();i.lastSignature=n.signature,i.running=!0;const s=new se(e,null);return s.markReentrantBind(),s.runWithResult().then(()=>{}).finally(()=>{if(i.running=!1,i.rerunRequested)return i.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 z.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=F.get(r);i!==null&&i.getParent()!==e&&e.pushChild(i)})}static scan(e){return f.scanElement(e,!0)}static scanElement(e,t){const r=F.get(e);if(!r)return Promise.resolve();const i=f.initializeElementFragment(r,!1).then(()=>I.restoreInitialValues(e));return f.initialValueRestores.add(i),i.then(()=>{f.initialValueRestores.delete(i),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(),I.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=F.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&&I.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=F.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 T=i.getRawBindingData()??A;let k=a?i.setAttribute(`${l.prefix}bind`,JSON.stringify(f.withoutReservedBindingKeys(T))):Promise.resolve();return e.tagName==="FORM"&&(k=k.then(()=>{if(i.wasResetAfter(g))return;const H=i.getRawBindingData()??A;return I.syncValues(i,I.resolveSyncValues(i,H),!1,u)})),k=k.then(()=>I.syncAncestorArgForms(i,g,u,y)),k=k.then(()=>f.evaluateAll(i,n)),k=k.then(()=>w.retryUnappliedValueWrites(e,g)),k=k.then(()=>f.reevaluateReactiveSpecialAttributes(i,n)),k.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 T=n===""?E:`${n}.${E}`,k=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,T);k!==f.ABSENT_PATH&&(g[E]=k),k!==(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=F.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=F.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=F.get(e);if(r.isSkipMutationNode(t))return Promise.resolve();const i=F.get(t.nextSibling),n=F.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=F.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNode(e))return;t.remove()}}static changeText(e,t){const r=F.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=F.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=I.getValues(n),a=n.getAttribute(`${l.prefix}form-arg`),o=n.getRawBindingData();let c;if(a){c={...o??{}};const u=String(a),d=I.resolveAncestorArgOwner(n,u);c[u]=I.mergeCollectedValues((d?d.value:c[u])??null,s)}else c=I.mergeCollectedValues(o,s,I.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 (
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 I.warnUnvalidatedCustomValidity(e,`${l.prefix}${this.eventType??"fetch"}-validate の指定がありません`),!0;I.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=I.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 T=A[g],k=T!==null&&typeof T=="object"&&!Array.isArray(T)?T:{};E[g]=this.mergeAppendBindingData(o,i,k)}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,[d]),{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,Object.keys(u)),{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,r){const i=this.requestUserEditSequence;if(i===null)return t;const n=this.eventType==="poll";if(!n&&!this.twoWayCommitBind&&$.clearUserEditMarks(e,i),!(e.getTarget()instanceof HTMLFormElement))return this.reconcileAncestorArgFormEdits(e,t,r,n?0:i);const s=I.getValuesEditedAfter(e,n?0:i);if(Object.keys(s).length===0)return t;const a=e.getAttribute(`${l.prefix}form-arg`);if(a){const o=String(a),c=t[o],u=c&&typeof c=="object"&&!Array.isArray(c)?c:{};return{...t,[o]:pe(u,s)}}return pe(t,s)}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=I.getValuesEditedAfter(e,i?0:r);return Object.keys(n).length===0?t:pe(t,n)}reconcileAncestorArgFormEdits(e,t,r,i){let n=t;for(const{form:s,key:a}of I.collectArgForms(e)){if(!r.includes(a))continue;const o=I.getValuesEditedAfter(s,i);if(Object.keys(o).length===0)continue;const c=n[a],u=c&&typeof c=="object"&&!Array.isArray(c)?c:{};n={...n,[a]:pe(u,o)}}return n}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=I.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=I.getValues(r);Object.assign(e,i),I.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=yt(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=F.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"&&I.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"&&I.clearRowUserEditMarksForChangedKeys(e,t),I.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=F.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`)&&I.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();if(!t&&f.initialValueRestores.size>0&&e.hasAttribute(`${l.prefix}fetch-form`))return Promise.all(f.initialValueRestores).then(()=>f.executeManagedFetch(e,!0)).catch(a=>{m.error("Haori",`初期表示の取得に失敗しました: ${a}`)}),Promise.resolve();const i=f.getReactiveFetchState(r),n=se.resolveAutoFetchSignature(e);if(i.running)return(n.hasUnresolvedReference||n.signature!==i.lastSignature)&&(i.rerunRequested=!0),Promise.resolve();if(n.hasUnresolvedReference||n.signature===null)return i.lastSignature=null,Promise.resolve();if(i.lastSignature===n.signature)return Promise.resolve();i.lastSignature=n.signature,i.running=!0;const s=new se(e,null);return s.markReentrantBind(),s.runWithResult().then(()=>{}).finally(()=>{if(i.running=!1,i.rerunRequested)return i.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 z.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=F.get(r);i!==null&&i.getParent()!==e&&e.pushChild(i)})}static scan(e){return f.scanElement(e,!0)}static scanElement(e,t){const r=F.get(e);if(!r)return Promise.resolve();const i=f.initializeElementFragment(r,!1).then(()=>I.restoreInitialValues(e));return f.initialValueRestores.add(i),i.then(()=>{f.initialValueRestores.delete(i),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(),I.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=F.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&&I.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=F.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 T=i.getRawBindingData()??A;let k=a?i.setAttribute(`${l.prefix}bind`,JSON.stringify(f.withoutReservedBindingKeys(T))):Promise.resolve();return e.tagName==="FORM"&&(k=k.then(()=>{if(i.wasResetAfter(g))return;const H=i.getRawBindingData()??A;return I.syncValues(i,I.resolveSyncValues(i,H),!1,u)})),k=k.then(()=>I.syncAncestorArgForms(i,g,u,y)),k=k.then(()=>f.evaluateAll(i,n)),k=k.then(()=>w.retryUnappliedValueWrites(e,g)),k=k.then(()=>f.reevaluateReactiveSpecialAttributes(i,n)),k.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 T=n===""?E:`${n}.${E}`,k=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,T);k!==f.ABSENT_PATH&&(g[E]=k),k!==(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=F.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=F.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=F.get(e);if(r.isSkipMutationNode(t))return Promise.resolve();const i=F.get(t.nextSibling),n=F.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=F.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNode(e))return;t.remove()}}static changeText(e,t){const r=F.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=F.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=I.getValues(n),a=n.getAttribute(`${l.prefix}form-arg`),o=n.getRawBindingData();let c;if(a){c={...o??{}};const u=String(a),d=I.resolveAncestorArgOwner(n,u);c[u]=I.mergeCollectedValues((d?d.value:c[u])??null,s)}else c=I.mergeCollectedValues(o,s,I.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
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=F.get(c);d instanceof w&&(r=d.clone(),f.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const u=F.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=F.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((N,K)=>f.createListKey(N,n?String(n):null,K)),o=new Set(a),c=new Map;a.forEach(N=>{c.set(N,(c.get(N)??0)+1)}),n&&o.size!==a.length&&f.warnDuplicateEachKey(String(n));const u=[];let d=e.getChildren().filter(N=>N instanceof w).filter(N=>!N.hasAttribute(`${l.prefix}each-before`)&&!N.hasAttribute(`${l.prefix}each-after`));const g=d.map(N=>N.getListKey()),y=new Set;d=d.filter((N,K)=>{const Z=String(N.getListKey()),ee=c.get(Z)??0;if(ee===0){y.add(N);const L=N.getListKey();return L!==null&&B.rowRemove(N.getTarget(),L,K),u.push(N.remove()),!1}return c.set(Z,ee-1),!0});const A=d.map(N=>N.getListKey()),E=new Map;d.forEach(N=>{const K=N.getListKey();if(K===null)return;const Z=E.get(K);Z?Z.push(N):E.set(K,[N])});const T=e.getChildElementFragments().filter(N=>!y.has(N)),k=T.filter(N=>N.hasAttribute(`${l.prefix}each-before`)).length;let H=Promise.resolve();return a.forEach((N,K)=>{const Z=t[K],ee=K;let L;const ae=E.get(N)?.shift();if(ae){L=ae;const Y=k+K;H=H.then(()=>f.updateRowFragment(L,Z,i,ee,s?String(s):null,N).then(D=>f.repositionEachRow(e,L,T,Y).then(O=>{if(O!==null&&B.rowMove(L.getTarget(),N,O-k,K),!(!D&&f.isRowLocalEachTemplate(e)))return f.evaluateAll(L).then(()=>f.applyRowFormValues(e,L,Z))})))}else{L=r.clone();const Y=k+K;H=H.then(()=>f.updateRowFragment(L,Z,i,ee,s?String(s):null,N).then(()=>{const D=T[Y]??null;return e.insertBefore(L,D).then(()=>{T.splice(Y,0,L)}).then(()=>f.initializeFreshEachRow(L)).then(()=>f.applyRowFormValues(e,L,Z)).then(()=>{B.rowAdd(L.getTarget(),N,ee,Z)})}))}}),Promise.all(u).then(()=>H).then(()=>{const N=a.filter(Y=>Y!==null),K=A.filter(Y=>Y!==null),Z=new Set(K),ee=N.filter(Y=>!Z.has(Y)),ae=g.filter(Y=>Y!==null).filter(Y=>!o.has(Y));B.eachUpdate(e.getTarget(),ee,ae,N)})}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`)||!I.isCollectedListFromEachSource(e)||typeof r!="object"||r===null||Array.isArray(r)?Promise.resolve():I.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.initialValueRestores=new Set,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||I.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=F.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=F.get(i);n instanceof w&&this.isFromTarget(n,t)&&new se(n,"on",t).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})})}isFromTarget(e,t){const r=`${this.onAttributeName}-target`;if(!e.hasAttribute(r))return!0;const i=j.read(e,r),n=t.target;return i===null||!(n instanceof Node)?!1:j.queryAll(i,r).some(s=>s.contains(n))}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=F.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=F.get(e);t instanceof w&&t.markUserEdit()}syncUserEdit(e,t){const r=F.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=F.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=F.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=F.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=F.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 Et="0.59.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=F.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 z.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(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),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:I,Fragment:F,Haori:oe,Log:m,Queue:z,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}();
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=F.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 Et="0.59.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=F.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 z.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(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),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:I,Fragment:F,Haori:oe,Log:m,Queue:z,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}();
33
33
  //# sourceMappingURL=haori.iife.js.map
package/dist/index.d.ts CHANGED
@@ -4804,7 +4804,7 @@ declare interface ValueChangeOrigin {
4804
4804
  * リリース時に `package.json` と揃えて更新します(`tests/version.test.ts` が
4805
4805
  * 一致を検査します)。
4806
4806
  */
4807
- export declare const version = "0.59.0";
4807
+ export declare const version = "0.59.1";
4808
4808
 
4809
4809
  /**
4810
4810
  * すべてのレンダリングタスク(追従投入分を含む)の完了を待ちます。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "haori",
3
- "version": "0.59.0",
3
+ "version": "0.59.1",
4
4
  "description": "A lightweight HTML-first UI engine powered by declarative data bindings and expressions.",
5
5
  "scripts": {
6
6
  "dev": "vite",