haori 0.11.0 → 0.11.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.10.0
5
+ バージョン: 0.11.1
6
6
 
7
7
  ---
8
8
 
@@ -111,6 +111,7 @@ Haori.mount(document.body, {items: [{name: 'りんご'}, {name: 'みかん'}]});
111
111
  - `data-click-*`・`data-change-*`・`data-load-*`・`data-intersect-*` は、それぞれクリック・フォーム変更・要素ロード・ビューポート交差を契機に処理(fetch、bind、copy、ダイアログ操作など)を宣言します。`data-load-*` は `data-if` 要素が非表示→表示へ遷移した(`haori:show`)タイミングでも発火するため、ネイティブの `load` が発生しない `<button>` などでも利用できます。
112
112
  - `data-click-copy-source` — `data-click-copy` のコピー元要素を明示指定します(既定は `data-click-form` のフォーム、無ければイベント発火元の binding)。
113
113
  - `data-click-no-disabled` / `data-click-defer` — 他ライブラリとの併用補助です。`no-disabled` はクリック手続き実行中に `disabled` 属性を付与せず実行します(Bootstrap collapse など disabled 要素を無視するライブラリ・CSS が動作し続けます。多重実行は内部マーカーで防止)。`defer` はクリック手続きを次フレーム(`requestAnimationFrame`/`setTimeout(0)`)で実行し、他ライブラリの同期 click ハンドラを先に完了させます。遅延後は `preventDefault()` できないため、`<a href>` や `type="submit"` への `defer` 併用は避けてください。
114
+ - `data-{event}-run`(例: `data-click-run`・`data-change-run`)— フェッチを伴わず任意の JavaScript をイベント時に実行します。属性値は `new Function` で実 JS として実行され(`-before-run`/`-after-run` と同方式)、`{{...}}` はレンダリング時に展開、`event` が引数で渡されます。本体が `false` を返すと `event.preventDefault()` を呼びます(`onclick="return false"` の慣習)。**セキュリティ**: 展開後の `{{...}}` は実行コードへ結合されるため、信頼できる値(数値 index・自前採番 ID 等)のみを入れてください。API レスポンスやユーザー入力などの信頼できない文字列を入れると任意コード実行(XSS)になり得ます。信頼できない値は `data-bind` 経由で渡し、呼び出す関数の内部で参照してください。
114
115
 
115
116
  ライフサイクルイベント:
116
117
 
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.10.0
5
+ Version: 0.11.1
6
6
 
7
7
  ---
8
8
 
@@ -111,6 +111,7 @@ Event-driven actions:
111
111
  - `data-click-*`, `data-change-*`, `data-load-*`, `data-intersect-*` declare actions (fetch, bind, copy, dialog control, etc.) triggered by click, form change, element load, and viewport intersection respectively. `data-load-*` also fires when a `data-if` element transitions from hidden to shown (the `haori:show` timing), so it works on elements like `<button>` that never receive a native `load` event.
