haori 0.12.0 → 0.13.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.
Files changed (303) hide show
  1. package/README.ja.md +2 -1
  2. package/README.md +2 -1
  3. package/dist/haori.cjs.js +2 -2
  4. package/dist/haori.es.js +23 -3
  5. package/dist/haori.iife.js +2 -2
  6. package/dist/index.d.ts +13 -1
  7. package/package.json +11 -3
  8. package/dist/haori.cjs.js.map +0 -1
  9. package/dist/haori.es.js.map +0 -1
  10. package/dist/haori.iife.js.map +0 -1
  11. package/dist/package.json +0 -70
  12. package/dist/src/builtins.d.ts +0 -100
  13. package/dist/src/builtins.d.ts.map +0 -1
  14. package/dist/src/builtins.js +0 -194
  15. package/dist/src/builtins.js.map +0 -1
  16. package/dist/src/core.d.ts +0 -505
  17. package/dist/src/core.d.ts.map +0 -1
  18. package/dist/src/core.js +0 -1817
  19. package/dist/src/core.js.map +0 -1
  20. package/dist/src/dev.d.ts +0 -35
  21. package/dist/src/dev.d.ts.map +0 -1
  22. package/dist/src/dev.js +0 -44
  23. package/dist/src/dev.js.map +0 -1
  24. package/dist/src/env.d.ts +0 -43
  25. package/dist/src/env.d.ts.map +0 -1
  26. package/dist/src/env.js +0 -108
  27. package/dist/src/env.js.map +0 -1
  28. package/dist/src/event.d.ts +0 -171
  29. package/dist/src/event.d.ts.map +0 -1
  30. package/dist/src/event.js +0 -235
  31. package/dist/src/event.js.map +0 -1
  32. package/dist/src/event_dispatcher.d.ts +0 -66
  33. package/dist/src/event_dispatcher.d.ts.map +0 -1
  34. package/dist/src/event_dispatcher.js +0 -167
  35. package/dist/src/event_dispatcher.js.map +0 -1
  36. package/dist/src/expression.d.ts +0 -260
  37. package/dist/src/expression.d.ts.map +0 -1
  38. package/dist/src/expression.js +0 -975
  39. package/dist/src/expression.js.map +0 -1
  40. package/dist/src/form.d.ts +0 -148
  41. package/dist/src/form.d.ts.map +0 -1
  42. package/dist/src/form.js +0 -428
  43. package/dist/src/form.js.map +0 -1
  44. package/dist/src/fragment.d.ts +0 -609
  45. package/dist/src/fragment.d.ts.map +0 -1
  46. package/dist/src/fragment.js +0 -1940
  47. package/dist/src/fragment.js.map +0 -1
  48. package/dist/src/haori.d.ts +0 -130
  49. package/dist/src/haori.d.ts.map +0 -1
  50. package/dist/src/haori.js +0 -215
  51. package/dist/src/haori.js.map +0 -1
  52. package/dist/src/import.d.ts +0 -19
  53. package/dist/src/import.d.ts.map +0 -1
  54. package/dist/src/import.js +0 -64
  55. package/dist/src/import.js.map +0 -1
  56. package/dist/src/index.d.ts +0 -27
  57. package/dist/src/index.d.ts.map +0 -1
  58. package/dist/src/index.js +0 -30
  59. package/dist/src/index.js.map +0 -1
  60. package/dist/src/intersect.d.ts +0 -28
  61. package/dist/src/intersect.d.ts.map +0 -1
  62. package/dist/src/intersect.js +0 -201
  63. package/dist/src/intersect.js.map +0 -1
  64. package/dist/src/log.d.ts +0 -32
  65. package/dist/src/log.d.ts.map +0 -1
  66. package/dist/src/log.js +0 -43
  67. package/dist/src/log.js.map +0 -1
  68. package/dist/src/observer.d.ts +0 -24
  69. package/dist/src/observer.d.ts.map +0 -1
  70. package/dist/src/observer.js +0 -131
  71. package/dist/src/observer.js.map +0 -1
  72. package/dist/src/procedure.d.ts +0 -447
  73. package/dist/src/procedure.d.ts.map +0 -1
  74. package/dist/src/procedure.js +0 -1921
  75. package/dist/src/procedure.js.map +0 -1
  76. package/dist/src/queue.d.ts +0 -35
  77. package/dist/src/queue.d.ts.map +0 -1
  78. package/dist/src/queue.js +0 -202
  79. package/dist/src/queue.js.map +0 -1
  80. package/dist/src/url.d.ts +0 -14
  81. package/dist/src/url.d.ts.map +0 -1
  82. package/dist/src/url.js +0 -22
  83. package/dist/src/url.js.map +0 -1
  84. package/dist/tests/bind-arg-own-binding.test.d.ts +0 -2
  85. package/dist/tests/bind-arg-own-binding.test.d.ts.map +0 -1
  86. package/dist/tests/bind-arg-own-binding.test.js +0 -63
  87. package/dist/tests/bind-arg-own-binding.test.js.map +0 -1
  88. package/dist/tests/bindcomplete-and-scope.test.d.ts +0 -2
  89. package/dist/tests/bindcomplete-and-scope.test.d.ts.map +0 -1
  90. package/dist/tests/bindcomplete-and-scope.test.js +0 -115
  91. package/dist/tests/bindcomplete-and-scope.test.js.map +0 -1
  92. package/dist/tests/builtins.test.d.ts +0 -2
  93. package/dist/tests/builtins.test.d.ts.map +0 -1
  94. package/dist/tests/builtins.test.js +0 -152
  95. package/dist/tests/builtins.test.js.map +0 -1
  96. package/dist/tests/click-attributes.test.d.ts +0 -2
  97. package/dist/tests/click-attributes.test.d.ts.map +0 -1
  98. package/dist/tests/click-attributes.test.js +0 -113
  99. package/dist/tests/click-attributes.test.js.map +0 -1
  100. package/dist/tests/click-no-disabled.test.d.ts +0 -2
  101. package/dist/tests/click-no-disabled.test.d.ts.map +0 -1
  102. package/dist/tests/click-no-disabled.test.js +0 -67
  103. package/dist/tests/click-no-disabled.test.js.map +0 -1
  104. package/dist/tests/core.test.d.ts +0 -5
  105. package/dist/tests/core.test.d.ts.map +0 -1
  106. package/dist/tests/core.test.js +0 -1056
  107. package/dist/tests/core.test.js.map +0 -1
  108. package/dist/tests/data-bind-arg-reeval.test.d.ts +0 -2
  109. package/dist/tests/data-bind-arg-reeval.test.d.ts.map +0 -1
  110. package/dist/tests/data-bind-arg-reeval.test.js +0 -119
  111. package/dist/tests/data-bind-arg-reeval.test.js.map +0 -1
  112. package/dist/tests/data-bind-merge.test.d.ts +0 -2
  113. package/dist/tests/data-bind-merge.test.d.ts.map +0 -1
  114. package/dist/tests/data-bind-merge.test.js +0 -86
  115. package/dist/tests/data-bind-merge.test.js.map +0 -1
  116. package/dist/tests/data-click-defer.test.d.ts +0 -2
  117. package/dist/tests/data-click-defer.test.d.ts.map +0 -1
  118. package/dist/tests/data-click-defer.test.js +0 -57
  119. package/dist/tests/data-click-defer.test.js.map +0 -1
  120. package/dist/tests/data-click-run.test.d.ts +0 -5
  121. package/dist/tests/data-click-run.test.d.ts.map +0 -1
  122. package/dist/tests/data-click-run.test.js +0 -109
  123. package/dist/tests/data-click-run.test.js.map +0 -1
  124. package/dist/tests/data-derive.test.d.ts +0 -2
  125. package/dist/tests/data-derive.test.d.ts.map +0 -1
  126. package/dist/tests/data-derive.test.js +0 -999
  127. package/dist/tests/data-derive.test.js.map +0 -1
  128. package/dist/tests/data-each-browserlike.test.d.ts +0 -2
  129. package/dist/tests/data-each-browserlike.test.d.ts.map +0 -1
  130. package/dist/tests/data-each-browserlike.test.js +0 -48
  131. package/dist/tests/data-each-browserlike.test.js.map +0 -1
  132. package/dist/tests/data-each-fragment-debug.test.d.ts +0 -2
  133. package/dist/tests/data-each-fragment-debug.test.d.ts.map +0 -1
  134. package/dist/tests/data-each-fragment-debug.test.js +0 -119
  135. package/dist/tests/data-each-fragment-debug.test.js.map +0 -1
  136. package/dist/tests/data-each-table.test.d.ts +0 -2
  137. package/dist/tests/data-each-table.test.d.ts.map +0 -1
  138. package/dist/tests/data-each-table.test.js +0 -131
  139. package/dist/tests/data-each-table.test.js.map +0 -1
  140. package/dist/tests/data-each-template-recovery.test.d.ts +0 -2
  141. package/dist/tests/data-each-template-recovery.test.d.ts.map +0 -1
  142. package/dist/tests/data-each-template-recovery.test.js +0 -87
  143. package/dist/tests/data-each-template-recovery.test.js.map +0 -1
  144. package/dist/tests/data-event-prevent.test.d.ts +0 -2
  145. package/dist/tests/data-event-prevent.test.d.ts.map +0 -1
  146. package/dist/tests/data-event-prevent.test.js +0 -76
  147. package/dist/tests/data-event-prevent.test.js.map +0 -1
  148. package/dist/tests/data-fetch-form-input-binding.test.d.ts +0 -2
  149. package/dist/tests/data-fetch-form-input-binding.test.d.ts.map +0 -1
  150. package/dist/tests/data-fetch-form-input-binding.test.js +0 -202
  151. package/dist/tests/data-fetch-form-input-binding.test.js.map +0 -1
  152. package/dist/tests/data-fetch-tbody-dom.test.d.ts +0 -2
  153. package/dist/tests/data-fetch-tbody-dom.test.d.ts.map +0 -1
  154. package/dist/tests/data-fetch-tbody-dom.test.js +0 -82
  155. package/dist/tests/data-fetch-tbody-dom.test.js.map +0 -1
  156. package/dist/tests/data-form-container.test.d.ts +0 -2
  157. package/dist/tests/data-form-container.test.d.ts.map +0 -1
  158. package/dist/tests/data-form-container.test.js +0 -87
  159. package/dist/tests/data-form-container.test.js.map +0 -1
  160. package/dist/tests/data-if-dev-diagnostics.test.d.ts +0 -2
  161. package/dist/tests/data-if-dev-diagnostics.test.d.ts.map +0 -1
  162. package/dist/tests/data-if-dev-diagnostics.test.js +0 -55
  163. package/dist/tests/data-if-dev-diagnostics.test.js.map +0 -1
  164. package/dist/tests/data-if-falsy.test.d.ts +0 -2
  165. package/dist/tests/data-if-falsy.test.d.ts.map +0 -1
  166. package/dist/tests/data-if-falsy.test.js +0 -73
  167. package/dist/tests/data-if-falsy.test.js.map +0 -1
  168. package/dist/tests/data-load-on-show.test.d.ts +0 -2
  169. package/dist/tests/data-load-on-show.test.d.ts.map +0 -1
  170. package/dist/tests/data-load-on-show.test.js +0 -98
  171. package/dist/tests/data-load-on-show.test.js.map +0 -1
  172. package/dist/tests/derive-each-render-wait.test.d.ts +0 -2
  173. package/dist/tests/derive-each-render-wait.test.d.ts.map +0 -1
  174. package/dist/tests/derive-each-render-wait.test.js +0 -90
  175. package/dist/tests/derive-each-render-wait.test.js.map +0 -1
  176. package/dist/tests/dev.test.d.ts +0 -2
  177. package/dist/tests/dev.test.d.ts.map +0 -1
  178. package/dist/tests/dev.test.js +0 -51
  179. package/dist/tests/dev.test.js.map +0 -1
  180. package/dist/tests/each-update-event.test.d.ts +0 -2
  181. package/dist/tests/each-update-event.test.d.ts.map +0 -1
  182. package/dist/tests/each-update-event.test.js +0 -83
  183. package/dist/tests/each-update-event.test.js.map +0 -1
  184. package/dist/tests/each_arg.test.d.ts +0 -2
  185. package/dist/tests/each_arg.test.d.ts.map +0 -1
  186. package/dist/tests/each_arg.test.js +0 -41
  187. package/dist/tests/each_arg.test.js.map +0 -1
  188. package/dist/tests/env.test.d.ts +0 -2
  189. package/dist/tests/env.test.d.ts.map +0 -1
  190. package/dist/tests/env.test.js +0 -124
  191. package/dist/tests/env.test.js.map +0 -1
  192. package/dist/tests/evaluation-profile.test.d.ts +0 -2
  193. package/dist/tests/evaluation-profile.test.d.ts.map +0 -1
  194. package/dist/tests/evaluation-profile.test.js +0 -92
  195. package/dist/tests/evaluation-profile.test.js.map +0 -1
  196. package/dist/tests/event.test.d.ts +0 -2
  197. package/dist/tests/event.test.d.ts.map +0 -1
  198. package/dist/tests/event.test.js +0 -300
  199. package/dist/tests/event.test.js.map +0 -1
  200. package/dist/tests/expression-disallowed-keyword-hint.test.d.ts +0 -2
  201. package/dist/tests/expression-disallowed-keyword-hint.test.d.ts.map +0 -1
  202. package/dist/tests/expression-disallowed-keyword-hint.test.js +0 -45
  203. package/dist/tests/expression-disallowed-keyword-hint.test.js.map +0 -1
  204. package/dist/tests/expression-forbidden-hint.test.d.ts +0 -2
  205. package/dist/tests/expression-forbidden-hint.test.d.ts.map +0 -1
  206. package/dist/tests/expression-forbidden-hint.test.js +0 -37
  207. package/dist/tests/expression-forbidden-hint.test.js.map +0 -1
  208. package/dist/tests/expression.test.d.ts +0 -2
  209. package/dist/tests/expression.test.d.ts.map +0 -1
  210. package/dist/tests/expression.test.js +0 -482
  211. package/dist/tests/expression.test.js.map +0 -1
  212. package/dist/tests/fetch-and-procedure-scenarios.test.d.ts +0 -2
  213. package/dist/tests/fetch-and-procedure-scenarios.test.d.ts.map +0 -1
  214. package/dist/tests/fetch-and-procedure-scenarios.test.js +0 -195
  215. package/dist/tests/fetch-and-procedure-scenarios.test.js.map +0 -1
  216. package/dist/tests/form.test.d.ts +0 -2
  217. package/dist/tests/form.test.d.ts.map +0 -1
  218. package/dist/tests/form.test.js +0 -635
  219. package/dist/tests/form.test.js.map +0 -1
  220. package/dist/tests/fragment.test.d.ts +0 -2
  221. package/dist/tests/fragment.test.d.ts.map +0 -1
  222. package/dist/tests/fragment.test.js +0 -284
  223. package/dist/tests/fragment.test.js.map +0 -1
  224. package/dist/tests/haori.test.d.ts +0 -2
  225. package/dist/tests/haori.test.d.ts.map +0 -1
  226. package/dist/tests/haori.test.js +0 -149
  227. package/dist/tests/haori.test.js.map +0 -1
  228. package/dist/tests/helpers/async.d.ts +0 -20
  229. package/dist/tests/helpers/async.d.ts.map +0 -1
  230. package/dist/tests/helpers/async.js +0 -35
  231. package/dist/tests/helpers/async.js.map +0 -1
  232. package/dist/tests/import.test.d.ts +0 -2
  233. package/dist/tests/import.test.d.ts.map +0 -1
  234. package/dist/tests/import.test.js +0 -148
  235. package/dist/tests/import.test.js.map +0 -1
  236. package/dist/tests/intersect.test.d.ts +0 -2
  237. package/dist/tests/intersect.test.d.ts.map +0 -1
  238. package/dist/tests/intersect.test.js +0 -173
  239. package/dist/tests/intersect.test.js.map +0 -1
  240. package/dist/tests/log.test.d.ts +0 -2
  241. package/dist/tests/log.test.d.ts.map +0 -1
  242. package/dist/tests/log.test.js +0 -58
  243. package/dist/tests/log.test.js.map +0 -1
  244. package/dist/tests/observer.test.d.ts +0 -2
  245. package/dist/tests/observer.test.d.ts.map +0 -1
  246. package/dist/tests/observer.test.js +0 -64
  247. package/dist/tests/observer.test.js.map +0 -1
  248. package/dist/tests/placeholder-resolution.test.d.ts +0 -2
  249. package/dist/tests/placeholder-resolution.test.d.ts.map +0 -1
  250. package/dist/tests/placeholder-resolution.test.js +0 -463
  251. package/dist/tests/placeholder-resolution.test.js.map +0 -1
  252. package/dist/tests/procedure-action-operations.test.d.ts +0 -2
  253. package/dist/tests/procedure-action-operations.test.d.ts.map +0 -1
  254. package/dist/tests/procedure-action-operations.test.js +0 -1140
  255. package/dist/tests/procedure-action-operations.test.js.map +0 -1
  256. package/dist/tests/procedure-bind-append.test.d.ts +0 -2
  257. package/dist/tests/procedure-bind-append.test.d.ts.map +0 -1
  258. package/dist/tests/procedure-bind-append.test.js +0 -80
  259. package/dist/tests/procedure-bind-append.test.js.map +0 -1
  260. package/dist/tests/procedure-fetch-options.test.d.ts +0 -2
  261. package/dist/tests/procedure-fetch-options.test.d.ts.map +0 -1
  262. package/dist/tests/procedure-fetch-options.test.js +0 -255
  263. package/dist/tests/procedure-fetch-options.test.js.map +0 -1
  264. package/dist/tests/procedure.test.d.ts +0 -2
  265. package/dist/tests/procedure.test.d.ts.map +0 -1
  266. package/dist/tests/procedure.test.js +0 -137
  267. package/dist/tests/procedure.test.js.map +0 -1
  268. package/dist/tests/procedure_events.test.d.ts +0 -7
  269. package/dist/tests/procedure_events.test.d.ts.map +0 -1
  270. package/dist/tests/procedure_events.test.js +0 -261
  271. package/dist/tests/procedure_events.test.js.map +0 -1
  272. package/dist/tests/render-wait.test.d.ts +0 -2
  273. package/dist/tests/render-wait.test.d.ts.map +0 -1
  274. package/dist/tests/render-wait.test.js +0 -68
  275. package/dist/tests/render-wait.test.js.map +0 -1
  276. package/dist/tests/reset_each.test.d.ts +0 -2
  277. package/dist/tests/reset_each.test.d.ts.map +0 -1
  278. package/dist/tests/reset_each.test.js +0 -215
  279. package/dist/tests/reset_each.test.js.map +0 -1
  280. package/dist/tests/row-move.test.d.ts +0 -2
  281. package/dist/tests/row-move.test.d.ts.map +0 -1
  282. package/dist/tests/row-move.test.js +0 -220
  283. package/dist/tests/row-move.test.js.map +0 -1
  284. package/dist/tests/row-operations.test.d.ts +0 -2
  285. package/dist/tests/row-operations.test.d.ts.map +0 -1
  286. package/dist/tests/row-operations.test.js +0 -259
  287. package/dist/tests/row-operations.test.js.map +0 -1
  288. package/dist/tests/scheduled-evaluate-wait.test.d.ts +0 -2
  289. package/dist/tests/scheduled-evaluate-wait.test.d.ts.map +0 -1
  290. package/dist/tests/scheduled-evaluate-wait.test.js +0 -68
  291. package/dist/tests/scheduled-evaluate-wait.test.js.map +0 -1
  292. package/dist/tests/url.test.d.ts +0 -2
  293. package/dist/tests/url.test.d.ts.map +0 -1
  294. package/dist/tests/url.test.js +0 -150
  295. package/dist/tests/url.test.js.map +0 -1
  296. package/dist/vite.config.d.ts +0 -3
  297. package/dist/vite.config.d.ts.map +0 -1
  298. package/dist/vite.config.js +0 -28
  299. package/dist/vite.config.js.map +0 -1
  300. package/dist/vitest.config.d.ts +0 -3
  301. package/dist/vitest.config.d.ts.map +0 -1
  302. package/dist/vitest.config.js +0 -19
  303. package/dist/vitest.config.js.map +0 -1
@@ -3,7 +3,7 @@ var Haori=function(O){"use strict";const G=class G{static isEnabled(){return G.d
3
3
  ${n};
4
4
  return (${e});`:`"use strict";
5
5
  return (${e});`;try{return s=new Function(...r,a),this.EXPRESSION_CACHE.set(i,s),{bindKeys:r,evaluator:s,compileFailed:!1}}catch(o){return p.error("[Haori]","Failed to compile expression:",e,o),{bindKeys:r,evaluator:null,compileFailed:!0}}}static extractMissingIdentifier(e){return String(e.message||"").match(/^([A-Za-z_$][A-Za-z0-9_$]*) is not defined$/)?.[1]||null}static canRecoverMissingIdentifier(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?t[e]===void 0&&!(e in t):!1}static canAttemptMissingIdentifierRecovery(e){return e.includes("?.")||e.includes("??")||e.includes("||")||e.includes("&&")}static containsDangerousPatterns(e){return this.hasAllowedSyntax(e)?[/\beval\s*\(/,/\barguments\s*\[/,/\barguments\s*\./].some(r=>r.test(e)):!0}static detectDisallowedKeywords(e){const t=[];return this.DISALLOWED_KEYWORDS.forEach(r=>{new RegExp(`(^|[^\\w$.])${r}(?![\\w$])`).test(e)&&t.push(r)}),t}static hasAllowedSyntax(e){const t=this.tokenizeExpression(e);if(t===null||t.length===0)return!1;const r=[];let i=null;for(let s=0;s<t.length;s++){const n=t[s],a=t[s+1]||null,o=r[r.length-1]||null,c=t[s-2]||null,d=t[s-3]||null;if(this.startsObjectKey(o,i,c,d)&&(n.value==="["||n.type==="identifier"&&this.FORBIDDEN_PROPERTY_NAMES.has(n.value)||n.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(n.value)))||n.type==="identifier"&&(this.DISALLOWED_KEYWORDS.has(n.value)||this.STRICT_FORBIDDEN_NAMES.includes(n.value)||(i?.value==="."||i?.value==="?.")&&this.FORBIDDEN_PROPERTY_NAMES.has(n.value))||o==="member"&&n.value!=="]"&&n.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(n.value))||n.value==="."&&a?.type!=="identifier"||n.value==="?."&&a?.type!=="identifier"&&a?.value!=="["&&a?.value!=="(")return!1;switch(n.value){case"(":r.push("paren");break;case")":{if(r.pop()!=="paren")return!1;break}case"[":{const h=this.startsMemberAccess(i)?"member":"array";r.push(h);break}case"{":r.push("object");break;case"]":{if(r.pop()===void 0)return!1;break}case"}":{if(r.pop()!=="object")return!1;break}}i=n}return r.length===0}static tokenizeExpression(e){const t=[],r=["===","!==","...","?.","&&","||",">=","<=","==","!=","=>"],i=new Set(["(",")","{","}","[","]",".",",","?",":","+","-","*","/","%","!",">","<"]);let s=0;for(;s<e.length;){const n=e[s];if(/\s/.test(n)){s+=1;continue}if(n==="/"&&(e[s+1]==="/"||e[s+1]==="*"))return null;if(n==='"'||n==="'"){const o=this.readStringToken(e,s);if(o===null)return null;t.push(o.token),s=o.nextIndex;continue}const a=r.find(o=>e.startsWith(o,s));if(a){t.push({type:"operator",value:a,position:s}),s+=a.length;continue}if(/[0-9]/.test(n)){const o=this.readNumberToken(e,s);t.push(o.token),s=o.nextIndex;continue}if(/[A-Za-z_$]/.test(n)){const o=this.readIdentifierToken(e,s);t.push(o.token),s=o.nextIndex;continue}if(i.has(n)){t.push({type:"operator",value:n,position:s}),s+=1;continue}return null}return t}static readStringToken(e,t){const r=e[t];let i=t+1;for(;i<e.length;){const s=e[i];if(s==="\\"){i+=2;continue}if(s===r)return{token:{type:"string",value:e.slice(t,i+1),position:t},nextIndex:i+1};i+=1}return null}static readNumberToken(e,t){let r=t;for(;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;if(e[r]===".")for(r+=1;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;return{token:{type:"number",value:e.slice(t,r),position:t},nextIndex:r}}static readIdentifierToken(e,t){let r=t;for(;r<e.length&&/[A-Za-z0-9_$]/.test(e[r]);)r+=1;return{token:{type:"identifier",value:e.slice(t,r),position:t},nextIndex:r}}static startsMemberAccess(e){return e===null?!1:e.type==="identifier"||e.type==="number"?!0:e.value===")"||e.value==="]"||e.value==="?."}static startsObjectKey(e,t,r,i){return e!=="object"?!1:t?.value==="{"||t?.value===","||t?.type==="identifier"&&this.OBJECT_PROPERTY_MODIFIERS.has(t.value)&&(r?.value==="{"||r?.value===",")?!0:t?.value!=="*"?!1:r?.value==="{"||r?.value===","?!0:r?.type==="identifier"&&r.value==="async"&&(i?.value==="{"||i?.value===",")}static decodeStringLiteral(e){return e.slice(1,-1).replace(/\\u\{([0-9a-fA-F]+)\}/g,(t,r)=>String.fromCodePoint(parseInt(r,16))).replace(/\\u([0-9a-fA-F]{4})/g,(t,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\x([0-9a-fA-F]{2})/g,(t,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\(["'\\bfnrtv0])/g,(t,r)=>{switch(r){case"b":return"\b";case"f":return"\f";case"n":return`
6
- `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return r}})}static wrapBoundValues(e){const t=new WeakMap,r={};return Object.entries(e).forEach(([i,s])=>{r[i]=this.wrapBoundValue(s,t)}),r}static wrapBoundValue(e,t){if(!this.shouldWrapValue(e))return e;const r=e,i=t.get(r);if(i!==void 0)return i;const s=new Proxy(r,{get:(n,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const c=Reflect.get(n,a,o);return typeof a=="symbol"?c:this.wrapBoundValue(c,t)},has:(n,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(n,a),getOwnPropertyDescriptor:(n,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(n,a)},apply:(n,a,o)=>{const c=Reflect.apply(n,a,o);return this.isIteratorLike(c)?c:this.wrapBoundValue(c,t)},construct:(n,a,o)=>this.wrapBoundValue(Reflect.construct(n,a,o),t)});return t.set(r,s),s}static shouldWrapValue(e){if(typeof e=="function")return!0;if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}static withBlockedPropertyAccess(e){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:s})=>{Object.defineProperty(i,s,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return e()}finally{r.forEach(({target:i,property:s,descriptor:n})=>{n!==void 0&&Object.defineProperty(i,s,n)})}}static isIteratorLike(e){return e===null||typeof e!="object"?!1:typeof e.next=="function"}static containsForbiddenKeys(e){if(!e||typeof e!="object")return!1;for(const t of Object.keys(e))if(this.FORBIDDEN_BINDING_NAMES.has(t))return!0;return!1}static containsForbiddenBindingValues(e,t=new WeakSet,r=this.getForbiddenBindingValueSet()){if(!e||typeof e!="object")return!1;const i=this.forbiddenBindingValueCache.get(e);if(i!==void 0)return i;if(t.has(e))return!1;if(t.add(e),r.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const s of Object.values(e)){if(typeof s=="function"){if(r.has(s))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(s,t,r))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};C.MAX_IDENTIFIER_RECOVERY_COUNT=8,C.BUILTIN_NAMESPACE="haori",C.BUILTIN_HELPERS={...Ae},C.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,C.forbiddenBindingValueCache=new WeakMap,C.forbiddenBindingValueCacheResetScheduled=!1,C.FORBIDDEN_NAMES=["window","self","globalThis","frames","parent","top","Function","setTimeout","setInterval","requestAnimationFrame","alert","confirm","prompt","fetch","XMLHttpRequest","Reflect","constructor","__proto__","prototype","Object","document","location","navigator","localStorage","sessionStorage","IndexedDB","history"],C.STRICT_FORBIDDEN_NAMES=["eval","arguments"],C.REBINDABLE_FORBIDDEN_NAMES=new Set(["location"]),C.FORBIDDEN_BINDING_NAMES=new Set([...C.FORBIDDEN_NAMES.filter(e=>!C.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...C.STRICT_FORBIDDEN_NAMES]),C.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),C.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),C.DISALLOWED_KEYWORDS=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","finally","for","function","if","import","in","instanceof","let","new","return","switch","this","throw","try","typeof","var","void","while","with","yield"]),C.EXPRESSION_CACHE=new Map;let X=C;class ne{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(e,t=!1){let r,i;const s=new Promise((a,o)=>{r=a,i=o}),n={task:e,timestamp:performance.now(),promise:s,resolve:r,reject:i};return t?this.queue.unshift(n):this.queue.push(n),this.scheduleProcessing(),s}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const e=performance.now();for(;this.queue.length>0;){const t=this.queue.shift();if(!t)return;try{const r=await t.task();t.resolve(r)}catch(r){t.reject(r),p.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){p.error("[Haori]","Error processing queue:",e)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const e=this.queue.map(t=>t.promise);e.length>0&&await Promise.allSettled(e)}async waitForIdle(e=1e3){let t=0,r=0;for(;t<2&&r<e;)this.processing||this.queue.length>0?(await this.wait(),t=0):t+=1,await ne.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const ce=class ce{static enqueue(e,t=!1){return this.ASYNC_QUEUE.enqueue(e,t)}static wait(){return this.ASYNC_QUEUE.wait()}static waitForIdle(e=1e3){return this.ASYNC_QUEUE.waitForIdle(e)}};ce.ASYNC_QUEUE=new ne;let M=ce;class z{static get runtime(){return l.runtime}static setRuntime(e){l.setRuntime(e)}static waitForRenders(){return M.waitForIdle()}static dialog(e){return M.enqueue(()=>{window.alert(e)},!0)}static async toast(e,t="info"){const r=document.createElement("div");r.className=`haori-toast haori-toast-${t}`,r.textContent=e,r.setAttribute("popover","manual"),r.setAttribute("role","status"),r.setAttribute("aria-live",t==="error"?"assertive":"polite"),document.body.appendChild(r),r.showPopover(),setTimeout(()=>{try{r.hidePopover()}finally{r.remove()}},3e3)}static confirm(e){return M.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return M.enqueue(()=>{e instanceof HTMLDialogElement?e.showModal():p.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return M.enqueue(()=>{e instanceof HTMLDialogElement?e.close():p.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return z.addMessage(e,t,"error")}static addMessage(e,t,r){return M.enqueue(()=>{const i=e instanceof HTMLFormElement?e:e.parentElement??e;i.setAttribute("data-message",t),r!==void 0?i.setAttribute("data-message-level",r):i.removeAttribute("data-message-level")},!0)}static clearMessages(e){return M.enqueue(()=>{e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})},!0)}static date(e,t){return fe(e,t)}static number(e,t){return pe(e,t)}static range(e,t,r){return ge(e,t,r)}static pages(e,t,r){return me(e,t,r)}}const Se=["addErrorMessage","clearMessages"];function be(){const e=globalThis.window?.Haori;return Se.every(r=>typeof e?.[r]=="function")?e:z}class S{static getValues(e){const t={};return S.getPartValues(e,t)}static getPartValues(e,t){const r=e.getAttribute("name"),i=e.getAttribute(`${l.prefix}form-object`),s=e.getAttribute(`${l.prefix}form-list`);if(r){s?Array.isArray(t[String(r)])?t[String(r)].push(e.getValue()):t[String(r)]=[e.getValue()]:t[String(r)]=e.getValue(),i&&p.warn("Haori",`Element cannot have both ${l.prefix}form-object and name attributes.`);for(const n of e.getChildElementFragments())S.getPartValues(n,t)}else if(i){const n={};for(const a of e.getChildElementFragments())S.getPartValues(a,n);Object.keys(n).length>0&&(t[String(i)]=n),s&&p.warn("Haori",`Element cannot have both ${l.prefix}form-list and ${l.prefix}form-object attributes.`)}else if(s){const n=[];for(const a of e.getChildElementFragments()){const o={};S.getPartValues(a,o),Object.keys(o).length>0&&n.push(o)}n.length>0&&(t[String(s)]=n)}else for(const n of e.getChildElementFragments())S.getPartValues(n,t);return t}static setValues(e,t,r=!1){return S.setPartValues(e,t,null,r,!0)}static syncValues(e,t,r=!1){return S.setPartValues(e,t,null,r,!1)}static applyFragmentValue(e,t,r){return r?e.setValue(t):e.syncBindingValue(t)}static setPartValues(e,t,r=null,i=!1,s=!0){const n=[],a=e.getAttribute("name"),o=e.getAttribute(`${l.prefix}form-object`),c=e.getAttribute(`${l.prefix}form-list`),d=e.getAttribute(`${l.prefix}form-detach`);if(a){if(!d||i){const h=t[String(a)];c&&Array.isArray(h)&&r!==null?n.push(S.applyFragmentValue(e,h[r]??null,s)):typeof h>"u"||(typeof h=="string"||typeof h=="number"||typeof h=="boolean"||h===null?n.push(S.applyFragmentValue(e,h,s)):n.push(S.applyFragmentValue(e,String(h),s)))}}else if(o){const h=t[String(o)];if(h&&typeof h=="object")for(const g of e.getChildElementFragments())n.push(S.setPartValues(g,h,null,i,s))}else if(c){const h=t[String(c)];if(Array.isArray(h)){const g=e.getChildElementFragments();for(let v=0;v<g.length;v++){const T=g[v];h.length>v?n.push(S.setPartValues(T,h[v],v,i,s)):n.push(S.setPartValues(T,{},v,i,s))}}}else for(const h of e.getChildElementFragments())n.push(S.setPartValues(h,t,null,i,s));return Promise.all(n).then(()=>{})}static async reset(e){S.clearValues(e),await Promise.all([S.clearMessages(e),S.clearEachClones(e)]),await M.enqueue(()=>{const t=e.getTarget();if(t instanceof HTMLFormElement)t.reset();else{const r=t.parentElement;if(r){const i=t.nextElementSibling,s=document.createElement("form");s.appendChild(t),s.reset(),r.insertBefore(t,i)}}}),await P.evaluateAll(e)}static clearEachClones(e){const t=[],r=s=>{if(s.hasAttribute(`${l.prefix}each`))for(const n of s.getChildElementFragments()){const a=n.hasAttribute(`${l.prefix}each-before`),o=n.hasAttribute(`${l.prefix}each-after`);!a&&!o&&t.push(n.remove())}},i=s=>{r(s);for(const n of s.getChildElementFragments())i(n)};r(e);for(const s of e.getChildElementFragments())i(s);return Promise.all(t).then(()=>{})}static clearValues(e){e.clearValue();for(const t of e.getChildElementFragments())S.clearValues(t)}static clearMessages(e){return be().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return S.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const s=[],n=be(),a=n.addMessage,o=d=>typeof a=="function"?a.call(n,d,r,i):n.addErrorMessage(d,r),c=S.findFragmentsByKey(e,t);return c.forEach(d=>{s.push(o(d.getTarget()))}),c.length===0&&s.push(o(e.getTarget())),Promise.all(s).then(()=>{})}static findFragmentsByKey(e,t){return S.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&e.getAttribute("name")===i&&r.push(e),e.hasAttribute(`${l.prefix}form-object`))t.length>1&&e.getAttribute(`${l.prefix}form-object`)===i&&e.getChildElementFragments().forEach(n=>{r.push(...S.findFragmentByKeyParts(n,t.slice(1)))});else if(e.hasAttribute(`${l.prefix}form-list`)){if(t.length>1){const s=e.getAttribute(`${l.prefix}form-list`),n=i.lastIndexOf("["),a=i.lastIndexOf("]");if(n!==-1&&a!==-1&&n<a){const o=i.substring(0,n);if(s===o){const c=i.substring(n+1,a),d=Number(c);if(isNaN(d))p.error("Haori",`Invalid index: ${i}`);else{const h=e.getChildElementFragments().filter(g=>g.hasAttribute(`${l.prefix}row`));d<h.length&&r.push(...S.findFragmentByKeyParts(h[d],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(s=>{r.push(...S.findFragmentByKeyParts(s,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${l.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}}const N=class N{static reset(){N.ELEMENT_STORES.clear(),N.ensureGlobalAccess()}static snapshot(){return N.ensureGlobalAccess(),[...N.ELEMENT_STORES.entries()].map(([e,t])=>({elementId:e,tagName:t.tagName,attributes:[...t.attributes.entries()].map(([r,i])=>({name:r,template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:N.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls),texts:[...t.texts.entries()].map(([r,i])=>({childIndex:Number(r),template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:N.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls)})).sort((e,t)=>{const r=e.attributes.reduce((s,n)=>s+n.calls,0)+e.texts.reduce((s,n)=>s+n.calls,0);return t.attributes.reduce((s,n)=>s+n.calls,0)+t.texts.reduce((s,n)=>s+n.calls,0)-r})}static record(e,t,r){if(!B.isEnabled()||!e||t.length===0)return;N.ensureGlobalAccess();const i=N.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const n=N.getOrCreateCounter(i.attributes,e.rawName,e.template);N.updateCounter(n,t,r);return}const s=N.getOrCreateCounter(i.texts,String(e.childIndex),e.template);N.updateCounter(s,t,r)}static ensureGlobalAccess(){if(!B.isEnabled())return;const e=globalThis;e[N.GLOBAL_KEY]===void 0&&(e[N.GLOBAL_KEY]={reset:()=>N.reset(),snapshot:()=>N.snapshot()})}static getOrCreateElementStore(e){const t=N.createElementId(e),r=N.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return N.ELEMENT_STORES.set(t,i),i}static getOrCreateCounter(e,t,r){const i=e.get(t);if(i)return i;const s={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return e.set(t,s),s}static getOrCreatePlaceholder(e,t){const r=e.get(t);if(r)return r;const i={calls:0,totalDurationMs:0,maxDurationMs:0};return e.set(t,i),i}static updateCounter(e,t,r){e.calls+=1,e.totalDurationMs+=r,e.maxDurationMs=Math.max(e.maxDurationMs,r),t.forEach(i=>{const s=N.getOrCreatePlaceholder(e.placeholders,i.expression);s.calls+=1,s.totalDurationMs+=i.durationMs,s.maxDurationMs=Math.max(s.maxDurationMs,i.durationMs)})}static sortPlaceholders(e){return[...e.entries()].map(([t,r])=>({expression:t,calls:r.calls,totalDurationMs:r.totalDurationMs,maxDurationMs:r.maxDurationMs})).sort((t,r)=>r.calls!==t.calls?r.calls-t.calls:r.totalDurationMs-t.totalDurationMs)}static now(){return globalThis.performance?.now()??Date.now()}static measure(e){const t=N.now();return{value:e(),durationMs:N.now()-t}}static createElementId(e){const t=[];let r=e;for(;r;){let i=r.tagName.toLowerCase();const s=r.getAttribute("id")||"";if(s.trim()!==""){i+=`#${s.trim()}`,t.unshift(i);break}const n=r.getAttribute(`${l.prefix}derive-name`);n&&n.trim()!==""&&(i+=`[${l.prefix}derive-name="${n.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};N.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",N.ELEMENT_STORES=new Map;let Z=N;const W=class W{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,W.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(W.FRAGMENT_CACHE.has(e))return W.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new I(e);break;case Node.TEXT_NODE:t=new H(e);break;case Node.COMMENT_NODE:t=new ae(e);break;default:return p.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return M.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode===e.getTarget()&&e.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{e.skipMutationNodes=t})}else{const e=this.target.parentNode;if(e)return M.enqueue(()=>{this.target.parentNode===e&&e.removeChild(this.target),this.mounted=!1});this.mounted=!1}return Promise.resolve()}mount(){if(this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return M.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode!==e.getTarget()&&e.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{e.skipMutationNodes=t})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(e){this.mounted=e}remove(e=!0){return this.parent&&this.parent.removeChild(this),W.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};W.FRAGMENT_CACHE=new WeakMap;let w=W;const K=class K extends w{constructor(e){super(e),this.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],this.children=[],this.attributeMap=new Map,this.bindingData=null,this.derivedBindingData=null,this.bindingDataCache=null,this.descendantBindingDataCache=null,this.visible=!0,this.display=null,this.displayPriority=null,this.template=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.skipMutationAttributes=!1,this.skipChangeValue=!1,this.syncValue(),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new _(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=w.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof K)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){p.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new K(this.target.cloneNode(!1));return this.attributeMap.forEach((t,r)=>{e.attributeMap.set(r,t)}),this.children.forEach(t=>{const r=t.clone();e.getTarget().appendChild(r.getTarget()),e.pushChild(r)}),e.mounted=!1,e.bindingData=this.bindingData,e.derivedBindingData=this.derivedBindingData,e.clearBindingDataCache(),e.visible=!0,e.display=this.display,e.displayPriority=this.displayPriority,e.template=this.template,e.renderSignature=this.renderSignature,e.eachInputSignature=this.eachInputSignature,e.deriveSubtreeSignature=null,e.deriveInputSignature=null,e.freshInitializationSkippable=this.freshInitializationSkippable,e.normalizeClonedVisibilityState(),e}normalizeClonedVisibilityState(){(this.visible===!1||this.getTarget().style.display==="none"||this.getTarget().hasAttribute(`${l.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${l.prefix}if-false`)),this.children.forEach(e=>{e instanceof K&&e.normalizeClonedVisibilityState()})}remove(e=!0){const t=[];return this.children.forEach(r=>{t.push(r.remove(!1))}),this.children.length=0,this.attributeMap.clear(),this.bindingData=null,this.bindingDataCache=null,this.derivedBindingData=null,this.descendantBindingDataCache=null,this.template&&(t.push(this.template.remove(!1)),this.template=null),this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,t.push(super.remove(e)),Promise.all(t).then(()=>{})}getTarget(){return this.target}getBindingData(){return this.bindingDataCache?this.bindingDataCache:(this.bindingDataCache={},this.parent&&Object.assign(this.bindingDataCache,this.parent.getDescendantBindingData()),this.bindingData&&Object.assign(this.bindingDataCache,this.bindingData),this.bindingDataCache)}getDescendantBindingData(){return this.descendantBindingDataCache?this.descendantBindingDataCache:(this.descendantBindingDataCache={...this.getBindingData()},this.derivedBindingData&&Object.assign(this.descendantBindingDataCache,this.derivedBindingData),this.descendantBindingDataCache)}getRawBindingData(){return this.bindingData}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(e){this.bindingData=e,this.clearBindingDataCache()}setDerivedBindingData(e){this.derivedBindingData=e,this.clearBindingDataCache()}setParent(e){this.parent!==e&&(this.parent=e,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(e=>{e instanceof K&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e}setListKey(e){this.listKey=e}getListKey(){return this.listKey}getRenderSignature(){return this.renderSignature}setRenderSignature(e){this.renderSignature=e}getEachInputSignature(){return this.eachInputSignature}setEachInputSignature(e){this.eachInputSignature=e}getDeriveSubtreeSignature(){return this.deriveSubtreeSignature}setDeriveSubtreeSignature(e){this.deriveSubtreeSignature=e}getDeriveInputSignature(){return this.deriveInputSignature}setDeriveInputSignature(e){this.deriveInputSignature=e}isFreshInitializationSkippable(){return this.freshInitializationSkippable}setFreshInitializationSkippable(e){this.freshInitializationSkippable=e}setValue(e){return this.applyValue(e,!0)}syncBindingValue(e){return this.applyValue(e,!1)}applyValue(e,t){if(this.skipChangeValue||this.value===e)return Promise.resolve();const r=this.getTarget();if(r instanceof HTMLInputElement&&(r.type==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),s=r.type==="checkbox"&&i==="true";let n;return s?n=e===!0||e==="true":i==="false"?n=e===!1:n=i===String(e),this.value=s?n:n?e:null,r.checked===n?Promise.resolve():(this.skipChangeValue=!0,M.enqueue(()=>{r.checked=n,t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else return r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement?(this.value=e,this.skipChangeValue=!0,M.enqueue(()=>{r.value=e===null?"":String(e),t&&((r instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(r.type)||r instanceof HTMLTextAreaElement)&&r.dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0})))}).finally(()=>{this.skipChangeValue=!1})):(p.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve())}getValue(){return this.value}clearValue(){this.value=null}syncValue(){const e=this.getTarget();if(e instanceof HTMLInputElement)if(e.type==="checkbox"||e.type==="radio"){const t=e.type==="checkbox"&&e.value==="true";if(e.checked){const r=e.value;t?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=e.value;t?this.value=!1:r==="false"?this.value=!0:this.value=null}}else this.value=e.value;else e instanceof HTMLTextAreaElement?this.value=e.value:e instanceof HTMLSelectElement&&(this.value=e.value)}setAttribute(e,t,r=!1){return this.setAttributeInternal(e,e,t,!0,r)}setAliasedAttribute(e,t,r,i=!1){return this.setAttributeInternal(e,t,r,!1,i)}removeAliasedAttribute(e,t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const r=this.getTarget();return M.enqueue(()=>{r.removeAttribute(e),t!==e&&r.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}setAttributeInternal(e,t,r,i,s=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const n=new _(e,r);if(s){const V=this.attributeMap.get(e);if(V&&(V.isEvaluate||V.isForceEvaluation())&&!n.isEvaluate&&!n.isForceEvaluation())return this.skipMutationAttributes=!0,M.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(e,n);const a=this.getTarget(),o=n.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:e,template:r}),c=n.isEvaluate||n.isRawEvaluate,d=e===t&&K.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),h=n.isSingleExpression(),g=j.joinEvaluateResults(o.results),v=o.results.length===1?o.results[0]:g,T=!n.isForceEvaluation()&&(t!==e||d||h?o.hasUnresolvedReference||v===null||v===void 0||v===!1:c&&g===""),b=n.isForceEvaluation()?r:h?v:g,y=i&&n.isEvaluate&&t==="value"&&(a instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(a.type)||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement),m=T||b===null||b===!1?null:String(b),A=e!==t&&a.getAttribute(e)!==r,F=m===null?a.hasAttribute(t):a.getAttribute(t)!==m,x=y&&m!==null&&a.value!==m;return!A&&!F&&!x?(y&&m!==null&&(this.value=m),Promise.resolve()):(this.skipMutationAttributes=!0,M.enqueue(()=>{A&&a.setAttribute(e,r),m===null?a.removeAttribute(t):(F&&a.setAttribute(t,m),y&&(this.value=m,x&&(a.value=m)))}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const t=this.getTarget();return M.enqueue(()=>{t.removeAttribute(e)}).finally(()=>{this.skipMutationAttributes=!1})}getAttribute(e){return this.getAttributeEvaluation(e)?.value??null}getAttributeEvaluation(e){const t=this.attributeMap.get(e);if(t===void 0)return null;const r=t.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:this.getTarget(),rawName:e,template:t.getValue()});return r.results.length===1?{value:r.results[0],hasUnresolvedReference:r.hasUnresolvedReference}:{value:j.joinEvaluateResults(r.results),hasUnresolvedReference:r.hasUnresolvedReference}}getRawAttribute(e){const t=this.attributeMap.get(e);return t===void 0?null:t.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(e){return this.attributeMap.has(e)}resolveInsertionPointFromDom(e,t){const r=e.getTarget();if(r.parentNode!==this.target)return null;const i=t?r.nextSibling:r;let s=t?r.nextSibling:r;for(;s!==null;){const n=w.get(s);if(n!==null){const a=this.children.indexOf(n);if(a!==-1)return{index:a,referenceNode:i}}s=s.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(e,t,r){if(this.skipMutationNodes)return Promise.resolve();if(e===this)return p.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let s=this.parent;for(;s;)i.add(s),s=s.getParent();if(i.has(e))return p.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const n=e.getParent()===this;let a=-1,o=-1;n&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const c=e.getParent();c!==null&&c.removeChild(e);let d=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let g;if(n?a!==-1&&a<o?g=o-1:g=o:g=this.children.indexOf(t),g===-1){const v=this.resolveInsertionPointFromDom(t,!1);v===null?(p.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(v.index,0,e),d=v.referenceNode)}else this.children.splice(g,0,e)}e.setParent(this),e.setMounted(this.mounted);const h=this.skipMutationNodes;return this.skipMutationNodes=!0,M.enqueue(()=>{this.target.insertBefore(e.getTarget(),d)}).finally(()=>{this.skipMutationNodes=h})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(p.warn("[Haori]","Reference child not found in children.",t),this.insertBefore(e,null)):this.insertBefore(e,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(e,this.children[r+1]||null)}getPrevious(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<=0?null:t[r-1]}getNext(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<0||r+1>=t.length?null:t[r+1]}isVisible(){return this.visible}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const e=this.getTarget();return this.display=e.style.getPropertyValue("display"),this.displayPriority=e.style.getPropertyPriority("display"),e.style.setProperty("display","none","important"),e.setAttribute(`${l.prefix}if-false`,""),Promise.resolve()}show(){if(this.visible)return Promise.resolve();const e=this.getTarget();return this.display===null||this.display===""?e.style.removeProperty("display"):e.style.setProperty("display",this.display,this.displayPriority??""),this.display=null,this.displayPriority=null,e.removeAttribute(`${l.prefix}if-false`),this.visible=!0,Promise.resolve()}closestByAttribute(e){if(this.hasAttribute(e))return this;const t=this.getParent();return t===null?null:t.closestByAttribute(e)}};K.BOOLEAN_ATTRIBUTES=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","hidden","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]);let I=K;class H extends w{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new j(this.text)}clone(){const e=new H(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e.contents=this.contents,e.renderedText=this.renderedText,e}getTarget(){return this.target}hasDynamicContent(){return this.contents.isEvaluate||this.contents.isRawEvaluate}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new j(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):M.enqueue(()=>{this.skipMutation=!0;let e=this.text;this.contents.isRawEvaluate?e=this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})[0]:this.contents.isEvaluate&&(e=j.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})));const t=this.contents.isRawEvaluate?this.parent.getTarget().innerHTML:this.target.textContent||"";this.renderedText===e&&t===e||(this.contents.isRawEvaluate?this.parent.getTarget().innerHTML=e:this.target.textContent=e,this.renderedText=e)}).finally(()=>{this.skipMutation=!1})}}class ae extends w{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new ae(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e}getTarget(){return this.target}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,M.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const te=class te{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(te.PLACEHOLDER_REGEX)];let r=0,i=!1,s=!1;for(const n of t){n.index>r&&this.contents.push({text:e.slice(r,n.index),type:0});const a={text:n[1]??n[2],type:n[1]?2:1};i=!0,s=s||a.type===2,this.contents.push(a),r=n.index+n[0].length}r<e.length&&this.contents.push({text:e.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=s,this.checkRawExpressions()}static joinEvaluateResults(e){return e===null||e.length===0?"":e.map(t=>t==null||t===!1||Number.isNaN(t)?"":typeof t!="string"?String(t):t).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(p.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const s=[],n=[];let a=0,o=!1;return this.contents.forEach(c=>{try{if(r(c)){const d=Z.measure(()=>X.evaluateDetailed(c.text,e)),h=d.value;a+=d.durationMs,n.push({expression:c.text,durationMs:d.durationMs}),o=o||h.unresolvedReference,s.push(h.value)}else s.push(c.text)}catch(d){p.error("[Haori]",`Error evaluating ${i} expression: ${c.text}`,d),n.push({expression:c.text,durationMs:0}),s.push("")}}),Z.record(t,n,a),{results:s,hasUnresolvedReference:o}}};te.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let j=te;const re=class re extends j{constructor(e,t){super(t),this.forceEvaluation=re.FORCE_EVALUATION_ATTRIBUTES.includes(e)}isForceEvaluation(){return this.forceEvaluation}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){if(!this.isEvaluate&&!this.forceEvaluation)return{results:this.contents.map(i=>i.text),hasUnresolvedReference:!1};const r=this.evaluateWithProfile(e,t,i=>this.forceEvaluation&&i.type===0||i.type===1||i.type===2,"attribute");return this.forceEvaluation&&r.results.length>1?(p.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};re.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let _=re;class D{static dispatch(e,t,r,i){const s=new CustomEvent(`haori:${t}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return e.dispatchEvent(s)}static ready(e){D.dispatch(document,"ready",{version:e})}static render(e){D.dispatch(e,"render",{target:e})}static importStart(e,t){D.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){D.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){D.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const s=[],n=new Set(Object.keys(t||{})),a=new Set(Object.keys(r)),o=new Set([...n,...a]);for(const c of o){const d=t?.[c],h=r[c];d!==h&&s.push(c)}D.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:s,reason:i})}static bindComplete(e,t=null,r="other"){D.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){D.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){D.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){D.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){D.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){D.dispatch(e,"show",{visible:!0})}static hide(e){D.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,s){D.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...s})}static fetchEnd(e,t,r,i){D.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,s){D.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:s?performance.now()-s:void 0})}}const Te=["addErrorMessage","closeDialog","confirm","dialog","openDialog","toast"],we="__haoriHistoryState__",oe="data-haori-click-lock";function le(){const e=globalThis.window?.Haori;return Te.every(r=>typeof e?.[r]=="function")?e:z}const De=new Set(["GET","HEAD","OPTIONS"]);function Re(E){return De.has(E.toUpperCase())}function Fe(E,e){for(const[t,r]of Object.entries(e))r!==void 0&&(r===null?E.append(t,""):Array.isArray(r)?r.forEach(i=>{E.append(t,String(i))}):typeof r=="object"||typeof r=="function"?E.append(t,JSON.stringify(r)):E.append(t,String(r)))}function Ne(E,e){const t=new URL(E,window.location.href),r=new URLSearchParams(t.search);return Fe(r,e),t.search=r.toString(),t.toString()}function Me(E){return E==null?null:typeof E=="string"?E:E instanceof URLSearchParams?E.toString():E instanceof FormData?Array.from(E.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(E)}function xe(E,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[s])=>i.localeCompare(s));return JSON.stringify({url:E,method:String(e.method||"GET").toUpperCase(),headers:r,body:Me(e.body||null)})}const f=class f{static attrName(e,t,r=!1){return e?`${l.prefix}${e}-${t}`:r?`${l.prefix}fetch-${t}`:`${l.prefix}${t}`}static resolveDataParamString(e,t){return f.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(f.DATA_PLACEHOLDER_REGEX,(s,n,a)=>{const o=X.evaluateDetailed(n??a??"",t);return r=r||o.unresolvedReference,o.value===null||o.value===void 0||Number.isNaN(o.value)?"":typeof o.value=="object"?encodeURIComponent(JSON.stringify(o.value)):encodeURIComponent(String(o.value))}),hasUnresolvedReference:r}}static isJsonStringContext(e,t){let r=!1,i=!1;for(let s=0;s<t;s+=1){const n=e[s];if(i){i=!1;continue}if(n==="\\"){i=!0;continue}n==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(e){if(e===void 0||Number.isNaN(e))return"null";try{return JSON.stringify(e)??JSON.stringify(String(e))}catch{return JSON.stringify(String(e))}}static stringifyJsonTemplateStringContent(e){if(e==null||Number.isNaN(e))return"";const t=typeof e=="object"?f.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return f.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(f.DATA_PLACEHOLDER_REGEX,(s,n,a,o)=>{const c=X.evaluateDetailed(n??a??"",t);return r=r||c.unresolvedReference,f.isJsonStringContext(e,o)?f.stringifyJsonTemplateStringContent(c.value):f.stringifyJsonTemplateValue(c.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return f.resolveDataAttributeDetailed(e,t).value}static resolveDataAttributeDetailed(e,t){const r=e.getRawAttribute(t),i=e.getAttributeEvaluation(t),s=i?.value??null,n=i?.hasUnresolvedReference??!1;if(s&&typeof s=="object"&&!Array.isArray(s))return{value:s,hasUnresolvedReference:n};if(typeof s!="string"||r===null)return{value:null,hasUnresolvedReference:n};const a=r.trim();if(f.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:P.parseDataBind(s),hasUnresolvedReference:n};if(a.startsWith("{")||a.startsWith("[")){const c=f.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:P.parseDataBind(c.value),hasUnresolvedReference:n||c.hasUnresolvedReference}}const o=f.resolveDataParamStringDetailed(r,e.getBindingData());return{value:P.parseDataBind(o.value),hasUnresolvedReference:n||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e};if(t){if(e.hasAttribute(f.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(f.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(f.attrName(t,"confirm")).replace(/\\n/g,`
6
+ `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return r}})}static wrapBoundValues(e){const t=new WeakMap,r={};return Object.entries(e).forEach(([i,s])=>{r[i]=this.wrapBoundValue(s,t)}),r}static wrapBoundValue(e,t){if(!this.shouldWrapValue(e))return e;const r=e,i=t.get(r);if(i!==void 0)return i;const s=new Proxy(r,{get:(n,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const c=Reflect.get(n,a,o);return typeof a=="symbol"?c:this.wrapBoundValue(c,t)},has:(n,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(n,a),getOwnPropertyDescriptor:(n,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(n,a)},apply:(n,a,o)=>{const c=Reflect.apply(n,a,o);return this.isIteratorLike(c)?c:this.wrapBoundValue(c,t)},construct:(n,a,o)=>this.wrapBoundValue(Reflect.construct(n,a,o),t)});return t.set(r,s),s}static shouldWrapValue(e){if(typeof e=="function")return!0;if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}static withBlockedPropertyAccess(e){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:s})=>{Object.defineProperty(i,s,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return e()}finally{r.forEach(({target:i,property:s,descriptor:n})=>{n!==void 0&&Object.defineProperty(i,s,n)})}}static isIteratorLike(e){return e===null||typeof e!="object"?!1:typeof e.next=="function"}static containsForbiddenKeys(e){if(!e||typeof e!="object")return!1;for(const t of Object.keys(e))if(this.FORBIDDEN_BINDING_NAMES.has(t))return!0;return!1}static containsForbiddenBindingValues(e,t=new WeakSet,r=this.getForbiddenBindingValueSet()){if(!e||typeof e!="object")return!1;const i=this.forbiddenBindingValueCache.get(e);if(i!==void 0)return i;if(t.has(e))return!1;if(t.add(e),r.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const s of Object.values(e)){if(typeof s=="function"){if(r.has(s))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(s,t,r))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};C.MAX_IDENTIFIER_RECOVERY_COUNT=8,C.BUILTIN_NAMESPACE="haori",C.BUILTIN_HELPERS={...Ae},C.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,C.forbiddenBindingValueCache=new WeakMap,C.forbiddenBindingValueCacheResetScheduled=!1,C.FORBIDDEN_NAMES=["window","self","globalThis","frames","parent","top","Function","setTimeout","setInterval","requestAnimationFrame","alert","confirm","prompt","fetch","XMLHttpRequest","Reflect","constructor","__proto__","prototype","Object","document","location","navigator","localStorage","sessionStorage","IndexedDB","history"],C.STRICT_FORBIDDEN_NAMES=["eval","arguments"],C.REBINDABLE_FORBIDDEN_NAMES=new Set(["location"]),C.FORBIDDEN_BINDING_NAMES=new Set([...C.FORBIDDEN_NAMES.filter(e=>!C.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...C.STRICT_FORBIDDEN_NAMES]),C.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),C.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),C.DISALLOWED_KEYWORDS=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","finally","for","function","if","import","in","instanceof","let","new","return","switch","this","throw","try","typeof","var","void","while","with","yield"]),C.EXPRESSION_CACHE=new Map;let X=C;class ne{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(e,t=!1){let r,i;const s=new Promise((a,o)=>{r=a,i=o}),n={task:e,timestamp:performance.now(),promise:s,resolve:r,reject:i};return t?this.queue.unshift(n):this.queue.push(n),this.scheduleProcessing(),s}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const e=performance.now();for(;this.queue.length>0;){const t=this.queue.shift();if(!t)return;try{const r=await t.task();t.resolve(r)}catch(r){t.reject(r),p.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){p.error("[Haori]","Error processing queue:",e)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const e=this.queue.map(t=>t.promise);e.length>0&&await Promise.allSettled(e)}async waitForIdle(e=1e3){let t=0,r=0;for(;t<2&&r<e;)this.processing||this.queue.length>0?(await this.wait(),t=0):t+=1,await ne.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const ce=class ce{static enqueue(e,t=!1){return this.ASYNC_QUEUE.enqueue(e,t)}static wait(){return this.ASYNC_QUEUE.wait()}static waitForIdle(e=1e3){return this.ASYNC_QUEUE.waitForIdle(e)}};ce.ASYNC_QUEUE=new ne;let M=ce;class z{static get runtime(){return l.runtime}static setRuntime(e){l.setRuntime(e)}static waitForRenders(){return M.waitForIdle()}static dialog(e){return M.enqueue(()=>{window.alert(e)},!0)}static async toast(e,t="info"){const r=document.createElement("div");r.className=`haori-toast haori-toast-${t}`,r.textContent=e,r.setAttribute("popover","manual"),r.setAttribute("role","status"),r.setAttribute("aria-live",t==="error"?"assertive":"polite"),document.body.appendChild(r),r.showPopover(),setTimeout(()=>{try{r.hidePopover()}finally{r.remove()}},3e3)}static confirm(e){return M.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return M.enqueue(()=>{e instanceof HTMLDialogElement?e.showModal():p.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return M.enqueue(()=>{e instanceof HTMLDialogElement?e.close():p.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return z.addMessage(e,t,"error")}static addMessage(e,t,r){return M.enqueue(()=>{const i=e instanceof HTMLFormElement?e:e.parentElement??e;i.setAttribute("data-message",t),r!==void 0?i.setAttribute("data-message-level",r):i.removeAttribute("data-message-level")},!0)}static clearMessages(e){return M.enqueue(()=>{e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})},!0)}static date(e,t){return fe(e,t)}static number(e,t){return pe(e,t)}static range(e,t,r){return ge(e,t,r)}static pages(e,t,r){return me(e,t,r)}}const Se=["addErrorMessage","clearMessages"];function be(){const e=globalThis.window?.Haori;return Se.every(r=>typeof e?.[r]=="function")?e:z}class S{static getValues(e){const t={};return S.getPartValues(e,t)}static getPartValues(e,t){const r=e.getAttribute("name"),i=e.getAttribute(`${l.prefix}form-object`),s=e.getAttribute(`${l.prefix}form-list`);if(r){s?Array.isArray(t[String(r)])?t[String(r)].push(e.getValue()):t[String(r)]=[e.getValue()]:t[String(r)]=e.getValue(),i&&p.warn("Haori",`Element cannot have both ${l.prefix}form-object and name attributes.`);for(const n of e.getChildElementFragments())S.getPartValues(n,t)}else if(i){const n={};for(const a of e.getChildElementFragments())S.getPartValues(a,n);Object.keys(n).length>0&&(t[String(i)]=n),s&&p.warn("Haori",`Element cannot have both ${l.prefix}form-list and ${l.prefix}form-object attributes.`)}else if(s){const n=[];for(const a of e.getChildElementFragments()){const o={};S.getPartValues(a,o),Object.keys(o).length>0&&n.push(o)}n.length>0&&(t[String(s)]=n)}else for(const n of e.getChildElementFragments())S.getPartValues(n,t);return t}static setValues(e,t,r=!1){return S.setPartValues(e,t,null,r,!0)}static syncValues(e,t,r=!1){return S.setPartValues(e,t,null,r,!1)}static applyFragmentValue(e,t,r){return r?e.setValue(t):e.syncBindingValue(t)}static setPartValues(e,t,r=null,i=!1,s=!0){const n=[],a=e.getAttribute("name"),o=e.getAttribute(`${l.prefix}form-object`),c=e.getAttribute(`${l.prefix}form-list`),d=e.getAttribute(`${l.prefix}form-detach`);if(a){if(!d||i){const h=t[String(a)];c&&Array.isArray(h)&&r!==null?n.push(S.applyFragmentValue(e,h[r]??null,s)):typeof h>"u"||(typeof h=="string"||typeof h=="number"||typeof h=="boolean"||h===null?n.push(S.applyFragmentValue(e,h,s)):n.push(S.applyFragmentValue(e,String(h),s)))}}else if(o){const h=t[String(o)];if(h&&typeof h=="object")for(const g of e.getChildElementFragments())n.push(S.setPartValues(g,h,null,i,s))}else if(c){const h=t[String(c)];if(Array.isArray(h)){const g=e.getChildElementFragments();for(let v=0;v<g.length;v++){const T=g[v];h.length>v?n.push(S.setPartValues(T,h[v],v,i,s)):n.push(S.setPartValues(T,{},v,i,s))}}}else for(const h of e.getChildElementFragments())n.push(S.setPartValues(h,t,null,i,s));return Promise.all(n).then(()=>{})}static async reset(e){S.clearValues(e),await Promise.all([S.clearMessages(e),S.clearEachClones(e)]),await M.enqueue(()=>{const t=e.getTarget();if(t instanceof HTMLFormElement)t.reset();else{const r=t.parentElement;if(r){const i=t.nextElementSibling,s=document.createElement("form");s.appendChild(t),s.reset(),r.insertBefore(t,i)}}}),await P.evaluateAll(e)}static clearEachClones(e){const t=[],r=s=>{if(s.hasAttribute(`${l.prefix}each`))for(const n of s.getChildElementFragments()){const a=n.hasAttribute(`${l.prefix}each-before`),o=n.hasAttribute(`${l.prefix}each-after`);!a&&!o&&t.push(n.remove())}},i=s=>{r(s);for(const n of s.getChildElementFragments())i(n)};r(e);for(const s of e.getChildElementFragments())i(s);return Promise.all(t).then(()=>{})}static clearValues(e){e.clearValue();for(const t of e.getChildElementFragments())S.clearValues(t)}static clearMessages(e){return be().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return S.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const s=[],n=be(),a=n.addMessage,o=d=>typeof a=="function"?a.call(n,d,r,i):n.addErrorMessage(d,r),c=S.findFragmentsByKey(e,t);return c.forEach(d=>{s.push(o(d.getTarget()))}),c.length===0&&s.push(o(e.getTarget())),Promise.all(s).then(()=>{})}static findFragmentsByKey(e,t){return S.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&e.getAttribute("name")===i&&r.push(e),e.hasAttribute(`${l.prefix}form-object`))t.length>1&&e.getAttribute(`${l.prefix}form-object`)===i&&e.getChildElementFragments().forEach(n=>{r.push(...S.findFragmentByKeyParts(n,t.slice(1)))});else if(e.hasAttribute(`${l.prefix}form-list`)){if(t.length>1){const s=e.getAttribute(`${l.prefix}form-list`),n=i.lastIndexOf("["),a=i.lastIndexOf("]");if(n!==-1&&a!==-1&&n<a){const o=i.substring(0,n);if(s===o){const c=i.substring(n+1,a),d=Number(c);if(isNaN(d))p.error("Haori",`Invalid index: ${i}`);else{const h=e.getChildElementFragments().filter(g=>g.hasAttribute(`${l.prefix}row`));d<h.length&&r.push(...S.findFragmentByKeyParts(h[d],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(s=>{r.push(...S.findFragmentByKeyParts(s,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${l.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}}const N=class N{static reset(){N.ELEMENT_STORES.clear(),N.ensureGlobalAccess()}static snapshot(){return N.ensureGlobalAccess(),[...N.ELEMENT_STORES.entries()].map(([e,t])=>({elementId:e,tagName:t.tagName,attributes:[...t.attributes.entries()].map(([r,i])=>({name:r,template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:N.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls),texts:[...t.texts.entries()].map(([r,i])=>({childIndex:Number(r),template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:N.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls)})).sort((e,t)=>{const r=e.attributes.reduce((s,n)=>s+n.calls,0)+e.texts.reduce((s,n)=>s+n.calls,0);return t.attributes.reduce((s,n)=>s+n.calls,0)+t.texts.reduce((s,n)=>s+n.calls,0)-r})}static record(e,t,r){if(!B.isEnabled()||!e||t.length===0)return;N.ensureGlobalAccess();const i=N.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const n=N.getOrCreateCounter(i.attributes,e.rawName,e.template);N.updateCounter(n,t,r);return}const s=N.getOrCreateCounter(i.texts,String(e.childIndex),e.template);N.updateCounter(s,t,r)}static ensureGlobalAccess(){if(!B.isEnabled())return;const e=globalThis;e[N.GLOBAL_KEY]===void 0&&(e[N.GLOBAL_KEY]={reset:()=>N.reset(),snapshot:()=>N.snapshot()})}static getOrCreateElementStore(e){const t=N.createElementId(e),r=N.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return N.ELEMENT_STORES.set(t,i),i}static getOrCreateCounter(e,t,r){const i=e.get(t);if(i)return i;const s={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return e.set(t,s),s}static getOrCreatePlaceholder(e,t){const r=e.get(t);if(r)return r;const i={calls:0,totalDurationMs:0,maxDurationMs:0};return e.set(t,i),i}static updateCounter(e,t,r){e.calls+=1,e.totalDurationMs+=r,e.maxDurationMs=Math.max(e.maxDurationMs,r),t.forEach(i=>{const s=N.getOrCreatePlaceholder(e.placeholders,i.expression);s.calls+=1,s.totalDurationMs+=i.durationMs,s.maxDurationMs=Math.max(s.maxDurationMs,i.durationMs)})}static sortPlaceholders(e){return[...e.entries()].map(([t,r])=>({expression:t,calls:r.calls,totalDurationMs:r.totalDurationMs,maxDurationMs:r.maxDurationMs})).sort((t,r)=>r.calls!==t.calls?r.calls-t.calls:r.totalDurationMs-t.totalDurationMs)}static now(){return globalThis.performance?.now()??Date.now()}static measure(e){const t=N.now();return{value:e(),durationMs:N.now()-t}}static createElementId(e){const t=[];let r=e;for(;r;){let i=r.tagName.toLowerCase();const s=r.getAttribute("id")||"";if(s.trim()!==""){i+=`#${s.trim()}`,t.unshift(i);break}const n=r.getAttribute(`${l.prefix}derive-name`);n&&n.trim()!==""&&(i+=`[${l.prefix}derive-name="${n.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};N.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",N.ELEMENT_STORES=new Map;let Z=N;const W=class W{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,W.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(W.FRAGMENT_CACHE.has(e))return W.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new I(e);break;case Node.TEXT_NODE:t=new H(e);break;case Node.COMMENT_NODE:t=new ae(e);break;default:return p.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return M.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode===e.getTarget()&&e.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{e.skipMutationNodes=t})}else{const e=this.target.parentNode;if(e)return M.enqueue(()=>{this.target.parentNode===e&&e.removeChild(this.target),this.mounted=!1});this.mounted=!1}return Promise.resolve()}mount(){if(this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return M.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode!==e.getTarget()&&e.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{e.skipMutationNodes=t})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(e){this.mounted=e}remove(e=!0){return this.parent&&this.parent.removeChild(this),W.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};W.FRAGMENT_CACHE=new WeakMap;let w=W;const K=class K extends w{constructor(e){super(e),this.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],this.children=[],this.attributeMap=new Map,this.bindingData=null,this.derivedBindingData=null,this.bindingDataCache=null,this.descendantBindingDataCache=null,this.visible=!0,this.display=null,this.displayPriority=null,this.template=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.skipMutationAttributes=!1,this.skipChangeValue=!1,this.syncValue(),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new _(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=w.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof K)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){p.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new K(this.target.cloneNode(!1));return this.attributeMap.forEach((t,r)=>{e.attributeMap.set(r,t)}),this.children.forEach(t=>{const r=t.clone();e.getTarget().appendChild(r.getTarget()),e.pushChild(r)}),e.mounted=!1,e.bindingData=this.bindingData,e.derivedBindingData=this.derivedBindingData,e.clearBindingDataCache(),e.visible=!0,e.display=this.display,e.displayPriority=this.displayPriority,e.template=this.template,e.renderSignature=this.renderSignature,e.eachInputSignature=this.eachInputSignature,e.deriveSubtreeSignature=null,e.deriveInputSignature=null,e.freshInitializationSkippable=this.freshInitializationSkippable,e.normalizeClonedVisibilityState(),e}normalizeClonedVisibilityState(){(this.visible===!1||this.getTarget().style.display==="none"||this.getTarget().hasAttribute(`${l.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${l.prefix}if-false`)),this.children.forEach(e=>{e instanceof K&&e.normalizeClonedVisibilityState()})}remove(e=!0){const t=[];return this.children.forEach(r=>{t.push(r.remove(!1))}),this.children.length=0,this.attributeMap.clear(),this.bindingData=null,this.bindingDataCache=null,this.derivedBindingData=null,this.descendantBindingDataCache=null,this.template&&(t.push(this.template.remove(!1)),this.template=null),this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,t.push(super.remove(e)),Promise.all(t).then(()=>{})}getTarget(){return this.target}getBindingData(){return this.bindingDataCache?this.bindingDataCache:(this.bindingDataCache={},this.parent&&Object.assign(this.bindingDataCache,this.parent.getDescendantBindingData()),this.bindingData&&Object.assign(this.bindingDataCache,this.bindingData),this.bindingDataCache)}getDescendantBindingData(){return this.descendantBindingDataCache?this.descendantBindingDataCache:(this.descendantBindingDataCache={...this.getBindingData()},this.derivedBindingData&&Object.assign(this.descendantBindingDataCache,this.derivedBindingData),this.descendantBindingDataCache)}getRawBindingData(){return this.bindingData}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(e){this.bindingData=e,this.clearBindingDataCache()}setDerivedBindingData(e){this.derivedBindingData=e,this.clearBindingDataCache()}setParent(e){this.parent!==e&&(this.parent=e,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(e=>{e instanceof K&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e}setListKey(e){this.listKey=e}getListKey(){return this.listKey}getRenderSignature(){return this.renderSignature}setRenderSignature(e){this.renderSignature=e}getEachInputSignature(){return this.eachInputSignature}setEachInputSignature(e){this.eachInputSignature=e}getDeriveSubtreeSignature(){return this.deriveSubtreeSignature}setDeriveSubtreeSignature(e){this.deriveSubtreeSignature=e}getDeriveInputSignature(){return this.deriveInputSignature}setDeriveInputSignature(e){this.deriveInputSignature=e}isFreshInitializationSkippable(){return this.freshInitializationSkippable}setFreshInitializationSkippable(e){this.freshInitializationSkippable=e}setValue(e){return this.applyValue(e,!0)}syncBindingValue(e){return this.applyValue(e,!1)}applyValue(e,t){if(this.skipChangeValue||this.value===e)return Promise.resolve();const r=this.getTarget();if(r instanceof HTMLInputElement&&(r.type==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),s=r.type==="checkbox"&&i==="true";let n;return s?n=e===!0||e==="true":i==="false"?n=e===!1:n=i===String(e),this.value=s?n:n?e:null,r.checked===n?Promise.resolve():(this.skipChangeValue=!0,M.enqueue(()=>{r.checked=n,t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else return r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement?(this.value=this.normalizeValueForElement(r,e),this.skipChangeValue=!0,M.enqueue(()=>{r.value=e===null?"":String(e),t&&((r instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(r.type)||r instanceof HTMLTextAreaElement)&&r.dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0})))}).finally(()=>{this.skipChangeValue=!1})):(p.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve())}getValue(){return this.value}clearValue(){this.value=null}normalizeValueForElement(e,t){if(e instanceof HTMLInputElement&&e.type==="number"){if(t===null||t==="")return null;const r=typeof t=="number"?t:Number(t);return Number.isNaN(r)?null:r}return t}syncValue(){const e=this.getTarget();if(e instanceof HTMLInputElement)if(e.type==="checkbox"||e.type==="radio"){const t=e.type==="checkbox"&&e.value==="true";if(e.checked){const r=e.value;t?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=e.value;t?this.value=!1:r==="false"?this.value=!0:this.value=null}}else this.value=this.normalizeValueForElement(e,e.value);else e instanceof HTMLTextAreaElement?this.value=e.value:e instanceof HTMLSelectElement&&(this.value=e.value)}setAttribute(e,t,r=!1){return this.setAttributeInternal(e,e,t,!0,r)}setAliasedAttribute(e,t,r,i=!1){return this.setAttributeInternal(e,t,r,!1,i)}removeAliasedAttribute(e,t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const r=this.getTarget();return M.enqueue(()=>{r.removeAttribute(e),t!==e&&r.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}setAttributeInternal(e,t,r,i,s=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const n=new _(e,r);if(s){const V=this.attributeMap.get(e);if(V&&(V.isEvaluate||V.isForceEvaluation())&&!n.isEvaluate&&!n.isForceEvaluation())return this.skipMutationAttributes=!0,M.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(e,n);const a=this.getTarget(),o=n.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:e,template:r}),c=n.isEvaluate||n.isRawEvaluate,d=e===t&&K.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),h=n.isSingleExpression(),g=j.joinEvaluateResults(o.results),v=o.results.length===1?o.results[0]:g,T=!n.isForceEvaluation()&&(t!==e||d||h?o.hasUnresolvedReference||v===null||v===void 0||v===!1:c&&g===""),b=n.isForceEvaluation()?r:h?v:g,y=i&&n.isEvaluate&&t==="value"&&(a instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(a.type)||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement),m=T||b===null||b===!1?null:String(b),A=e!==t&&a.getAttribute(e)!==r,F=m===null?a.hasAttribute(t):a.getAttribute(t)!==m,x=y&&m!==null&&a.value!==m;return!A&&!F&&!x?(y&&m!==null&&(this.value=m),Promise.resolve()):(this.skipMutationAttributes=!0,M.enqueue(()=>{A&&a.setAttribute(e,r),m===null?a.removeAttribute(t):(F&&a.setAttribute(t,m),y&&(this.value=m,x&&(a.value=m)))}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const t=this.getTarget();return M.enqueue(()=>{t.removeAttribute(e)}).finally(()=>{this.skipMutationAttributes=!1})}getAttribute(e){return this.getAttributeEvaluation(e)?.value??null}getAttributeEvaluation(e){const t=this.attributeMap.get(e);if(t===void 0)return null;const r=t.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:this.getTarget(),rawName:e,template:t.getValue()});return r.results.length===1?{value:r.results[0],hasUnresolvedReference:r.hasUnresolvedReference}:{value:j.joinEvaluateResults(r.results),hasUnresolvedReference:r.hasUnresolvedReference}}getRawAttribute(e){const t=this.attributeMap.get(e);return t===void 0?null:t.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(e){return this.attributeMap.has(e)}resolveInsertionPointFromDom(e,t){const r=e.getTarget();if(r.parentNode!==this.target)return null;const i=t?r.nextSibling:r;let s=t?r.nextSibling:r;for(;s!==null;){const n=w.get(s);if(n!==null){const a=this.children.indexOf(n);if(a!==-1)return{index:a,referenceNode:i}}s=s.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(e,t,r){if(this.skipMutationNodes)return Promise.resolve();if(e===this)return p.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let s=this.parent;for(;s;)i.add(s),s=s.getParent();if(i.has(e))return p.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const n=e.getParent()===this;let a=-1,o=-1;n&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const c=e.getParent();c!==null&&c.removeChild(e);let d=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let g;if(n?a!==-1&&a<o?g=o-1:g=o:g=this.children.indexOf(t),g===-1){const v=this.resolveInsertionPointFromDom(t,!1);v===null?(p.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(v.index,0,e),d=v.referenceNode)}else this.children.splice(g,0,e)}e.setParent(this),e.setMounted(this.mounted);const h=this.skipMutationNodes;return this.skipMutationNodes=!0,M.enqueue(()=>{this.target.insertBefore(e.getTarget(),d)}).finally(()=>{this.skipMutationNodes=h})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(p.warn("[Haori]","Reference child not found in children.",t),this.insertBefore(e,null)):this.insertBefore(e,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(e,this.children[r+1]||null)}getPrevious(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<=0?null:t[r-1]}getNext(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<0||r+1>=t.length?null:t[r+1]}isVisible(){return this.visible}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const e=this.getTarget();return this.display=e.style.getPropertyValue("display"),this.displayPriority=e.style.getPropertyPriority("display"),e.style.setProperty("display","none","important"),e.setAttribute(`${l.prefix}if-false`,""),Promise.resolve()}show(){if(this.visible)return Promise.resolve();const e=this.getTarget();return this.display===null||this.display===""?e.style.removeProperty("display"):e.style.setProperty("display",this.display,this.displayPriority??""),this.display=null,this.displayPriority=null,e.removeAttribute(`${l.prefix}if-false`),this.visible=!0,Promise.resolve()}closestByAttribute(e){if(this.hasAttribute(e))return this;const t=this.getParent();return t===null?null:t.closestByAttribute(e)}};K.BOOLEAN_ATTRIBUTES=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","hidden","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]);let I=K;class H extends w{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new j(this.text)}clone(){const e=new H(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e.contents=this.contents,e.renderedText=this.renderedText,e}getTarget(){return this.target}hasDynamicContent(){return this.contents.isEvaluate||this.contents.isRawEvaluate}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new j(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):M.enqueue(()=>{this.skipMutation=!0;let e=this.text;this.contents.isRawEvaluate?e=this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})[0]:this.contents.isEvaluate&&(e=j.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})));const t=this.contents.isRawEvaluate?this.parent.getTarget().innerHTML:this.target.textContent||"";this.renderedText===e&&t===e||(this.contents.isRawEvaluate?this.parent.getTarget().innerHTML=e:this.target.textContent=e,this.renderedText=e)}).finally(()=>{this.skipMutation=!1})}}class ae extends w{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new ae(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e}getTarget(){return this.target}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,M.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const te=class te{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(te.PLACEHOLDER_REGEX)];let r=0,i=!1,s=!1;for(const n of t){n.index>r&&this.contents.push({text:e.slice(r,n.index),type:0});const a={text:n[1]??n[2],type:n[1]?2:1};i=!0,s=s||a.type===2,this.contents.push(a),r=n.index+n[0].length}r<e.length&&this.contents.push({text:e.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=s,this.checkRawExpressions()}static joinEvaluateResults(e){return e===null||e.length===0?"":e.map(t=>t==null||t===!1||Number.isNaN(t)?"":typeof t!="string"?String(t):t).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(p.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const s=[],n=[];let a=0,o=!1;return this.contents.forEach(c=>{try{if(r(c)){const d=Z.measure(()=>X.evaluateDetailed(c.text,e)),h=d.value;a+=d.durationMs,n.push({expression:c.text,durationMs:d.durationMs}),o=o||h.unresolvedReference,s.push(h.value)}else s.push(c.text)}catch(d){p.error("[Haori]",`Error evaluating ${i} expression: ${c.text}`,d),n.push({expression:c.text,durationMs:0}),s.push("")}}),Z.record(t,n,a),{results:s,hasUnresolvedReference:o}}};te.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let j=te;const re=class re extends j{constructor(e,t){super(t),this.forceEvaluation=re.FORCE_EVALUATION_ATTRIBUTES.includes(e)}isForceEvaluation(){return this.forceEvaluation}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){if(!this.isEvaluate&&!this.forceEvaluation)return{results:this.contents.map(i=>i.text),hasUnresolvedReference:!1};const r=this.evaluateWithProfile(e,t,i=>this.forceEvaluation&&i.type===0||i.type===1||i.type===2,"attribute");return this.forceEvaluation&&r.results.length>1?(p.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};re.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let _=re;class D{static dispatch(e,t,r,i){const s=new CustomEvent(`haori:${t}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return e.dispatchEvent(s)}static ready(e){D.dispatch(document,"ready",{version:e})}static render(e){D.dispatch(e,"render",{target:e})}static importStart(e,t){D.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){D.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){D.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const s=[],n=new Set(Object.keys(t||{})),a=new Set(Object.keys(r)),o=new Set([...n,...a]);for(const c of o){const d=t?.[c],h=r[c];d!==h&&s.push(c)}D.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:s,reason:i})}static bindComplete(e,t=null,r="other"){D.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){D.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){D.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){D.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){D.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){D.dispatch(e,"show",{visible:!0})}static hide(e){D.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,s){D.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...s})}static fetchEnd(e,t,r,i){D.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,s){D.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:s?performance.now()-s:void 0})}}const Te=["addErrorMessage","closeDialog","confirm","dialog","openDialog","toast"],we="__haoriHistoryState__",oe="data-haori-click-lock";function le(){const e=globalThis.window?.Haori;return Te.every(r=>typeof e?.[r]=="function")?e:z}const De=new Set(["GET","HEAD","OPTIONS"]);function Re(E){return De.has(E.toUpperCase())}function Fe(E,e){for(const[t,r]of Object.entries(e))r!==void 0&&(r===null?E.append(t,""):Array.isArray(r)?r.forEach(i=>{E.append(t,String(i))}):typeof r=="object"||typeof r=="function"?E.append(t,JSON.stringify(r)):E.append(t,String(r)))}function Ne(E,e){const t=new URL(E,window.location.href),r=new URLSearchParams(t.search);return Fe(r,e),t.search=r.toString(),t.toString()}function Me(E){return E==null?null:typeof E=="string"?E:E instanceof URLSearchParams?E.toString():E instanceof FormData?Array.from(E.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(E)}function xe(E,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[s])=>i.localeCompare(s));return JSON.stringify({url:E,method:String(e.method||"GET").toUpperCase(),headers:r,body:Me(e.body||null)})}const f=class f{static attrName(e,t,r=!1){return e?`${l.prefix}${e}-${t}`:r?`${l.prefix}fetch-${t}`:`${l.prefix}${t}`}static resolveDataParamString(e,t){return f.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(f.DATA_PLACEHOLDER_REGEX,(s,n,a)=>{const o=X.evaluateDetailed(n??a??"",t);return r=r||o.unresolvedReference,o.value===null||o.value===void 0||Number.isNaN(o.value)?"":typeof o.value=="object"?encodeURIComponent(JSON.stringify(o.value)):encodeURIComponent(String(o.value))}),hasUnresolvedReference:r}}static isJsonStringContext(e,t){let r=!1,i=!1;for(let s=0;s<t;s+=1){const n=e[s];if(i){i=!1;continue}if(n==="\\"){i=!0;continue}n==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(e){if(e===void 0||Number.isNaN(e))return"null";try{return JSON.stringify(e)??JSON.stringify(String(e))}catch{return JSON.stringify(String(e))}}static stringifyJsonTemplateStringContent(e){if(e==null||Number.isNaN(e))return"";const t=typeof e=="object"?f.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return f.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(f.DATA_PLACEHOLDER_REGEX,(s,n,a,o)=>{const c=X.evaluateDetailed(n??a??"",t);return r=r||c.unresolvedReference,f.isJsonStringContext(e,o)?f.stringifyJsonTemplateStringContent(c.value):f.stringifyJsonTemplateValue(c.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return f.resolveDataAttributeDetailed(e,t).value}static resolveDataAttributeDetailed(e,t){const r=e.getRawAttribute(t),i=e.getAttributeEvaluation(t),s=i?.value??null,n=i?.hasUnresolvedReference??!1;if(s&&typeof s=="object"&&!Array.isArray(s))return{value:s,hasUnresolvedReference:n};if(typeof s!="string"||r===null)return{value:null,hasUnresolvedReference:n};const a=r.trim();if(f.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:P.parseDataBind(s),hasUnresolvedReference:n};if(a.startsWith("{")||a.startsWith("[")){const c=f.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:P.parseDataBind(c.value),hasUnresolvedReference:n||c.hasUnresolvedReference}}const o=f.resolveDataParamStringDetailed(r,e.getBindingData());return{value:P.parseDataBind(o.value),hasUnresolvedReference:n||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e};if(t){if(e.hasAttribute(f.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(f.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(f.attrName(t,"confirm")).replace(/\\n/g,`
7
7
  `)),e.hasAttribute(f.attrName(t,"data"))&&(r.dataAttrName=f.attrName(t,"data")),e.hasAttribute(f.attrName(t,"form"))){const y=e.getRawAttribute(f.attrName(t,"form"));if(y){const m=document.body.querySelector(y);m!==null?r.formFragment=S.getFormFragment(w.get(m)):p.error("Haori",`Form element not found: ${y} (${f.attrName(t,"form")})`)}else r.formFragment=S.getFormFragment(e)}else t==="change"&&(r.formFragment=S.getFormFragment(e));if(e.hasAttribute(`${l.prefix}${t}-before-run`)){const y=e.getRawAttribute(`${l.prefix}${t}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
8
8
  "use strict";
9
9
  ${y}
@@ -16,5 +16,5 @@ ${m}
16
16
  `)}catch(A){p.error("Haori",`Invalid after script: ${A}`)}}if(e.hasAttribute(f.attrName(t,"dialog"))&&(r.dialogMessage=e.getAttribute(f.attrName(t,"dialog")).replace(/\\n/g,`
17
17
  `)),e.hasAttribute(f.attrName(t,"toast"))){r.toastMessage=e.getAttribute(f.attrName(t,"toast"));const m=e.getRawAttribute(f.attrName(t,"toast-level")),F=["info","warning","error","success"].includes(m);r.toastLevel=F?m:null}if(e.hasAttribute(f.attrName(t,"redirect"))&&(r.redirectUrl=e.getAttribute(f.attrName(t,"redirect"))),e.hasAttribute(f.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(f.attrName(t,"scroll"))&&(r.scrollTarget=e.getAttribute(f.attrName(t,"scroll"))),e.hasAttribute(f.attrName(t,"history"))&&(r.historyUrl=e.getAttribute(f.attrName(t,"history"))),e.hasAttribute(f.attrName(t,"history-data"))&&(r.historyDataAttrName=f.attrName(t,"history-data")),e.hasAttribute(f.attrName(t,"history-form"))){const m=e.getRawAttribute(f.attrName(t,"history-form"));if(m){const A=document.body.querySelector(m);A!==null?r.historyFormFragment=S.getFormFragment(w.get(A)):p.error("Haori",`Form element not found: ${m} (${f.attrName(t,"history-form")})`)}else r.historyFormFragment=S.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(m=>{const A=f.attrName(t,m);if(!e.hasAttribute(A))return;const F=e.getRawAttribute(A),x=[];if(F?(document.body.querySelectorAll(F).forEach(U=>{const Y=w.get(U);Y&&x.push(Y)}),x.length===0&&p.error("Haori",`Element not found: ${F} (${A})`)):x.push(e),x.length>0)switch(m){case"reset-before":r.resetBeforeFragments=x;break;case"reset":r.resetFragments=x;break;case"refetch":r.refetchFragments=x;break;case"click":r.clickFragments=x;break;case"copy":r.copyFragments=x;break;case"open":r.openFragments=x;break;case"close":r.closeFragments=x;break}});const y=f.attrName(t,"copy-source");if(e.hasAttribute(y)){const m=e.getRawAttribute(y);if(m){const A=document.body.querySelector(m);if(A!==null){const F=w.get(A);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(f.attrName(null,"data",!0))&&(r.dataAttrName=f.attrName(null,"data",!0)),e.hasAttribute(f.attrName(null,"form",!0)))){const b=e.getRawAttribute(f.attrName(null,"form",!0));if(b){const y=document.body.querySelector(b);y!==null?r.formFragment=S.getFormFragment(w.get(y)):p.error("Haori",`Form element not found: ${b} (${f.attrName(null,"fetch-form",!0)})`)}else r.formFragment=S.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){f.isElementFragment(e)?(this.options=f.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static resolveAutoFetchSignature(e){return new f(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 d=this.options.targetFragment?.getTarget()??null;try{this.options.runScript.call(d,this.domEvent)===!1&&this.domEvent&&this.domEvent.preventDefault()}catch(h){p.error("Haori",`Run script execution error: ${h}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(d=>S.reset(d))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let s=r.url,n=r.options;if(this.options.beforeCallback){const d=this.options.beforeCallback(s||null,n||null);if(d!=null){if(d===!1||typeof d=="object"&&d.stop)return!1;typeof d=="object"&&(s="fetchUrl"in d?d.fetchUrl:s,n="fetchOptions"in d?d.fetchOptions:n)}}const a=Object.keys(i).length>0;if(s){const d={...n||{}},h=r.requestedMethod,g=r.effectiveMethod,v=r.transportMode==="query-get",T=r.queryString;if(v&&p.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:h,effectiveMethod:g,transportMode:"query-get",url:s,payload:a?i:void 0,queryString:T}),this.options.targetFragment&&s){const b=performance.now(),y={runtime:l.runtime,requestedMethod:h,effectiveMethod:g,transportMode:v?"query-get":"http",...v?{queryString:T}:{}};return D.fetchStart(this.options.targetFragment.getTarget(),s,d,a?i:void 0,y),fetch(s,d).then(m=>this.handleFetchResult(m,s||void 0,b)).catch(m=>{throw s&&D.fetchError(this.options.targetFragment.getTarget(),s,m),m})}return fetch(s,d).then(b=>this.handleFetchResult(b,s||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const d=this.options.formFragment,h=d.getTarget(),g=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&g.add(this.options.targetFragment),h.setAttribute(`${l.prefix}bind`,JSON.stringify(i));const v=d.getBindingData();Object.assign(v,i),await P.setBindingData(h,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(f.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(oe))return!1;const r=t.hasAttribute(`${l.prefix}click-no-disabled`);return f.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(oe,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(f.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(oe),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=le();if(!e.ok)return this.options.targetFragment&&t&&D.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&&D.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=>S.reset(a))),await this.copy();const n=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{n.push(new f(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[d,h]of Object.entries(c))h!=null&&(Array.isArray(h)?h.forEach(g=>a.searchParams.append(d,String(g))):typeof h=="object"?a.searchParams.set(d,JSON.stringify(h)):a.searchParams.set(d,String(h)))};i&&o(t),s&&o(r),history.pushState({[we]:!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=S.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=async n=>{const a=t?t.getTarget():document.body;await le().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 S.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):le().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=>{D.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"?S.getValues(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?S.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,S.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=f.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"&&!Re(a),c=o?"GET":a;if(s.method=c,c==="GET"||c==="HEAD"||c==="OPTIONS")Object.keys(t).length>0&&(i=Ne(i,t));else if(Object.keys(t).length>0){const h=n.get("Content-Type")||"";if(/multipart\/form-data/i.test(h)){n.delete("Content-Type");const g=new FormData;for(const[v,T]of Object.entries(t))T==null?g.append(v,""):T instanceof Blob?g.append(v,T):Array.isArray(T)?T.forEach(b=>g.append(v,String(b))):typeof T=="object"?g.append(v,JSON.stringify(T)):g.append(v,String(T));s.body=g}else if(/application\/x-www-form-urlencoded/i.test(h)){const g=new URLSearchParams;for(const[v,T]of Object.entries(t))T!==void 0&&(T===null?g.append(v,""):Array.isArray(T)?T.forEach(b=>g.append(v,String(b))):typeof T=="object"?g.append(v,JSON.stringify(T)):g.append(v,String(T)));s.body=g}else n.set("Content-Type","application/json"),s.body=JSON.stringify(t)}s.headers=n;let d;return o&&(d=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:d,transportMode:o?"query-get":"http",signature:xe(i,s)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=f.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?S.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?f.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return S.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(S.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()}};f.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,f.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,f.RUNNING_CLICK_TARGETS=new WeakSet;let q=f;class Pe{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,s)=>{e[s]=i}),e}}class Ie{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 I?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 I?t.push(u.evaluateAll(r)):r instanceof H&&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 I&&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`,""),D.importStart(t,s),Ie.load(s).then(a=>{const o=new TextEncoder().encode(a).length;return M.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${l.prefix}importing`),D.importEnd(t,s,o,n),!document.body.hasAttribute("data-haori-ready")){const c=[];return t.childNodes.forEach(d=>{const h=w.get(d);h instanceof I?c.push(u.scan(h.getTarget())):h instanceof H&&c.push(u.evaluateText(h))}),Promise.all(c).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${l.prefix}importing`),D.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 I?r.push(u.initializeElementFragment(i,t)):i instanceof H&&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 d=s.getAttribute(`${l.prefix}url-arg`),h=Pe.readParams();if(d===null)a.push(u.setBindingData(e,h));else{const g=s.getRawBindingData()||{};g[String(d)]=h,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(d=>{if(d)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(()=>S.syncValues(i,o))}return n=n.then(()=>u.evaluateAll(i,r)),n=n.then(()=>u.reevaluateReactiveSpecialAttributes(i,r)),D.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 d=c.getTarget();return d.id?`#${d.id}`:d.tagName.toLowerCase()},n=(c,d,h,g)=>{if(c)for(const v of Object.keys(c))v in i||(i[v]={value:c[v],source:s(d),kind:h,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 B.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 I?u.scan(s.getTarget()):s instanceof H&&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=S.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,d=!1,h=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}h=u.createDescendantBindingSignature(e,"evaluateAll"),d=!0,c=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===h,u.logDerivedSubtreeProfileSnapshot(e,c?"skip-hit":"skip-miss")})),r.then(()=>{if(c)return;const g=[];return e.getChildren().forEach(v=>{if(v instanceof I){if(u.canSkipUnchangedNestedEach(v))return;g.push(u.evaluateAll(v,t))}else v instanceof H&&g.push(u.evaluateText(v))}),Promise.all(g).then(()=>{})}).then(()=>{d&&h!==null&&e.setDeriveSubtreeSignature(h)}))}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=X.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))B.isEnabled()&&u.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{D.hide(e.getTarget())}));else{const i=e.isVisible(),s=[];e.getChildren().forEach(n=>{n instanceof I?s.push(n.isMounted()?u.evaluateAll(n):u.scan(n.getTarget())):n instanceof H&&s.push(u.evaluateText(n))}),t.push(e.show().then(()=>{D.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 I){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 h=w.get(c);h instanceof I&&(r=h.clone(),u.markFreshInitializationSkippable(r),e.setTemplate(r),n=!0)}const d=w.get(c);d instanceof I&&e.getChildren().includes(d)&&(e.removeChild(d),d.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 I?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(!B.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 I).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 H&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(s=>u.isFreshInitializationDynamicAttribute(e,s)),r=e.getChildren().some(s=>s instanceof I?!u.markFreshInitializationSkippable(s):s instanceof H?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((A,F)=>{const x=u.createListKey(A,s?String(s):null,F);o.push(x),a.set(x,{item:A,itemIndex:F})});const c=new Set(o),d=[];let h=e.getChildren().filter(A=>A instanceof I).filter(A=>!A.hasAttribute(`${l.prefix}each-before`)&&!A.hasAttribute(`${l.prefix}each-after`));const g=h.map(A=>A.getListKey());h=h.filter(A=>c.has(String(A.getListKey()))?!0:(d.push(A.remove()),!1));const v=h.map(A=>A.getListKey()),T=new Map;h.forEach(A=>{const F=A.getListKey();F!==null&&!T.has(F)&&T.set(F,A)});const b=e.getChildElementFragments().slice(),y=b.filter(A=>A.hasAttribute(`${l.prefix}each-before`)).length;let m=Promise.resolve();return o.forEach((A,F)=>{const{item:x,itemIndex:V}=a.get(A);let U;const Y=T.get(A);if(Y)U=Y,m=m.then(()=>u.updateRowFragment(U,x,i,V,n?String(n):null,A).then(k=>{if(k)return u.evaluateAll(U)}));else{U=r.clone();const k=y+F;m=m.then(()=>u.updateRowFragment(U,x,i,V,n?String(n):null,A).then(()=>{const Oe=b[k]??null;return e.insertBefore(U,Oe).then(()=>{b.splice(k,0,U)}).then(()=>u.initializeFreshEachRow(U))}))}}),Promise.all(d).then(()=>m).then(()=>{const A=o.filter(k=>k!==null),F=v.filter(k=>k!==null),x=new Set(F),V=A.filter(k=>!x.has(k)),Y=g.filter(k=>k!==null).filter(k=>!c.has(k));D.eachUpdate(e.getTarget(),V,Y,A)})}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 ie=class ie{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[ie.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;r.hasAttribute(`data-${t}-prevent`)&&e.preventDefault();const i=w.get(r);if(!i)return;t==="change"&&i instanceof I&&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}};ie.HISTORY_STATE_KEY="__haoriHistoryState__";let ue=ie;const R=class R{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)&&(R.isHtmlElement(e)&&R.syncElement(e),e.querySelectorAll("*").forEach(t=>{R.syncElement(t)}))}static syncElement(e){const t=R.registrations.get(e),r=w.get(e);if(!r||!R.shouldObserve(r)){t&&(t.observer.disconnect(),R.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=R.resolveRoot(r),s=R.resolveRootMargin(r),n=R.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===s&&R.sameThreshold(t.observer.thresholds,n)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),R.registrations.delete(e));const o=new IntersectionObserver(c=>{const d=R.registrations.get(e);d&&c.forEach(h=>{!h.isIntersecting||d.running||R.isDisabled(d.fragment)||(d.running=!0,new q(d.fragment,"intersect").runWithResult().then(g=>{g&&d.once&&(d.observer.disconnect(),R.registrations.delete(e))}).catch(g=>{p.error("[Haori]","Intersect procedure execution error:",g)}).finally(()=>{const g=R.registrations.get(e);g&&(g.running=!1)}))})},{root:i,rootMargin:s,threshold:n});o.observe(e),R.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(R.isHtmlElement(e)){const t=R.registrations.get(e);t&&(t.observer.disconnect(),R.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=R.registrations.get(t);r&&(r.observer.disconnect(),R.registrations.delete(t))})}static disconnectAll(){R.registrations.forEach(e=>{e.observer.disconnect()}),R.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!R.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 R.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}};R.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),R.registrations=new Map;let Q=R;const $=class ${static disconnectMutationObservers(){$._mutationObservers.forEach(e=>{e.disconnect()}),$._mutationObservers.length=0}static async init(){if($._initialized)return;$._initialized=!0,$.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",""),$.observe(document.head),$.observe(document.body),new ue().start(),Q.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),Q.syncElement(s);break}case"childList":{Array.from(i.removedNodes).forEach(s=>{Q.cleanupTree(s),P.removeNode(s)}),Array.from(i.addedNodes).forEach(s=>{s.parentElement instanceof Element&&(P.addNode(s.parentElement,s),Q.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}),$._mutationObservers.push(t)}};$._initialized=!1,$._mutationObservers=[];let ee=$;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ee.init):ee.init();const Ce=()=>z.waitForRenders(),ke="0.12.0";return O.Core=P,O.Env=l,O.Form=S,O.Fragment=w,O.Haori=z,O.Log=p,O.Queue=M,O.default=z,O.version=ke,O.waitForRenders=Ce,Object.defineProperties(O,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),O}({});
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 S.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):le().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=>{D.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"?S.getValues(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?S.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,S.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=f.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"&&!Re(a),c=o?"GET":a;if(s.method=c,c==="GET"||c==="HEAD"||c==="OPTIONS")Object.keys(t).length>0&&(i=Ne(i,t));else if(Object.keys(t).length>0){const h=n.get("Content-Type")||"";if(/multipart\/form-data/i.test(h)){n.delete("Content-Type");const g=new FormData;for(const[v,T]of Object.entries(t))T==null?g.append(v,""):T instanceof Blob?g.append(v,T):Array.isArray(T)?T.forEach(b=>g.append(v,String(b))):typeof T=="object"?g.append(v,JSON.stringify(T)):g.append(v,String(T));s.body=g}else if(/application\/x-www-form-urlencoded/i.test(h)){const g=new URLSearchParams;for(const[v,T]of Object.entries(t))T!==void 0&&(T===null?g.append(v,""):Array.isArray(T)?T.forEach(b=>g.append(v,String(b))):typeof T=="object"?g.append(v,JSON.stringify(T)):g.append(v,String(T)));s.body=g}else n.set("Content-Type","application/json"),s.body=JSON.stringify(t)}s.headers=n;let d;return o&&(d=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:d,transportMode:o?"query-get":"http",signature:xe(i,s)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=f.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?S.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?f.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return S.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(S.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()}};f.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,f.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,f.RUNNING_CLICK_TARGETS=new WeakSet;let q=f;class Pe{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,s)=>{e[s]=i}),e}}class Ie{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 I?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 I?t.push(u.evaluateAll(r)):r instanceof H&&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 I&&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`,""),D.importStart(t,s),Ie.load(s).then(a=>{const o=new TextEncoder().encode(a).length;return M.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${l.prefix}importing`),D.importEnd(t,s,o,n),!document.body.hasAttribute("data-haori-ready")){const c=[];return t.childNodes.forEach(d=>{const h=w.get(d);h instanceof I?c.push(u.scan(h.getTarget())):h instanceof H&&c.push(u.evaluateText(h))}),Promise.all(c).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${l.prefix}importing`),D.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 I?r.push(u.initializeElementFragment(i,t)):i instanceof H&&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 d=s.getAttribute(`${l.prefix}url-arg`),h=Pe.readParams();if(d===null)a.push(u.setBindingData(e,h));else{const g=s.getRawBindingData()||{};g[String(d)]=h,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(d=>{if(d)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(()=>S.syncValues(i,o))}return n=n.then(()=>u.evaluateAll(i,r)),n=n.then(()=>u.reevaluateReactiveSpecialAttributes(i,r)),D.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 d=c.getTarget();return d.id?`#${d.id}`:d.tagName.toLowerCase()},n=(c,d,h,g)=>{if(c)for(const v of Object.keys(c))v in i||(i[v]={value:c[v],source:s(d),kind:h,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 B.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 I?u.scan(s.getTarget()):s instanceof H&&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=S.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,d=!1,h=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}h=u.createDescendantBindingSignature(e,"evaluateAll"),d=!0,c=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===h,u.logDerivedSubtreeProfileSnapshot(e,c?"skip-hit":"skip-miss")})),r.then(()=>{if(c)return;const g=[];return e.getChildren().forEach(v=>{if(v instanceof I){if(u.canSkipUnchangedNestedEach(v))return;g.push(u.evaluateAll(v,t))}else v instanceof H&&g.push(u.evaluateText(v))}),Promise.all(g).then(()=>{})}).then(()=>{d&&h!==null&&e.setDeriveSubtreeSignature(h)}))}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=X.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))B.isEnabled()&&u.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{D.hide(e.getTarget())}));else{const i=e.isVisible(),s=[];e.getChildren().forEach(n=>{n instanceof I?s.push(n.isMounted()?u.evaluateAll(n):u.scan(n.getTarget())):n instanceof H&&s.push(u.evaluateText(n))}),t.push(e.show().then(()=>{D.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 I){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 h=w.get(c);h instanceof I&&(r=h.clone(),u.markFreshInitializationSkippable(r),e.setTemplate(r),n=!0)}const d=w.get(c);d instanceof I&&e.getChildren().includes(d)&&(e.removeChild(d),d.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 I?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(!B.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 I).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 H&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(s=>u.isFreshInitializationDynamicAttribute(e,s)),r=e.getChildren().some(s=>s instanceof I?!u.markFreshInitializationSkippable(s):s instanceof H?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((A,F)=>{const x=u.createListKey(A,s?String(s):null,F);o.push(x),a.set(x,{item:A,itemIndex:F})});const c=new Set(o),d=[];let h=e.getChildren().filter(A=>A instanceof I).filter(A=>!A.hasAttribute(`${l.prefix}each-before`)&&!A.hasAttribute(`${l.prefix}each-after`));const g=h.map(A=>A.getListKey());h=h.filter(A=>c.has(String(A.getListKey()))?!0:(d.push(A.remove()),!1));const v=h.map(A=>A.getListKey()),T=new Map;h.forEach(A=>{const F=A.getListKey();F!==null&&!T.has(F)&&T.set(F,A)});const b=e.getChildElementFragments().slice(),y=b.filter(A=>A.hasAttribute(`${l.prefix}each-before`)).length;let m=Promise.resolve();return o.forEach((A,F)=>{const{item:x,itemIndex:V}=a.get(A);let U;const Y=T.get(A);if(Y)U=Y,m=m.then(()=>u.updateRowFragment(U,x,i,V,n?String(n):null,A).then(k=>{if(k)return u.evaluateAll(U)}));else{U=r.clone();const k=y+F;m=m.then(()=>u.updateRowFragment(U,x,i,V,n?String(n):null,A).then(()=>{const Oe=b[k]??null;return e.insertBefore(U,Oe).then(()=>{b.splice(k,0,U)}).then(()=>u.initializeFreshEachRow(U))}))}}),Promise.all(d).then(()=>m).then(()=>{const A=o.filter(k=>k!==null),F=v.filter(k=>k!==null),x=new Set(F),V=A.filter(k=>!x.has(k)),Y=g.filter(k=>k!==null).filter(k=>!c.has(k));D.eachUpdate(e.getTarget(),V,Y,A)})}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 ie=class ie{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[ie.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;r.hasAttribute(`data-${t}-prevent`)&&e.preventDefault();const i=w.get(r);if(!i)return;t==="change"&&i instanceof I&&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}};ie.HISTORY_STATE_KEY="__haoriHistoryState__";let ue=ie;const R=class R{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)&&(R.isHtmlElement(e)&&R.syncElement(e),e.querySelectorAll("*").forEach(t=>{R.syncElement(t)}))}static syncElement(e){const t=R.registrations.get(e),r=w.get(e);if(!r||!R.shouldObserve(r)){t&&(t.observer.disconnect(),R.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=R.resolveRoot(r),s=R.resolveRootMargin(r),n=R.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===s&&R.sameThreshold(t.observer.thresholds,n)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),R.registrations.delete(e));const o=new IntersectionObserver(c=>{const d=R.registrations.get(e);d&&c.forEach(h=>{!h.isIntersecting||d.running||R.isDisabled(d.fragment)||(d.running=!0,new q(d.fragment,"intersect").runWithResult().then(g=>{g&&d.once&&(d.observer.disconnect(),R.registrations.delete(e))}).catch(g=>{p.error("[Haori]","Intersect procedure execution error:",g)}).finally(()=>{const g=R.registrations.get(e);g&&(g.running=!1)}))})},{root:i,rootMargin:s,threshold:n});o.observe(e),R.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(R.isHtmlElement(e)){const t=R.registrations.get(e);t&&(t.observer.disconnect(),R.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=R.registrations.get(t);r&&(r.observer.disconnect(),R.registrations.delete(t))})}static disconnectAll(){R.registrations.forEach(e=>{e.observer.disconnect()}),R.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!R.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 R.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}};R.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),R.registrations=new Map;let Q=R;const $=class ${static disconnectMutationObservers(){$._mutationObservers.forEach(e=>{e.disconnect()}),$._mutationObservers.length=0}static async init(){if($._initialized)return;$._initialized=!0,$.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",""),$.observe(document.head),$.observe(document.body),new ue().start(),Q.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),Q.syncElement(s);break}case"childList":{Array.from(i.removedNodes).forEach(s=>{Q.cleanupTree(s),P.removeNode(s)}),Array.from(i.addedNodes).forEach(s=>{s.parentElement instanceof Element&&(P.addNode(s.parentElement,s),Q.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}),$._mutationObservers.push(t)}};$._initialized=!1,$._mutationObservers=[];let ee=$;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ee.init):ee.init();const Ce=()=>z.waitForRenders(),ke="0.13.1";return O.Core=P,O.Env=l,O.Form=S,O.Fragment=w,O.Haori=z,O.Log=p,O.Queue=M,O.default=z,O.version=ke,O.waitForRenders=Ce,Object.defineProperties(O,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),O}({});
20
20
  //# sourceMappingURL=haori.iife.js.map
package/dist/index.d.ts CHANGED
@@ -818,6 +818,18 @@ declare class ElementFragment extends Fragment {
818
818
  * 内部の値をクリアします。エレメントのvalue値は変化しません。
819
819
  */
820
820
  clearValue(): void;
821
+ /**
822
+ * 入力要素の種別に応じて値を正規化します。
823
+ *
824
+ * `type="number"` の input では、文字列の入力値・バインド値を数値へ変換します
825
+ * (DTO が数値型を期待する場合に文字列で送られるのを防ぐため)。空文字・null・
826
+ * 数値化できない値は `null` を返します。それ以外の要素では値をそのまま返します。
827
+ *
828
+ * @param element 対象の入力要素
829
+ * @param value 正規化する値
830
+ * @returns 正規化後の値(`type="number"` なら数値または null)
831
+ */
832
+ private normalizeValueForElement;
821
833
  /**
822
834
  * 内部の値をDOMの値と同期します。
823
835
  * changeイベント時など、DOM値が変更された後に呼び出されます。
@@ -1531,7 +1543,7 @@ declare class TextFragment extends Fragment {
1531
1543
  evaluate(): Promise<void>;
1532
1544
  }
1533
1545
 
1534
- export declare const version = "0.12.0";
1546
+ export declare const version = "0.13.1";
1535
1547
 
1536
1548
  /**
1537
1549
  * すべてのレンダリングタスク(追従投入分を含む)の完了を待ちます。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "haori",
3
- "version": "0.12.0",
3
+ "version": "0.13.1",
4
4
  "description": "A lightweight HTML-first UI engine powered by declarative data bindings and expressions.",
5
5
  "scripts": {
6
6
  "dev": "vite",
@@ -41,13 +41,21 @@
41
41
  "type": "module",
42
42
  "exports": {
43
43
  ".": {
44
- "import": "./dist/haori.js"
44
+ "types": "./dist/index.d.ts",
45
+ "import": "./dist/haori.es.js",
46
+ "require": "./dist/haori.cjs.js"
45
47
  }
46
48
  },
47
49
  "main": "dist/haori.es.js",
50
+ "module": "dist/haori.es.js",
51
+ "unpkg": "dist/haori.iife.js",
52
+ "jsdelivr": "dist/haori.iife.js",
48
53
  "types": "./dist/index.d.ts",
49
54
  "files": [
50
- "dist"
55
+ "dist/haori.es.js",
56
+ "dist/haori.cjs.js",
57
+ "dist/haori.iife.js",
58
+ "dist/index.d.ts"
51
59
  ],
52
60
  "bugs": {
53
61
  "url": "https://github.com/meibinlab/haori-js/issues"