112
112
  - `data-click-copy-source` — explicitly set the copy source element for `data-click-copy` (defaults to the form given by `data-click-form`, otherwise the event element's binding).
113
113
  - `data-click-no-disabled` / `data-click-defer` — coexistence helpers for other libraries. `no-disabled` runs the click procedure without adding the `disabled` attribute (so libraries/CSS that ignore disabled elements, e.g. Bootstrap collapse, keep working; double execution is still prevented internally). `defer` runs the click procedure on the next frame (`requestAnimationFrame`/`setTimeout(0)`) so other libraries' synchronous click handlers complete first. Avoid `defer` on `<a href>` / `type="submit"` because the deferred procedure cannot `preventDefault()` the default action.
114
+ - `data-{event}-run` (e.g. `data-click-run`, `data-change-run`) — run arbitrary JavaScript on the event without a fetch. The value is executed as real JS via `new Function` (like `-before-run`/`-after-run`), with `{{...}}` expanded at render time and `event` passed as an argument. Returning `false` calls `event.preventDefault()` (the `onclick="return false"` convention). **Security:** the expanded `{{...}}` is concatenated into executable code, so only interpolate trusted values (numeric indexes, IDs you control) — never untrusted strings (API/user input), which would run as code (XSS). Pass untrusted values via `data-bind` and read them inside the called function instead.
114
115
 
115
116
  Lifecycle events:
116
117
 
package/dist/haori.cjs.js CHANGED
@@ -16,5 +16,5 @@ ${m}
16
16
  `)}catch(E){p.error("Haori",`Invalid after script: ${E}`)}}if(e.hasAttribute(d.attrName(t,"dialog"))&&(r.dialogMessage=e.getAttribute(d.attrName(t,"dialog")).replace(/\\n/g,`
17
17
  `)),e.hasAttribute(d.attrName(t,"toast"))){r.toastMessage=e.getAttribute(d.attrName(t,"toast"));const m=e.getRawAttribute(d.attrName(t,"toast-level")),F=["info","warning","error","success"].includes(m);r.toastLevel=F?m:null}if(e.hasAttribute(d.attrName(t,"redirect"))&&(r.redirectUrl=e.getAttribute(d.attrName(t,"redirect"))),e.hasAttribute(d.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(d.attrName(t,"scroll"))&&(r.scrollTarget=e.getAttribute(d.attrName(t,"scroll"))),e.hasAttribute(d.attrName(t,"history"))&&(r.historyUrl=e.getAttribute(d.attrName(t,"history"))),e.hasAttribute(d.attrName(t,"history-data"))&&(r.historyDataAttrName=d.attrName(t,"history-data")),e.hasAttribute(d.attrName(t,"history-form"))){const m=e.getRawAttribute(d.attrName(t,"history-form"));if(m){const E=document.body.querySelector(m);E!==null?r.historyFormFragment=A.getFormFragment(w.get(E)):p.error("Haori",`Form element not found: ${m} (${d.attrName(t,"history-form")})`)}else r.historyFormFragment=A.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(m=>{const E=d.attrName(t,m);if(!e.hasAttribute(E))return;const F=e.getRawAttribute(E),N=[];if(F?(document.body.querySelectorAll(F).forEach(B=>{const K=w.get(B);K&&N.push(K)}),N.length===0&&p.error("Haori",`Element not found: ${F} (${E})`)):N.push(e),N.length>0)switch(m){case"reset-before":r.resetBeforeFragments=N;break;case"reset":r.resetFragments=N;break;case"refetch":r.refetchFragments=N;break;case"click":r.clickFragments=N;break;case"copy":r.copyFragments=N;break;case"open":r.openFragments=N;break;case"close":r.closeFragments=N;break}});const y=d.attrName(t,"copy-source");if(e.hasAttribute(y)){const m=e.getRawAttribute(y);if(m){const E=document.body.querySelector(m);if(E!==null){const F=w.get(E);F?r.copySourceFragment=F:p.error("Haori",`Element is not managed by Haori: ${m} (${y})`)}else p.error("Haori",`Element not found: ${m} (${y})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(d.attrName(null,"data",!0))&&(r.dataAttrName=d.attrName(null,"data",!0)),e.hasAttribute(d.attrName(null,"form",!0)))){const b=e.getRawAttribute(d.attrName(null,"form",!0));if(b){const y=document.body.querySelector(b);y!==null?r.formFragment=A.getFormFragment(w.get(y)):p.error("Haori",`Form element not found: ${b} (${d.attrName(null,"fetch-form",!0)})`)}else r.formFragment=A.getFormFragment(e)}return s&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e]),r}static isElementFragment(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.getTarget=="function"&&typeof t.getChildElementFragments=="function"}constructor(e,t=null,r=null){d.isElementFragment(e)?(this.options=d.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static resolveAutoFetchSignature(e){return new d(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}runWithResult(){return this.execute()}async execute(){const e=this.acquireExecutionLock();if(e===!1)return!1;try{if(Object.keys(this.options).length===0||this.options.formFragment&&this.validate(this.options.formFragment)===!1)return!1;if(this.options.runScript){const h=this.options.targetFragment?.getTarget()??null;try{this.options.runScript.call(h,this.domEvent)===!1&&this.domEvent&&this.domEvent.preventDefault()}catch(f){p.error("Haori",`Run script execution error: ${f}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(h=>A.reset(h))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let s=r.url,n=r.options;if(this.options.beforeCallback){const h=this.options.beforeCallback(s||null,n||null);if(h!=null){if(h===!1||typeof h=="object"&&h.stop)return!1;typeof h=="object"&&(s="fetchUrl"in h?h.fetchUrl:s,n="fetchOptions"in h?h.fetchOptions:n)}}const a=Object.keys(i).length>0;if(s){const h={...n||{}},f=r.requestedMethod,g=r.effectiveMethod,v=r.transportMode==="query-get",S=r.queryString;if(v&&p.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:f,effectiveMethod:g,transportMode:"query-get",url:s,payload:a?i:void 0,queryString:S}),this.options.targetFragment&&s){const b=performance.now(),y={runtime:l.runtime,requestedMethod:f,effectiveMethod:g,transportMode:v?"query-get":"http",...v?{queryString:S}:{}};return R.fetchStart(this.options.targetFragment.getTarget(),s,h,a?i:void 0,y),fetch(s,h).then(m=>this.handleFetchResult(m,s||void 0,b)).catch(m=>{throw s&&R.fetchError(this.options.targetFragment.getTarget(),s,m),m})}return fetch(s,h).then(b=>this.handleFetchResult(b,s||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const h=this.options.formFragment,f=h.getTarget(),g=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&g.add(this.options.targetFragment),f.setAttribute(`${l.prefix}bind`,JSON.stringify(i));const v=h.getBindingData();Object.assign(v,i),await P.setBindingData(f,v,g)}const o=a?i:{},c=new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(c)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const t=this.options.targetFragment.getTarget();if(d.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(re))return!1;const r=t.hasAttribute(`${l.prefix}click-no-disabled`);return d.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(re,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(d.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(re),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=ie();if(!e.ok)return this.options.targetFragment&&t&&R.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r),await this.handleFetchError(e),!1;if(this.options.targetFragment&&t&&r&&R.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const a=this.options.afterCallback(e);if(a!=null){if(a===!1||typeof a=="object"&&a.stop)return!1;typeof a=="object"&&"response"in a&&(e="response"in a?a.response:e)}}const s=[];s.push(this.bindResult(e)),s.push(this.adjust()),s.push(this.addRow()),s.push(this.removeRow()),s.push(this.movePrevRow()),s.push(this.moveNextRow()),await Promise.all(s),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(a=>A.reset(a))),await this.copy();const n=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{n.push(new d(a,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const a of this.options.clickFragments){await P.evaluateAll(a);const o=a.getTarget();typeof o.click=="function"?o.click():o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}return this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?n.push(i.openDialog(o)):p.error("Haori","Element is not an HTML element: ",o)}),this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?n.push(i.closeDialog(o)):p.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(n),this.options.dialogMessage&&await i.dialog(this.options.dialogMessage),this.options.toastMessage&&await i.toast(this.options.toastMessage,this.options.toastLevel??"info"),this.pushHistory(),this.options.scrollTarget&&document.querySelector(this.options.scrollTarget)?.scrollIntoView({behavior:"smooth",block:"nearest"}),this.options.redirectUrl&&(window.location.href=this.options.redirectUrl),!0}pushHistory(){const e=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,t=this.resolveHistoryDataValues(),r=this.resolveHistoryFormValues(),i=t!=null,s=r!=null;if(!(!e&&!i&&!s))try{const n=e?this.options.historyUrl:window.location.pathname,a=new URL(n,window.location.href);if(a.origin!==window.location.origin){const c="history.pushState: cross-origin URL is not allowed: "+a.toString();p.error("Haori",c);return}const o=c=>{for(const[h,f]of Object.entries(c))f!=null&&(Array.isArray(f)?f.forEach(g=>a.searchParams.append(h,String(g))):typeof f=="object"?a.searchParams.set(h,JSON.stringify(f)):a.searchParams.set(h,String(f)))};i&&o(t),s&&o(r),history.pushState({[ge]:!0},"",a.toString())}catch(n){p.error("Haori",`history.pushState failed: ${n}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=A.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=async n=>{const a=t?t.getTarget():document.body;await ie().addErrorMessage(a,n)},i=()=>{if(!this.options.scrollOnError)return;const n=t?t.getTarget():document.body;(n.getAttribute("data-message-level")==="error"?n:n.parentElement?.getAttribute("data-message-level")==="error"?n.parentElement:n.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const n=await e.json(),a=[];if(n&&typeof n=="object"){if(typeof n.message=="string"&&a.push({message:n.message}),Array.isArray(n.messages))for(const o of n.messages)typeof o=="string"&&a.push({message:o});if(n.errors&&typeof n.errors=="object")for(const[o,c]of Object.entries(n.errors))Array.isArray(c)?a.push({key:o,message:c.join(`
18
18
  `)}):typeof c=="string"?a.push({key:o,message:c}):c!=null&&a.push({key:o,message:String(c)});if(a.length===0)for(const[o,c]of Object.entries(n))o==="message"||o==="messages"||o==="errors"||(Array.isArray(c)?a.push({key:o,message:c.join(`
19
- `)}):typeof c=="string"&&a.push({key:o,message:c}))}if(a.length===0)return await r(`${e.status} ${e.statusText}`),i(),!1;for(const o of a)o.key&&t?await A.addErrorMessage(t,o.key,o.message):await r(o.message);return i(),!1}catch{}try{const n=await e.text();n&&n.trim().length>0?await r(n.trim()):await r(`${e.status} ${e.statusText}`)}catch{await r(`${e.status} ${e.statusText}`)}return i(),!1}validate(e){if(this.options.valid!==!0)return!0;const t=this.findFirstInvalid(e);return t===null?!0:(t.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(e){let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):ie().confirm(e)}bindResult(e){return!this.options.bindFragments||this.options.bindFragments.length===0?Promise.resolve():(e.headers.get("Content-Type")?.includes("application/json")?e.json():e.text()).then(r=>{if(this.options.bindParams){const s={};this.options.bindParams.forEach(n=>{r&&typeof r=="object"&&n in r&&(s[n]=r[n])}),r=s}const i=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const n={...s.getRawBindingData()??{}},a=this.options.bindArg;if(r&&typeof r=="object"&&!Array.isArray(r)){const o=n[a],c=o&&typeof o=="object"&&!Array.isArray(o)?o:{};n[a]=this.mergeAppendBindingData(s,r,c)}else n[a]=r;i.push(P.setBindingData(s.getTarget(),n))});else{if(typeof r=="string")return p.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."));this.options.bindFragments.forEach(s=>{const n=this.mergeAppendBindingData(s,r),a=this.options.bindMerge?{...s.getRawBindingData()??{},...n}:n;i.push(P.setBindingData(s.getTarget(),a))})}return Promise.all(i).then(()=>{const s=this.options.bindArg??null;this.options.bindFragments.forEach(n=>{R.bindComplete(n.getTarget(),s)})})})}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},s=r;for(const n of this.options.bindAppendParams){const a=i[n],o=s[n];Array.isArray(o)&&Array.isArray(a)&&(i[n]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=this.options.copyFragments.map(i=>{const s={...i.getBindingData(),...t};return P.setBindingData(i.getTarget(),s)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?A.getValues(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?A.getValues(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const e={};let t=!1;if(this.options.formFragment&&Object.assign(e,A.getValues(this.options.formFragment)),this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const r=d.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||r.hasUnresolvedReference,r.value&&Object.assign(e,r.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}}prepareFetchRequest(){const e=this.buildPayloadResolution(),t=e.payload,r=!!this.options.fetchHasUnresolvedReference||e.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const s={...this.options.fetchOptions||{}},n=new Headers(s.headers||void 0),a=(s.method||"GET").toUpperCase(),o=l.runtime==="demo"&&!be(a),c=o?"GET":a;if(s.method=c,c==="GET"||c==="HEAD"||c==="OPTIONS")Object.keys(t).length>0&&(i=ye(i,t));else if(Object.keys(t).length>0){const f=n.get("Content-Type")||"";if(/multipart\/form-data/i.test(f)){n.delete("Content-Type");const g=new FormData;for(const[v,S]of Object.entries(t))S==null?g.append(v,""):S instanceof Blob?g.append(v,S):Array.isArray(S)?S.forEach(b=>g.append(v,String(b))):typeof S=="object"?g.append(v,JSON.stringify(S)):g.append(v,String(S));s.body=g}else if(/application\/x-www-form-urlencoded/i.test(f)){const g=new URLSearchParams;for(const[v,S]of Object.entries(t))S!==void 0&&(S===null?g.append(v,""):Array.isArray(S)?S.forEach(b=>g.append(v,String(b))):typeof S=="object"?g.append(v,JSON.stringify(S)):g.append(v,String(S)));s.body=g}else n.set("Content-Type","application/json"),s.body=JSON.stringify(t)}s.headers=n;let h;return o&&(h=new URL(i,window.location.href).search||void 0,n.delete("Content-Type")),{url:i,options:s,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:c,queryString:h,transportMode:o?"query-get":"http",signature:Ae(i,s)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=d.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?A.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?d.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return A.getValues(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(n=>{const a=n.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(n=>{n in e&&(r.has(n)||(i[n]=e[n]))}),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 s=Number(i);isNaN(s)&&(s=0),s+=e,t.push(r.setValue(String(s)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return p.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return e||(p.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=[],r=e.clone();return t.push(e.getParent().insertAfter(r,e)),t.push(P.evaluateAll(r)),t.push(A.reset(r)),Promise.all(t).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getParent();return t&&t.getChildElementFragments().filter(i=>!i.hasAttribute(`${l.prefix}each-before`)&&!i.hasAttribute(`${l.prefix}each-after`)).length<=1?Promise.resolve():e.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getPrevious();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertBefore(e,t):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getNext();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertAfter(e,t):Promise.resolve()}};d.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,d.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,d.RUNNING_CLICK_TARGETS=new WeakSet;let q=d;class Se{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,s)=>{e[s]=i}),e}}class Te{static async load(e,t){let r;try{r=await fetch(e,t)}catch(s){throw p.error("[Haori]","Failed to fetch import source:",e,s),new Error(`Failed to fetch: ${e}`)}if(!r.ok){const s=`${r.status} ${r.statusText}`;throw p.error("[Haori]","Import HTTP error:",e,s),new Error(`Failed to load ${e}: ${s}`)}let i;try{i=await r.text()}catch(s){throw p.error("[Haori]","Failed to read response text:",e,s),new Error(`Failed to read response from: ${e}`)}try{const n=new DOMParser().parseFromString(i,"text/html");return n&&n.body?n.body.innerHTML:(p.warn("[Haori]","No body found in imported document:",e),i)}catch(s){return p.error("[Haori]","Failed to parse imported HTML:",e,s),i}}}const u=class u{static isDeferredAttributeName(e){return u.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return u.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!u.isEvaluateAllExcludedAttributeName(e)&&u.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${l.prefix}${u.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=w.get(e);return r instanceof C?r.hasAttribute(`${l.prefix}${u.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);u.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>u.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof C?t.push(u.evaluateAll(r)):r instanceof L&&t.push(u.evaluateText(r))}),Promise.all(t).then(()=>{})}static getReactiveFetchState(e){const t=u.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return u.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=u.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return u.REACTIVE_IMPORT_STATES.set(e,r),r}static reevaluateReactiveSpecialAttributes(e,t=new Set){if(t.has(e))return Promise.resolve();const r=[];return e.hasAttribute(`${l.prefix}fetch`)&&r.push(u.executeManagedFetch(e)),e.hasAttribute(`${l.prefix}import`)&&r.push(u.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof C&&r.push(u.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=u.getReactiveFetchState(t),i=q.resolveAutoFetchSignature(e);return r.running?((i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve()):i.hasUnresolvedReference||i.signature===null?(r.lastSignature=null,Promise.resolve()):r.lastSignature===i.signature?Promise.resolve():(r.lastSignature=i.signature,r.running=!0,new q(e,null).runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,u.executeManagedFetch(e)}))}static executeManagedImport(e){const t=e.getTarget(),r=u.getReactiveImportState(t),i=e.getAttributeEvaluation(`${l.prefix}import`),s=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return s!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(s===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===s)return Promise.resolve();r.lastUrl=s,r.running=!0;const n=performance.now();return t.setAttribute(`${l.prefix}importing`,""),R.importStart(t,s),Te.load(s).then(a=>{const o=new TextEncoder().encode(a).length;return M.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${l.prefix}importing`),R.importEnd(t,s,o,n),!document.body.hasAttribute("data-haori-ready")){const c=[];return t.childNodes.forEach(h=>{const f=w.get(h);f instanceof C?c.push(u.scan(f.getTarget())):f instanceof L&&c.push(u.evaluateText(f))}),Promise.all(c).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${l.prefix}importing`),R.importError(t,s,a),p.error("[Haori]","Failed to import HTML:",s,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,u.executeManagedImport(e)})}static scan(e){const t=w.get(e);return t?u.initializeElementFragment(t,!1):Promise.resolve()}static initializeFreshEachRow(e){return u.initializeElementFragment(e,!0).then(()=>{u.needsScheduledEvaluateAll(e)&&u.scheduleEvaluateAll(e)})}static initializeElementFragment(e,t){return u.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():u.initializeElementAttributes(e).then(()=>{if(u.shouldSkipChildInitialization(e,t)){u.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof C?r.push(u.initializeElementFragment(i,t)):i instanceof L&&r.push(u.evaluateText(i))}),Promise.all(r).then(()=>{u.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 u.PRIORITY_ATTRIBUTE_SUFFIXES){const s=l.prefix+i;e.hasAttribute(s)&&(t=t.then(()=>u.setAttribute(e.getTarget(),s,e.getRawAttribute(s))),r.add(s))}for(const i of e.getAttributeNames()){if(r.has(i)||u.isDeferredAttributeName(i))continue;const s=e.getRawAttribute(i);s!==null&&(t=t.then(()=>u.setAttribute(e.getTarget(),i,s)))}for(const i of u.DEFERRED_ATTRIBUTE_SUFFIXES){const s=l.prefix+i;e.hasAttribute(s)&&(t=t.then(()=>u.setAttribute(e.getTarget(),s,e.getRawAttribute(s))),r.add(s))}return t.then(()=>{})}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${l.prefix}if`);return e.hasAttribute(`${l.prefix}if`)&&u.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${l.prefix}each`)}static setAttribute(e,t,r,i=!1){const s=w.get(e),n=u.getAliasedAttributeName(t);if(n!==null)return r===null?s.removeAliasedAttribute(t,n):s.setAliasedAttribute(t,n,r,i);const a=[];let o=null,c=null;switch(t){case`${l.prefix}bind`:{r===null?(s.clearBindingDataCache(),s.setBindingData({})):s.setBindingData(u.parseDataBind(r));break}case`${l.prefix}derive`:c=u.createDeriveInputSignature(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),o=u.evaluateDerive(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${l.prefix}derive-name`:c=u.createDeriveInputSignature(s,s.getRawAttribute(`${l.prefix}derive`),r),o=u.evaluateDerive(s,s.getRawAttribute(`${l.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${l.prefix}if`:a.push(u.evaluateIf(s));break;case`${l.prefix}each`:a.push(u.evaluateEach(s));break;case`${l.prefix}fetch`:a.push(u.executeManagedFetch(s));break;case`${l.prefix}import`:typeof r=="string"&&a.push(u.executeManagedImport(s));break;case`${l.prefix}url-param`:{const h=s.getAttribute(`${l.prefix}url-arg`),f=Se.readParams();if(h===null)a.push(u.setBindingData(e,f));else{const g=s.getRawBindingData()||{};g[String(h)]=f,a.push(u.setBindingData(e,g))}break}}return r===null?a.push(s.removeAttribute(t)):a.push(s.setAttribute(t,r,i)),Promise.all(a).then(()=>{if(o!==null)return s.setDeriveInputSignature(c),o.then(h=>{if(h)return u.reevaluateChildren(s)})}).then(()=>{})}static setBindingData(e,t,r=new Set){const i=w.get(e),s=i.getRawBindingData();i.setBindingData(t);let n=i.setAttribute(`${l.prefix}bind`,JSON.stringify(t));if(e.tagName==="FORM"){const a=i.getAttribute(`${l.prefix}form-arg`),o=a&&t[String(a)]&&typeof t[String(a)]=="object"&&!Array.isArray(t[String(a)])?t[String(a)]:a?{}:t;n=n.then(()=>A.syncValues(i,o))}return n=n.then(()=>u.evaluateAll(i,r)),n=n.then(()=>u.reevaluateReactiveSpecialAttributes(i,r)),R.bindChange(e,s,t,"manual"),n.then(()=>{})}static dumpScope(e){const t=w.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},s=c=>{const h=c.getTarget();return h.id?`#${h.id}`:h.tagName.toLowerCase()},n=(c,h,f,g)=>{if(c)for(const v of Object.keys(c))v in i||(i[v]={value:c[v],source:s(h),kind:f,depth:g})};let a=t,o=0;for(;a;)a!==t&&n(a.getRawDerivedBindingData(),a,"derive",o),n(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return $.isEnabled()&&p.info("[Haori]","scope dump for",e,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return p.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,s]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(s):r[i]=[r[i],s]:r[i]=s;return r}}static addNode(e,t){const r=w.get(e);if(r.isSkipMutationNodes())return;const i=w.get(t.nextSibling),s=w.get(t);s&&(r.insertBefore(s,i),s instanceof C?u.scan(s.getTarget()):s instanceof L&&u.evaluateText(s))}static removeNode(e){const t=w.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=w.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=w.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const s=u.getFormFragment(r);if(s){const n=A.getValues(s),a=s.getAttribute(`${l.prefix}form-arg`);let o;a?(o=s.getRawBindingData(),o||(o={}),o[String(a)]=n):o=n,i.push(u.setBindingData(s.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?u.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=u.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${l.prefix}derive`),s=e.hasAttribute(`${l.prefix}if`),n=e.hasAttribute(`${l.prefix}each`),a=e.getRawAttribute(`${l.prefix}derive`),o=e.getRawAttribute(`${l.prefix}derive-name`);let c=!1,h=!1,f=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const g=u.createDeriveInputSignature(e,a,o);g===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>u.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==g&&(r=r.then(()=>u.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(g)})))}return s&&(r=r.then(()=>u.evaluateIf(e))),n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>u.evaluateEach(e))):s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!u.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),u.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}f=u.createDescendantBindingSignature(e,"evaluateAll"),h=!0,c=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===f,u.logDerivedSubtreeProfileSnapshot(e,c?"skip-hit":"skip-miss")})),r.then(()=>{if(c)return;const g=[];return e.getChildren().forEach(v=>{if(v instanceof C){if(u.canSkipUnchangedNestedEach(v))return;g.push(u.evaluateAll(v,t))}else v instanceof L&&g.push(u.evaluateText(v))}),Promise.all(g).then(()=>{})}).then(()=>{h&&f!==null&&e.setDeriveSubtreeSignature(f)}))}static evaluateDerive(e,t=e.getRawAttribute(`${l.prefix}derive`),r=e.getRawAttribute(`${l.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),s=typeof r=="string"?r.trim():"";if(!t||s==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const n=J.evaluateDetailed(t,e.getBindingData());if(n.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[s]:n.value};return u.createBindingSignature(i)===u.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;const{sources:r}=u.dumpScope(e.getTarget()),i=new Set,s=t.match(/[A-Za-z_$][\w$]*/g)??[];let n=0;s.forEach(o=>{const c=t.indexOf(o,n);n=c+o.length,!(c>0&&t[c-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),p.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${l.prefix}if`);if(u.isHiddenIfCondition(r))$.isEnabled()&&u.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{R.hide(e.getTarget())}));else{const i=e.isVisible(),s=[];e.getChildren().forEach(n=>{n instanceof C?s.push(n.isMounted()?u.evaluateAll(n):u.scan(n.getTarget())):n instanceof L&&s.push(u.evaluateText(n))}),t.push(e.show().then(()=>{R.show(e.getTarget()),i||u.triggerLoadOnShow(e)})),t.push(Promise.all(s).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${l.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new q(e,"load").run().catch(i=>{p.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=u.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},u.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(!e.isVisible()||!e.isMounted())return Promise.resolve();const t=u.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):u.runEachUpdateLoop(e,t)}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${l.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await u.performEachUpdate(e);while(t.rerunRequested);e.getTarget().setAttribute(`${l.prefix}each-done`,"")}finally{t.running=!1,t.settled=null}})();return t.settled=r,r}static performEachUpdate(e){const t=u.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`),s=u.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let n=!1;if(e.getChildren().forEach(a=>{if(!n&&a instanceof C){if(a.hasAttribute(`${l.prefix}each-before`)||a.hasAttribute(`${l.prefix}each-after`))return;r=a.clone(),u.markFreshInitializationSkippable(r),e.setTemplate(r),n=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!n){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(!n){const f=w.get(c);f instanceof C&&(r=f.clone(),u.markFreshInitializationSkippable(r),e.setTemplate(r),n=!0)}const h=w.get(c);h instanceof C&&e.getChildren().includes(h)&&(e.removeChild(h),h.setMounted(!1)),c.parentNode&&c.parentNode.removeChild(c)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(s)})}return e.getEachInputSignature()===s?Promise.resolve():this.updateDiff(e,t).then(()=>{e.setEachInputSignature(s)})}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:(p.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`)||u.hasNonEachDynamicElementState(e))return!1;const r=u.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${l.prefix}each-key`),s=u.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===s}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:!u.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof C?t.hasAttribute(`${l.prefix}derive`)||t.hasAttribute(`${l.prefix}derive-name`)||t.hasAttribute(`${l.prefix}fetch`)||t.hasAttribute(`${l.prefix}import`)?!0:u.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return u.recordDerivedSubtreeSignatureComputation(e,t),u.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:u.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!u.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),u.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(u.createDescendantBindingSignature(e,"refresh")),u.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!$.isEnabled()||!e.hasAttribute(`${l.prefix}derive`))return null;const t=u.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:u.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return u.DERIVE_SUBTREE_PROFILES.set(e,r),r}static createDerivedSubtreeHostId(e){const t=[];let r=e;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let s=i.tagName.toLowerCase();if(i.id.trim()!==""){s+=`#${i.id.trim()}`,t.unshift(s);break}const n=r.getRawAttribute(`${l.prefix}derive-name`);typeof n=="string"&&n.trim()!==""&&(s+=`[${l.prefix}derive-name="${n.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(c=>c instanceof C).findIndex(c=>c===r);s+=`:nth-child(${o+1})`}t.unshift(s),r=a}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=u.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=u.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),p.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 s=e.getRawAttribute(i);return typeof s=="string"&&s.includes("{{")})?!0:e.getChildren().some(i=>i instanceof L&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(s=>u.isFreshInitializationDynamicAttribute(e,s)),r=e.getChildren().some(s=>s instanceof C?!u.markFreshInitializationSkippable(s):s instanceof L?s.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 p.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=e.getAttribute(`${l.prefix}each-index`);i&&(i=String(i));const s=e.getAttribute(`${l.prefix}each-key`),n=e.getAttribute(`${l.prefix}each-arg`),a=new Map,o=[];t.forEach((E,F)=>{const N=u.createListKey(E,s?String(s):null,F);o.push(N),a.set(N,{item:E,itemIndex:F})});const c=new Set(o),h=[];let f=e.getChildren().filter(E=>E instanceof C).filter(E=>!E.hasAttribute(`${l.prefix}each-before`)&&!E.hasAttribute(`${l.prefix}each-after`));const g=f.map(E=>E.getListKey());f=f.filter(E=>c.has(String(E.getListKey()))?!0:(h.push(E.remove()),!1));const v=f.map(E=>E.getListKey()),S=new Map;f.forEach(E=>{const F=E.getListKey();F!==null&&!S.has(F)&&S.set(F,E)});const b=e.getChildElementFragments().slice(),y=b.filter(E=>E.hasAttribute(`${l.prefix}each-before`)).length;let m=Promise.resolve();return o.forEach((E,F)=>{const{item:N,itemIndex:U}=a.get(E);let B;const K=S.get(E);if(K)B=K,m=m.then(()=>u.updateRowFragment(B,N,i,U,n?String(n):null,E).then(k=>{if(k)return u.evaluateAll(B)}));else{B=r.clone();const k=y+F;m=m.then(()=>u.updateRowFragment(B,N,i,U,n?String(n):null,E).then(()=>{const he=b[k]??null;return e.insertBefore(B,he).then(()=>{b.splice(k,0,B)}).then(()=>u.initializeFreshEachRow(B))}))}}),Promise.all(h).then(()=>m).then(()=>{const E=o.filter(k=>k!==null),F=v.filter(k=>k!==null),N=new Set(F),U=E.filter(k=>!N.has(k)),K=g.filter(k=>k!==null).filter(k=>!c.has(k));R.eachUpdate(e.getTarget(),U,K,E)})}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const s=e[t];s==null?i=`__index_${r}`:typeof s=="object"?i=JSON.stringify(s):i=String(s)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,s,n){let a=t;if(typeof t=="object"&&t!==null)a={...t},r&&(a[r]=i),s&&(a={[s]:a});else if(s)a={[s]:t},r&&(a[r]=i);else return p.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);const o=a,c=u.createBindingSignature({listKey:n,bindingData:o});return e.getListKey()===n&&e.getRenderSignature()===c?Promise.resolve(!1):(e.setListKey(n),e.setRenderSignature(c),e.setBindingData(o),e.setAttribute(`${l.prefix}row`,n).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()&&u.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(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(s=>u.createBindingSignature(s,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 s=e;return`{${Object.keys(s).sort().map(n=>`${JSON.stringify(n)}:${u.createBindingSignature(s[n],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{u.evaluateAll(e)},100)}};u.ATTRIBUTE_ALIAS_SUFFIX="attr-",u.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],u.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],u.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],u.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,u.REACTIVE_FETCH_STATES=new WeakMap,u.REACTIVE_IMPORT_STATES=new WeakMap,u.DERIVE_SUBTREE_PROFILES=new WeakMap,u.EACH_UPDATE_STATES=new WeakMap;let P=u;const te=class te{constructor(e=document){this.onClick=t=>this.delegate(t,"click"),this.onChange=t=>this.delegate(t,"change"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{const t=document.documentElement,r=w.get(t);r&&new q(r,"load").run()},this.onPopstate=t=>{const r=t.state;!r||r[te.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}start(){this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),this.root.addEventListener("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("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad),window.removeEventListener("popstate",this.onPopstate)}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(!r)return;const i=w.get(r);if(!i)return;t==="change"&&i instanceof C&&i.syncValue();const s=()=>{new q(i,t,e).run().catch(n=>{p.error("[Haori]","Procedure execution error:",n)})};if(t==="click"&&r.hasAttribute("data-click-defer")){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>s()):setTimeout(s,0);return}s()}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){let t=e;for(;t;){if(t.getAttributeNames().some(r=>r.startsWith("data-click-")))return t;t=t.parentElement}return null}};te.HISTORY_STATE_KEY="__haoriHistoryState__";let ne=te;const D=class D{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(D.isHtmlElement(e)&&D.syncElement(e),e.querySelectorAll("*").forEach(t=>{D.syncElement(t)}))}static syncElement(e){const t=D.registrations.get(e),r=w.get(e);if(!r||!D.shouldObserve(r)){t&&(t.observer.disconnect(),D.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=D.resolveRoot(r),s=D.resolveRootMargin(r),n=D.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===s&&D.sameThreshold(t.observer.thresholds,n)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),D.registrations.delete(e));const o=new IntersectionObserver(c=>{const h=D.registrations.get(e);h&&c.forEach(f=>{!f.isIntersecting||h.running||D.isDisabled(h.fragment)||(h.running=!0,new q(h.fragment,"intersect").runWithResult().then(g=>{g&&h.once&&(h.observer.disconnect(),D.registrations.delete(e))}).catch(g=>{p.error("[Haori]","Intersect procedure execution error:",g)}).finally(()=>{const g=D.registrations.get(e);g&&(g.running=!1)}))})},{root:i,rootMargin:s,threshold:n});o.observe(e),D.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(D.isHtmlElement(e)){const t=D.registrations.get(e);t&&(t.observer.disconnect(),D.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=D.registrations.get(t);r&&(r.observer.disconnect(),D.registrations.delete(t))})}static disconnectAll(){D.registrations.forEach(e=>{e.observer.disconnect()}),D.registrations.clear()}static shouldObserve(e){return e.getAttributeNames().some(t=>{if(!t.startsWith(`${l.prefix}intersect-`))return!1;const r=t.slice(`${l.prefix}intersect-`.length);return!D.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=document.querySelector(r);return D.isHtmlElement(i)?i:(p.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"}static sameThreshold(e,t){return e.length===1&&e[0]===t}};D.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),D.registrations=new Map;let Y=D;const O=class O{static disconnectMutationObservers(){O._mutationObservers.forEach(e=>{e.disconnect()}),O._mutationObservers.length=0}static async init(){if(O._initialized)return;O._initialized=!0,O.disconnectMutationObservers();const e=await Promise.allSettled([P.scan(document.head),P.scan(document.body)]),[t,r]=e;t.status!=="fulfilled"&&p.error("[Haori]","Failed to build head fragment:",t.reason),r.status!=="fulfilled"&&p.error("[Haori]","Failed to build body fragment:",r.reason),await M.wait(),document.body.setAttribute("data-haori-ready",""),O.observe(document.head),O.observe(document.body),new ne().start(),Y.syncTree(document.body)}static observe(e){const t=new MutationObserver(async r=>{for(const i of r)try{switch(i.type){case"attributes":{const s=i.target;if(i.attributeName&&s.hasAttribute("data-haori-click-lock")&&(i.attributeName==="disabled"||i.attributeName==="data-haori-click-lock")||i.attributeName&&P.isAliasedAttributeReflection(s,i.attributeName))break;P.setAttribute(s,i.attributeName,s.getAttribute(i.attributeName),!0),Y.syncElement(s);break}case"childList":{Array.from(i.removedNodes).forEach(s=>{Y.cleanupTree(s),P.removeNode(s)}),Array.from(i.addedNodes).forEach(s=>{s.parentElement instanceof Element&&(P.addNode(s.parentElement,s),Y.syncTree(s))});break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?P.changeText(i.target,i.target.textContent):p.warn("[Haori]","Unsupported character data type:",i.target);break}default:p.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(s){p.error("[Haori]","Error processing mutation:",s)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),O._mutationObservers.push(t)}};O._initialized=!1,O._mutationObservers=[];let Z=O;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Z.init):Z.init();const we=()=>W.waitForRenders(),De="0.11.0";exports.Core=P;exports.Env=l;exports.Form=A;exports.Fragment=w;exports.Haori=W;exports.Log=p;exports.Queue=M;exports.default=W;exports.version=De;exports.waitForRenders=we;
19
+ `)}):typeof c=="string"&&a.push({key:o,message:c}))}if(a.length===0)return await r(`${e.status} ${e.statusText}`),i(),!1;for(const o of a)o.key&&t?await A.addErrorMessage(t,o.key,o.message):await r(o.message);return i(),!1}catch{}try{const n=await e.text();n&&n.trim().length>0?await r(n.trim()):await r(`${e.status} ${e.statusText}`)}catch{await r(`${e.status} ${e.statusText}`)}return i(),!1}validate(e){if(this.options.valid!==!0)return!0;const t=this.findFirstInvalid(e);return t===null?!0:(t.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(e){let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):ie().confirm(e)}bindResult(e){return!this.options.bindFragments||this.options.bindFragments.length===0?Promise.resolve():(e.headers.get("Content-Type")?.includes("application/json")?e.json():e.text()).then(r=>{if(this.options.bindParams){const s={};this.options.bindParams.forEach(n=>{r&&typeof r=="object"&&n in r&&(s[n]=r[n])}),r=s}const i=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const n={...s.getRawBindingData()??{}},a=this.options.bindArg;if(r&&typeof r=="object"&&!Array.isArray(r)){const o=n[a],c=o&&typeof o=="object"&&!Array.isArray(o)?o:{};n[a]=this.mergeAppendBindingData(s,r,c)}else n[a]=r;i.push(P.setBindingData(s.getTarget(),n))});else{if(typeof r=="string")return p.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."));this.options.bindFragments.forEach(s=>{const n=this.mergeAppendBindingData(s,r),a=this.options.bindMerge?{...s.getRawBindingData()??{},...n}:n;i.push(P.setBindingData(s.getTarget(),a))})}return Promise.all(i).then(()=>{const s=this.options.bindArg??null;this.options.bindFragments.forEach(n=>{R.bindComplete(n.getTarget(),s)})})})}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},s=r;for(const n of this.options.bindAppendParams){const a=i[n],o=s[n];Array.isArray(o)&&Array.isArray(a)&&(i[n]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=this.options.copyFragments.map(i=>{const s={...i.getBindingData(),...t};return P.setBindingData(i.getTarget(),s)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?A.getValues(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?A.getValues(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const e={};let t=!1;if(this.options.formFragment&&Object.assign(e,A.getValues(this.options.formFragment)),this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const r=d.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||r.hasUnresolvedReference,r.value&&Object.assign(e,r.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}}prepareFetchRequest(){const e=this.buildPayloadResolution(),t=e.payload,r=!!this.options.fetchHasUnresolvedReference||e.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const s={...this.options.fetchOptions||{}},n=new Headers(s.headers||void 0),a=(s.method||"GET").toUpperCase(),o=l.runtime==="demo"&&!be(a),c=o?"GET":a;if(s.method=c,c==="GET"||c==="HEAD"||c==="OPTIONS")Object.keys(t).length>0&&(i=ye(i,t));else if(Object.keys(t).length>0){const f=n.get("Content-Type")||"";if(/multipart\/form-data/i.test(f)){n.delete("Content-Type");const g=new FormData;for(const[v,S]of Object.entries(t))S==null?g.append(v,""):S instanceof Blob?g.append(v,S):Array.isArray(S)?S.forEach(b=>g.append(v,String(b))):typeof S=="object"?g.append(v,JSON.stringify(S)):g.append(v,String(S));s.body=g}else if(/application\/x-www-form-urlencoded/i.test(f)){const g=new URLSearchParams;for(const[v,S]of Object.entries(t))S!==void 0&&(S===null?g.append(v,""):Array.isArray(S)?S.forEach(b=>g.append(v,String(b))):typeof S=="object"?g.append(v,JSON.stringify(S)):g.append(v,String(S)));s.body=g}else n.set("Content-Type","application/json"),s.body=JSON.stringify(t)}s.headers=n;let h;return o&&(h=new URL(i,window.location.href).search||void 0,n.delete("Content-Type")),{url:i,options:s,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:c,queryString:h,transportMode:o?"query-get":"http",signature:Ae(i,s)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=d.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?A.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?d.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return A.getValues(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(n=>{const a=n.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(n=>{n in e&&(r.has(n)||(i[n]=e[n]))}),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 s=Number(i);isNaN(s)&&(s=0),s+=e,t.push(r.setValue(String(s)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return p.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return e||(p.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=[],r=e.clone();return t.push(e.getParent().insertAfter(r,e)),t.push(P.evaluateAll(r)),t.push(A.reset(r)),Promise.all(t).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getParent();return t&&t.getChildElementFragments().filter(i=>!i.hasAttribute(`${l.prefix}each-before`)&&!i.hasAttribute(`${l.prefix}each-after`)).length<=1?Promise.resolve():e.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getPrevious();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertBefore(e,t):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getNext();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertAfter(e,t):Promise.resolve()}};d.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,d.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,d.RUNNING_CLICK_TARGETS=new WeakSet;let q=d;class Se{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,s)=>{e[s]=i}),e}}class Te{static async load(e,t){let r;try{r=await fetch(e,t)}catch(s){throw p.error("[Haori]","Failed to fetch import source:",e,s),new Error(`Failed to fetch: ${e}`)}if(!r.ok){const s=`${r.status} ${r.statusText}`;throw p.error("[Haori]","Import HTTP error:",e,s),new Error(`Failed to load ${e}: ${s}`)}let i;try{i=await r.text()}catch(s){throw p.error("[Haori]","Failed to read response text:",e,s),new Error(`Failed to read response from: ${e}`)}try{const n=new DOMParser().parseFromString(i,"text/html");return n&&n.body?n.body.innerHTML:(p.warn("[Haori]","No body found in imported document:",e),i)}catch(s){return p.error("[Haori]","Failed to parse imported HTML:",e,s),i}}}const u=class u{static isDeferredAttributeName(e){return u.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return u.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!u.isEvaluateAllExcludedAttributeName(e)&&u.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${l.prefix}${u.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=w.get(e);return r instanceof C?r.hasAttribute(`${l.prefix}${u.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);u.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>u.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof C?t.push(u.evaluateAll(r)):r instanceof L&&t.push(u.evaluateText(r))}),Promise.all(t).then(()=>{})}static getReactiveFetchState(e){const t=u.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return u.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=u.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return u.REACTIVE_IMPORT_STATES.set(e,r),r}static reevaluateReactiveSpecialAttributes(e,t=new Set){if(t.has(e))return Promise.resolve();const r=[];return e.hasAttribute(`${l.prefix}fetch`)&&r.push(u.executeManagedFetch(e)),e.hasAttribute(`${l.prefix}import`)&&r.push(u.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof C&&r.push(u.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=u.getReactiveFetchState(t),i=q.resolveAutoFetchSignature(e);return r.running?((i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve()):i.hasUnresolvedReference||i.signature===null?(r.lastSignature=null,Promise.resolve()):r.lastSignature===i.signature?Promise.resolve():(r.lastSignature=i.signature,r.running=!0,new q(e,null).runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,u.executeManagedFetch(e)}))}static executeManagedImport(e){const t=e.getTarget(),r=u.getReactiveImportState(t),i=e.getAttributeEvaluation(`${l.prefix}import`),s=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return s!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(s===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===s)return Promise.resolve();r.lastUrl=s,r.running=!0;const n=performance.now();return t.setAttribute(`${l.prefix}importing`,""),R.importStart(t,s),Te.load(s).then(a=>{const o=new TextEncoder().encode(a).length;return M.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${l.prefix}importing`),R.importEnd(t,s,o,n),!document.body.hasAttribute("data-haori-ready")){const c=[];return t.childNodes.forEach(h=>{const f=w.get(h);f instanceof C?c.push(u.scan(f.getTarget())):f instanceof L&&c.push(u.evaluateText(f))}),Promise.all(c).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${l.prefix}importing`),R.importError(t,s,a),p.error("[Haori]","Failed to import HTML:",s,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,u.executeManagedImport(e)})}static scan(e){const t=w.get(e);return t?u.initializeElementFragment(t,!1):Promise.resolve()}static initializeFreshEachRow(e){return u.initializeElementFragment(e,!0).then(()=>{u.needsScheduledEvaluateAll(e)&&u.scheduleEvaluateAll(e)})}static initializeElementFragment(e,t){return u.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():u.initializeElementAttributes(e).then(()=>{if(u.shouldSkipChildInitialization(e,t)){u.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof C?r.push(u.initializeElementFragment(i,t)):i instanceof L&&r.push(u.evaluateText(i))}),Promise.all(r).then(()=>{u.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 u.PRIORITY_ATTRIBUTE_SUFFIXES){const s=l.prefix+i;e.hasAttribute(s)&&(t=t.then(()=>u.setAttribute(e.getTarget(),s,e.getRawAttribute(s))),r.add(s))}for(const i of e.getAttributeNames()){if(r.has(i)||u.isDeferredAttributeName(i))continue;const s=e.getRawAttribute(i);s!==null&&(t=t.then(()=>u.setAttribute(e.getTarget(),i,s)))}for(const i of u.DEFERRED_ATTRIBUTE_SUFFIXES){const s=l.prefix+i;e.hasAttribute(s)&&(t=t.then(()=>u.setAttribute(e.getTarget(),s,e.getRawAttribute(s))),r.add(s))}return t.then(()=>{})}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${l.prefix}if`);return e.hasAttribute(`${l.prefix}if`)&&u.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${l.prefix}each`)}static setAttribute(e,t,r,i=!1){const s=w.get(e),n=u.getAliasedAttributeName(t);if(n!==null)return r===null?s.removeAliasedAttribute(t,n):s.setAliasedAttribute(t,n,r,i);const a=[];let o=null,c=null;switch(t){case`${l.prefix}bind`:{r===null?(s.clearBindingDataCache(),s.setBindingData({})):s.setBindingData(u.parseDataBind(r));break}case`${l.prefix}derive`:c=u.createDeriveInputSignature(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),o=u.evaluateDerive(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${l.prefix}derive-name`:c=u.createDeriveInputSignature(s,s.getRawAttribute(`${l.prefix}derive`),r),o=u.evaluateDerive(s,s.getRawAttribute(`${l.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${l.prefix}if`:a.push(u.evaluateIf(s));break;case`${l.prefix}each`:a.push(u.evaluateEach(s));break;case`${l.prefix}fetch`:a.push(u.executeManagedFetch(s));break;case`${l.prefix}import`:typeof r=="string"&&a.push(u.executeManagedImport(s));break;case`${l.prefix}url-param`:{const h=s.getAttribute(`${l.prefix}url-arg`),f=Se.readParams();if(h===null)a.push(u.setBindingData(e,f));else{const g=s.getRawBindingData()||{};g[String(h)]=f,a.push(u.setBindingData(e,g))}break}}return r===null?a.push(s.removeAttribute(t)):a.push(s.setAttribute(t,r,i)),Promise.all(a).then(()=>{if(o!==null)return s.setDeriveInputSignature(c),o.then(h=>{if(h)return u.reevaluateChildren(s)})}).then(()=>{})}static setBindingData(e,t,r=new Set){const i=w.get(e),s=i.getRawBindingData();i.setBindingData(t);let n=i.setAttribute(`${l.prefix}bind`,JSON.stringify(t));if(e.tagName==="FORM"){const a=i.getAttribute(`${l.prefix}form-arg`),o=a&&t[String(a)]&&typeof t[String(a)]=="object"&&!Array.isArray(t[String(a)])?t[String(a)]:a?{}:t;n=n.then(()=>A.syncValues(i,o))}return n=n.then(()=>u.evaluateAll(i,r)),n=n.then(()=>u.reevaluateReactiveSpecialAttributes(i,r)),R.bindChange(e,s,t,"manual"),n.then(()=>{})}static dumpScope(e){const t=w.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},s=c=>{const h=c.getTarget();return h.id?`#${h.id}`:h.tagName.toLowerCase()},n=(c,h,f,g)=>{if(c)for(const v of Object.keys(c))v in i||(i[v]={value:c[v],source:s(h),kind:f,depth:g})};let a=t,o=0;for(;a;)a!==t&&n(a.getRawDerivedBindingData(),a,"derive",o),n(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return $.isEnabled()&&p.info("[Haori]","scope dump for",e,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return p.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,s]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(s):r[i]=[r[i],s]:r[i]=s;return r}}static addNode(e,t){const r=w.get(e);if(r.isSkipMutationNodes())return;const i=w.get(t.nextSibling),s=w.get(t);s&&(r.insertBefore(s,i),s instanceof C?u.scan(s.getTarget()):s instanceof L&&u.evaluateText(s))}static removeNode(e){const t=w.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=w.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=w.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const s=u.getFormFragment(r);if(s){const n=A.getValues(s),a=s.getAttribute(`${l.prefix}form-arg`);let o;a?(o=s.getRawBindingData(),o||(o={}),o[String(a)]=n):o=n,i.push(u.setBindingData(s.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?u.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=u.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${l.prefix}derive`),s=e.hasAttribute(`${l.prefix}if`),n=e.hasAttribute(`${l.prefix}each`),a=e.getRawAttribute(`${l.prefix}derive`),o=e.getRawAttribute(`${l.prefix}derive-name`);let c=!1,h=!1,f=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const g=u.createDeriveInputSignature(e,a,o);g===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>u.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==g&&(r=r.then(()=>u.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(g)})))}return s&&(r=r.then(()=>u.evaluateIf(e))),n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>u.evaluateEach(e))):s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!u.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),u.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}f=u.createDescendantBindingSignature(e,"evaluateAll"),h=!0,c=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===f,u.logDerivedSubtreeProfileSnapshot(e,c?"skip-hit":"skip-miss")})),r.then(()=>{if(c)return;const g=[];return e.getChildren().forEach(v=>{if(v instanceof C){if(u.canSkipUnchangedNestedEach(v))return;g.push(u.evaluateAll(v,t))}else v instanceof L&&g.push(u.evaluateText(v))}),Promise.all(g).then(()=>{})}).then(()=>{h&&f!==null&&e.setDeriveSubtreeSignature(f)}))}static evaluateDerive(e,t=e.getRawAttribute(`${l.prefix}derive`),r=e.getRawAttribute(`${l.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),s=typeof r=="string"?r.trim():"";if(!t||s==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const n=J.evaluateDetailed(t,e.getBindingData());if(n.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[s]:n.value};return u.createBindingSignature(i)===u.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;const{sources:r}=u.dumpScope(e.getTarget()),i=new Set,s=t.match(/[A-Za-z_$][\w$]*/g)??[];let n=0;s.forEach(o=>{const c=t.indexOf(o,n);n=c+o.length,!(c>0&&t[c-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),p.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${l.prefix}if`);if(u.isHiddenIfCondition(r))$.isEnabled()&&u.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{R.hide(e.getTarget())}));else{const i=e.isVisible(),s=[];e.getChildren().forEach(n=>{n instanceof C?s.push(n.isMounted()?u.evaluateAll(n):u.scan(n.getTarget())):n instanceof L&&s.push(u.evaluateText(n))}),t.push(e.show().then(()=>{R.show(e.getTarget()),i||u.triggerLoadOnShow(e)})),t.push(Promise.all(s).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${l.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new q(e,"load").run().catch(i=>{p.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=u.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},u.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(!e.isVisible()||!e.isMounted())return Promise.resolve();const t=u.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):u.runEachUpdateLoop(e,t)}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${l.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await u.performEachUpdate(e);while(t.rerunRequested);e.getTarget().setAttribute(`${l.prefix}each-done`,"")}finally{t.running=!1,t.settled=null}})();return t.settled=r,r}static performEachUpdate(e){const t=u.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`),s=u.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let n=!1;if(e.getChildren().forEach(a=>{if(!n&&a instanceof C){if(a.hasAttribute(`${l.prefix}each-before`)||a.hasAttribute(`${l.prefix}each-after`))return;r=a.clone(),u.markFreshInitializationSkippable(r),e.setTemplate(r),n=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!n){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(!n){const f=w.get(c);f instanceof C&&(r=f.clone(),u.markFreshInitializationSkippable(r),e.setTemplate(r),n=!0)}const h=w.get(c);h instanceof C&&e.getChildren().includes(h)&&(e.removeChild(h),h.setMounted(!1)),c.parentNode&&c.parentNode.removeChild(c)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(s)})}return e.getEachInputSignature()===s?Promise.resolve():this.updateDiff(e,t).then(()=>{e.setEachInputSignature(s)})}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:(p.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`)||u.hasNonEachDynamicElementState(e))return!1;const r=u.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${l.prefix}each-key`),s=u.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===s}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:!u.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof C?t.hasAttribute(`${l.prefix}derive`)||t.hasAttribute(`${l.prefix}derive-name`)||t.hasAttribute(`${l.prefix}fetch`)||t.hasAttribute(`${l.prefix}import`)?!0:u.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return u.recordDerivedSubtreeSignatureComputation(e,t),u.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:u.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!u.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),u.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(u.createDescendantBindingSignature(e,"refresh")),u.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!$.isEnabled()||!e.hasAttribute(`${l.prefix}derive`))return null;const t=u.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:u.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return u.DERIVE_SUBTREE_PROFILES.set(e,r),r}static createDerivedSubtreeHostId(e){const t=[];let r=e;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let s=i.tagName.toLowerCase();if(i.id.trim()!==""){s+=`#${i.id.trim()}`,t.unshift(s);break}const n=r.getRawAttribute(`${l.prefix}derive-name`);typeof n=="string"&&n.trim()!==""&&(s+=`[${l.prefix}derive-name="${n.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(c=>c instanceof C).findIndex(c=>c===r);s+=`:nth-child(${o+1})`}t.unshift(s),r=a}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=u.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=u.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),p.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 s=e.getRawAttribute(i);return typeof s=="string"&&s.includes("{{")})?!0:e.getChildren().some(i=>i instanceof L&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(s=>u.isFreshInitializationDynamicAttribute(e,s)),r=e.getChildren().some(s=>s instanceof C?!u.markFreshInitializationSkippable(s):s instanceof L?s.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 p.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=e.getAttribute(`${l.prefix}each-index`);i&&(i=String(i));const s=e.getAttribute(`${l.prefix}each-key`),n=e.getAttribute(`${l.prefix}each-arg`),a=new Map,o=[];t.forEach((E,F)=>{const N=u.createListKey(E,s?String(s):null,F);o.push(N),a.set(N,{item:E,itemIndex:F})});const c=new Set(o),h=[];let f=e.getChildren().filter(E=>E instanceof C).filter(E=>!E.hasAttribute(`${l.prefix}each-before`)&&!E.hasAttribute(`${l.prefix}each-after`));const g=f.map(E=>E.getListKey());f=f.filter(E=>c.has(String(E.getListKey()))?!0:(h.push(E.remove()),!1));const v=f.map(E=>E.getListKey()),S=new Map;f.forEach(E=>{const F=E.getListKey();F!==null&&!S.has(F)&&S.set(F,E)});const b=e.getChildElementFragments().slice(),y=b.filter(E=>E.hasAttribute(`${l.prefix}each-before`)).length;let m=Promise.resolve();return o.forEach((E,F)=>{const{item:N,itemIndex:U}=a.get(E);let B;const K=S.get(E);if(K)B=K,m=m.then(()=>u.updateRowFragment(B,N,i,U,n?String(n):null,E).then(k=>{if(k)return u.evaluateAll(B)}));else{B=r.clone();const k=y+F;m=m.then(()=>u.updateRowFragment(B,N,i,U,n?String(n):null,E).then(()=>{const he=b[k]??null;return e.insertBefore(B,he).then(()=>{b.splice(k,0,B)}).then(()=>u.initializeFreshEachRow(B))}))}}),Promise.all(h).then(()=>m).then(()=>{const E=o.filter(k=>k!==null),F=v.filter(k=>k!==null),N=new Set(F),U=E.filter(k=>!N.has(k)),K=g.filter(k=>k!==null).filter(k=>!c.has(k));R.eachUpdate(e.getTarget(),U,K,E)})}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const s=e[t];s==null?i=`__index_${r}`:typeof s=="object"?i=JSON.stringify(s):i=String(s)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,s,n){let a=t;if(typeof t=="object"&&t!==null)a={...t},r&&(a[r]=i),s&&(a={[s]:a});else if(s)a={[s]:t},r&&(a[r]=i);else return p.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);const o=a,c=u.createBindingSignature({listKey:n,bindingData:o});return e.getListKey()===n&&e.getRenderSignature()===c?Promise.resolve(!1):(e.setListKey(n),e.setRenderSignature(c),e.setBindingData(o),e.setAttribute(`${l.prefix}row`,n).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()&&u.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(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(s=>u.createBindingSignature(s,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 s=e;return`{${Object.keys(s).sort().map(n=>`${JSON.stringify(n)}:${u.createBindingSignature(s[n],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{u.evaluateAll(e)},100)}};u.ATTRIBUTE_ALIAS_SUFFIX="attr-",u.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],u.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],u.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],u.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,u.REACTIVE_FETCH_STATES=new WeakMap,u.REACTIVE_IMPORT_STATES=new WeakMap,u.DERIVE_SUBTREE_PROFILES=new WeakMap,u.EACH_UPDATE_STATES=new WeakMap;let P=u;const te=class te{constructor(e=document){this.onClick=t=>this.delegate(t,"click"),this.onChange=t=>this.delegate(t,"change"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{const t=document.documentElement,r=w.get(t);r&&new q(r,"load").run()},this.onPopstate=t=>{const r=t.state;!r||r[te.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}start(){this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),this.root.addEventListener("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("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad),window.removeEventListener("popstate",this.onPopstate)}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(!r)return;const i=w.get(r);if(!i)return;t==="change"&&i instanceof C&&i.syncValue();const s=()=>{new q(i,t,e).run().catch(n=>{p.error("[Haori]","Procedure execution error:",n)})};if(t==="click"&&r.hasAttribute("data-click-defer")){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>s()):setTimeout(s,0);return}s()}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){let t=e;for(;t;){if(t.getAttributeNames().some(r=>r.startsWith("data-click-")))return t;t=t.parentElement}return null}};te.HISTORY_STATE_KEY="__haoriHistoryState__";let ne=te;const D=class D{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(D.isHtmlElement(e)&&D.syncElement(e),e.querySelectorAll("*").forEach(t=>{D.syncElement(t)}))}static syncElement(e){const t=D.registrations.get(e),r=w.get(e);if(!r||!D.shouldObserve(r)){t&&(t.observer.disconnect(),D.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=D.resolveRoot(r),s=D.resolveRootMargin(r),n=D.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===s&&D.sameThreshold(t.observer.thresholds,n)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),D.registrations.delete(e));const o=new IntersectionObserver(c=>{const h=D.registrations.get(e);h&&c.forEach(f=>{!f.isIntersecting||h.running||D.isDisabled(h.fragment)||(h.running=!0,new q(h.fragment,"intersect").runWithResult().then(g=>{g&&h.once&&(h.observer.disconnect(),D.registrations.delete(e))}).catch(g=>{p.error("[Haori]","Intersect procedure execution error:",g)}).finally(()=>{const g=D.registrations.get(e);g&&(g.running=!1)}))})},{root:i,rootMargin:s,threshold:n});o.observe(e),D.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(D.isHtmlElement(e)){const t=D.registrations.get(e);t&&(t.observer.disconnect(),D.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=D.registrations.get(t);r&&(r.observer.disconnect(),D.registrations.delete(t))})}static disconnectAll(){D.registrations.forEach(e=>{e.observer.disconnect()}),D.registrations.clear()}static shouldObserve(e){return e.getAttributeNames().some(t=>{if(!t.startsWith(`${l.prefix}intersect-`))return!1;const r=t.slice(`${l.prefix}intersect-`.length);return!D.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=document.querySelector(r);return D.isHtmlElement(i)?i:(p.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"}static sameThreshold(e,t){return e.length===1&&e[0]===t}};D.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),D.registrations=new Map;let Y=D;const O=class O{static disconnectMutationObservers(){O._mutationObservers.forEach(e=>{e.disconnect()}),O._mutationObservers.length=0}static async init(){if(O._initialized)return;O._initialized=!0,O.disconnectMutationObservers();const e=await Promise.allSettled([P.scan(document.head),P.scan(document.body)]),[t,r]=e;t.status!=="fulfilled"&&p.error("[Haori]","Failed to build head fragment:",t.reason),r.status!=="fulfilled"&&p.error("[Haori]","Failed to build body fragment:",r.reason),await M.wait(),document.body.setAttribute("data-haori-ready",""),O.observe(document.head),O.observe(document.body),new ne().start(),Y.syncTree(document.body)}static observe(e){const t=new MutationObserver(async r=>{for(const i of r)try{switch(i.type){case"attributes":{const s=i.target;if(i.attributeName&&s.hasAttribute("data-haori-click-lock")&&(i.attributeName==="disabled"||i.attributeName==="data-haori-click-lock")||i.attributeName&&P.isAliasedAttributeReflection(s,i.attributeName))break;P.setAttribute(s,i.attributeName,s.getAttribute(i.attributeName),!0),Y.syncElement(s);break}case"childList":{Array.from(i.removedNodes).forEach(s=>{Y.cleanupTree(s),P.removeNode(s)}),Array.from(i.addedNodes).forEach(s=>{s.parentElement instanceof Element&&(P.addNode(s.parentElement,s),Y.syncTree(s))});break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?P.changeText(i.target,i.target.textContent):p.warn("[Haori]","Unsupported character data type:",i.target);break}default:p.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(s){p.error("[Haori]","Error processing mutation:",s)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),O._mutationObservers.push(t)}};O._initialized=!1,O._mutationObservers=[];let Z=O;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Z.init):Z.init();const we=()=>W.waitForRenders(),De="0.11.1";exports.Core=P;exports.Env=l;exports.Form=A;exports.Fragment=w;exports.Haori=W;exports.Log=p;exports.Queue=M;exports.default=W;exports.version=De;exports.waitForRenders=we;
20
20
  //# sourceMappingURL=haori.cjs.js.map