@hyperfixi/core 2.0.0

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 (381) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +218 -0
  3. package/dist/__test-utils__/context-builders.d.ts +42 -0
  4. package/dist/__test-utils__/error-testing.d.ts +18 -0
  5. package/dist/__test-utils__/index.d.ts +6 -0
  6. package/dist/__test-utils__/mock-types.d.ts +57 -0
  7. package/dist/__test-utils__/parser-context-mock.d.ts +7 -0
  8. package/dist/__test-utils__/parser-helpers.d.ts +38 -0
  9. package/dist/api/dom-processor.d.ts +17 -0
  10. package/dist/api/hyperscript-api.d.ts +68 -0
  11. package/dist/api/lokascript-api.d.ts +9 -0
  12. package/dist/ast-utils/analyzer.d.ts +19 -0
  13. package/dist/ast-utils/documentation.d.ts +8 -0
  14. package/dist/ast-utils/generator.d.ts +9 -0
  15. package/dist/ast-utils/index.d.ts +12 -0
  16. package/dist/ast-utils/index.js +3366 -0
  17. package/dist/ast-utils/index.mjs +3320 -0
  18. package/dist/ast-utils/interchange/from-core.d.ts +8 -0
  19. package/dist/ast-utils/interchange/index.d.ts +6 -0
  20. package/dist/ast-utils/interchange/lsp.d.ts +108 -0
  21. package/dist/ast-utils/interchange/to-core.d.ts +8 -0
  22. package/dist/ast-utils/interchange/types.d.ts +113 -0
  23. package/dist/ast-utils/query.d.ts +25 -0
  24. package/dist/ast-utils/transformer.d.ts +14 -0
  25. package/dist/ast-utils/types.d.ts +162 -0
  26. package/dist/ast-utils/visitor.d.ts +40 -0
  27. package/dist/behaviors/boosted.d.ts +29 -0
  28. package/dist/behaviors/history-swap.d.ts +24 -0
  29. package/dist/behaviors/index.d.ts +4 -0
  30. package/dist/behaviors/index.js +1149 -0
  31. package/dist/behaviors/index.mjs +1139 -0
  32. package/dist/bundle-generator/generator.d.ts +4 -0
  33. package/dist/bundle-generator/index.d.ts +6 -0
  34. package/dist/bundle-generator/index.js +2294 -0
  35. package/dist/bundle-generator/index.mjs +2271 -0
  36. package/dist/bundle-generator/parser-templates.d.ts +6 -0
  37. package/dist/bundle-generator/template-capabilities.d.ts +10 -0
  38. package/dist/bundle-generator/templates.d.ts +11 -0
  39. package/dist/bundle-generator/types.d.ts +34 -0
  40. package/dist/bundles/test-minimal.d.ts +3 -0
  41. package/dist/bundles/test-standard.d.ts +3 -0
  42. package/dist/chunks/bridge-I6ceoWxV.js +2 -0
  43. package/dist/chunks/browser-modular-Dv6PAV3c.js +2 -0
  44. package/dist/chunks/feature-eventsource-DWb514fy.js +2 -0
  45. package/dist/chunks/feature-sockets-3PFuvCVY.js +2 -0
  46. package/dist/chunks/feature-webworker-DTm_eh-E.js +2 -0
  47. package/dist/commands/advanced/async.d.ts +28 -0
  48. package/dist/commands/advanced/js.d.ts +28 -0
  49. package/dist/commands/animation/measure.d.ts +31 -0
  50. package/dist/commands/animation/settle.d.ts +26 -0
  51. package/dist/commands/animation/take.d.ts +28 -0
  52. package/dist/commands/animation/transition.d.ts +31 -0
  53. package/dist/commands/async/fetch.d.ts +44 -0
  54. package/dist/commands/async/wait.d.ts +41 -0
  55. package/dist/commands/behaviors/install.d.ts +41 -0
  56. package/dist/commands/content/append.d.ts +27 -0
  57. package/dist/commands/control-flow/break.d.ts +15 -0
  58. package/dist/commands/control-flow/continue.d.ts +15 -0
  59. package/dist/commands/control-flow/exit.d.ts +15 -0
  60. package/dist/commands/control-flow/halt.d.ts +25 -0
  61. package/dist/commands/control-flow/if.d.ts +45 -0
  62. package/dist/commands/control-flow/repeat.d.ts +35 -0
  63. package/dist/commands/control-flow/return.d.ts +23 -0
  64. package/dist/commands/control-flow/signal-base.d.ts +25 -0
  65. package/dist/commands/control-flow/throw.d.ts +22 -0
  66. package/dist/commands/control-flow/unless.d.ts +3 -0
  67. package/dist/commands/data/decrement.d.ts +3 -0
  68. package/dist/commands/data/default.d.ts +31 -0
  69. package/dist/commands/data/get.d.ts +23 -0
  70. package/dist/commands/data/increment.d.ts +25 -0
  71. package/dist/commands/data/set.d.ts +56 -0
  72. package/dist/commands/decorators/index.d.ts +30 -0
  73. package/dist/commands/dom/__tests__/add-standalone-helpers.d.ts +11 -0
  74. package/dist/commands/dom/add.d.ts +31 -0
  75. package/dist/commands/dom/dom-modification-base.d.ts +48 -0
  76. package/dist/commands/dom/hide.d.ts +12 -0
  77. package/dist/commands/dom/make.d.ts +21 -0
  78. package/dist/commands/dom/process-partials.d.ts +39 -0
  79. package/dist/commands/dom/put.d.ts +31 -0
  80. package/dist/commands/dom/remove.d.ts +33 -0
  81. package/dist/commands/dom/show.d.ts +13 -0
  82. package/dist/commands/dom/swap.d.ts +38 -0
  83. package/dist/commands/dom/toggle.d.ts +55 -0
  84. package/dist/commands/dom/visibility-base.d.ts +20 -0
  85. package/dist/commands/events/send.d.ts +3 -0
  86. package/dist/commands/events/trigger.d.ts +36 -0
  87. package/dist/commands/execution/call.d.ts +24 -0
  88. package/dist/commands/execution/pseudo-command.d.ts +42 -0
  89. package/dist/commands/helpers/attribute-manipulation.d.ts +11 -0
  90. package/dist/commands/helpers/batch-dom-operations.d.ts +12 -0
  91. package/dist/commands/helpers/class-manipulation.d.ts +11 -0
  92. package/dist/commands/helpers/condition-helpers.d.ts +4 -0
  93. package/dist/commands/helpers/dom-mutation.d.ts +15 -0
  94. package/dist/commands/helpers/duration-parsing.d.ts +8 -0
  95. package/dist/commands/helpers/element-property-access.d.ts +7 -0
  96. package/dist/commands/helpers/element-resolution.d.ts +17 -0
  97. package/dist/commands/helpers/error-helpers.d.ts +17 -0
  98. package/dist/commands/helpers/event-helpers.d.ts +13 -0
  99. package/dist/commands/helpers/event-waiting.d.ts +37 -0
  100. package/dist/commands/helpers/index.d.ts +32 -0
  101. package/dist/commands/helpers/input-validator.d.ts +23 -0
  102. package/dist/commands/helpers/loop-executor.d.ts +53 -0
  103. package/dist/commands/helpers/numeric-target-parser.d.ts +14 -0
  104. package/dist/commands/helpers/property-target.d.ts +30 -0
  105. package/dist/commands/helpers/selector-type-detection.d.ts +24 -0
  106. package/dist/commands/helpers/smart-element.d.ts +16 -0
  107. package/dist/commands/helpers/style-manipulation.d.ts +16 -0
  108. package/dist/commands/helpers/temporal-modifiers.d.ts +15 -0
  109. package/dist/commands/helpers/url-argument-parser.d.ts +10 -0
  110. package/dist/commands/helpers/url-validation.d.ts +7 -0
  111. package/dist/commands/helpers/variable-access.d.ts +10 -0
  112. package/dist/commands/helpers/visibility-target-parser.d.ts +11 -0
  113. package/dist/commands/index.d.ts +139 -0
  114. package/dist/commands/index.js +9186 -0
  115. package/dist/commands/index.mjs +9032 -0
  116. package/dist/commands/navigation/go.d.ts +35 -0
  117. package/dist/commands/navigation/push-url.d.ts +35 -0
  118. package/dist/commands/navigation/replace-url.d.ts +3 -0
  119. package/dist/commands/templates/render.d.ts +48 -0
  120. package/dist/commands/utility/beep.d.ts +32 -0
  121. package/dist/commands/utility/copy.d.ts +29 -0
  122. package/dist/commands/utility/log.d.ts +24 -0
  123. package/dist/commands/utility/pick.d.ts +26 -0
  124. package/dist/commands/utility/tell.d.ts +26 -0
  125. package/dist/compatibility/browser-bundle-animation-generated.d.ts +16 -0
  126. package/dist/compatibility/browser-bundle-classic-i18n.d.ts +63 -0
  127. package/dist/compatibility/browser-bundle-classic.d.ts +17 -0
  128. package/dist/compatibility/browser-bundle-forms-generated.d.ts +16 -0
  129. package/dist/compatibility/browser-bundle-hybrid-complete.d.ts +28 -0
  130. package/dist/compatibility/browser-bundle-hybrid-hx.d.ts +43 -0
  131. package/dist/compatibility/browser-bundle-lite-plus.d.ts +25 -0
  132. package/dist/compatibility/browser-bundle-lite.d.ts +23 -0
  133. package/dist/compatibility/browser-bundle-minimal-generated.d.ts +16 -0
  134. package/dist/compatibility/browser-bundle-minimal-v2.d.ts +17 -0
  135. package/dist/compatibility/browser-bundle-minimal.d.ts +8 -0
  136. package/dist/compatibility/browser-bundle-modular.d.ts +18 -0
  137. package/dist/compatibility/browser-bundle-multilingual.d.ts +19 -0
  138. package/dist/compatibility/browser-bundle-semantic-complete.d.ts +24 -0
  139. package/dist/compatibility/browser-bundle-standard-v2.d.ts +17 -0
  140. package/dist/compatibility/browser-bundle-standard.d.ts +8 -0
  141. package/dist/compatibility/browser-bundle-textshelf-minimal.d.ts +16 -0
  142. package/dist/compatibility/browser-bundle-textshelf-profile.d.ts +18 -0
  143. package/dist/compatibility/browser-bundle.d.ts +140 -0
  144. package/dist/compatibility/browser-modular.d.ts +53 -0
  145. package/dist/compatibility/browser-tests/test-utils.d.ts +21 -0
  146. package/dist/compatibility/eval-hyperscript.d.ts +15 -0
  147. package/dist/compatibility/feature-loader.d.ts +8 -0
  148. package/dist/compatibility/hyperscript-adapter.d.ts +38 -0
  149. package/dist/compatibility/hyperscript-tests/test-adapter.d.ts +13 -0
  150. package/dist/core/ast-property-utils.d.ts +2 -0
  151. package/dist/core/base-expression-evaluator.d.ts +70 -0
  152. package/dist/core/binary-expression-evaluator.d.ts +7 -0
  153. package/dist/core/call-expression-evaluator.d.ts +7 -0
  154. package/dist/core/configurable-expression-evaluator.d.ts +5 -0
  155. package/dist/core/context.d.ts +15 -0
  156. package/dist/core/dom.d.ts +15 -0
  157. package/dist/core/evaluator-types.d.ts +5 -0
  158. package/dist/core/events.d.ts +48 -0
  159. package/dist/core/executor.d.ts +34 -0
  160. package/dist/core/expression-evaluator.d.ts +6 -0
  161. package/dist/core/lazy-expression-evaluator.d.ts +22 -0
  162. package/dist/core/parser.d.ts +21 -0
  163. package/dist/core/selector-evaluator.d.ts +15 -0
  164. package/dist/core/template-literal-evaluator.d.ts +5 -0
  165. package/dist/dom/attribute-processor.d.ts +40 -0
  166. package/dist/dom/minimal-attribute-processor.d.ts +20 -0
  167. package/dist/experimental/binary-tree/accessor.d.ts +10 -0
  168. package/dist/experimental/binary-tree/ast-serializer.d.ts +26 -0
  169. package/dist/experimental/binary-tree/benchmark.d.ts +24 -0
  170. package/dist/experimental/binary-tree/buffer-context.d.ts +27 -0
  171. package/dist/experimental/binary-tree/deserializer.d.ts +17 -0
  172. package/dist/experimental/binary-tree/index.d.ts +22 -0
  173. package/dist/experimental/binary-tree/serializer.d.ts +4 -0
  174. package/dist/experimental/binary-tree/types.d.ts +54 -0
  175. package/dist/expressions/base-expression.d.ts +27 -0
  176. package/dist/expressions/bundles/common-expressions.d.ts +9 -0
  177. package/dist/expressions/bundles/core-expressions.d.ts +7 -0
  178. package/dist/expressions/bundles/full-expressions.d.ts +10 -0
  179. package/dist/expressions/bundles/index.d.ts +7 -0
  180. package/dist/expressions/comparison/index.d.ts +80 -0
  181. package/dist/expressions/comparison/utils.d.ts +2 -0
  182. package/dist/expressions/conversion/impl/bridge.d.ts +117 -0
  183. package/dist/expressions/conversion/impl/index.d.ts +59 -0
  184. package/dist/expressions/conversion/index.d.ts +23 -0
  185. package/dist/expressions/expression-tiers.d.ts +13 -0
  186. package/dist/expressions/index.d.ts +11 -0
  187. package/dist/expressions/index.js +6930 -0
  188. package/dist/expressions/index.mjs +6912 -0
  189. package/dist/expressions/logical/impl/index.d.ts +54 -0
  190. package/dist/expressions/logical/impl/pattern-matching.d.ts +58 -0
  191. package/dist/expressions/logical/index.d.ts +59 -0
  192. package/dist/expressions/mathematical/index.d.ts +69 -0
  193. package/dist/expressions/positional/impl/bridge.d.ts +95 -0
  194. package/dist/expressions/positional/impl/index.d.ts +73 -0
  195. package/dist/expressions/positional/index.d.ts +26 -0
  196. package/dist/expressions/properties/impl/index.d.ts +105 -0
  197. package/dist/expressions/properties/index.d.ts +26 -0
  198. package/dist/expressions/property/index.d.ts +55 -0
  199. package/dist/expressions/property-access-utils.d.ts +23 -0
  200. package/dist/expressions/references/impl/bridge.d.ts +54 -0
  201. package/dist/expressions/references/impl/index.d.ts +65 -0
  202. package/dist/expressions/references/index.d.ts +40 -0
  203. package/dist/expressions/shared/comparison-utils.d.ts +10 -0
  204. package/dist/expressions/shared/index.d.ts +9 -0
  205. package/dist/expressions/shared/number-utils.d.ts +7 -0
  206. package/dist/expressions/shared/validation-utils.d.ts +13 -0
  207. package/dist/expressions/special/index.d.ts +104 -0
  208. package/dist/expressions/type-helpers.d.ts +11 -0
  209. package/dist/expressions/type-registry.d.ts +57 -0
  210. package/dist/expressions/validation-helpers.d.ts +15 -0
  211. package/dist/extensions/index.d.ts +3 -0
  212. package/dist/extensions/tailwind.d.ts +22 -0
  213. package/dist/features/behaviors.d.ts +153 -0
  214. package/dist/features/def.d.ts +135 -0
  215. package/dist/features/eventsource.d.ts +140 -0
  216. package/dist/features/init.d.ts +135 -0
  217. package/dist/features/on.d.ts +131 -0
  218. package/dist/features/predefined-behaviors/dropdown-behavior.d.ts +20 -0
  219. package/dist/features/predefined-behaviors/index.d.ts +12 -0
  220. package/dist/features/predefined-behaviors/modal-behavior.d.ts +18 -0
  221. package/dist/features/predefined-behaviors/toggle-group-behavior.d.ts +23 -0
  222. package/dist/features/predefined-behaviors/types.d.ts +14 -0
  223. package/dist/features/sockets.d.ts +162 -0
  224. package/dist/features/webworker.d.ts +135 -0
  225. package/dist/htmx/htmx-attribute-processor.d.ts +84 -0
  226. package/dist/htmx/htmx-translator.d.ts +19 -0
  227. package/dist/htmx/index.d.ts +3 -0
  228. package/dist/hyperfixi-classic-i18n.js +2 -0
  229. package/dist/hyperfixi-hx.js +1 -0
  230. package/dist/hyperfixi-hybrid-complete.js +1 -0
  231. package/dist/hyperfixi-lite-plus.js +1 -0
  232. package/dist/hyperfixi-lite.js +1 -0
  233. package/dist/hyperfixi-minimal.js +1 -0
  234. package/dist/hyperfixi-multilingual.js +2 -0
  235. package/dist/hyperfixi-standard.js +2 -0
  236. package/dist/hyperfixi.js +2 -0
  237. package/dist/hyperfixi.mjs +2 -0
  238. package/dist/index.d.ts +25 -0
  239. package/dist/index.js +65387 -0
  240. package/dist/index.min.js +2 -0
  241. package/dist/index.mjs +65343 -0
  242. package/dist/lib/index.d.ts +4 -0
  243. package/dist/lib/morph-adapter.d.ts +22 -0
  244. package/dist/lib/swap-executor.d.ts +22 -0
  245. package/dist/lib/view-transitions.d.ts +33 -0
  246. package/dist/lokascript-browser-classic-i18n.js +2 -0
  247. package/dist/lokascript-browser-minimal.js +1 -0
  248. package/dist/lokascript-browser-standard.js +2 -0
  249. package/dist/lokascript-browser.js +2 -0
  250. package/dist/lokascript-hybrid-complete.js +1 -0
  251. package/dist/lokascript-hybrid-hx.js +1 -0
  252. package/dist/lokascript-lite-plus.js +1 -0
  253. package/dist/lokascript-lite.js +1 -0
  254. package/dist/lokascript-multilingual.js +2 -0
  255. package/dist/lsp-metadata.d.ts +25 -0
  256. package/dist/lsp-metadata.js +680 -0
  257. package/dist/lsp-metadata.mjs +670 -0
  258. package/dist/metadata.d.ts +213 -0
  259. package/dist/metadata.js +378 -0
  260. package/dist/metadata.mjs +368 -0
  261. package/dist/mod.d.ts +63 -0
  262. package/dist/multilingual/bridge.d.ts +36 -0
  263. package/dist/multilingual/index.d.ts +32 -0
  264. package/dist/multilingual/index.js +285 -0
  265. package/dist/multilingual/index.mjs +278 -0
  266. package/dist/parser/__types__/test-helpers.d.ts +25 -0
  267. package/dist/parser/command-node-builder.d.ts +45 -0
  268. package/dist/parser/command-parsers/animation-commands.d.ts +5 -0
  269. package/dist/parser/command-parsers/async-commands.d.ts +5 -0
  270. package/dist/parser/command-parsers/control-flow-commands.d.ts +7 -0
  271. package/dist/parser/command-parsers/dom-commands.d.ts +8 -0
  272. package/dist/parser/command-parsers/event-commands.d.ts +4 -0
  273. package/dist/parser/command-parsers/utility-commands.d.ts +9 -0
  274. package/dist/parser/command-parsers/variable-commands.d.ts +12 -0
  275. package/dist/parser/error-handler.d.ts +34 -0
  276. package/dist/parser/expression-parser.d.ts +6 -0
  277. package/dist/parser/full-parser.d.ts +4 -0
  278. package/dist/parser/full-parser.js +6532 -0
  279. package/dist/parser/full-parser.mjs +6529 -0
  280. package/dist/parser/helpers/ast-helpers.d.ts +22 -0
  281. package/dist/parser/helpers/parsing-helpers.d.ts +19 -0
  282. package/dist/parser/helpers/token-helpers.d.ts +28 -0
  283. package/dist/parser/hybrid/aliases.d.ts +7 -0
  284. package/dist/parser/hybrid/aliases.js +44 -0
  285. package/dist/parser/hybrid/aliases.mjs +37 -0
  286. package/dist/parser/hybrid/ast-types.d.ts +97 -0
  287. package/dist/parser/hybrid/ast-types.js +3 -0
  288. package/dist/parser/hybrid/ast-types.mjs +2 -0
  289. package/dist/parser/hybrid/index.d.ts +6 -0
  290. package/dist/parser/hybrid/index.js +1015 -0
  291. package/dist/parser/hybrid/index.mjs +1005 -0
  292. package/dist/parser/hybrid/parser-core.d.ts +57 -0
  293. package/dist/parser/hybrid/parser-core.js +1001 -0
  294. package/dist/parser/hybrid/parser-core.mjs +999 -0
  295. package/dist/parser/hybrid/tokenizer.d.ts +9 -0
  296. package/dist/parser/hybrid/tokenizer.js +242 -0
  297. package/dist/parser/hybrid/tokenizer.mjs +239 -0
  298. package/dist/parser/hybrid-parser.d.ts +10 -0
  299. package/dist/parser/hybrid-parser.js +1078 -0
  300. package/dist/parser/hybrid-parser.mjs +1071 -0
  301. package/dist/parser/parser-constants.d.ts +102 -0
  302. package/dist/parser/parser-interface.d.ts +11 -0
  303. package/dist/parser/parser-types.d.ts +175 -0
  304. package/dist/parser/parser.d.ts +146 -0
  305. package/dist/parser/regex-parser.d.ts +4 -0
  306. package/dist/parser/regex-parser.js +412 -0
  307. package/dist/parser/regex-parser.mjs +409 -0
  308. package/dist/parser/runtime.d.ts +3 -0
  309. package/dist/parser/semantic-integration.d.ts +61 -0
  310. package/dist/parser/token-consumer.d.ts +35 -0
  311. package/dist/parser/token-predicates.d.ts +77 -0
  312. package/dist/parser/tokenizer.d.ts +57 -0
  313. package/dist/parser/types.d.ts +118 -0
  314. package/dist/performance/expression-cache.d.ts +78 -0
  315. package/dist/performance/integration.d.ts +40 -0
  316. package/dist/performance/production-monitor.d.ts +67 -0
  317. package/dist/reference/index.d.ts +41 -0
  318. package/dist/reference/index.js +586 -0
  319. package/dist/reference/index.mjs +577 -0
  320. package/dist/registry/browser-types.d.ts +20 -0
  321. package/dist/registry/browser-types.js +81 -0
  322. package/dist/registry/browser-types.mjs +76 -0
  323. package/dist/registry/context-provider-registry.d.ts +38 -0
  324. package/dist/registry/environment.d.ts +19 -0
  325. package/dist/registry/environment.js +36 -0
  326. package/dist/registry/environment.mjs +30 -0
  327. package/dist/registry/event-source-registry.d.ts +54 -0
  328. package/dist/registry/examples/server-commands.d.ts +6 -0
  329. package/dist/registry/examples/server-event-source.d.ts +32 -0
  330. package/dist/registry/index.d.ts +54 -0
  331. package/dist/registry/index.js +7636 -0
  332. package/dist/registry/index.mjs +7612 -0
  333. package/dist/registry/multilingual/examples.d.ts +16 -0
  334. package/dist/registry/multilingual/index.d.ts +68 -0
  335. package/dist/registry/runtime-integration.d.ts +30 -0
  336. package/dist/registry/universal-types.d.ts +34 -0
  337. package/dist/registry/universal-types.js +91 -0
  338. package/dist/registry/universal-types.mjs +86 -0
  339. package/dist/runtime/cleanup-registry.d.ts +47 -0
  340. package/dist/runtime/command-adapter.d.ts +63 -0
  341. package/dist/runtime/environment.d.ts +75 -0
  342. package/dist/runtime/runtime-base.d.ts +78 -0
  343. package/dist/runtime/runtime-experimental.d.ts +18 -0
  344. package/dist/runtime/runtime-factory.d.ts +30 -0
  345. package/dist/runtime/runtime.d.ts +19 -0
  346. package/dist/runtime/temporal-modifiers.d.ts +37 -0
  347. package/dist/scripts/code-generator.d.ts +64 -0
  348. package/dist/scripts/generate-missing-commands.d.ts +4 -0
  349. package/dist/test-setup.d.ts +45 -0
  350. package/dist/test-utilities.d.ts +52 -0
  351. package/dist/tokenizer.d.ts +49 -0
  352. package/dist/types/base-types.d.ts +336 -0
  353. package/dist/types/code-fix.d.ts +39 -0
  354. package/dist/types/command-metadata.d.ts +57 -0
  355. package/dist/types/command-types.d.ts +272 -0
  356. package/dist/types/context-types.d.ts +106 -0
  357. package/dist/types/core-context.d.ts +21 -0
  358. package/dist/types/core.d.ts +203 -0
  359. package/dist/types/error-codes.d.ts +207 -0
  360. package/dist/types/expression-types.d.ts +155 -0
  361. package/dist/types/feature-types.d.ts +81 -0
  362. package/dist/types/hooks.d.ts +45 -0
  363. package/dist/types/index.d.ts +32 -0
  364. package/dist/types/result.d.ts +72 -0
  365. package/dist/types/template-types.d.ts +162 -0
  366. package/dist/types/type-guards.d.ts +24 -0
  367. package/dist/types/unified-types.d.ts +99 -0
  368. package/dist/utils/debug-events.d.ts +41 -0
  369. package/dist/utils/debug.d.ts +35 -0
  370. package/dist/utils/dom-utils.d.ts +16 -0
  371. package/dist/utils/element-check.d.ts +7 -0
  372. package/dist/utils/keyboard-shortcuts.d.ts +18 -0
  373. package/dist/utils/performance.d.ts +40 -0
  374. package/dist/validation/command-pattern-validator.d.ts +53 -0
  375. package/dist/validation/common-validators.d.ts +24 -0
  376. package/dist/validation/lightweight-validators.d.ts +113 -0
  377. package/dist/validation/partial-validation-types.d.ts +50 -0
  378. package/dist/validation/partial-validator.d.ts +6 -0
  379. package/dist/validation/partial-warning-formatter.d.ts +6 -0
  380. package/dist/validation/validate-cli.d.ts +41 -0
  381. package/package.json +292 -0
@@ -0,0 +1,2 @@
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LokaScriptCore={})}(this,function(e){"use strict";const t="then",n="else",r="end",i="and",a="if",o="for",s="while",l="until",c="forever",u="times",p="each",m="index",d="in",h="to",f="from",y="with",v="of",g="by",b="between",k="on",w="event",z="def",x="behavior",E="global",S="local",T="the",C="start",A=[t,i,n,r,k],j=new Set(["add","append","async","beep","break","call","continue","copy","decrement","default","exit","fetch","for","get","go","halt","hide","if","increment","install","js","log","make","measure","morph","pick","process","push","put","remove","render","repeat","replace","return","send","set","settle","show","swap","take","tell","throw","toggle","transition","trigger","unless","wait"]),L=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","tell","swap","morph","push","replace","process"]),P=new Set(["if","unless","repeat","wait","for","while"]),I="at",N="at start of",O="at end of",R=["into","before","after",I,N,O,"at the start of","at the end of"],M=new Set(["if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","without","as","matches","contains","then","on","when","every","init","def","behavior","the","of","first","last"]),W={isCommand:e=>j.has(e.toLowerCase()),isCompoundCommand:e=>L.has(e.toLowerCase()),isControlFlowCommand:e=>P.has(e.toLowerCase()),isKeyword:e=>M.has(e.toLowerCase()),isTerminator:e=>A.includes(e),isPutOperation:e=>R.includes(e),isCSSFunction:e=>$.has(e.toLowerCase())},$=new Set(["hsl","hsla","rgb","rgba","hwb","lab","lch","oklch","oklab","color","color-mix","calc","min","max","clamp","var","url","linear-gradient","radial-gradient","conic-gradient","repeating-linear-gradient","repeating-radial-gradient","repeating-conic-gradient"]),H=new Set(["me","it","you","result","my","its","your"]),q=new Set(["and","or","not","no"]),D=new Set(["==","!=","===","!==","<",">","<=",">=","is","is not","is a","is an","is not a","is not an","contains","has","have","does not contain","include","includes","does not include","match","matches","exists","does not exist","is empty","is not empty","is in","is not in","equals","in","is equal to","is really equal to","is not equal to","is not really equal to","is greater than","is less than","is greater than or equal to","is less than or equal to","really equals"]),_=new Set(["click","dblclick","mousedown","mouseup","mouseover","mouseout","mousemove","mouseenter","mouseleave","focus","blur","change","input","submit","reset","select","load","unload","resize","scroll","keydown","keyup","keypress","touchstart","touchend","touchmove","touchcancel","drag","drop","dragover","dragenter","dragleave","cut","copy","paste","toggle"]),V=new Set(["on","init","behavior","def","if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","as","then","when","where","after","before","by","at","between","async","no","start","of","the","new","global","local","equal","equals","greater","less","than","really","catch","finally","throw","return"]);var B,F;function U(e){switch(e){case F.KEYWORD:case F.COMMAND:case F.EXPRESSION:case F.CONTEXT_VAR:case F.GLOBAL_VAR:case F.EVENT:case F.IDENTIFIER:return B.IDENTIFIER;case F.STRING:return B.STRING;case F.NUMBER:return B.NUMBER;case F.BOOLEAN:return B.IDENTIFIER;case F.TEMPLATE_LITERAL:return B.TEMPLATE;case F.CSS_SELECTOR:case F.ID_SELECTOR:case F.CLASS_SELECTOR:case F.QUERY_REFERENCE:return B.SELECTOR;case F.OPERATOR:case F.LOGICAL_OPERATOR:case F.COMPARISON_OPERATOR:return B.OPERATOR;case F.TIME_EXPRESSION:return B.TIME;case F.COMMENT:return B.COMMENT;case F.SYMBOL:return B.SYMBOL;case F.OBJECT_LITERAL:case F.ARRAY_LITERAL:case F.UNKNOWN:default:return B.UNKNOWN}}!function(e){e.IDENTIFIER="identifier",e.STRING="string",e.NUMBER="number",e.SELECTOR="selector",e.OPERATOR="operator",e.TIME="time",e.TEMPLATE="template",e.COMMENT="comment",e.SYMBOL="symbol",e.UNKNOWN="unknown"}(B||(B={})),function(e){e.KEYWORD="keyword",e.COMMAND="command",e.EXPRESSION="expression",e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.TEMPLATE_LITERAL="template_literal",e.CSS_SELECTOR="css_selector",e.ID_SELECTOR="id_selector",e.CLASS_SELECTOR="class_selector",e.QUERY_REFERENCE="query_reference",e.CONTEXT_VAR="context_var",e.GLOBAL_VAR="global_var",e.EVENT="event",e.OPERATOR="operator",e.LOGICAL_OPERATOR="logical_operator",e.COMPARISON_OPERATOR="comparison_operator",e.TIME_EXPRESSION="time_expression",e.OBJECT_LITERAL="object_literal",e.ARRAY_LITERAL="array_literal",e.SYMBOL="symbol",e.COMMENT="comment",e.IDENTIFIER="identifier",e.UNKNOWN="unknown"}(F||(F={}));const K=V,G=new Set(["+","-","*","/","mod"]),Q=new Set(["ms","s","seconds","minutes","hours","days"]);function J(e,t=1){const n=e.position+t;return n<e.input.length?e.input[n]:""}function Y(e){const t=e.input[e.position];if(e.position++,"\n"===t)e.line++,e.column=1;else if("\r"===t){"\n"===(e.position<e.input.length?e.input[e.position]:"")&&e.position++,e.line++,e.column=1}else e.column++;return t}function Z(e){const t=e.input,n=t.length;for(;e.position<n;){const n=t[e.position];if(" "!==n&&"\t"!==n&&"\r"!==n&&"\n"!==n)break;Y(e)}}function X(e,t,n,r,i){const a=r??e.position-n.length,o=e.position;let s=e.column-n.length;if(void 0!==r){s=1;let t=-1;for(let n=0;n<r;n++)"\n"!==e.input[n]&&"\r"!==e.input[n]||(t=n);s=r-t}const l={kind:U(t),value:n,start:a,end:o,line:ee(e,a),column:s};e.tokens.push(l)}function ee(e,t){let n=1;for(let r=0;r<t&&r<e.input.length;r++){const t=e.input[r];"\n"===t?n++:"\r"===t&&(n++,r+1<e.input.length&&"\n"===e.input[r+1]&&r++)}return n}function te(e){const t=e.position;let n="";for(Y(e),Y(e);e.position<e.input.length;){if("\n"===e.input[e.position])break;n+=Y(e)}X(e,F.COMMENT,"--"+n,t)}function ne(e){const t=e.position,n=Y(e);let r=n;for(;e.position<e.input.length;){const t=Y(e);if(r+=t,t===n)break;"\\"===t&&e.position<e.input.length&&(r+=Y(e))}X(e,F.STRING,r,t)}function re(e){const t=e.position;Y(e);let n="";for(;e.position<e.input.length;){const t=e.input[e.position];if("`"===t){Y(e);break}if("\\"===t){if(Y(e),e.position<e.input.length){const t=Y(e);switch(t){case"n":n+="\n";break;case"t":n+="\t";break;case"r":n+="\r";break;case"\\":n+="\\";break;case"`":n+="`";break;default:n+=t}}}else n+=Y(e)}if(e.position>=e.input.length&&!e.input.endsWith("`"))throw new Error(`Unterminated template literal at line ${e.line}, column ${e.column-n.length}`);X(e,F.TEMPLATE_LITERAL,n,t)}function ie(e){const t=e.position,n=Y(e);let r=n;for(;e.position<e.input.length;){const t=e.input[e.position];if(!me(t)&&"-"!==t&&"_"!==t&&":"!==t)break;r+=Y(e)}X(e,"#"===n?F.ID_SELECTOR:F.CLASS_SELECTOR,r,t)}function ae(e){const t=e.position;let n="";for(n+=Y(e);e.position<e.input.length-1;){const t=e.input[e.position],r=e.input[e.position+1];if(n+=Y(e),"/"===t&&">"===r){n+=Y(e);break}}X(e,F.QUERY_REFERENCE,n,t)}function oe(e){const t=e.position;let n=Y(e);for(;e.position<e.input.length;){const t=e.input[e.position];if(!me(t)&&"_"!==t&&"-"!==t)break;n+=Y(e)}X(e,F.SYMBOL,n,t)}function se(e){const t=e.position;let n="";const r=e.input[e.position];if(("'"===r||"'"===r)&&"s"===J(e,1))return n="'s",Y(e),Y(e),void X(e,F.OPERATOR,n,t);const i=e.input.substring(e.position,e.position+2),a=e.input.substring(e.position,e.position+3);["===","!=="].includes(a)?(n=a,Y(e),Y(e),Y(e)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(i)?(n=i,Y(e),Y(e)):n=Y(e);let o=F.OPERATOR;D.has(n)?o=F.COMPARISON_OPERATOR:["&&","||"].includes(n)?o=F.LOGICAL_OPERATOR:G.has(n)&&(o=F.OPERATOR),X(e,o,n,t)}function le(e){const t=e.position,n=e.input,r=n.length;let i="";for(;e.position<r;){const t=n[e.position];if(!(t>="0"&&t<="9"))break;i+=Y(e)}if(e.position<r&&"."===n[e.position]&&!(e.position+1<r&&"."===n[e.position+1]))for(i+=Y(e);e.position<r;){const t=n[e.position];if(!(t>="0"&&t<="9"))break;i+=Y(e)}if(e.position<r){const t=n[e.position];if("e"===t||"E"===t){const t=e.position+1<r?n[e.position+1]:"",a=e.position+2<r?n[e.position+2]:"";if(t>="0"&&t<="9"||("+"===t||"-"===t)&&a>="0"&&a<="9")for(i+=Y(e),"+"!==n[e.position]&&"-"!==n[e.position]||(i+=Y(e));e.position<r;){const t=n[e.position];if(!(t>="0"&&t<="9"))break;i+=Y(e)}}}const a=e.position;let o="";for(;e.position<r;){const t=n[e.position];if(!(t>="a"&&t<="z"||t>="A"&&t<="Z"))break;o+=Y(e)}Q.has(o)?X(e,F.TIME_EXPRESSION,i+o,t):(e.position=a,X(e,F.NUMBER,i,t))}function ce(e){const t=e.position,n=e.input,r=n.length;let i="";for(;e.position<r;){const t=n[e.position];if(!(t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t||"-"===t))break;i+=Y(e)}const a=function(e,t,n){const r=t.toLowerCase(),i=e.position;if("'s"===t||"'s"===t)return!1;const a=e.tokens[e.tokens.length-1];if(a&&("identifier"===a.kind||"id_selector"===a.kind||"class_selector"===a.kind||"context_var"===a.kind)){const t=e.position<e.input.length?e.input[e.position]:"";if("'"===t||"'"===t)return!1}Z(e);let o="";for(;e.position<e.input.length;){const t=e.input[e.position];if(!(t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t||"-"===t))break;o+=Y(e)}if(o){const t=o.toLowerCase(),i=`${r} ${t}`,a=function(e,t,n,r){const i=t.toLowerCase(),a=n.toLowerCase();if("at"===i){const t=e.position;if("the"===a){Z(e);let n="";for(;e.position<e.input.length;){const t=e.input[e.position];if(!(t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t||"-"===t))break;n+=Y(e)}const i=n.toLowerCase();if("start"===i||"end"===i){Z(e);let t="";for(;e.position<e.input.length;){const n=e.input[e.position];if(!(n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||"_"===n||"-"===n))break;t+=Y(e)}if("of"===t.toLowerCase()){const t=`at the ${i} of`;return X(e,F.KEYWORD,t,r),!0}}return e.position=t,!1}if("start"===a||"end"===a){Z(e);let n="";for(;e.position<e.input.length;){const t=e.input[e.position];if(!(t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t||"-"===t))break;n+=Y(e)}if("of"===n.toLowerCase()){const t=`at ${a} of`;return X(e,F.KEYWORD,t,r),!0}return e.position=t,!1}}return!1}(e,r,t,n);if(a)return!0;const s=function(e,t,n){const r=e.position;let i=`${t} ${n}`,a=e.position;const o=[t,n],s=8;for(;o.length<s&&(Z(e),!(e.position>=e.input.length));){let t="";for(;e.position<e.input.length;){const n=e.input[e.position];if(!(n>="a"&&n<="z"||n>="A"&&n<="Z"))break;t+=Y(e)}if(!t)break;o.push(t.toLowerCase());const n=o.join(" ");D.has(n)&&(i=n,a=e.position)}if(D.has(i)&&i!==`${t} ${n}`)return e.position=a,i;return e.position=r,null}(e,r,t);if(s)return X(e,F.COMPARISON_OPERATOR,s,n),!0;if(D.has(i))return X(e,F.COMPARISON_OPERATOR,i,n),!0}if(D.has(r))return e.position=i,X(e,F.COMPARISON_OPERATOR,t,n),!0;return e.position=i,!1}(e,i,t);if(a)return;const o=function(e){const t=e.toLowerCase();if("include"===t||"includes"===t)return F.COMPARISON_OPERATOR;if(q.has(t))return F.LOGICAL_OPERATOR;if(G.has(e)||G.has(t))return F.OPERATOR;if(D.has(t))return F.COMPARISON_OPERATOR;if("I"===e)return F.CONTEXT_VAR;if(H.has(t))return F.CONTEXT_VAR;if(j.has(t))return F.COMMAND;if(_.has(t))return F.EVENT;if(["true","false","null","undefined"].includes(t))return F.BOOLEAN;if(K.has(t))return F.KEYWORD;return F.IDENTIFIER}(i);X(e,o,i,t)}function ue(e){const t=e.position,n=e.input,r=n.length;Y(e);let i="$";for(;e.position<r;){const t=n[e.position];if(!(t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t))break;i+=Y(e)}X(e,F.GLOBAL_VAR,i,t)}function pe(e){return/[a-zA-Z]/.test(e)}function me(e){return/[a-zA-Z0-9]/.test(e)}function de(e){let t=e.position+1,n=!1;for(;t<e.input.length;){const r=e.input[t];if("/"===r&&t+1<e.input.length&&">"===e.input[t+1])return n;if(me(r)||"."===r||"#"===r||"["===r||"]"===r||":"===r||"-"===r||"_"===r||" "===r||"="===r||'"'===r||"'"===r||"("===r||")"===r||"*"===r||"^"===r||"$"===r||"~"===r||"|"===r||">"===r||"+"===r||","===r)n=!0,t++;else{if(" "!==r&&"\t"!==r)return!1;t++}if(t-e.position>50)return!1}return!1}function he(e){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(e)}const fe=function(){if("undefined"!=typeof localStorage)try{const e=localStorage,t=e.getItem("hyperfixi:debug")||e.getItem("lokascript:debug");if("*"===t||"true"===t)return!0}catch{}return!("undefined"==typeof window||!window.__HYPERFIXI_DEBUG__)||"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG}(),ye=fe,ve=fe,ge=fe,be=fe,ke=fe,we=(...e)=>{ye&&console.log("🔧",...e)},ze=(...e)=>{ve&&console.log("🎯",...e)},xe=(...e)=>{ge&&console.log("📝",...e)},Ee=(...e)=>{be&&console.log("🔍",...e)},Se=(...e)=>{ke&&console.log("🚀",...e)};let Te=!1,Ce=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(Te=!0,Ce=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let Ae={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class je{constructor(e){this.analyzer=e.analyzer,this.language=e.language,this.confidenceThreshold=e.confidenceThreshold??.5,this.debugEnabled=e.debug??!1}isAvailable(){return this.analyzer.supportsLanguage(this.language)}shouldSkipSemantic(e){const t=e.trim().split(/\s+/)[0]?.toLowerCase();if(je.SKIP_SEMANTIC_COMMANDS.has(t))return!0;const n=e.toLowerCase();return!!/\bjs\b/.test(n)||!!/\btell\b/.test(n)}trySemanticParse(e){const t=performance.now();if(this.shouldSkipSemantic(e))return{success:!1,confidence:0,errors:["Command skipped for semantic parsing - using traditional parser"]};if(!this.isAvailable())return{success:!1,confidence:0,errors:[`Semantic parsing not available for language '${this.language}'`]};try{const r=this.analyzer.analyze(e,this.language),i=performance.now()-t;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:e,language:this.language,confidence:r.confidence,command:r.command?.name,threshold:this.confidenceThreshold});const a=r.confidence>=this.confidenceThreshold&&!!r.command,o=!a&&r.confidence>0;if(Te){const t={};if(r.command?.roles)for(const[e,n]of r.command.roles)t[e]=n.value;const s={input:e.substring(0,100),language:this.language,confidence:r.confidence,threshold:this.confidenceThreshold,semanticSuccess:a,fallbackTriggered:o,command:r.command?.name,roles:Object.keys(t).length>0?t:void 0,errors:r.errors,timestamp:Date.now(),duration:i};!function(e){if(!Te)return;const t=e.semanticSuccess?"semantic":e.fallbackTriggered?"fallback":"traditional",n=Math.round(100*e.confidence),r=Math.round(100*e.threshold),i=e.semanticSuccess?"color: #4caf50; font-weight: bold":e.fallbackTriggered?"color: #ff9800; font-weight: bold":"color: #9e9e9e";if(console.groupCollapsed(`%c[Semantic] ${t.toUpperCase()} %c${e.input.substring(0,50)}${e.input.length>50?"...":""}`,i,"color: #888"),console.log(`Confidence: ${n}% (threshold: ${r}%)`),e.command&&console.log(`Command: ${e.command}`),e.roles&&Object.keys(e.roles).length>0&&console.log("Roles:",e.roles),e.duration&&console.log(`Duration: ${e.duration.toFixed(2)}ms`),e.errors?.length&&console.log("Errors:",e.errors),console.groupEnd(),Ce){const t=new CustomEvent("lokascript:semantic:parse",{detail:e,bubbles:!0});Ce.dispatchEvent(t)}}(s),n=s,Ae.totalParses++,n.semanticSuccess?Ae.semanticSuccesses++:n.fallbackTriggered?Ae.semanticFallbacks++:Ae.traditionalParses++,Ae.confidenceHistory.push(n.confidence),Ae.confidenceHistory.length>100&&Ae.confidenceHistory.shift(),Ae.averageConfidence=Ae.confidenceHistory.reduce((e,t)=>e+t,0)/Ae.confidenceHistory.length}if(!a)return{success:!1,confidence:r.confidence,tokensConsumed:r.tokensConsumed,errors:r.errors};return{success:!0,node:this.buildCommandNode(r),confidence:r.confidence,tokensConsumed:r.tokensConsumed}}catch(e){return{success:!1,confidence:0,errors:[e instanceof Error?e.message:String(e)]}}var n}buildCommandNode(e){const{command:t}=e;if(!t)throw new Error("Cannot build command node without command data");if("repeat"===t.name)return this.buildRepeatCommandNode(t);if("for"===t.name)return this.buildRepeatCommandNode(t);if("set"===t.name)return this.buildSetCommandNode(t);if("if"===t.name||"unless"===t.name)return this.buildIfCommandNode(t);const n=[],r={};for(const[e,i]of t.roles){const a=this.semanticValueToExpression(i);switch(e){case"patient":case"event":n.push(a);break;case"destination":"put"===t.name?r.into=a:"add"===t.name||"append"===t.name||"prepend"===t.name?r.to=a:r.on=a;break;case"source":"fetch"===t.name?n.push(a):r.from=a;break;case"quantity":r.by=a;break;case"duration":r.over=a;break;case"responseType":r.as=a;break;case"method":r.method=a;break;case"style":r.with=a;break;case"condition":r.when=a;break;default:r[e]=a}}return{type:"command",name:t.name,args:n,modifiers:Object.keys(r).length>0?r:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildRepeatCommandNode(e){const t=[],n={},r=e.roles.get("loopType");r&&t.push({type:"identifier",name:String(r.value),start:0,end:0,line:1,column:0});const i=e.roles.get("patient");"for"===(r?String(r.value):"")&&i&&t.push({type:"identifier",name:"expression"===i.type&&i.raw||String(i.value),start:0,end:0,line:1,column:0});const a=e.roles.get("event");a&&t.push({type:"string",value:String(a.value),start:0,end:0,line:1,column:0});const o=e.roles.get("source");o&&t.push(this.semanticValueToExpression(o));const s=e.roles.get("quantity");s&&t.push(this.semanticValueToExpression(s));const l=e.roles.get("condition");return l&&(n.condition=this.semanticValueToExpression(l)),{type:"command",name:"repeat",args:t,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildSetCommandNode(e){const t=[],n=e.roles.get("destination");if(n)if("property-path"===n.type){const e=n;t.push({type:"possessiveExpression",object:this.semanticValueToExpression(e.object),property:this.createPropertyNode(e.property),start:0,end:0,line:1,column:0})}else t.push(this.semanticValueToExpression(n));t.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const r=e.roles.get("patient");return r&&t.push(this.semanticValueToExpression(r)),{type:"command",name:"set",args:t,isBlocking:!1,start:0,end:0,line:1,column:0}}createPropertyNode(e){return e.startsWith("*")?{type:"cssProperty",name:e.substring(1),start:0,end:0,line:1,column:0}:{type:"identifier",name:e,start:0,end:0,line:1,column:0}}buildIfCommandNode(e){const t=[],n=e.roles.get("condition");return n&&t.push(this.semanticValueToExpression(n)),{type:"command",name:e.name,args:t,isBlocking:!1,start:0,end:0,line:1,column:0}}semanticValueToExpression(e){switch(e.type){case"selector":return{type:"selector",value:e.value,start:0,end:0,line:1,column:0};case"reference":return{type:"identifier",name:e.value,start:0,end:0,line:1,column:0};case"literal":return"string"==typeof e.value&&e.value.includes("${")&&e.value.includes("}")?{type:"templateLiteral",value:e.value,start:0,end:0,line:1,column:0}:{type:"literal",value:e.value,raw:e.raw??e.value,start:0,end:0,line:1,column:0};case"property-path":{const t=e;return{type:"memberExpression",object:this.semanticValueToExpression(t.object),property:{type:"identifier",name:t.property,start:0,end:0,line:1,column:0},computed:!1,start:0,end:0,line:1,column:0}}default:{const t=e.raw||"";return this.parseExpressionString(t)}}}parseExpressionString(e){let t=0;const n=()=>{for(;t<e.length&&/\s/.test(e[t]);)t++},r=()=>{n();const r=t;for(;t<e.length&&/[a-zA-Z0-9_$]/.test(e[t]);)t++;return e.slice(r,t)},i=()=>{const r=[];if(t++,n(),")"!==e[t])for(r.push(a()),n();","===e[t];)t++,n(),r.push(a()),n();return")"===e[t]&&t++,r},a=()=>{n();const a=r();if(!a)return{type:"identifier",name:e.trim(),start:0,end:0,line:1,column:0};let o={type:"identifier",name:a,start:0,end:0,line:1,column:0};for(;t<e.length;){n();const a=e[t];if("."===a){t++;const e=r();e&&(o={type:"memberExpression",object:o,property:{type:"identifier",name:e,start:0,end:0,line:1,column:0},computed:!1,start:0,end:0,line:1,column:0})}else{if("("!==a)break;o={type:"callExpression",callee:o,arguments:i(),start:0,end:0,line:1,column:0}}}return o};return a()}getLanguage(){return this.language}getConfidenceThreshold(){return this.confidenceThreshold}}function Le(e){return e.kind===B.IDENTIFIER&&j.has(e.value.toLowerCase())}function Pe(e){return e.kind===B.IDENTIFIER&&V.has(e.value.toLowerCase())}function Ie(e){return e.kind===B.IDENTIFIER&&_.has(e.value.toLowerCase())}function Ne(e){return e.kind===B.IDENTIFIER&&H.has(e.value.toLowerCase())}function Oe(e){return e.kind,B.OPERATOR,D.has(e.value.toLowerCase())}function Re(e){return e.kind===B.IDENTIFIER}function Me(e){return e.kind===B.SELECTOR}function We(e){return e.kind===B.SELECTOR&&!e.value.startsWith("<")}function $e(e){return e.kind===B.STRING||e.kind===B.NUMBER||e.kind===B.TEMPLATE}function He(e){return e.kind===B.IDENTIFIER}function qe(e){return e.kind===B.TIME}function De(e){return e.kind===B.SYMBOL}function _e(e){return e.kind===B.COMMENT}function Ve(e){if(e.kind!==B.IDENTIFIER)return!1;const t=e.value.toLowerCase();return!(j.has(t)||V.has(t)||_.has(t)||H.has(t))}function Be(e){return e.kind===B.STRING}function Fe(e){return e.kind===B.NUMBER}function Ue(e){if(e.kind===B.IDENTIFIER){const t=e.value;return"true"===t||"false"===t||"null"===t||"undefined"===t}return!1}function Ke(e){return e.kind===B.TEMPLATE}function Ge(e){return e.kind===B.SELECTOR&&e.value.startsWith("<")}function Qe(e){return e.kind===B.SELECTOR&&e.value.startsWith("#")}function Je(e){return e.kind===B.SELECTOR&&e.value.startsWith(".")}function Ye(e){return e.kind===B.SELECTOR&&(!e.value.startsWith("#")&&!e.value.startsWith("."))}function Ze(e){if(e.kind!==B.OPERATOR)return!1;const t=e.value.toLowerCase();return!q.has(t)&&!D.has(t)}function Xe(e){const t=e.value.toLowerCase();return"then"===t||"and"===t||"else"===t||"end"===t||"on"===t}function et(e,t,n){return{type:"literal",value:e,raw:t,start:n.start,end:n.end,line:n.line,column:n.column}}function tt(e,t){return{type:"identifier",name:e,start:t.start,end:t.end,line:t.line,column:t.column}}function nt(e,t,n,r){return{type:"binaryExpression",operator:e,left:t,right:n,start:r.start,end:r.end,line:r.line,column:r.column}}function rt(e,t){return{type:"block",commands:e,start:t.start,end:t.end,line:t.line,column:t.column}}function it(e,t){return{type:"string",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}function at(e,t){return{type:"objectLiteral",properties:e,start:t.start,end:t.end,line:t.line,column:t.column}}function ot(e,t){return{type:"arrayLiteral",elements:e,start:t.start,end:t.end,line:t.line,column:t.column}}function st(e,t,n){return{type:"propertyOfExpression",property:e,target:t,start:n.start,end:n.end,line:n.line,column:n.column}}je.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const lt=[{command:"append",keywords:["to"],syntax:"append <value> [to <target>]"},{command:"make",keywords:["a","an"],syntax:"make (a|an) <type>"},{command:"send",keywords:["to"],syntax:"send <event> to <target>"},{command:"throw",keywords:[],syntax:"throw <error>"}];function ct(e,t){return!!e&&t.some(t=>e.value===t||e.value.toLowerCase()===t)}const ut=[t,i,n,r];function pt(e,t=[]){if(e.isAtEnd())return!0;for(const t of ut)if(e.check(t))return!0;for(const n of t)if(e.check(n))return!0;return!!e.checkIsCommand()}function mt(e,t=[]){if(!pt(e,t))return e.parseExpression()}function dt(e,t,n){return!!e.check(t)&&(e.advance(),n.push(e.createIdentifier(t)),!0)}function ht(e,t,n){for(const r of t)if(e.check(r))return e.advance(),n.push(e.createIdentifier(r)),r;return null}function ft(e,t){return!!e.check(t)&&(e.advance(),!0)}class yt{constructor(e){this.args=[],this.isBlocking=!1,this.name=e}static from(e){const t=new yt(e.value);return t.startPos={start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1},t}static fromIdentifier(e){const t=new yt(e.name);return void 0!==e.start&&(t.startPos={start:e.start,end:e.end??0,line:e.line??1,column:e.column??1}),t}static named(e){return new yt(e)}withArgs(...e){return this.args.push(...e),this}withBody(e){return this.body=e,this}withImplicitTarget(e){return this.implicitTarget=e,this}withModifier(e,t){return this.modifiers||(this.modifiers={}),this.modifiers[e]=t,this}withModifiers(e){return this.modifiers={...this.modifiers,...e},this}withName(e){return this.name=e,this}withOriginalCommand(e){return this.originalCmd=e,this}blocking(e=!0){return this.isBlocking=e,this}startingAt(e){return this.startPos={start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1},this}endingAt(e){return this.endPos={start:e.start??this.startPos?.start??0,end:e.end,line:e.line??this.startPos?.line??1,column:e.column??this.startPos?.column??1},this}build(){const e=this.startPos?.start??0,t=this.endPos?.end??this.startPos?.end??0,n=this.startPos?.line??1,r=this.startPos?.column??1,i={type:"command",name:this.name,args:this.args,isBlocking:this.isBlocking,start:e,end:t,line:n,column:r};return this.body&&(i.body=this.body),this.implicitTarget&&(i.implicitTarget=this.implicitTarget),this.modifiers&&(i.modifiers=this.modifiers),this.originalCmd&&(i.originalCommand=this.originalCmd),i}clone(){const e=new yt(this.name);return e.args=[...this.args],e.body=this.body?[...this.body]:void 0,e.implicitTarget=this.implicitTarget,e.isBlocking=this.isBlocking,e.modifiers=this.modifiers?{...this.modifiers}:void 0,e.originalCmd=this.originalCmd,e.startPos=this.startPos?{...this.startPos}:void 0,e.endPos=this.endPos?{...this.endPos}:void 0,e}}function vt(e,t){const n=[];let r="";const i=e.peek().start||0,a=e.peek().line||1,o=e.peek().column||1;if(e.checkIdentifierLike()){for(r=e.advance().value;e.check(":")&&!e.isAtEnd();)e.advance(),r+=":",e.checkIdentifierLike()&&(r+=e.advance().value);if(e.check("(")){e.advance();const t=[];for(;!e.isAtEnd()&&!e.check(")");){const n=e.savePosition();let r;if(e.checkIdentifierLike()){const t=e.peek().value;e.advance(),e.check(":")?(e.advance(),r=t):e.restorePosition(n)}const i=e.parseExpression();if(void 0!==r?t.push({type:"objectLiteral",properties:[{key:{type:"identifier",name:r},value:i}],start:i.start,end:i.end,line:i.line,column:i.column}):t.push(i),e.check(","))e.advance();else if(!e.check(")"))break}e.check(")")&&e.advance(),n.push({type:"functionCall",name:r,args:t,start:i,end:e.getPosition().end,line:a,column:o})}else n.push({type:"string",value:r,start:i,end:e.getPosition().end,line:a,column:o})}for(;!pt(e);)n.push(e.parsePrimary());let s=-1,l="on";for(let e=0;e<n.length;e++){const t=n[e],r=t,i=r.name||r.value;if(!("identifier"!==t.type&&"literal"!==t.type&&"keyword"!==t.type||"on"!==i&&"to"!==i)){s=e,l=i;break}}const c=[];if(-1===s)c.push(...n);else{const t=n.slice(0,s),r=n.slice(s+1);c.push(...t),c.push(e.createIdentifier(l)),c.push(...r)}return yt.fromIdentifier(t).withArgs(...c).endingAt(e.getPosition()).build()}function gt(e,t){const n=[];if(e.check(T)){const t=e.advance();if(n.push({type:"identifier",name:T,start:t.start,end:t.end,line:t.line,column:t.column}),e.check(w)){const t=e.advance();n.push({type:"identifier",name:w,start:t.start,end:t.end,line:t.line,column:t.column})}}return yt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function bt(e,i){const o=[];let s=!1;const l=e.savePosition();for(let n=0;n<500&&!e.isAtEnd();n++){const n=e.peek();if(n.value===t){s=!0;break}if(n.value===r||n.value===x||n.value===z||n.value===k)break;e.advance()}e.restorePosition(l);let c=!1;if(!s){const t=e.savePosition(),a=i.line,o=100;for(;!e.isAtEnd()&&e.current-t<o;){const t=e.peek(),i=t.value?.toLowerCase();if(i===x||i===z||i===k)break;if(i===n||i===r){t.line===a&&(c=!0);break}if((e.checkIsCommand()||e.isCommand(i))&&void 0!==t.line&&t.line!==a){c=!0;break}e.advance()}e.restorePosition(t)}const u=s||c;let p;if(u)p=e.parseExpression();else{const n=[],r=20;let a=0;for(;!e.isAtEnd()&&!e.checkIsCommand()&&!e.isCommand(e.peek().value)&&!e.check(t)&&a<r;){const t=e.savePosition();n.push(e.parseLogicalAnd()),e.savePosition()===t&&e.advance(),a++}if(0===n.length)throw new Error("Expected condition after if/unless");p=1===n.length?n[0]:{type:"expression",tokens:n,start:n[0].start,end:n[n.length-1].end,line:i.line,column:i.column}}if(o.push(p),u){s&&e.advance();const t=[];for(;!e.isAtEnd()&&!e.check(n)&&!e.check(r)&&(e.checkIsCommand()||e.isCommand(e.peek().value));){e.advance();const n=e.parseCommand();n&&t.push(n)}if(0===t.length&&e.isAtEnd())throw new Error("Expected command after 'then' in if statement - incomplete conditional");o.push(rt(t,{start:i.start,end:e.getPosition().end,line:i.line,column:i.column}));let l=!1;if(e.check(n))if(e.advance(),e.check(a)){const t=e.peek();e.advance();const n=bt(e,t);o.push(rt([n],{start:t.start,end:e.getPosition().end,line:t.line,column:t.column})),l=!0}else{const t=[];for(;!e.isAtEnd()&&!e.check(r)&&(e.checkIsCommand()||e.isCommand(e.peek().value));){e.advance();const n=e.parseCommand();n&&t.push(n)}o.push(rt(t,{start:i.start,end:e.getPosition().end,line:i.line,column:i.column}))}l||e.consume(r,"Expected 'end' after if block")}else{if(!e.checkIsCommand()&&!e.isCommand(e.peek().value))throw new Error("Expected command after if condition in single-line form");{e.advance();const t=e.parseCommand();o.push(rt([t],{start:i.start,end:e.getPosition().end,line:i.line,column:i.column}))}}return yt.from(i).withArgs(...o).endingAt(e.getPosition()).build()}function kt(e,t){const n=[],r={};if(e.checkAnySelector()||e.checkContextVar()||e.match("<")){const t=e.parsePrimary();if(n.push(t),e.match("*")){if(e.checkIdentifierLike()){const t=e.advance();n.push({type:"identifier",name:"*"+t.value,start:t.start-1,end:t.end,line:t.line,column:t.column})}}else if(e.checkIdentifierLike()){const t=e.parsePrimary();n.push(t)}}else if(e.checkIdentifierLike()){const t=e.parsePrimary();n.push(t)}if(e.match("and")&&e.match("set")&&e.checkIdentifierLike()){const t=e.advance();r.set={type:"identifier",name:t.value,start:t.start,end:t.end,line:t.line,column:t.column}}const i=yt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition());return Object.keys(r).length>0&&i.withModifiers(r),i.build()}function wt(e,t){const n=[],r=mt(e,[f]);r&&n.push(r),dt(e,f,n);const i=mt(e);return i&&n.push(i),yt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function zt(e,t){const n=[];if(e.check(b)){e.advance(),n.push(e.createIdentifier("between"));const r=mt(e,[i]);r&&n.push(r),dt(e,i,n);const a=mt(e,[f,k,o]);a&&n.push(a);if(ht(e,[f,k],n)){const t=mt(e);t&&n.push(t)}return yt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}const r=mt(e,[f,k]);r&&n.push(r);if(ht(e,[f,k],n)){const t=mt(e);t&&n.push(t)}return yt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function xt(e,t){const n=e.parseExpression();if(!n)return e.addError("Put command requires content expression"),null;const i=e.peek();if(!i||!R.includes(i.value))return e.addError(`Expected operation keyword (${R.join(", ")}) after put expression, got: ${i?.value}`),null;let a=e.advance().value;const o=a.toLowerCase();"at start of"===o||"at the start of"===o?a=N:"at end of"===o||"at the end of"===o?a=O:a===I&&(e.check(C)||e.check(T)?(ft(e,T),e.check(C)&&(e.advance(),e.check(v)&&(e.advance(),a=N))):e.check(r)&&(e.advance(),e.check(v)&&(e.advance(),a=O)));const s=e.parseExpression();return s?yt.fromIdentifier(t).withArgs(n,e.createIdentifier(a),s).endingAt(e.getPosition()).build():(e.addError("Put command requires target expression after operation keyword"),null)}const Et=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function St(e,a){const o=e.savePosition();let s=null,l=[];try{s=function(e){if(!e.check(":"))return null;if(e.advance(),e.check(":")){e.advance();const t=e.advance();return{type:"identifier",name:t.value,scope:"global",start:t.start-2,end:t.end}}const t=e.advance();return{type:"identifier",name:t.value,scope:"local",start:t.start-1,end:t.end}}(e)??function(e){if(!e.check(E)&&!e.check(S))return null;const t=e.advance(),n=e.advance();return{type:"identifier",name:n.value,scope:t.value,start:t.start,end:n.end}}(e)??function(e,t){if(!e.check(T))return null;const n=e.savePosition();e.advance();const r=e.peek(),i=e.peekAt(1);if(r&&i&&i.value===v){const n=e.advance();if(e.check(v)){e.advance();const r=e.advance(),i=r.value.startsWith("#");return{type:"propertyOfExpression",property:{type:"identifier",name:n.value,start:n.start,end:n.end},target:{type:i?"idSelector":"cssSelector",value:r.value,start:r.start,end:r.end},start:t,end:e.savePosition()}}return e.restorePosition(t),null}if(r&&i&&i.value===h){const t=e.advance();return{type:"identifier",name:t.value,start:t.start,end:t.end}}return e.restorePosition(n),null}(e,o),s||(s=e.parseExpression())}catch{e.restorePosition(o),s=null}if(!s){const a=function(e){if(e.match(":")){const t=e.advance();return{expression:{type:"identifier",name:t.value,scope:"local",start:t.start,end:t.end},tokens:[]}}const a=[];for(;!(e.isAtEnd()||e.check(h)||e.check(t)||e.check(i)||e.check(n)||e.check(r));)a.push(e.parsePrimary());if(0===a.length)return{expression:null,tokens:[]};if(a.length>=4){const e=(e,t)=>e[t];if(e(a[0],"value")===T&&e(a[2],"value")===v){const t=a[1],n=a[3];return{expression:st(tt(e(t,"value")||e(t,"name")||"",{start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1}),{type:"idSelector"===n.type?"idSelector":"cssSelector",value:e(n,"value")||e(n,"name")||"",start:n.start??0,end:n.end??0,line:n.line,column:n.column},{start:a[0].start??0,end:n.end??0,line:a[0].line??1,column:a[0].column??1}),tokens:[]}}}return 1===a.length?{expression:a[0],tokens:[]}:{expression:null,tokens:a}}(e);s=a.expression,l=a.tokens}if(!e.check(h)){const t=e.isAtEnd()?"end of input":e.peek().value;throw new Error(`Expected 'to' in set command, found: ${t}`)}e.advance();const c=e.parseExpression()??e.parsePrimary(),u=[];return s?u.push(s):l.length>0&&u.push(...l),u.push(e.createIdentifier(h)),c&&u.push(c),yt.fromIdentifier(a).withArgs(...u).endingAt(e.getPosition()).build()}function Tt(e,a){switch(a.name.toLowerCase()){case"put":return xt(e,a);case"trigger":case"send":return vt(e,a);case"remove":return wt(e,a);case"toggle":return zt(e,a);case"set":return St(e,a);case"halt":return gt(e,a);case"measure":return kt(e,a);case"js":return function(e,t){const n=[];if(e.match("(")){for(;!e.check(")")&&!e.isAtEnd();)e.checkIdentifierLike()&&n.push(e.advance().value),e.match(",");e.consume(")","Expected ) after js parameters")}const i=e.peek().start;for(;!e.check(r)&&!e.isAtEnd();)e.advance();const a=e.peek(),o=a.start;e.consume(r,"Expected end after js code body");const s=e.getInputSlice(i,o),l={type:"literal",value:s.trim(),start:t.start,end:e.getPosition().end},c={type:"arrayLiteral",elements:n.map(e=>({type:"literal",value:e,start:t.start,end:t.end})),start:t.start,end:e.getPosition().end};return yt.fromIdentifier(t).withArgs(l,c).endingAt(e.getPosition()).build()}(e,a);case"tell":return function(e,a){const o=e.parseExpression();if(!o)throw new Error("tell command requires a target expression");const s=[];for(;!e.isAtEnd();){if(e.checkIsCommand()){try{e.advance();const t=e.parseCommand();if(!t)break;s.push(t)}catch{break}if(e.match(i))continue;if(e.check(t)||e.check(n)||e.check(r))break;if(e.checkIsCommand())continue;break}break}if(0===s.length)throw new Error("tell command requires at least one command after the target");return yt.fromIdentifier(a).withArgs(o,...s).endingAt(e.getPosition()).build()}(e,a);case"swap":case"morph":return function(e,t){console.log("[PARSER DEBUG] parseSwapCommand called");const n=[];let r=null;if(!e.isAtEnd()){const t=e.peek();if(t&&t.value){const i=t.value.toLowerCase();Et.includes(i)&&(r=i,e.advance(),n.push(e.createIdentifier(r)))}}if("delete"===r){const r=e.parseExpression();return r&&n.push(r),yt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}!e.isAtEnd()&&e.check(v)&&(e.advance(),n.push(e.createIdentifier("of")));const i=e.parseExpression();if(i&&n.push(i),!e.isAtEnd()&&e.check(y)){e.advance(),n.push(e.createIdentifier("with"));const t=e.parseExpression();t&&n.push(t)}return yt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}(e,a);default:return Ct(e,a)}}function Ct(e,t){const n=[];for(;!pt(e,["catch","finally"])&&(e.checkIdentifierLike()||e.checkSelector()||e.checkLiteral()||e.checkTimeExpression()||e.match("<"));)n.push(e.parsePrimary());return yt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function At(e){if(e.isAtEnd())return!0;const t=e.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(t)||pt(e)}function jt(e,t){const n={};let r=null;if(!e.isAtEnd()&&e.check("/")&&(r=function(e){const t=e.savePosition();let n="";for(;!e.isAtEnd()&&!At(e);)n+=e.advance().value;return n&&"/"!==n?{type:"literal",value:n,raw:n,start:t,end:e.savePosition()}:(e.restorePosition(t),null)}(e)),r||(r=e.parsePrimary()),!r)return e.addError("fetch requires a URL"),yt.from(t).endingAt(e.getPosition()).build();!e.isAtEnd()&&e.check("{")&&(n.with=e.parsePrimary());for(let t=0;t<2&&!e.isAtEnd();t++)if(!e.check("as")||n.as){if(!e.check("with")||n.with)break;e.advance(),Lt(e)?n.with=Pt(e):n.with=e.parsePrimary()}else e.advance(),e.isAtEnd()||ft(e,"a")||ft(e,"an"),n.as=e.parsePrimary();const i=yt.from(t).withArgs(r).endingAt(e.getPosition());return Object.keys(n).length>0&&i.withModifiers(n),i.build()}function Lt(e){if(e.check("{"))return!1;if(!e.checkIdentifierLike())return!1;const t=e.peekAt(1);return null!==t&&":"===t.value}function Pt(e){const t=[],n=e.getPosition();do{if(!e.checkIdentifierLike())break;const n=e.advance(),r={type:"identifier",name:n.value,start:n.start,end:n.end,line:n.line,column:n.column};e.consume(":","Expected ':' after property name in fetch named arguments");const i=e.parsePrimary();i&&t.push({key:r,value:i})}while(e.match(",")&&!e.isAtEnd());const r=e.getPosition();return{type:"objectLiteral",properties:t,start:n.start,end:r.end,line:n.line,column:n.column}}class It{constructor(e,t,n){this.current=0,this.warnings=[],this.tokens=e,this.keywordResolver=t?.keywords,this.registryIntegration=t?.registryIntegration,t?.semanticAnalyzer&&t?.language&&(this.semanticAdapter=new je({analyzer:t.semanticAnalyzer,language:t.language,confidenceThreshold:t.semanticConfidenceThreshold??.5})),this.originalInput=n||e.map(e=>e.value).join(" ")}resolveKeyword(e){return this.keywordResolver?this.keywordResolver.resolve(e)??e:e}addWarning(e){this.warnings.push(e)}parse(){try{if(0===this.tokens.length)return this.addError("Cannot parse empty input"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings};if(this.check("behavior")){const e=[];for(;this.check("behavior");){this.advance();const t=this.parseBehaviorDefinition();if(t&&e.push(t),this.error)break}return this.error?{success:!1,node:1===e.length?e[0]:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:1===e.length?e[0]:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}}if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()){const e=[];for(;!this.isAtEnd();)if(this.checkComment())this.advance();else if(this.check("init")){this.advance();const t=this.parseTopLevelInitBlock();t&&e.push(t)}else if(this.check("on")){this.advance();const t=this.parseEventHandler();t&&e.push(t)}else{if(!this.check("def"))break;{this.advance();const t=this.parseDefFeature();t&&e.push(t)}}return this.isAtEnd()?this.error?{success:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}:(this.addError(`Unexpected token: ${this.peek().value}`),{success:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings})}if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){const e=this.parseCommandSequence();if(e){if(!this.isAtEnd()&&this.check("on")){xe("✅ PARSER: Found event handlers after command sequence, parsing as program");const t=[e];xe(`✅ PARSER: Starting with ${t.length} statement(s) from command sequence`);let n=0;for(;!this.isAtEnd()&&this.check("on");){xe(`✅ PARSER: Parsing event handler #${n+1}, current token: ${this.peek().value}`),this.advance();const e=this.parseEventHandler();if(xe("✅ PARSER: parseEventHandler returned:",e?`type=${e.type}, event=${e.event}`:"null"),e&&(t.push(e),n++,xe(`✅ PARSER: Added event handler, now have ${t.length} statements total`)),xe(`✅ PARSER: After parsing event handler, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd=${this.isAtEnd()}, check('on')=${this.check("on")}`),!this.isAtEnd()&&!this.check("on")){if(!this.isAtEnd())return xe(`⚠️ PARSER: Unexpected token after event handlers: ${this.peek().value}`),this.addError(`Unexpected token after event handlers: ${this.peek().value}`),{success:!1,node:this.createProgramNode(t),tokens:this.tokens,error:this.error};xe("✅ PARSER: No more event handlers, at end of input");break}}return xe(`✅ PARSER: Finished parsing, creating Program node with ${t.length} statements`),this.error?{success:!1,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}}return this.isAtEnd()?this.error?{success:!1,node:e,tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:e,tokens:this.tokens,warnings:this.warnings}:(this.addError(`Unexpected token: ${this.peek().value}`),{success:!1,node:e||this.createErrorNode(),tokens:this.tokens,error:this.error})}}const e=this.parseExpression();return this.error?{success:!1,node:e||this.createErrorNode(),tokens:this.tokens,error:this.error}:this.isAtEnd()?{success:!0,node:e,tokens:this.tokens,warnings:this.warnings}:(this.addError(`Unexpected token: ${this.peek().value}`),{success:!1,node:e||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings})}catch(e){return this.addError(e instanceof Error?e.message:"Unknown parsing error"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}}parseExpression(){return this.parseAssignment()}parseAssignment(){let e=this.parseLogicalOr();if(this.match("=")){if(this.check(">")){if(this.advance(),this.addError('Arrow functions (=>) are not supported in hyperscript. Use "js ... end" blocks for JavaScript callbacks.'),!this.isAtEnd())try{this.parseExpression()}catch{}return this.createErrorNode()}const t=this.previous().value,n=this.parseAssignment();e=this.createBinaryExpression(t,e,n)}return e}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.match("or");){const t=this.previous().value,n=this.parseLogicalAnd();e=this.createBinaryExpression(t,e,n)}return e}parseLogicalAnd(){let e=this.parseEquality();for(;this.match("and");){const t=this.previous().value,n=this.parseEquality();e=this.createBinaryExpression(t,e,n)}return e}parseEquality(){let e=this.parseComparison();for(;this.matchComparisonOperator()||this.match("is","match","matches","contains","include","includes","in","of","as","really");){const t=this.previous().value;if(It.POSTFIX_UNARY_OPERATORS.has(t)){e=this.createUnaryExpression(t,e,!1);continue}const n=this.parseComparison();e=this.createBinaryExpression(t,e,n)}return e}parseComparison(){let e=this.parseAddition();for(;this.matchComparisonOperator();){const t=this.previous().value;if(It.POSTFIX_UNARY_OPERATORS.has(t)){e=this.createUnaryExpression(t,e,!1);continue}const n=this.parseAddition();e=this.createBinaryExpression(t,e,n)}return e}parseAddition(){let e=this.parseMultiplication();for(;this.match("+","-")||this.matchOperator("+")||this.matchOperator("-");){const t=this.previous().value;if(this.check("+")||this.check("-"))return this.addError(`Invalid operator combination: ${t}${this.peek().value}`),e;if(this.isAtEnd())return this.addError(`Expected expression after '${t}' operator`),e;const n=this.parseMultiplication();e=this.createBinaryExpression(t,e,n)}return e}parseMultiplication(){let e=this.parseUnary();for(;this.match("*","/","%","mod");){const t=this.previous().value;if(this.check("*")||this.check("/")||this.check("%")||this.check("+")||this.check("-")){const n=this.peek().value;return"*"===t&&"*"===n?this.addError(`Unexpected token: ${n}`):this.addError(`Invalid operator combination: ${t}${n}`),e}if(this.isAtEnd())return this.addError(`Expected expression after '${t}' operator`),e;const n=this.parseUnary();e=this.createBinaryExpression(t,e,n)}return e}parseUnary(){if(this.match("not","no","exists","some","-","+")){const e=this.previous().value;if(this.isAtEnd())return this.addError(`Expected expression after '${e}' operator`),this.createErrorNode();const t=this.parseUnary();return this.createUnaryExpression(e,t,!0)}if(this.check("does")&&this.current+1<this.tokens.length&&"not"===this.tokens[this.current+1].value&&this.current+2<this.tokens.length&&"exist"===this.tokens[this.current+2].value){if(this.advance(),this.advance(),this.advance(),this.isAtEnd())return this.addError("Expected expression after 'does not exist' operator"),this.createErrorNode();const e=this.parseUnary();return this.createUnaryExpression("does not exist",e,!0)}return this.parseImplicitBinary()}parseImplicitBinary(){let e=this.parseCall();for(;!(this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("and")||this.check("else")||this.check(")")||this.check("]")||this.check(","));){if("identifier"!==e.type){if("literal"===e.type&&(this.checkNumber()||this.checkIdentifier())){const t=this.peek();return this.addError(`Missing operator between '${e.raw||e.value}' and '${t.value}'`),e}break}if(this.isCommand(e.name))if(this.isCompoundCommand(e.name.toLowerCase())){if(!(this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkTimeExpression()||this.checkString()||this.checkNumber()||this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()))break;{const t=this.createCommandFromIdentifier(e);t&&(e=t)}}else{if("wait"===e.name.toLowerCase()&&this.checkTimeExpression()){const t=this.createCommandFromIdentifier(e);t&&(e=t)}else{if(!this.checkSelector())break;{const t=this.parseCall();e=this.createBinaryExpression(" ",e,t)}}}else{if(!this.checkSelector())break;{const t=this.parseCall();e=this.createBinaryExpression(" ",e,t)}}}return e}isCommand(e){return this.keywordResolver?this.keywordResolver.isCommand(e):W.isCommand(e)}isKeyword(e){return this.keywordResolver?this.keywordResolver.isKeyword(e):W.isKeyword(e)}createCommandFromIdentifier(e){const t=[],n=this.resolveKeyword(e.name.toLowerCase());if(this.isCompoundCommand(n))return this.parseCompoundCommand(e);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.checkIsCommand())&&(this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()||this.checkEvent()||this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkString()||this.checkNumber()||this.checkTimeExpression()||this.match("<"));)t.push(this.parsePrimary());return{type:"command",name:e.name,args:t,isBlocking:!1,...void 0!==e.start&&{start:e.start},end:this.getPosition().end,...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}}isCompoundCommand(e){return W.isCompoundCommand(e)}parseCompoundCommand(e){return Tt(this.getContext(),e)}parsePutCommand(e){return xt(this.getContext(),e)}parseSetCommand(e){return St(this.getContext(),e)}parseHaltCommand(e){return gt(this.getContext(),e)}parseMeasureCommand(e){return kt(this.getContext(),e)}parseTriggerCommand(e){return vt(this.getContext(),e)}parseCommandListUntilEnd(){const e=[];for(xe("🔄 parseCommandListUntilEnd: Starting to parse command list");!this.isAtEnd()&&!this.check("end");){xe("📍 Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let t=!1;const n=this.checkIsCommand(),r=!n&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(n||r){xe(n?"✅ Found COMMAND token:":"✅ Found IDENTIFIER that is a command:",this.peek().value),this.advance();const r=this.error;try{const n=this.parseCommand();this.error&&this.error!==r&&(xe("⚠️ parseCommandListUntilEnd: Command parsing added error, restoring error state. Error was:",this.error.message),this.error=r),n&&(xe("✅ Parsed command:",n.name),e.push(n),t=!0)}catch(e){xe("⚠️ parseCommandListUntilEnd: Command parsing threw exception, restoring error state:",e instanceof Error?e.message:String(e)),this.error=r}}else this.checkIdentifier()&&xe("❌ IDENTIFIER is not a command:",this.peek().value);if(!t){xe("❌ No command parsed, breaking. Current token:",this.peek().value);break}for(xe("📍 After parsing command, current token:",this.peek().value);!(this.isAtEnd()||this.check("end")||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)xe("⚠️ Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))xe("✅ Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){xe("📍 No separator and no command, breaking. Current token:",this.peek().value);break}xe("✅ Next token is a command, continuing without separator")}}if(xe('🔍 After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw xe('❌ ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),new Error('Expected "end" to close repeat block');return xe('✅ Found "end", consuming it'),this.advance(),xe("✅ parseCommandListUntilEnd: Successfully parsed",e.length,"commands"),e}parseRepeatCommand(e){return function(e,t){const n=[];let r="forever",i=null,a=null,p=null,h=null,v=null,g=null;if(e.check(o)){e.advance(),r=o;const t=e.peek();Re(t)&&(v=t.value,e.advance()),e.check(d)&&(e.advance(),h=e.parseExpression())}else if(e.check(d))e.advance(),r=o,v="it",h=e.parseExpression();else if(e.check(s))e.advance(),r=s,p=e.parseExpression();else if(e.check(l))if(e.advance(),r=l,e.check(w)){e.advance(),r="until-event";const t=e.peek();if(xe("📍 Parsing event name, current token:",{value:t.value,kind:t.kind}),!Re(t)&&!Ie(t))throw new Error('Expected event name after "event"');if(i=t.value,e.advance(),xe("✅ Got event name:",i,"Next token:",e.peek().value),xe('🔍 Checking for "from", current token:',e.peek().value),e.check(f)){xe('✅ Found "from", advancing...'),e.advance(),xe('📍 After consuming "from", current token:',e.peek().value),ft(e,T)&&xe('✅ Found "the", advancing...');const t=e.peek();xe("🔍 Before parsePrimary for event target:",{value:t.value,kind:t.kind,position:t.start}),a=e.parsePrimary(),xe("✅ After parsePrimary, eventTarget:",a)}else xe('❌ No "from" found, skipping target parsing')}else p=e.parseExpression();else e.check(c)?(e.advance(),r=c):(g=e.parseExpression(),e.check(u)&&(e.advance(),r=u));let b=null;if(e.check(y)){const t=e.peekAt(1);t&&t.value.toLowerCase()===m&&(e.advance(),e.advance(),b=m)}else if(e.check(m)){e.advance();const t=e.peek();Re(t)?(b=t.value,e.advance()):b=m}const k=e.parseCommandListUntilEnd();n.push({type:"identifier",name:r,start:t.start,end:t.end,line:t.line,column:t.column});const z={start:t.start,end:t.end,line:t.line,column:t.column};return v&&n.push(it(v,z)),h&&n.push(h),p&&n.push(p),g&&n.push(g),i&&n.push(it(i,z)),a&&n.push(a),b&&n.push(it(b,z)),n.push(rt(k,{...z,end:z.end||0})),yt.from(t).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseForCommand(e){return function(e,t){const n=[];let r=null,i=null;e.check(p)&&e.advance();const a=e.peek();if(!Re(a))throw new Error('Expected variable name after "for"');if(r=a.value,e.advance(),!e.check(d))throw new Error('Expected "in" after variable name in for loop');if(e.advance(),i=e.parseExpression(),!i)throw new Error('Expected collection expression after "in"');let o=null;if(e.check(y)){const t=e.peekAt(1);t&&t.value.toLowerCase()===m&&(e.advance(),e.advance(),o=m)}else if(e.check(m)){e.advance();const t=e.peek();Re(t)?(o=t.value,e.advance()):o=m}const s=e.parseCommandListUntilEnd();n.push({type:"identifier",name:"for",start:t.start,end:t.end,line:t.line,column:t.column});const l={start:t.start,end:t.end,line:t.line,column:t.column};return n.push(it(r,l)),n.push(i),o&&n.push(it(o,l)),n.push(rt(s,{...l,end:l.end||0})),yt.from({...t,value:"repeat"}).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseWaitCommand(e){return function(e,t){const n=[];if(e.checkTimeExpression()||e.checkLiteral()){const r=e.parsePrimary();return n.push(r),yt.from(t).withArgs(...n).blocking().endingAt(e.getPosition()).build()}if(e.check("for")){e.advance();const r=[];do{const t=e.peek();if(!Re(t))throw new Error('Expected event name after "for"');const n=t.value;e.advance();const i=[];if(e.check("(")){for(e.advance();!e.isAtEnd()&&!e.check(")");){const t=e.peek();if(!Re(t))break;i.push(t.value),e.advance(),e.check(",")&&e.advance()}if(!e.check(")"))throw new Error('Expected ")" after event parameters');e.advance()}if(r.push({name:n,params:i}),!e.check("or"))break;e.advance()}while(!e.isAtEnd());let i=null;e.check(f)&&(e.advance(),ft(e,T),i=e.parsePrimary());const a={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};n.push(ot(r.map(e=>at([{key:tt("name",a),value:et(e.name,`"${e.name}"`,a)},{key:tt("args",a),value:ot(e.params.map(e=>et(e,`"${e}"`,a)),a)}],a)),a)),i&&n.push(i)}return yt.from(t).withArgs(...n).blocking().endingAt(e.getPosition()).build()}(this.getContext(),e)}parseInstallCommand(e){return function(e,t){const n=[];if(!e.checkIdentifierLike())throw new Error('Expected behavior name after "install"');const r=e.advance().value,i=e.previous();if(n.push(tt(r,{start:i.start,end:i.end,line:i.line,column:i.column})),e.check("(")){e.advance();const r=[];for(;!e.isAtEnd()&&!e.check(")");){const t=e.savePosition();let n;if(e.checkIdentifierLike()){const r=e.peek().value;e.advance(),e.check(":")?(e.advance(),n=r):e.restorePosition(t)}const i=e.parseExpression();if(r.push(void 0!==n?{name:n,value:i}:{value:i}),e.check(","))e.advance();else if(!e.check(")"))break}if(!e.check(")"))throw new Error('Expected ")" after behavior parameters');if(e.advance(),r.length>0){const i={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};n.push(at(r.map(e=>({key:e.name?tt(e.name,i):et("_positional","_positional",i),value:e.value})),i))}}return yt.from(t).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseTransitionCommand(e){return function(e,t){const n=[],r={};let i=null;const a=e.peek();if(Re(a)||"*"===a.value){let t="";e.check("*")&&(t="*",e.advance());const n=function(e){if(!e.checkIdentifierLike())return"";let t=e.advance().value;for(;e.check("-")&&!e.isAtEnd();)t+="-",e.advance(),e.checkIdentifierLike()&&(t+=e.advance().value);return t}(e);n&&(t+=n,i={type:"string",value:t,start:a.start||0,end:e.getPosition().end,line:a.line,column:a.column})}if(!i)throw new Error("Transition command requires a CSS property");if(n.push(i),!e.check(h))throw new Error('Expected "to" keyword after property in transition command');e.advance();const o=e.parsePrimary();if(r.to=o,e.check("over")){e.advance();const t=e.parsePrimary();r.over=t}if(e.check(y)){e.advance();const t=e.parsePrimary();r.with=t}return yt.from(t).withArgs(...n).withModifiers(r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseAddCommand(e){return function(e,t){const n=[];if(e.match("{"))n.push(e.parseCSSObjectLiteral());else{const t=mt(e,[h]);t&&n.push(t)}if(e.check(h)){e.advance();const t=mt(e);t&&n.push(t)}return yt.from(t).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseIfCommand(e){return bt(this.getContext(),e)}parseRemoveCommand(e){return wt(this.getContext(),e)}parseToggleCommand(e){return zt(this.getContext(),e)}parseRegularCommand(e){return Ct(this.getContext(),e)}parseCall(){let e=this.parsePrimary();for(;;)if(this.match("("))e=this.finishCall(e);else if(this.match(".")){const t=this.consumeIdentifier("Expected property name after '.' - malformed member access");e=this.createMemberExpression(e,this.createIdentifier(t.value),!1)}else if(this.match("[")){const t=this.parseExpression();this.consume("]","Expected ']' after array index"),e=this.createMemberExpression(e,t,!0)}else{if(!this.check("'s"))break;{let t;if(this.advance(),this.check("*")){this.advance();t="*"+this.consumeIdentifier("Expected property name after * in CSS property syntax").value}else if(De(this.peek())&&this.peek().value.startsWith("@"))t=this.advance().value;else{t=this.consumeIdentifier("Expected property name after possessive").value}e=this.createPossessiveExpression(e,this.createIdentifier(t))}}return e}parsePrimary(){if(this.check("*")){const e=this.current;if(this.advance(),!this.isAtEnd()&&Re(this.peek())){const e=this.advance().value;return this.createSelector("*"+e)}this.current=e}if(this.check("*")||this.check("/")||this.check("%")||this.check("mod")){const e=this.peek();return this.addError(`Binary operator '${e.value}' requires a left operand`),this.createErrorNode()}if(this.matchNumber()){const e=parseFloat(this.previous().value);return this.createLiteral(e,this.previous().value)}if(this.matchString()){const e=this.previous().value;if(e.length<2||e.startsWith('"')&&!e.endsWith('"')||e.startsWith("'")&&!e.endsWith("'"))return this.addError("Unclosed string literal - string not properly closed"),this.createErrorNode();const t=e.slice(1,-1),n=this.processEscapeSequences(t);return this.createLiteral(n,e)}if(this.matchTemplateLiteral()){const e=this.previous();return{type:"templateLiteral",value:e.value,start:e.start||0,end:e.end||0,line:e.line,column:e.column}}if(this.matchBoolean()){const e=this.previous().value;let t;switch(e){case"true":t=!0;break;case"false":t=!1;break;case"null":t=null;break;case"undefined":t=void 0;break;default:t="true"===e}return this.createLiteral(t,e)}if(this.matchTimeExpression()){const e=this.previous().value;return this.createLiteral(e,e)}if(this.matchQueryReference()){const e=this.previous().value.slice(1,-2).trim();return this.createSelector(e)}if(this.matchSelector())return this.createSelector(this.previous().value);if(this.match("<"))return this.parseHyperscriptSelector();if(this.match("(")){if(this.isAtEnd())return this.addError("Expected expression inside parentheses"),this.createErrorNode();const e=this.parseExpression();return this.consume(")","Expected closing parenthesis ')' after expression - unclosed parentheses"),e}if(this.match("{"))return this.parseObjectLiteral();if(this.match("["))return this.parseAttributeOrArrayLiteral();if(this.check(":")){if(this.advance(),this.check(":")){this.advance();const e=this.advance();return{type:"identifier",name:e.value,scope:"global",start:e.start-2,end:e.end,line:e.line,column:e.column}}{const e=this.advance();return{type:"identifier",name:e.value,scope:"local",start:e.start-1,end:e.end,line:e.line,column:e.column}}}if(this.matchBasicOperator()){const e=this.previous();return this.createIdentifier(e.value)}const e=this.peek();if(!(e&&("end"===e.value||"else"===e.value||"then"===e.value))&&(this.matchPredicate(Ve)||this.matchPredicate(Pe)||this.matchPredicate(Ne)||this.matchPredicate(Le)||this.matchPredicate(Ie))){const e=this.previous();if("new"===e.value)return this.parseConstructorCall();if("on"===e.value)return this.parseEventHandler();if("if"===e.value)return this.parseConditional();if("closest"===e.value||"first"===e.value||"last"===e.value||"previous"===e.value||"next"===e.value){if(this.check("(")||this.checkCssSelector()||this.checkClassSelector()||this.checkIdSelector()||this.check("<")||this.checkQueryReference())return this.parseNavigationFunction(e.value);if(this.check(".")){const t=this.current;if(this.advance(),this.checkIdentifier()){const t="."+this.advance().value,n=this.createSelector(t);return this.createCallExpression(this.createIdentifier(e.value),[n])}this.current=t}if(this.check("#")){const t=this.current;if(this.advance(),this.checkIdentifier()){const t="#"+this.advance().value,n=this.createSelector(t);return this.createCallExpression(this.createIdentifier(e.value),[n])}this.current=t}return this.createIdentifier(e.value)}return"my"!==e.value||this.check(".")?"its"!==e.value||this.check(".")?"your"!==e.value||this.check(".")?"the"===e.value?this.parseTheXofY():this.createIdentifier(e.value):this.parseContextPropertyAccess("you"):this.parseContextPropertyAccess("it"):this.parseContextPropertyAccess("me")}if(this.match("$"))return this.parseDollarExpression();if(De(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return{type:"attributeAccess",attributeName:e.value.substring(1),start:e.start,end:e.end,line:e.line,column:e.column}}const t=this.peek();return this.addError(`Unexpected token: ${t.value} at line ${t.line}, column ${t.column}`),this.advance(),this.createErrorNode()}parseDollarExpression(){if(this.checkNumber()){const e=this.advance().value;return this.createLiteral(e,`$${e}`)}if(this.checkIdentifier()){const e=this.advance();let t=this.createIdentifier(e.value);for(;this.match(".");){if(!this.checkIdentifier())return this.addError("Expected property name after '.' in dollar expression"),this.createErrorNode();{const e=this.advance();t=this.createMemberExpression(t,this.createIdentifier(e.value),!1)}}return{type:"dollarExpression",expression:t,raw:`$${e.value}${this.previous().value||""}`,line:e.line,column:e.column-1}}return this.addError("Expected identifier or number after '$'"),this.createErrorNode()}parseHyperscriptSelector(){let e="";for(;!this.check("/")&&!this.isAtEnd();)e+=this.advance().value;return this.consume("/","Expected '/' in hyperscript selector"),this.consume(">","Expected '>' after '/' in hyperscript selector"),this.createSelector(e)}parseObjectLiteral(){const e=[],t=this.getPosition();if(this.check("}"))return this.advance(),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column};do{let t;if(this.matchPredicate(Ve))t=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected property name in object literal"),this.createErrorNode();{const e=this.previous().value,n=e.slice(1,-1);t=this.createLiteral(n,e)}}this.consume(":","Expected ':' after property name in object literal");const n=this.parseExpression();if(e.push({key:t,value:n}),!this.match(","))break;if(this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after object literal properties"),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseCSSObjectLiteral(){const e=this.getPosition(),t=[];do{if(this.check("}"))break;let n;if(this.matchPredicate(Ve))n=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected CSS property name"),this.createErrorNode();{const e=this.previous().value,t=e.slice(1,-1);n=this.createLiteral(t,e)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const r=[];let i=!1,a=0;for(;!this.isAtEnd()&&(0!==a||!this.check(";")&&!this.check("}"));){const e=this.advance();r.push(e.value),"$"===e.value&&this.check("{")&&(i=!0),"{"===e.value&&a++,"}"===e.value&&a--}const o=r.join(""),s=i?{type:"templateLiteral",value:o,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}:this.createLiteral(o,o);if(t.push({key:n,value:s}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseConstructorCall(){const e=this.previous();if(!this.checkIdentifier())return this.addError('Expected constructor name after "new"'),this.createErrorNode();const t=this.advance(),n=t.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();this.advance();if(this.check(")"))this.advance();else{let e=1;for(;e>0&&!this.isAtEnd();){const t=this.advance();"("===t.value&&e++,")"===t.value&&e--}}return{type:"callExpression",callee:{type:"identifier",name:n,start:t.start,end:t.end,line:t.line,column:t.column},arguments:[],isConstructor:!0,start:e.start,end:this.previous().end,line:e.line,column:e.column}}parseTopLevelInitBlock(){const e=this.getPosition(),t=this.parseCommandBlock(["end"]);return this.consume("end","Expected 'end' after init block"),{type:"initBlock",commands:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseDefFeature(){const e=this.getPosition();let t="";if(!this.checkIdentifier())return this.addError("Expected function name after 'def'"),{type:"def",name:"",params:[],body:[],start:e.start,end:this.getPosition().end,line:e.line,column:e.column};for(t=this.advance().value;this.check(".");)this.advance(),this.checkIdentifier()&&(t+="."+this.advance().value);const n=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&n.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&n.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const r=this.parseCommandBlock(["end","catch","finally"]);let i,a,o;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(i=this.advance().value),a=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),o=this.parseCommandBlock(["end"])),this.consume("end","Expected 'end' after function definition"),{type:"def",name:t,params:n,body:r,...void 0!==i&&{errorSymbol:i},...void 0!==a&&{errorHandler:a},...void 0!==o&&{finallyHandler:o},start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseEventNameWithNamespace(e){let t;t=this.checkEvent()||this.checkIdentifier()||this.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(e);let n=t.value;if(this.check(":")){this.advance();n=`${n}:${this.advance().value}`}return n}callExprToCommandNode(e,t){return{type:"command",name:e.callee.name,args:e.arguments,isBlocking:!1,...void 0!==t.start&&{start:t.start},...void 0!==t.end&&{end:t.end},...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}}createPseudoCommandNode(e,t,n,r,i){return{type:"command",name:"pseudo-command",args:[{type:"objectLiteral",properties:[{key:{type:"identifier",name:"methodName"},value:{type:"literal",value:e,raw:`"${e}"`}},{key:{type:"identifier",name:"methodArgs"},value:{type:"literal",value:t.arguments,raw:JSON.stringify(t.arguments)}},...n?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:n,raw:`"${n}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:r}]}],isBlocking:!1,...void 0!==i.start&&{start:i.start},...void 0!==i.end&&{end:i.end},...void 0!==i.line&&{line:i.line},...void 0!==i.column&&{column:i.column}}}tryParsePseudoCommand(e,t){const n=e.callee.name,r=this.peek();if(!(It.PSEUDO_COMMAND_PREPOSITIONS.includes(r.value.toLowerCase())||Ve(r)&&!this.isCommand(r.value)||Ne(r)))return{node:this.callExprToCommandNode(e,t),isPseudo:!1,targetFailed:!1};let i,a;this.isCommand(n)&&this.addWarning({type:"command-shadow",message:`Method '${n}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${n}Fn', 'my${n.charAt(0).toUpperCase()+n.slice(1)}')`,`Use 'call' command instead: call ${n}(...)`,"This works but may cause ambiguity"],severity:"warning",code:"PSEUDO_CMD_SHADOW",...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}),It.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(i=this.advance().value.toLowerCase());try{a=this.parseExpression()}catch{return{node:this.callExprToCommandNode(e,t),isPseudo:!1,targetFailed:!0}}return{node:this.createPseudoCommandNode(n,e,i,a,t),isPseudo:!0,targetFailed:!1}}parseCommandWithErrorRecovery(){this.advance();const e=this.error;try{const t=this.parseCommand();return this.error&&this.error!==e&&(xe("⚠️ Command parsing added error, restoring error state. Error was:",this.error.message),this.error=e),t}catch(t){return xe("⚠️ Command parsing threw exception, restoring error state:",t instanceof Error?t.message:String(t)),this.error=e,null}}parseEventHandler(){xe("🔧 parseEventHandler: ENTRY - parsing event handler");const e=[],t=this.parseEventNameWithNamespace("Expected event name after 'on'");for(e.push(t),xe(`🔧 parseEventHandler: Parsed first event name: ${t}`);this.check("or");){this.advance(),xe("🔧 parseEventHandler: Found 'or', parsing additional event name");const t=this.parseEventNameWithNamespace("Expected event name after 'or'");e.push(t),xe(`🔧 parseEventHandler: Parsed additional event name: ${t}`)}let n;if(xe(`🔧 parseEventHandler: Total events parsed: ${e.join(", ")}`),this.registryIntegration){const t=e[0];if(this.registryIntegration.hasEventSource(t)){const e=this.registryIntegration.getEventSource(t);n=e?.name,xe(`🔧 parseEventHandler: Detected custom event source '${n}' for event '${t}'`)}}const r=[];if(this.match("(")){if(!this.check(")"))do{const e=this.advance();r.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),xe(`🔧 parseEventHandler: Parsed event parameters: ${r.join(", ")}`)}const i={};for(;this.check(".");){this.advance();const e=this.advance().value.toLowerCase();if("once"===e)i.once=!0,xe("🔧 parseEventHandler: Parsed modifier '.once'");else if("prevent"===e)i.prevent=!0,xe("🔧 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===e)i.stop=!0,xe("🔧 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===e||"throttle"===e){if(!this.check("("))throw new Error(`Expected '(' after '.${e}'`);{this.advance();const t=this.advance(),n=parseInt(t.value,10);if(isNaN(n))throw new Error(`Expected number for ${e} delay, got: ${t.value}`);"debounce"===e?(i.debounce=n,xe(`🔧 parseEventHandler: Parsed modifier '.debounce(${n})'`)):(i.throttle=n,xe(`🔧 parseEventHandler: Parsed modifier '.throttle(${n})'`)),this.consume(")",`Expected ')' after ${e} delay`)}}else xe(`🔧 parseEventHandler: Warning - unknown modifier '.${e}'`)}if(this.check("debounced")||this.check("throttled")){const e=this.advance().value.toLowerCase(),t="debounced"===e?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const n=this.advance(),r=(a=n.value).endsWith("ms")?parseInt(a,10):a.endsWith("seconds")||a.endsWith("s")?1e3*parseFloat(a):a.endsWith("minutes")?6e4*parseFloat(a):a.endsWith("hours")?36e5*parseFloat(a):a.endsWith("days")?864e5*parseFloat(a):parseInt(a,10);i[t]=r,xe(`🔧 parseEventHandler: Parsed '${e} at ${n.value}' (${r}ms)`)}else if(this.matchNumber()){const n=parseInt(this.previous().value,10);i[t]=n,xe(`🔧 parseEventHandler: Parsed '${e} at ${n}'`)}else this.addError(`Expected time expression after '${e} at', got: ${this.peek().value}`);else this.addError(`Expected 'at' after '${e}'`)}var a;let o,s,l,c;if(Object.keys(i).length>0&&xe("🔧 parseEventHandler: Parsed modifiers:",i),this.match("[")&&(o=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const e=this.advance();s=e.value,xe(`🔧 parseEventHandler: Parsed 'from' target: ${s} (kind: ${e.kind})`)}if(this.match("of")){const e=this.advance();l=e.value.startsWith("@")?e.value.substring(1):e.value,xe(`🔧 parseEventHandler: Parsed attribute name: ${l}`)}this.match("in")&&(xe("🔧 parseEventHandler: Found 'in' keyword, parsing watch target"),c=this.parseExpression(),xe("🔧 parseEventHandler: Parsed watch target expression"));const u=[];for(xe(`✅ parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(xe(`✅ parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){xe("✅ parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())xe(`✅ parseEventHandler: Skipping comment token: ${this.peek().value}`),this.advance();else{if(this.check("end")){xe("✅ parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.checkIsCommand()){const e="("===this.tokens[this.current+1]?.value,t=this.peek().value.toLowerCase();if(e&&!("js"===t||"tell"===t)){let e;const t=this.error;try{e=this.parseExpression()}catch(e){this.error=t,this.advance();const n=this.parseCommand();u.push(n);continue}if(e&&"callExpression"===e.type){const t=this.tryParsePseudoCommand(e,e);if(u.push(t.node),t.isPseudo||t.targetFailed)continue}}else{const e=this.parseCommandWithErrorRecovery();e&&(u.push(e),xe(`✅ parseEventHandler: Parsed command, next token: ${this.isAtEnd()?"END":this.peek().value}`))}}else{if(!this.checkIdentifier())break;{const e=this.peek();if(this.isCommand(e.value)){const e=this.parseCommandWithErrorRecovery();e&&u.push(e)}else{let e;const t=this.error;try{e=this.parseExpression()}catch(e){xe("⚠️ Expression parsing error, restoring error state:",e instanceof Error?e.message:String(e)),this.error=t;break}if(e&&"callExpression"===e.type){const t=this.tryParsePseudoCommand(e,e);if(u.push(t.node),t.targetFailed)continue}else{if(!e||"binaryExpression"!==e.type||" "!==e.operator)break;{const t=e;if(!t.left||"identifier"!==t.left.type||!this.isCommand(t.left.name))break;{const n={type:"command",name:t.left.name,args:[t.right],isBlocking:!1,...void 0!==e.start&&{start:e.start},...void 0!==e.end&&{end:e.end},...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}};u.push(n)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}const p=this.getPosition(),m={type:"eventHandler",event:1===e.length?e[0]:e.join("|"),events:e,commands:u,...r.length>0&&{params:r},...o&&{condition:o},...s&&{target:s},...l&&{attributeName:l},...c&&{watchTarget:c},...n&&{customEventSource:n},...Object.keys(i).length>0&&{modifiers:i},start:p.start,end:p.end,line:p.line,column:p.column};return xe(`🔧 parseEventHandler: Created node with events: ${e.join(", ")}, attributeName: ${l||"none"}, watchTarget: ${c?"yes":"none"}`),m}parseBehaviorDefinition(){const e=this.getPosition(),t=this.consumeIdentifier("Expected behavior name after 'behavior' keyword").value;/^[A-Z]/.test(t)||this.addError(`Behavior name must start with uppercase letter (got "${t}")`);const n=[];if(this.match("(")){if(!this.check(")"))do{const e=this.consumeIdentifierLike("Expected parameter name");n.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const r=new Set(n),i=[];let a;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const e=this.getPosition(),t=this.peek().value;this.advance();const n=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const e=this.peek();Ve(e)?(n.push(e.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let a;if(this.check("from")){this.advance();const e=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const t=this.peek(),n=r.has(t.value);this.checkIsCommand()&&!n||(e.push(t.value),a=t.value,this.advance())}}const o=[];for(;!this.isAtEnd()&&!this.check("end");){if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){this.check("end")||this.addError(`Unexpected token in event handler: ${this.peek().value}`);break}{this.advance();const e=this.error;try{const t=this.parseCommand();for(this.error&&this.error!==e&&(this.error=e),o.push(t);!(this.isAtEnd()||this.check("end")||this.checkIsCommand()||this.isCommand(this.peek().value));)this.advance()}catch(t){this.error=e;break}}}const s={type:"eventHandler",event:t,commands:o,...void 0!==a&&{target:a},...n.length>0&&{args:n},start:e.start,end:this.getPosition().end,line:e.line,column:e.column};i.push(s),this.consume("end","Expected 'end' after event handler body")}else{if(!this.match("init")){this.addError(`Unexpected token in behavior body: ${this.peek().value}`);break}a={type:"initBlock",commands:this.parseCommandBlock(["end"]),start:e.start,end:this.getPosition().end,line:e.line,column:e.column},this.consume("end","Expected 'end' after init block")}this.consume("end","Expected 'end' to close behavior definition");return{type:"behavior",name:t,parameters:n,eventHandlers:i,...void 0!==a?{initBlock:a}:{},start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseCommandSequence(){const e=[];for(;!this.isAtEnd();){if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){this.advance();const t=this.error,n=this.parseCommand();if(this.error&&this.error!==t){this.error.message.includes("Expected closing parenthesis")||this.error.message.includes("Expected ')'")||this.error.message.includes("unclosed parenthes")||this.error.message.includes("Unclosed parenthes")||(xe("⚠️ parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=t)}for(e.push(n);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)xe("⚠️ parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){xe('✅ parseCommandSequence: Found "on" token, stopping command sequence to allow event handler parsing');break}if(this.match("then"))continue;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}this.addError(`Expected command, got: ${this.peek().value}`);break}return 1===e.length?e[0]:function(e){return{type:"CommandSequence",commands:e,start:e[0]?.start||0,end:e[e.length-1]?.end||0,line:e[0]?.line||1,column:e[0]?.column||1}}(e)}getMultiWordPattern(e){return function(e){return lt.find(t=>t.command===e.toLowerCase())||null}(e)}isTokenKeyword(e,t){return ct(e,t)}parseMultiWordCommand(e,t){return function(e,t,n){const r=e.getMultiWordPattern(n);if(!r)return null;const i=[],a={};for(;!pt(e,["catch","finally",...r.keywords])&&!ct(e.peek(),r.keywords);){const t=e.parsePrimary();if(!t)break;if(i.push(t),!e.match(",")&&ct(e.peek(),r.keywords))break}for(;!e.isAtEnd()&&ct(e.peek(),r.keywords);){const t=e.advance().value,n=e.parseExpression();if(n&&(a[t]=n),!ct(e.peek(),r.keywords))break}const o=yt.from(t).withArgs(...i).endingAt(e.getPosition());return Object.keys(a).length>0&&o.withModifiers(a),o.build()}(this.getContext(),e,t)}parseCommandBlock(e){const t=[];for(;!this.isAtEnd()&&!e.some(e=>this.check(e));)if(this.checkComment())this.advance();else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value))break;{this.advance();const e=this.parseCommand();t.push(e)}}return t}trySemanticParse(e){if(!this.semanticAdapter||!this.semanticAdapter.isAvailable())return null;try{const t=this.semanticAdapter.trySemanticParse(e);return t.success&&t.node?(xe(`[Semantic] Successfully parsed with confidence ${t.confidence}:`,t.node.name),t.node):(xe(`[Semantic] Low confidence (${t.confidence}), falling back to traditional parser`),null)}catch(e){return xe("[Semantic] Error during semantic parse:",e),null}}getRemainingInput(){if(!this.originalInput)return this.tokens.slice(this.current>0?this.current-1:0).map(e=>e.value).join(" ");const e=this.current>0?this.tokens[this.current-1]:this.tokens[0];return e&&void 0!==e.start?this.originalInput.slice(e.start):this.originalInput}skipToCommandBoundary(){const e=["then","and","else","end"];for(;!this.isAtEnd();){const t=this.peek(),n=t.value.toLowerCase();if(e.includes(n))break;if(Le(t))break;this.advance()}}parseCommand(){const e=this.previous();let t=e.value;if(this.semanticAdapter&&!["install","wait","repeat","for","set","put","increment","decrement","add","if","unless","make","measure","trigger","halt","remove","exit","return","closest","js","tell"].includes(t.toLowerCase())){const e=this.getRemainingInput(),t=this.trySemanticParse(e);if(t)return this.skipToCommandBoundary(),t}if("beep"===t&&this.check("!")&&(this.advance(),t="beep!"),"fetch"===t)return jt(this.getContext(),e);const n=this.parseMultiWordCommand(e,t);if(n)return n;const r=t.toLowerCase();if("repeat"===r)return this.parseRepeatCommand(e);if("for"===r)return this.parseForCommand(e);if("if"===r||"unless"===r)return this.parseIfCommand(e);if("wait"===r)return this.parseWaitCommand(e);if("install"===r)return this.parseInstallCommand(e);if("transition"===r)return this.parseTransitionCommand(e);if("add"===r)return this.parseAddCommand(e);if(this.isCompoundCommand(r)){const t={type:"identifier",name:r,start:e.start||0,end:e.end||0,line:e.line,column:e.column};return this.parseCompoundCommand(t)||this.createErrorNode()}const i=[];if(("increment"===t||"decrement"===t)&&!this.isAtEnd())return function(e,t){const n=t.value,r="increment"===n?"+":"-";let i=!1;e.check(E)&&(i=!0,e.advance());const a=e.parseExpression();if(!a)throw new Error(`Expected variable or expression after ${n}`);let o;if(e.check(g)){e.advance();const t=e.parseExpression();if(!t)throw new Error(`Expected amount after 'by' in ${n} command`);o=t}else o=et(1,"1",{start:t.start,end:e.previous().end,line:t.line,column:t.column});let s=a;i&&"identifier"===a.type&&(s={...a,scope:"global"});const l={start:t.start,end:e.previous().end,line:t.line,column:t.column},c=nt(r,a,o,l),u=[s,tt(h,l),c];return yt.from(t).withName("set").withArgs(...u).withOriginalCommand(n).endingAt({end:e.previous().end}).build()}(this.getContext(),e);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.check("end")||this.checkIsCommand());){const e=this.parseExpression();if(e?i.push(e):i.push(this.parsePrimary()),this.match(","))continue;const t=["into","from","to","with","by","at","before","after","over"];if(t.some(e=>this.check(e)))continue;const n=i[i.length-1];if(!n||"identifier"!==n.type&&"keyword"!==n.type||!t.includes(n.name??n.value))break}const a=this.getPosition();return{type:"command",name:t,args:i,isBlocking:!1,start:a.start,end:a.end,line:a.line,column:a.column}}parseConditional(){const e=this.parseExpression();this.consume("then","Expected 'then' after if condition");const t=this.parseConditionalBranch();let n;this.match("else")&&(n=this.parseConditionalBranch());const r=this.getPosition();return{type:"conditionalExpression",test:e,consequent:t,alternate:n,start:r.start,end:r.end,line:r.line,column:r.column}}parseConditionalBranch(){if(this.checkIsCommand()){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}if(this.checkIdentifier()||this.checkKeyword()){const e=this.peek();if(this.isCommand(e.value)){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}}return this.parseExpression()}parseNavigationFunction(e){const t=[];if(this.match("of"))t.push(this.parseExpression());else{if(this.check("("))return this.finishCall(this.createIdentifier(e));this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||t.push(this.parsePrimary())}return this.createCallExpression(this.createIdentifier(e),t)}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const e=this.peek(),t=e.value;if(["first","last","next","previous","random","closest"].includes(t))return this.advance(),this.parseNavigationFunction(t);if(this.current,this.advance(),!this.check("of"))return this.createIdentifier(t);this.advance();return{type:"propertyOfExpression",property:{type:"identifier",name:t},target:this.parsePrimary(),line:e.line,column:e.column}}parseContextPropertyAccess(e){if("me"===e&&this.match("*")){let t="";if(!this.checkIdentifier())return this.addError("Expected property name after 'my *'"),this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(""),!1);for(t=this.advance().value;this.check("-")&&!this.isAtEnd();){if(t+="-",this.advance(),!this.checkIdentifier()){this.addError("Expected identifier after hyphen in CSS property name");break}t+=this.advance().value}const n=`computed-${t}`;return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(n),!1)}{if(De(this.peek())&&this.peek().value.startsWith("@")){const t=this.advance();return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(t.value),!1)}const t={me:"my",it:"its",you:"your"},n=this.consumeIdentifier(`Expected property name after '${t[e]}'`);return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(n.value),!1)}}parseMyPropertyAccess(){return this.parseContextPropertyAccess("me")}finishCall(e){const t=[];if(!this.check(")"))do{if(this.check(","))return this.addError("Unexpected token in function arguments"),this.createCallExpression(e,[this.createErrorNode()]);t.push(this.parseExpression())}while(this.match(","));if(!this.check(")")&&"identifier"===e.type){const t=e.name;W.isCSSFunction(t)&&xe(`💡 Tip: CSS functions like ${t}() should be quoted for clean parsing. Use '${t}(...)' or \`${t}(...)\` instead.`)}return this.consume(")","Expected ')' after arguments"),this.createCallExpression(e,t)}createLiteral(e,t){return et(e,t,this.getPosition())}createIdentifier(e){return tt(e,this.getPosition())}createBinaryExpression(e,t,n){return nt(e,t,n,this.getPosition())}createUnaryExpression(e,t,n){return function(e,t,n,r){return{type:"unaryExpression",operator:e,argument:t,prefix:n,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,n,this.getPosition())}createCallExpression(e,t){return function(e,t,n){return{type:"callExpression",callee:e,arguments:t,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,this.getPosition())}createMemberExpression(e,t,n){return function(e,t,n,r){return{type:"memberExpression",object:e,property:t,computed:n,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,n,this.getPosition())}createSelector(e){return function(e,t){return{type:"selector",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}(e,this.getPosition())}createPossessiveExpression(e,t){return function(e,t,n){return{type:"possessiveExpression",object:e,property:t,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,this.getPosition())}createErrorNode(){return function(e){return{type:"identifier",name:"__ERROR__",start:e.start,end:e.end,line:e.line,column:e.column}}(this.getPosition())}processEscapeSequences(e){return e.replace(/\\(.)/g,(e,t)=>{switch(t){case"n":return"\n";case"t":return"\t";case"r":return"\r";case"b":return"\b";case"f":return"\f";case"v":return"\v";case"0":return"\0";case"\\":return"\\";case'"':return'"';case"'":return"'";default:return t}})}createProgramNode(e){return function(e){if(xe(`✅ createProgramNode: Called with ${e.length} statements`),0===e.length)return xe("✅ createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===e.length)return xe(`✅ createProgramNode: Returning single statement (type=${e[0].type})`),e[0];const t={type:"Program",statements:e,start:e[0]?.start||0,end:e[e.length-1]?.end||0,line:e[0]?.line||1,column:e[0]?.column||1};return xe(`✅ createProgramNode: Returning Program node with ${e.length} statements, type=${t.type}`),t}(e)}match(...e){for(const t of e)if(this.check(t))return this.advance(),!0;return!1}matchOperator(e){if(this.isAtEnd())return!1;const t=this.peek();return!(!Ze(t)||t.value!==e)&&(this.advance(),!0)}check(e){if(this.isAtEnd())return!1;const t=this.peek().value;return this.resolveKeyword(t)===e}checkPredicate(e){return!this.isAtEnd()&&e(this.peek())}matchPredicate(e){return!!this.checkPredicate(e)&&(this.advance(),!0)}checkSelector(){return this.checkPredicate(We)}matchSelector(){return this.matchPredicate(We)}checkAnySelector(){return this.checkPredicate(Me)}checkLiteral(){return this.checkPredicate($e)}checkIdentifierLike(){return this.checkPredicate(Re)}checkIsCommand(){return this.checkPredicate(Le)}checkCommandTerminator(){return this.checkPredicate(Xe)}checkReference(){return this.checkPredicate(He)}checkTimeExpression(){return this.checkPredicate(qe)}checkEvent(){return this.checkPredicate(Ie)}checkContextVar(){return this.checkPredicate(Ne)}checkComment(){return this.checkPredicate(_e)}checkIdentifier(){return this.checkPredicate(Ve)}checkKeyword(){return this.checkPredicate(Pe)}checkString(){return this.checkPredicate(Be)}matchString(){return this.matchPredicate(Be)}checkNumber(){return this.checkPredicate(Fe)}matchNumber(){return this.matchPredicate(Fe)}checkBoolean(){return this.checkPredicate(Ue)}matchBoolean(){return this.matchPredicate(Ue)}checkTemplateLiteral(){return this.checkPredicate(Ke)}matchTemplateLiteral(){return this.matchPredicate(Ke)}checkQueryReference(){return this.checkPredicate(Ge)}matchQueryReference(){return this.matchPredicate(Ge)}checkIdSelector(){return this.checkPredicate(Qe)}checkClassSelector(){return this.checkPredicate(Je)}checkCssSelector(){return this.checkPredicate(Ye)}checkBasicOperator(){return this.checkPredicate(Ze)}matchBasicOperator(){return this.matchPredicate(Ze)}matchTimeExpression(){return this.matchPredicate(qe)}matchIdentifierLike(){return this.matchPredicate(Re)}matchComparisonOperator(){return this.matchPredicate(Oe)}consumePredicate(e,t){return this.checkPredicate(e)?this.advance():(this.addError(t),this.peek())}consumeIdentifier(e){return this.consumePredicate(Ve,e)}consumeIdentifierLike(e){return this.consumePredicate(Re,e)}consumeEvent(e){return this.consumePredicate(Ie,e)}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.current>=this.tokens.length}peek(){return this.isAtEnd()?{kind:"unknown",value:"",start:0,end:0,line:1,column:1}:this.tokens[this.current]}previous(){return this.tokens[this.current-1]}consume(e,t){return this.check(e)?this.advance():(this.addError(t),this.peek())}addError(e){const t=this.peek();let n=t.start||0,r=t.line||1,i=t.column||1;if(e.includes("property name after '.'")){const e=this.current>0?this.previous():t;n=e.end||e.start||0,r=e.line||1,i=e.column||1}if(e.includes("parenthes")){const e=this.current>0?this.previous():t;n=e.end||e.start||0,r=e.line||1,i=e.column||1,0===n&&this.current>0&&(n=this.current)}if(e.includes("Expected expression after")){const e=this.current>0?this.previous():t;n=e.start||0,r=e.line||1,i=e.column||1,0===n&&(n=Math.max(1,this.current-1))}if(e.includes("Missing operand")){let e=t;for(let t=this.current-1;t>=0;t--){const n=this.tokens[t];if(n&&("+"===n.value||"-"===n.value)){e=n;break}}n=e.start||0,r=e.line||1,i=e.column||1}this.error={message:e,line:Math.max(1,r),column:Math.max(1,i),position:Math.max(0,n)}}parseAttributeOrArrayLiteral(){const e=this.previous().start,t=this.previous().line,n=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const r=[];for(;!this.check("]")&&!this.isAtEnd();){const e=this.advance();r.push(e.value)}this.consume("]","Expected ']' after attribute literal");const i="["+r.join("")+"]";return{type:"literal",value:i,raw:i,start:e,end:this.previous().end,line:t,column:n}}const r=[];if(!this.check("]"))do{if(this.check("]"))break;r.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:r,start:e,end:this.previous().end,line:t,column:n}}getPosition(){const e=this.current>0?this.previous():this.peek();return{start:e.start||0,end:e.end||0,line:e.line||1,column:e.column||1}}getContext(){const e=this,t={tokens:this.tokens,advance:this.advance.bind(this),peek:this.peek.bind(this),previous:this.previous.bind(this),consume:this.consume.bind(this),check:this.check.bind(this),checkIdentifierLike:this.checkIdentifierLike.bind(this),checkSelector:this.checkSelector.bind(this),checkAnySelector:this.checkAnySelector.bind(this),checkLiteral:this.checkLiteral.bind(this),checkReference:this.checkReference.bind(this),checkTimeExpression:this.checkTimeExpression.bind(this),checkEvent:this.checkEvent.bind(this),checkIsCommand:this.checkIsCommand.bind(this),checkContextVar:this.checkContextVar.bind(this),match:this.match.bind(this),matchOperator:this.matchOperator.bind(this),isAtEnd:this.isAtEnd.bind(this),createIdentifier:this.createIdentifier.bind(this),createLiteral:this.createLiteral.bind(this),createSelector:this.createSelector.bind(this),createBinaryExpression:this.createBinaryExpression.bind(this),createUnaryExpression:this.createUnaryExpression.bind(this),createMemberExpression:this.createMemberExpression.bind(this),createPossessiveExpression:this.createPossessiveExpression.bind(this),createCallExpression:this.createCallExpression.bind(this),createErrorNode:this.createErrorNode.bind(this),createProgramNode:this.createProgramNode.bind(this),createCommandFromIdentifier:this.createCommandFromIdentifier.bind(this),parseExpression:this.parseExpression.bind(this),parsePrimary:this.parsePrimary.bind(this),parseCall:this.parseCall.bind(this),parseAssignment:this.parseAssignment.bind(this),parseLogicalOr:this.parseLogicalOr.bind(this),parseLogicalAnd:this.parseLogicalAnd.bind(this),parseEquality:this.parseEquality.bind(this),parseComparison:this.parseComparison.bind(this),parseAddition:this.parseAddition.bind(this),parseMultiplication:this.parseMultiplication.bind(this),parseImplicitBinary:this.parseImplicitBinary.bind(this),parseConditional:this.parseConditional.bind(this),parseConditionalBranch:this.parseConditionalBranch.bind(this),parseEventHandler:this.parseEventHandler.bind(this),parseBehaviorDefinition:this.parseBehaviorDefinition.bind(this),parseNavigationFunction:this.parseNavigationFunction.bind(this),parseMyPropertyAccess:this.parseMyPropertyAccess.bind(this),parseDollarExpression:this.parseDollarExpression.bind(this),parseHyperscriptSelector:this.parseHyperscriptSelector.bind(this),parseAttributeOrArrayLiteral:this.parseAttributeOrArrayLiteral.bind(this),parseObjectLiteral:this.parseObjectLiteral.bind(this),parseCSSObjectLiteral:this.parseCSSObjectLiteral.bind(this),parseCommand:this.parseCommand.bind(this),parseCommandSequence:this.parseCommandSequence.bind(this),parseCommandListUntilEnd:this.parseCommandListUntilEnd.bind(this),getPosition:this.getPosition.bind(this),addError:this.addError.bind(this),addWarning:this.addWarning.bind(this),isCommand:this.isCommand.bind(this),isCompoundCommand:this.isCompoundCommand.bind(this),isKeyword:this.isKeyword.bind(this),getMultiWordPattern:this.getMultiWordPattern.bind(this),resolveKeyword:this.resolveKeyword.bind(this),savePosition:()=>e.current,restorePosition:t=>{e.current=t},peekAt:t=>{const n=e.current+t;return n>=0&&n<e.tokens.length?e.tokens[n]:null},getInputSlice:(e,t)=>this.originalInput?e<0||e>=this.originalInput.length?"":void 0!==t?this.originalInput.slice(e,t):this.originalInput.slice(e):""};return Object.defineProperty(t,"current",{get:()=>e.current,set:t=>{e.current=t},enumerable:!0,configurable:!0}),t}}function Nt(e,t){const n=function(e){const t={input:"",position:0,line:1,column:1,tokens:[]};t.input=e;const n=e.length;for(;t.position<n&&(Z(t),!(t.position>=n));){const n=e[t.position];if("-"!==n||"-"!==J(t,1))if('"'!==n){if("'"===n||"'"===n){const e=J(t,1),n=t.tokens[t.tokens.length-1];if("s"!==e||!n||n.kind!==B.IDENTIFIER&&n.kind!==B.SELECTOR&&"]"!==n.value&&")"!==n.value&&"}"!==n.value)ne(t);else{const e=t.position;Y(t),Y(t),X(t,F.OPERATOR,"'s",e)}continue}if("`"!==n)if("<"!==n)if("#"!==n){if("."===n){if("."===J(t,1)){const e=t.position;Y(t),Y(t),X(t,F.OPERATOR,"..",e);continue}const e=t.tokens[t.tokens.length-1],n=new Set(["from","to","into","on","in","at","first","last","next","previous","closest","random"]),r=e&&e.kind===B.IDENTIFIER&&j.has(e.value.toLowerCase()),i=e&&e.kind===B.IDENTIFIER&&n.has(e.value.toLowerCase());if((!e||e.kind===B.OPERATOR&&")"!==e.value&&"]"!==e.value||r||i||"("===e.value||"["===e.value||"{"===e.value||","===e.value||";"===e.value)&&pe(J(t))){ie(t);continue}}if("@"!==n)if("{"!==n)if("}"!==n){if("["===n){const e=t.tokens[t.tokens.length-1],n=e&&(e.kind===F.EVENT||e.kind===F.IDENTIFIER&&_.has(e.value))&&t.tokens.length>=2&&"on"===t.tokens[t.tokens.length-2]?.value;(!e||e.kind!==F.IDENTIFIER&&e.kind!==F.CONTEXT_VAR&&")"!==e.value&&"]"!==e.value||n)&&n?(X(t,F.SYMBOL,"["),Y(t)):(X(t,F.OPERATOR,"["),Y(t));continue}if("]"!==n){if("$"===n){const e=J(t,1);if(e>="a"&&e<="z"||e>="A"&&e<="Z"||"_"===e){ue(t);continue}}he(n)?se(t):n>="0"&&n<="9"?le(t):n>="a"&&n<="z"||n>="A"&&n<="Z"||"_"===n?ce(t):(X(t,F.UNKNOWN,n),Y(t))}else X(t,F.OPERATOR,"]"),Y(t)}else X(t,F.OPERATOR,"}"),Y(t);else X(t,F.OPERATOR,"{"),Y(t);else oe(t)}else ie(t);else de(t)?ae(t):se(t);else re(t)}else ne(t);else te(t)}return t.tokens}(e);return new It(n,t,e).parse()}It.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty"]),It.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class Ot{constructor(){this.hooks=new Map,this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}register(e,t){this.unregister(e),this.hooks.set(e,t),t.beforeExecute&&this.beforeExecuteHooks.push(t.beforeExecute),t.afterExecute&&this.afterExecuteHooks.push(t.afterExecute),t.onError&&this.onErrorHooks.push(t.onError),t.interceptCommand&&this.interceptCommandHooks.push(t.interceptCommand)}unregister(e){const t=this.hooks.get(e);if(!t)return!1;if(t.beforeExecute){const e=this.beforeExecuteHooks.indexOf(t.beforeExecute);e>-1&&this.beforeExecuteHooks.splice(e,1)}if(t.afterExecute){const e=this.afterExecuteHooks.indexOf(t.afterExecute);e>-1&&this.afterExecuteHooks.splice(e,1)}if(t.onError){const e=this.onErrorHooks.indexOf(t.onError);e>-1&&this.onErrorHooks.splice(e,1)}if(t.interceptCommand){const e=this.interceptCommandHooks.indexOf(t.interceptCommand);e>-1&&this.interceptCommandHooks.splice(e,1)}return this.hooks.delete(e)}has(e){return this.hooks.has(e)}async runBeforeExecute(e){for(const t of this.beforeExecuteHooks)await t(e)}async runAfterExecute(e,t){for(const n of this.afterExecuteHooks)await n(e,t)}async runOnError(e,t){let n=t;for(const t of this.onErrorHooks){const r=await t(e,n);r instanceof Error&&(n=r)}return n}shouldIntercept(e,t){for(const n of this.interceptCommandHooks)if(n(e,t))return!0;return!1}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function Rt(e){return e instanceof Error&&("isHalt"in e||"isExit"in e||"isBreak"in e||"isContinue"in e||"isReturn"in e)?e:null}function Mt(e){return{ok:!0,value:e}}function Wt(e){return{ok:!1,error:e}}function $t(e){return!0===e.ok}class Ht{constructor(e){this.elementCleanups=new WeakMap,this.elementCount=0,this.typeCounts={listener:0,observer:0,interval:0,timeout:0,custom:0},this.globalCleanups=[],this.debugMode=e?.debug??!1}registerListener(e,t,n,r,i){this.addCleanup(e,{type:"listener",target:t,eventName:n,cleanup:()=>{t.removeEventListener(n,r,i),this.debugMode&&Se(`CleanupRegistry: Removed listener '${n}'`)},description:`${n} listener`})}registerObserver(e,t){this.addCleanup(e,{type:"observer",cleanup:()=>{t.disconnect(),this.debugMode&&Se("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(e,t){this.addCleanup(e,{type:"interval",cleanup:()=>{clearInterval(t),this.debugMode&&Se("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(e,t){this.addCleanup(e,{type:"timeout",cleanup:()=>{clearTimeout(t),this.debugMode&&Se("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(e,t,n){this.addCleanup(e,{type:"custom",cleanup:t,description:n||"Custom cleanup"})}registerGlobal(e,t="custom",n){this.globalCleanups.push({type:t,cleanup:e,description:n||"Global cleanup"}),this.debugMode&&Se(`CleanupRegistry: Registered global cleanup: ${n||t}`)}addCleanup(e,t){const n=this.elementCleanups.get(e);n?n.push(t):(this.elementCleanups.set(e,[t]),this.elementCount++),this.typeCounts[t.type]++,this.debugMode&&Se(`CleanupRegistry: Registered ${t.type} for element`,e)}cleanupElement(e){const t=this.elementCleanups.get(e);if(!t||0===t.length)return 0;let n=0;for(const e of t){try{e.cleanup(),n++}catch(e){this.debugMode&&Se("CleanupRegistry: Error during cleanup:",e)}this.typeCounts[e.type]--}return this.elementCleanups.delete(e),this.elementCount--,this.debugMode&&Se(`CleanupRegistry: Cleaned up ${n} resources for element`),n}cleanupElementTree(e){let t=this.cleanupElement(e);const n=e.querySelectorAll("*");for(const e of n)t+=this.cleanupElement(e);return t}cleanupGlobal(){let e=0;for(const t of this.globalCleanups)try{t.cleanup(),e++}catch(e){this.debugMode&&Se("CleanupRegistry: Error during global cleanup:",e)}return this.globalCleanups=[],this.debugMode&&Se(`CleanupRegistry: Cleaned up ${e} global resources`),e}cleanupAll(){return this.cleanupGlobal()}hasCleanups(e){const t=this.elementCleanups.get(e);return void 0!==t&&t.length>0}getCleanupCount(e){const t=this.elementCleanups.get(e);return t?.length??0}getStats(){let e=0,t=0,n=0,r=0,i=0;for(const a of this.globalCleanups)switch(a.type){case"listener":e++;break;case"observer":t++;break;case"interval":n++;break;case"timeout":r++;break;case"custom":i++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+e,observers:this.typeCounts.observer+t,intervals:this.typeCounts.interval+n,timeouts:this.typeCounts.timeout+r,custom:this.typeCounts.custom+i,global:this.globalCleanups.length}}setDebugMode(e){this.debugMode=e}}const qt=new Map;function Dt(e,t){return{me:e??null,it:null,you:null,result:null,locals:new Map,globals:t||qt,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}function _t(e,t){return{me:t??e.me,it:null,you:null,result:null,locals:new Map,globals:e.globals,parent:e,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}class Vt{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(e,t){const n=e.toLowerCase();this.sources.has(n)&&console.warn(`[EventSourceRegistry] Overwriting existing event source: ${e}`),this.sources.set(n,t)}unregister(e){const t=e.toLowerCase(),n=this.sources.get(t);if(n){for(const[e,n]of this.subscriptions.entries())n.source===t&&(n.unsubscribe(),this.subscriptions.delete(e));return n.destroy?.(),this.sources.delete(t)}return!1}get(e){return this.sources.get(e.toLowerCase())}has(e){return this.sources.has(e.toLowerCase())}subscribe(e,t,n){const r=this.get(e);if(!r)return void console.warn(`[EventSourceRegistry] Unknown event source: ${e}`);r.initialize?.();const i=r.subscribe(t,n);return this.subscriptions.set(i.id,i),i}unsubscribe(e){const t=this.subscriptions.get(e);return!!t&&(t.unsubscribe(),this.subscriptions.delete(e))}getSourceNames(){return Array.from(this.sources.keys())}getSubscriptions(){return Array.from(this.subscriptions.values())}findSourceForEvent(e){for(const[t,n]of this.sources.entries())if(n.supports?.(e)??n.supportedEvents?.includes(e))return t}generateId(){return`sub_${this.nextId++}_${Date.now().toString(36)}`}destroy(){for(const e of this.subscriptions.values())e.unsubscribe();this.subscriptions.clear();for(const e of this.sources.values())e.destroy?.();this.sources.clear()}}class Bt{constructor(){this.providers=new Map,this.globalProviders=new Map}register(e,t,n){const r=e.toLowerCase(),i="function"==typeof t?{name:r,provide:t,cache:n?.cache??!0,description:n?.description,dependencies:n?.dependencies}:t;this.providers.set(r,i)}registerGlobal(e,t,n){const r=e.toLowerCase(),i="function"==typeof t?{name:r,provide:t,cache:n?.cache??!0,description:n?.description,dependencies:n?.dependencies}:t;this.globalProviders.set(r,i)}unregister(e){return this.providers.delete(e.toLowerCase())}unregisterGlobal(e){return this.globalProviders.delete(e.toLowerCase())}get(e){const t=e.toLowerCase();return this.providers.get(t)??this.globalProviders.get(t)}has(e){const t=e.toLowerCase();return this.providers.has(t)||this.globalProviders.has(t)}async resolve(e,t,n){const r=this.get(e);if(!r)return;const i=`__provider_${r.name}`;if(r.cache&&n?.has(i))return n.get(i);if(r.dependencies)for(const e of r.dependencies)await this.resolve(e,t,n);const a=await r.provide(t);return r.cache&&n&&n.set(i,a),a}resolveSync(e,t,n){const r=this.get(e);if(!r)return;const i=`__provider_${r.name}`;if(r.cache&&n?.has(i))return n.get(i);const a=r.provide(t);if(a instanceof Promise)throw new Error(`Context provider '${e}' is async. Use resolve() instead of resolveSync().`);return r.cache&&n&&n.set(i,a),a}enhance(e){const t=this,n=new Map;return new Proxy(e,{get(e,r,i){if("string"==typeof r){if(t.get(r))try{return t.resolveSync(r,e,n)}catch{return t.resolve(r,e,n)}}return Reflect.get(e,r,i)},has:(e,n)=>!("string"!=typeof n||!t.has(n))||Reflect.has(e,n)})}async resolveAll(e){const t=new Map,n={},r=[...this.globalProviders.entries(),...this.providers.entries()];for(const[i,a]of r)try{n[i]=await this.resolve(i,e,t)}catch(e){console.warn(`[ContextProviderRegistry] Failed to resolve '${i}':`,e),n[i]=void 0}return n}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const Ft=new class{constructor(e={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:!1,cacheCoercions:!0,...e},this.registerBuiltinTypes()}register(e){this.types.has(e.name)&&console.warn(`ExpressionTypeRegistry: Overwriting existing type '${e.name}'`),this.types.set(e.name,e)}get(e){return this.types.get(e)}has(e){return this.types.has(e)}getTypeNames(){return Array.from(this.types.keys())}inferType(e){for(const[t,n]of this.types)if(n.isType(e))return t;return"Unknown"}getHyperScriptType(e){const t=this.inferType(e),n=this.types.get(t);return n?.hyperscriptType??"unknown"}coerce(e,t,n){const r=this.types.get(t);if(!r){if(this.config.strictMode)throw new Error(`Unknown target type: ${t}`);return null}if(r.isType(e))return e;if(this.config.cacheCoercions){const n=`${this.inferType(e)}:${t}:${JSON.stringify(e)}`;if(this.coercionCache.has(n))return this.coercionCache.get(n)}const i=this.inferType(e),a=r.coerceFrom?.[i];if(a){const r=a(e,n);if(this.config.cacheCoercions&&null!==r){const n=`${i}:${t}:${JSON.stringify(e)}`;this.coercionCache.set(n,r)}return r}return r.defaultValue}canCoerce(e,t){const n=this.types.get(t);if(!n)return!1;if(n.isType(e))return!0;const r=this.inferType(e);return void 0!==n.coerceFrom?.[r]}getCoercionInfo(e,t){const n=this.types.get(t);return n&&(e===t||n.coerceFrom?.[e])?{possible:!0,direct:!0}:{possible:!1,direct:!1}}clearCache(){this.coercionCache.clear()}getStats(){return{typeCount:this.types.size,cacheSize:this.coercionCache.size,typeNames:this.getTypeNames()}}registerBuiltinTypes(){this.register({name:"String",hyperscriptType:"string",tsType:"string",isType:e=>"string"==typeof e,defaultValue:"",description:"Text string value",examples:["hello","world",""],coerceFrom:{Number:e=>String(e),Boolean:e=>String(e),Null:()=>"",Undefined:()=>"",Array:e=>Array.isArray(e)?e.join(", "):null,Object:e=>{try{return JSON.stringify(e)}catch{return String(e)}},Element:e=>e instanceof Element?e.textContent??e.outerHTML:null}}),this.register({name:"Number",hyperscriptType:"number",tsType:"number",isType:e=>"number"==typeof e&&!isNaN(e),defaultValue:0,description:"Numeric value (integer or float)",examples:[0,1,3.14,-42],coerceFrom:{String:e=>{const t=parseFloat(e);return isNaN(t)?null:t},Boolean:e=>e?1:0,Null:()=>0,Undefined:()=>null}}),this.register({name:"Boolean",hyperscriptType:"boolean",tsType:"boolean",isType:e=>"boolean"==typeof e,defaultValue:!1,description:"True or false value",examples:[!0,!1],coerceFrom:{String:e=>{const t=e.toLowerCase().trim();return"true"===t||"yes"===t||"1"===t||"false"!==t&&"no"!==t&&"0"!==t&&""!==t&&t.length>0},Number:e=>0!==e,Null:()=>!1,Undefined:()=>!1,Array:e=>!!Array.isArray(e)&&e.length>0,Element:e=>e instanceof Element,ElementList:e=>Array.isArray(e)&&e.length>0}}),this.register({name:"Element",hyperscriptType:"element",tsType:"Element | HTMLElement",isType:e=>e instanceof Element,defaultValue:null,description:"DOM Element",coerceFrom:{String:(e,t)=>{const n=e;if(n.startsWith("#")||n.startsWith(".")||n.match(/^[\w-]+$/))try{return document.querySelector(n)}catch{return null}return null},ElementList:e=>Array.isArray(e)&&e.length>0?e[0]:null,NodeList:e=>{const t=e;return t.length>0?t[0]:null}}}),this.register({name:"ElementList",hyperscriptType:"element-list",tsType:"Element[]",isType:e=>Array.isArray(e)&&e.length>0&&e.every(e=>e instanceof Element),defaultValue:[],description:"Array of DOM Elements",coerceFrom:{Element:e=>e instanceof Element?[e]:[],NodeList:e=>Array.from(e),String:e=>{try{return Array.from(document.querySelectorAll(e))}catch{return[]}},Array:e=>{const t=e;return t.every(e=>e instanceof Element)?t:[]}}}),this.register({name:"Array",hyperscriptType:"array",tsType:"unknown[]",isType:e=>Array.isArray(e),defaultValue:[],description:"Array of values",coerceFrom:{String:e=>{const t=e;try{const e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t.split(",").map(e=>e.trim())},ElementList:e=>e,NodeList:e=>Array.from(e),Object:e=>Object.values(e)}}),this.register({name:"Object",hyperscriptType:"object",tsType:"Record<string, unknown>",isType:e=>!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof Element),defaultValue:{},description:"Plain JavaScript object",coerceFrom:{String:e=>{try{const t=JSON.parse(e);if("object"==typeof t&&null!==t&&!Array.isArray(t))return t}catch{}return null},Array:e=>{const t={};return e.forEach((e,n)=>{t[String(n)]=e}),t}}}),this.register({name:"Null",hyperscriptType:"null",tsType:"null",isType:e=>null===e,defaultValue:null,description:"Null value"}),this.register({name:"Undefined",hyperscriptType:"undefined",tsType:"undefined",isType:e=>void 0===e,defaultValue:void 0,description:"Undefined value"}),this.register({name:"Function",hyperscriptType:"function",tsType:"Function",isType:e=>"function"==typeof e,defaultValue:null,description:"JavaScript function"}),this.register({name:"Event",hyperscriptType:"event",tsType:"Event",isType:e=>e instanceof Event,defaultValue:null,description:"DOM Event"}),this.register({name:"NodeList",hyperscriptType:"element-list",tsType:"NodeList",isType:e=>e instanceof NodeList,defaultValue:null,description:"DOM NodeList (typically from querySelectorAll)",coerceFrom:{Array:e=>null}}),this.register({name:"Unknown",hyperscriptType:"unknown",tsType:"unknown",isType:e=>!0,defaultValue:null,description:"Unknown/any value type"})}};function Ut(e){const t=Ft.get("String");return t?t.isType(e):"string"==typeof e}function Kt(e){const t=Ft.get("Number");return t?t.isType(e):"number"==typeof e}function Gt(e){const t=Ft.get("Boolean");return t?t.isType(e):"boolean"==typeof e}function Qt(e){const t=Ft.get("Object");return t?t.isType(e):"object"==typeof e&&null!==e}function Jt(e){const t=Ft.get("Function");return t?t.isType(e):"function"==typeof e}function Yt(e){if(null===e||"object"!=typeof e||!("tagName"in e))return!1;const t=e.tagName;return"INPUT"===t||"SELECT"===t||"TEXTAREA"===t}function Zt(e){return e instanceof Element}const Xt=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function en(e,t){return Xt.has(t.toLowerCase())?e.hasAttribute(t):e.getAttribute(t)}const tn={id:e=>e.id,classname:e=>e.className,class:e=>e.className,tagname:e=>e.tagName.toLowerCase(),innertext:e=>e.textContent?.trim(),innerHTML:e=>e.innerHTML,outerhtml:e=>e.outerHTML,value:e=>Yt(e)?e.value:void 0,checked:e=>function(e){return null!==e&&"object"==typeof e&&"tagName"in e&&"INPUT"===e.tagName}(e)?e.checked:void 0,disabled:e=>Yt(e)?e.disabled:void 0,selected:e=>function(e){return null!=e&&"object"==typeof e&&"tagName"in e&&"OPTION"===e.tagName}(e)?e.selected:void 0,hidden:e=>function(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"style"in e}(e)?e.hidden:void 0,style:e=>getComputedStyle(e),children:e=>Array.from(e.children),parent:e=>e.parentElement,firstchild:e=>e.firstElementChild,lastchild:e=>e.lastElementChild,nextsibling:e=>e.nextElementSibling,previoussibling:e=>e.previousElementSibling};function nn(e,t){if(t.startsWith("computed-")){const n=t.slice(9);if(function(e){return e instanceof HTMLElement}(e)){return getComputedStyle(e).getPropertyValue(n)}return}if(t.startsWith("@")){return en(e,t.slice(1))}const n=tn[t.toLowerCase()];if(n)return n(e);if(function(e,t){return e.hasAttribute(t)}(e,t))return en(e,t);const r=e[t];return Jt(r)?r.bind(e):r}function rn(e){if("string"==typeof e)return e;if(e&&"object"==typeof e){if("string"==typeof e.name)return e.name;if("string"==typeof e.value)return e.value}return e}function an(e){return e.me?.ownerDocument??("undefined"!=typeof document?document:null)}function on(e,t){return t.locals?.has(e)?t.locals.get(e):t.globals?.has(e)?t.globals.get(e):t.variables?.has(e)?t.variables.get(e):"me"===e?t.me:"it"===e?t.it:"result"===e?t.result:void 0}async function sn(e,t){if(e.includes(".")){const n=e.split(".");let r=on(n[0],t);for(let e=1;e<n.length&&null!=r;e++)r=r[n[e]];return r}return on(e,t)}async function ln(e,t){if(Ee(`RESOLVE: Looking for '${e}' in context`,{hasInLocals:t.locals.has(e),localsKeys:Array.from(t.locals.keys()),value:t.locals.get(e)}),t.locals.has(e)){const n=t.locals.get(e);return Ee(`RESOLVE: Found '${e}' in locals:`,n),n}if(t.globals&&t.globals.has(e)){const n=t.globals.get(e);return Ee(`RESOLVE: Found '${e}' in globals:`,n),n}if(t.variables&&t.variables.has(e)){const n=t.variables.get(e);return Ee(`RESOLVE: Found '${e}' in variables (legacy):`,n),n}const n=Number(e);if(!isNaN(n))return n;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if(e.includes(".")){const n=e.split("."),r=n[0];let i=null;if(t.locals.has(r)?i=t.locals.get(r):t.globals&&t.globals.has(r)?i=t.globals.get(r):t.variables&&t.variables.has(r)&&(i=t.variables.get(r)),null!=i){for(let e=1;e<n.length;e++){if(null==i)return void Ee(`RESOLVE: Property access failed at '${n[e-1]}'`);i=i[n[e]]}return Ee(`RESOLVE: Property access '${e}' =`,i),i}}return e}async function cn(e,t){Ee("EVAL: Evaluating expression:",e);const n=e.match(/^(.+?)\s*\?(?![\.\[])\s*(.+?)\s*:\s*(.+)$/);if(n){const[,e,r,i]=n;Ee("EVAL: Parsed ternary:",{conditionExpr:e,trueExpr:r,falseExpr:i});const a=await ln(e.trim(),t);if(Ee("EVAL: Ternary condition value:",a),a){const e=await ln(r.trim(),t);return Ee("EVAL: Ternary returned true branch:",e),e}{const e=await ln(i.trim(),t);return Ee("EVAL: Ternary returned false branch:",e),e}}const r=e.match(/^([a-zA-Z_$][a-zA-Z0-9_$]*|\d+(?:\.\d+)?)\s*([\+\-\*\/\%])\s*([a-zA-Z_$][a-zA-Z0-9_$]*|\d+(?:\.\d+)?)$/);if(r){const[,e,n,i]=r;Ee("EVAL: Parsed arithmetic:",{left:e,operator:n,right:i});const a=await ln(e.trim(),t),o=await ln(i.trim(),t);Ee("EVAL: Resolved values:",{leftValue:a,rightValue:o});const s=Number(a),l=Number(o);if(!isNaN(s)&&!isNaN(l)){let e;switch(n){case"+":e=s+l;break;case"-":e=s-l;break;case"*":e=s*l;break;case"/":e=s/l;break;case"%":e=s%l;break;default:e=s}return Ee("EVAL: Arithmetic result:",e),e}}const i=await ln(e.trim(),t);return Ee("EVAL: Fallback result:",i),i}function un(e){if(Array.isArray(e)&&1===e.length&&(e=e[0]),null!==e&&"object"==typeof e&&"string"==typeof e.textContent){const t=e.value??e.textContent;if(null!=t){const e=String(t).trim();if(""===e)return 0;const n=parseFloat(e);return isNaN(n)?e:n}return 0}return e}async function pn(e,t,n,r,i){try{const a=i(await r(e.object,n));if(null==a)throw new Error("Cannot call method on null or undefined");const o=rn(e.property);if(!o||"string"!=typeof o)throw new Error(`Invalid method name: ${o}`);const s=a[o];if("function"!=typeof s)throw new Error(`Property "${o}" is not a function on ${a.constructor?.name||typeof a}`);const l=await Promise.all(t.map(e=>r(e,n)));return s.apply(a,l)}catch(e){if(e instanceof Error)throw e;throw new Error(`Failed to evaluate method call: ${e}`)}}class mn{constructor(){this.expressionRegistry=new Map}registerCategory(e){Object.entries(e).forEach(([e,t])=>{this.expressionRegistry.set(e,t)})}unwrapSelectorResult(e){if(e instanceof NodeList&&e.length>0)return e[0];if(Array.isArray(e)&&e.length>0){const t=e[0];return"index"in e&&"input"in e?e:t instanceof Element||t instanceof Node?t:e}return e}async evaluate(e,t){if(!e)return Ee("EVALUATOR: Received null/undefined node, returning null"),null;if(!e.type)throw console.error("EVALUATOR: Node missing type property:",e),new Error(`Node missing type property: ${JSON.stringify(e)}`);switch(e.type){case"identifier":return this.evaluateIdentifier(e,t);case"literal":return this.evaluateLiteral(e,t);case"string":return e.value??"";case"memberExpression":return this.evaluateMemberExpression(e,t);case"binaryExpression":return this.evaluateBinaryExpression(e,t);case"unaryExpression":return this.evaluateUnaryExpression(e,t);case"callExpression":return this.evaluateCallExpression(e,t);case"selector":return this.evaluateSelector(e,t);case"dollarExpression":return this.evaluateDollarExpression(e,t);case"possessiveExpression":return this.evaluatePossessiveExpression(e,t);case"templateLiteral":return this.evaluateTemplateLiteral(e,t);case"arrayLiteral":return this.evaluateArrayLiteral(e,t);case"objectLiteral":return this.evaluateObjectLiteral(e,t);case"conditionalExpression":return this.evaluateConditionalExpression(e,t);case"cssSelector":return this.evaluateCSSSelector(e,t);case"propertyAccess":return this.evaluatePropertyAccess(e,t);case"propertyOfExpression":return this.evaluatePropertyOfExpression(e,t);case"contextReference":return this.evaluateContextReference(e,t);case"queryReference":return this.evaluateQueryReference(e,t);case"idSelector":return this.evaluateIdSelector(e,t);case"attributeAccess":return this.evaluateAttributeAccess(e,t);default:throw new Error(`Unsupported AST node type for evaluation: ${e.type}`)}}async evaluateWithResult(e,t){try{return Mt(await this.evaluate(e,t))}catch(e){if(e instanceof Error){const t=e;if(t.isHalt||"HALT_EXECUTION"===t.message)return Wt({type:"halt"});if(t.isExit||"EXIT_COMMAND"===t.message)return Wt({type:"exit",returnValue:t.returnValue});if(t.isBreak)return Wt({type:"break"});if(t.isContinue)return Wt({type:"continue"});if(t.isReturn)return Wt({type:"return",returnValue:t.returnValue})}throw e}}async evaluateArrayLiteral(e,t){const n=e.elements||[],r=[];for(const e of n){const n=await this.evaluate(e,t);r.push(n)}return r}async evaluateObjectLiteral(e,t){const n=e.properties||[],r={};for(const e of n){let n;if("identifier"===e.key.type)n=e.key.name;else if("literal"===e.key.type)n=String(e.key.value);else{const r=await this.evaluate(e.key,t);n=String(r)}const i=await this.evaluate(e.value,t);r[n]=i}return r}async evaluateConditionalExpression(e,t){return await this.evaluate(e.test,t)?this.evaluate(e.consequent,t):e.alternate?this.evaluate(e.alternate,t):void 0}async evaluateTemplateLiteral(e,t){return async function(e,t){let n=e.value||"";Ee("TEMPLATE LITERAL: Evaluating",{template:n,node:e});const r=/\$([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g,i=[];let a;for(;null!==(a=r.exec(n));)"{"!==n[a.index+1]&&i.push({match:a[0],varName:a[1],index:a.index});for(let e=i.length-1;e>=0;e--){const{match:r,varName:a,index:o}=i[e],s=await sn(a,t);Ee(`TEMPLATE: $${a} resolved to`,s),n=n.slice(0,o)+String(s??"")+n.slice(o+r.length)}let o="",s=0;for(;s<n.length;){const e=n.indexOf("${",s);if(-1===e){o+=n.slice(s);break}o+=n.slice(s,e);let r=1,i=e+2;for(;i<n.length&&r>0;)"{"===n[i]&&r++,"}"===n[i]&&r--,r>0&&i++;if(0!==r)throw new Error(`Unterminated template expression in: ${n}`);const a=n.slice(e+2,i);let l;Ee("TEMPLATE: Evaluating expression:",a);const c=a.trim();t.locals.has(c)?(l=t.locals.get(c),Ee(`TEMPLATE: Found in locals: ${c} =`,l)):t.globals&&t.globals.has(c)?(l=t.globals.get(c),Ee(`TEMPLATE: Found in globals: ${c} =`,l)):t.variables&&t.variables.has(c)?(l=t.variables.get(c),Ee(`TEMPLATE: Found in variables (legacy): ${c} =`,l)):(l=await cn(a,t),Ee(`TEMPLATE: Evaluated expression "${a}" =`,l)),o+=String(l),s=i+1}return o}(e,t)}async evaluateSimpleExpression(e,t){return cn(e,t)}async resolveValue(e,t){return ln(e,t)}async evaluateIdentifier(e,t){const{name:n,scope:r}=e;if("me"===n||"my"===n||"I"===n)return t.me;if("you"===n||"your"===n)return t.you;if("it"===n||"its"===n)return t.it;if("result"===n)return t.result;if("event"===n)return t.event;const i=this.expressionRegistry.get(n);return i?i.evaluate(t):"local"===r?t.locals?.has(n)?t.locals.get(n):void 0:"global"===r?t.globals?.has(n)?t.globals.get(n):"undefined"!=typeof window&&n in window?window[n]:void 0:t.locals?.has(n)?t.locals.get(n):t.globals?.has(n)?t.globals.get(n):t.variables?.has(n)?t.variables.get(n):"undefined"!=typeof globalThis&&n in globalThis?globalThis[n]:"undefined"!=typeof window&&n in window?window[n]:void 0}async evaluateLiteral(e,t){return e.value}async evaluateContextReference(e,t){const{contextType:n}=e;switch(n){case"me":return t.me;case"it":return t.result;case"you":return t.you;case"event":return t.event;case"body":return t.meta?.ownerDocument?.body||document?.body;case"detail":return t.event?.detail;case"target":return t.you||t.event?.target;case"sender":return t.event?.target;default:return t.locals&&t.locals.has(n)?t.locals.get(n):void Ee(`Unknown context reference type: ${n}`)}}async evaluateMemberExpression(e,t){const{object:n,property:r,computed:i}=e;if("identifier"===n.type&&["add","remove"].includes(n.name)){const e=n.name,i=rn(r);if(!t.me)throw new Error('Context element "me" is null');return void("add"===e?t.me.classList.add(i):"remove"===e&&t.me.classList.remove(i))}let a=await this.evaluate(n,t);if(i){return a[await this.evaluate(r,t)]}{const e=rn(r);if(Array.isArray(a)&&"string"==typeof e&&("length"===e||e in Array.prototype)||(a=this.unwrapSelectorResult(a)),"string"==typeof e){if(e.startsWith("computed-")){const t=e.substring(9);if(a&&"undefined"!=typeof window&&a instanceof Element){return window.getComputedStyle(a).getPropertyValue(t)}return}if(e.startsWith("@")){const t=e.substring(1);return a&&"function"==typeof a.getAttribute?en(a,t):void 0}if(a&&a instanceof Element){if("previous"===e||"prev"===e)return a.previousElementSibling;if("next"===e)return a.nextElementSibling}}const t=a?.[e];return"function"==typeof t?t.bind(a):t}}coerceArithmeticOperand(e){return un(e)}async evaluateBinaryExpression(e,t){return async function(e,t,n,r,i){const{operator:a,left:o,right:s}=e;if("in"===a&&"selector"===o.type){let e=o.value;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const i=r(await n(s,t));if(!i||"function"!=typeof i.querySelector)throw new Error(`'in' operator requires a DOM element as the right operand (got: ${typeof i})`);const a=i.querySelectorAll(e);return Array.from(a)}if("in"===a&&"queryReference"===o.type){let e=o.selector;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const i=r(await n(s,t));if(!i||"function"!=typeof i.querySelector)throw new Error(`'in' operator requires a DOM element as the right operand (got: ${typeof i})`);const a=i.querySelectorAll(e);return Array.from(a)}if("in"===a){let e=null,i=null;if("positionalExpression"===o.type){e=o.operator;const r=o.argument;"cssSelector"===r?.type?i=r.selector:"selector"===r?.type?i=r.value:"classSelector"===r?.type?i="."+r.className:"idSelector"===r?.type?i="#"+r.id:r&&(i=String(await n(r,t)))}else if("memberExpression"!==o.type||"identifier"!==o.object?.type||"first"!==o.object.name&&"last"!==o.object.name){if("callExpression"===o.type&&"identifier"===o.callee?.type&&("first"===o.callee.name||"last"===o.callee.name)){e=o.callee.name;const r=o.arguments?.[0];"selector"===r?.type?i=r.value:"cssSelector"===r?.type?i=r.selector:"classSelector"===r?.type?i="."+r.className:"idSelector"===r?.type?i="#"+r.id:r&&(i=String(await n(r,t)))}}else e=o.object.name,"identifier"===o.property?.type&&o.property.name&&(i="."+o.property.name);if(e&&i){const a=r(await n(s,t));if(!a||"function"!=typeof a.querySelectorAll)return;const o=a.querySelectorAll(i),l=Array.from(o);return"first"===e?l.length>0?l[0]:void 0:"last"===e?l.length>0?l[l.length-1]:void 0:l}}if("matches"===a&&("selector"===s.type||"cssSelector"===s.type||"classSelector"===s.type)){const e=await n(o,t),r=s.value||s.selector;if(e&&"function"==typeof e.matches)try{return e.matches(r)}catch{return!1}return!1}const l=await n(o,t),c=await n(s,t);if("has"===a||"have"===a){if(l instanceof Element){if("cssSelector"===s.type&&"class"===s.selectorType||"selector"===s.type&&s.value?.startsWith(".")){const e=s.selector?.slice(1)||s.value?.slice(1)||"";return l.classList.contains(e)}if("attributeAccess"===s.type||"attributeRef"===s.type){const e=s.attributeName||s.name||s.value?.replace(/^@/,"")||"";return l.hasAttribute(e)}if("cssSelector"===s.type&&"attribute"===s.selectorType){const e=(s.selector||s.value||"").replace(/^@/,"");return l.hasAttribute(e)}if("cssSelector"===s.type&&"id"===s.selectorType||"idSelector"===s.type){const e=(s.selector||s.value||"").replace(/^#/,"");return null!==l.querySelector(`#${CSS.escape(e)}`)}if("selector"===s.type||"queryReference"===s.type){let e=s.value||s.selector||"";e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());try{return null!==l.querySelector(e)}catch{return!1}}if("cssSelector"===s.type){const e=s.selector||"";try{return null!==l.querySelector(e)}catch{return!1}}}return Array.isArray(l)?l.includes(c):"string"==typeof l&&l.includes(String(c))}switch(a){case">":case"is greater than":return l>c;case"<":case"is less than":return l<c;case">=":case"is greater than or equal to":return l>=c;case"<=":case"is less than or equal to":return l<=c;case"==":case"equals":case"is equal to":return l==c;case"===":case"is really equal to":case"really equals":return l===c;case"!=":case"is not equal to":return l!=c;case"!==":case"is not really equal to":return l!==c;case"+":{const e=un(l),n=un(c);if("string"==typeof e||"string"==typeof n){const r=i.get("stringConcatenation");if(r){Ee("Using string concatenation for:",{leftValue:e,rightValue:n});const i=await r.evaluate(t,{left:e,right:n});return i.success?i.value:e+n}}else{const r=i.get("addition");if(r){Ee("Using numeric addition for:",{leftValue:e,rightValue:n});const i=await r.evaluate(t,{left:e,right:n});return i.success?i.value:e+n}}return e+n}case"-":return un(l)-un(c);case"*":return un(l)*un(c);case"/":return un(l)/un(c);case"%":case"mod":return un(l)%un(c);case"as":const e="string"==typeof c?c:"identifier"===s.type?s.name:"literal"===s.type?s.value:String(c),n=i.get("as");return n?n.evaluate(t,l,e):l;case"&&":case"and":return l&&c;case"||":case"or":return l||c;case"is":return l===c;case"is not":return l!==c;case"is a":case"is an":switch("identifier"===s.type?s.name.toLowerCase():String(c).toLowerCase()){case"string":return"string"==typeof l;case"number":return"number"==typeof l;case"boolean":return"boolean"==typeof l;case"object":return"object"==typeof l&&null!==l;case"array":return Array.isArray(l);case"function":return"function"==typeof l;case"null":return null===l;case"undefined":return void 0===l;default:const e="identifier"===s.type?s.name:String(c);return null!=l&&l.constructor?.name===e}case"is not a":case"is not an":switch("identifier"===s.type?s.name.toLowerCase():String(c).toLowerCase()){case"string":return"string"!=typeof l;case"number":return"number"!=typeof l;case"boolean":return"boolean"!=typeof l;case"object":return!("object"==typeof l&&null!==l);case"array":return!Array.isArray(l);case"function":return"function"!=typeof l;case"null":return null!==l;case"undefined":return void 0!==l;default:const e="identifier"===s.type?s.name:String(c);return!(null!=l&&l.constructor?.name===e)}case"=":if("identifier"===o.type){const e=o.name;return"result"===e?t.result=c:"it"===e?t.it=c:"you"===e?t.you=c:t.locals.set(e,c),c}throw new Error("Left side of assignment must be an identifier");case"contains":case"include":case"includes":return Array.isArray(l)?l.includes(c):"string"==typeof l?l.includes(String(c)):!(!l||"function"!=typeof l.matches)&&l.matches(String(c));case"match":case"matches":if(l&&"function"==typeof l.matches){const e="string"==typeof c?c:String(c);try{return l.matches(e)}catch{return!1}}return!1;case"in":const r="string"==typeof l?l:String(l),u=c;if(!u||"function"!=typeof u.querySelector){if(Array.isArray(u))return u.includes(l);if("object"==typeof u&&null!==u)return r in u;throw new Error(`'in' operator requires a DOM element, array, or object as the right operand (got: ${typeof u})`)}return u.querySelector(r);case" ":return"string"==typeof l&&"string"==typeof c?{command:l,selector:c}:"identifier"===o.type&&"selector"===s.type?{command:o.name,selector:s.value}:c;default:throw new Error(`Unsupported binary operator: "${a}" (length: ${a.length})`)}}(e,t,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this),this.expressionRegistry,this.evaluateSelector.bind(this))}async evaluateUnaryExpression(e,t){const{operator:n,argument:r}=e,i=await this.evaluate(r,t);switch(n){case"not":case"!":const e=this.expressionRegistry.get("not");return e?e.evaluate(t,i):!i;case"no":const r=this.expressionRegistry.get("no");return!!r&&r.evaluate(t,i);case"some":return null!=i&&("string"==typeof i||Array.isArray(i)||i instanceof NodeList||i instanceof HTMLCollection?i.length>0:"object"!=typeof i||Object.keys(i).length>0);case"exists":const a=this.expressionRegistry.get("exists");return a?a.evaluate(t,i):null!=i;case"does not exist":const o=this.expressionRegistry.get("doesNotExist");return o?o.evaluate(t,i):null==i;case"-":return-i;case"+":return+i;default:throw new Error(`Unsupported unary operator: ${n}`)}}async evaluateCallExpression(e,t){return async function(e,t,n,r,i,a){const{callee:o,arguments:s,isConstructor:l}=e;if(l){const e=o.name,r=t.globals?.get(e)||window[e];if("function"==typeof r)return new r(...await Promise.all(s.map(e=>n(e,t))));throw new Error(`Unknown constructor: ${e}`)}if("memberExpression"===o.type||"propertyAccess"===o.type)return pn(o,s,t,n,r);const c=o.name||o,u=i.get(c);if(u){const e=["first","last","random","at"],r=["closest","previous","next"].includes(c),i=e.includes(c),o=await Promise.all(s.map(e=>r&&e&&"selector"===e.type&&"string"==typeof e.value?e.value:r&&e&&"identifier"===e.type&&"string"==typeof e.name?e.name:i&&e&&"selector"===e.type&&"string"==typeof e.value?a(e,t):n(e,t)));return u.evaluate(t,...o)}const p=t.globals?.get(c)||window[c];if("function"==typeof p)return p(...await Promise.all(s.map(e=>n(e,t))));throw new Error(`Unknown function: ${c}`)}(e,t,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this),this.expressionRegistry,this.evaluateSelector.bind(this))}async evaluateMethodCall(e,t,n){return pn(e,t,n,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this))}async evaluateSelector(e,t){return function(e,t){let n=e.value;n.startsWith("<")&&n.endsWith("/>")&&(n=n.slice(1,-2).trim());const r=an(t);if(!r)return[];const i=r.querySelectorAll(n);return Array.from(i).filter(e=>e&&"object"==typeof e&&1===e.nodeType&&"string"==typeof e.tagName)}(e,t)}evaluateAttributeAccess(e,t){return t.me&&"function"==typeof t.me.getAttribute?en(t.me,e.attributeName):`@${e.attributeName}`}getAvailableExpressions(){return Array.from(this.expressionRegistry.keys())}async evaluateDollarExpression(e,t){const n=await this.evaluate(e.expression,t);if("identifier"===e.expression.type){const n=e.expression.name;return/^\d+$/.test(n)?n:t.locals?.has(n)?t.locals.get(n):"me"===n&&t.me?t.me:"you"===n&&t.you?t.you:"it"===n&&t.it?t.it:"result"===n&&t.result?t.result:"undefined"!=typeof window&&"window"===n?window:t.globals?.has(n)?t.globals.get(n):void 0}return n}async evaluatePossessiveExpression(e,t){const{object:n,property:r}=e,i=this.unwrapSelectorResult(await this.evaluate(n,t));if(!i)return;const a=rn(r);return"string"==typeof a&&Zt(i)?nn(i,a):i[a]}hasExpression(e){return this.expressionRegistry.has(e)}async evaluateCSSSelector(e,t){return function(e,t){let n=e.selector;n.startsWith("<")&&n.endsWith("/>")&&(n=n.slice(1,-2).trim());const r=an(t);if(!r)return"id"===e.selectorType?null:[];if("id"===e.selectorType){const e=n.startsWith("#")?n.slice(1):n;return r.getElementById(e)}if("class"===e.selectorType){const e=n.replace(/:/g,"\\:"),t=r.querySelectorAll(e);return Array.from(t).filter(e=>e instanceof HTMLElement)}const i=r.querySelectorAll(n);return Array.from(i).filter(e=>e instanceof HTMLElement)}(e,t)}async evaluateIdSelector(e,t){return function(e,t){const n=an(t);if(!n)return null;const r=e.value.startsWith("#")?e.value.slice(1):e.value;return n.getElementById(r)}(e,t)}async evaluateQueryReference(e,t){return function(e,t){let n=e.selector;n.startsWith("<")&&n.endsWith("/>")&&(n=n.slice(1,-2).trim());const r=an(t);if(!r)return[];try{return r.querySelectorAll(n)}catch{return r.createDocumentFragment().childNodes}}(e,t)}async evaluatePropertyAccess(e,t){const n=await this.evaluate(e.object,t),r=e.property;if(null==n)throw new Error(`Cannot access property "${r.name||r.value}" of ${n}`);const i=r.name||r.value;if(!i)throw new Error("Property name must be an identifier");try{let e;return e=Zt(n)?nn(n,i):n[i],"function"==typeof e?e.bind(n):e}catch(e){throw new Error(`Error accessing property "${i}": ${e}`)}}async evaluatePropertyOfExpression(e,t){const n=e.property,r=n.name||n.value;if(!r)throw new Error('Property name must be an identifier in "the X of Y" pattern');const i=this.unwrapSelectorResult(await this.evaluate(e.target,t));if(null==i)throw new Error(`Cannot access property "${r}" of ${i}`);try{let e;return e=Zt(i)?nn(i,r):i[r],"function"==typeof e?e.bind(i):e}catch(e){throw new Error(`Failed to access property "${r}" on target: ${e}`)}}}const dn={1:"one",2:"two",3:"three",4:"four",5:"five"};function hn(e,t,n,r){if(e.length!==t){const e=r?` (${r})`:"";return`${n} requires exactly ${i=t,dn[i]??String(i)} argument${1===t?"":"s"}${e}`}var i;return null}function fn(e,t,n,r){if("string"!=typeof e[t]){return`${n} ${r||`argument ${t+1}`} must be a string`}return null}function yn(e,t,n){return hn(e,1,t,n)??fn(e,0,t,n)}function vn(e,t){return hn(e,2,t,"left, right")}function gn(){return null}function bn(e,t,n,r){if(e.length>t){const e=r?` (${r})`:"";return`${n} expression takes at most ${1===t?"one":String(t)} argument${1===t?"":"s"}${e}`}return null}function kn(e,t,n,r,i){if(e.length<t||e.length>n){return`${r} requires ${t}-${n} arguments${i?` (${i})`:""}`}return null}function wn(e,t,n,r=[]){return{type:e,message:t,suggestions:r,...n&&{path:n}}}const zn="undefined"!=typeof process&&"production"===process.env.NODE_ENV||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let xn;function En(){return xn({validate:e=>({success:!0,data:e})})}function Sn(e,t){if(zn)return En();const n=xn({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:!1,error:wn("type-mismatch","Expected object, received "+typeof n)};const r=n,i={};if(t?.strict){const t=Object.keys(e),n=Object.keys(r).filter(e=>!t.includes(e));if(n.length>0)return{success:!1,error:wn("runtime-error",`Unexpected properties: ${n.join(", ")}`)}}for(const[t,n]of Object.entries(e)){const e=r[t];if(!(t in r)&&!n._isOptional)return{success:!1,error:wn("missing-argument",`Required field "${t}" is missing`,t)};const a=n.validate(e);if(!a.success){const e=a.error.path?`${t}.${a.error.path}`:t;return{success:!1,error:wn("validation-error",a.error.message||`Field "${t}" validation failed`,e)}}void 0!==a.data&&(i[t]=a.data)}return{success:!0,data:i}}});return n.strict=()=>Sn(e,{strict:!0}),n}function Tn(e,t="Custom validation failed"){return zn?En():xn({validate:n=>e(n)?{success:!0,data:n}:{success:!1,error:wn("runtime-error",t)}})}xn=function(e){return e.describe||(e.describe=function(e){return this.description=e,this}),e.safeParse||(e.safeParse=function(e){const t=this.validate(e);return t.success?{success:!0,data:t.data}:{success:!1,error:{errors:t.error?[t.error]:[]}}}),e.parse||(e.parse=function(e){const t=this.validate(e);if(t.success&&void 0!==t.data)return t.data;throw new Error(t.error?.message||"Validation failed")}),e.optional||(e.optional=function(){const e=this.validate.bind(this),t={...this,_isOptional:!0,validate:t=>null==t?{success:!0,data:void 0}:e(t)};return xn(t)}),e.min||(e.min=function(e){const t=this.validate.bind(this),n={...this,validate:n=>{const r=t(n);return r.success&&"string"==typeof r.data&&r.data.length<e?{success:!1,error:wn("runtime-error",`String must be at least ${e} characters long`)}:r}};return xn(n)}),e.max||(e.max=function(e){const t=this.validate.bind(this),n={...this,validate:n=>{const r=t(n);return r.success&&"string"==typeof r.data&&r.data.length>e?{success:!1,error:wn("runtime-error",`String must be at most ${e} characters long`)}:r}};return xn(n)}),e.default||(e.default=function(e){const t=this.validate.bind(this),n={...this,_defaultValue:e,_hasDefault:!0,validate:n=>void 0===n?{success:!0,data:e}:t(n)};return xn(n)}),e.rest||(e.rest=function(e){return this}),e.refine||(e.refine=function(e,t){const n=this.validate.bind(this),r={...this,validate:r=>{const i=n(r);return i.success?e(i.data)?i:{success:!1,error:wn("runtime-error",t||"Refinement validation failed")}:i}};return xn(r)}),new Proxy(e,{get:(e,t,n)=>t in e||"string"!=typeof t||t.startsWith("_")||"constructor"===t||"validate"===t||"then"===t?Reflect.get(e,t,n):function(...e){return n}})};const Cn={string:e=>function(e={}){return zn?En():xn({validate:t=>e.optional&&null==t?{success:!0,data:void 0}:"string"!=typeof t?{success:!1,error:wn("type-mismatch","Expected string, received "+typeof t)}:void 0!==e.minLength&&t.length<e.minLength?{success:!1,error:wn("runtime-error",`String must be at least ${e.minLength} characters long`)}:void 0!==e.maxLength&&t.length>e.maxLength?{success:!1,error:wn("runtime-error",`String must be at most ${e.maxLength} characters long`)}:e.pattern&&!e.pattern.test(t)?e.pattern.source.startsWith("^")&&e.pattern.source.endsWith("$")?{success:!1,error:wn("runtime-error",`Expected "${e.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:!1,error:wn("missing-argument","String does not match required pattern")}:{success:!0,data:t},...e.description&&{description:e.description}})}(e||{}),number:e=>function(e={}){return zn?En():xn({validate:t=>{const n=Number(t);return isNaN(n)?{success:!1,error:wn("type-mismatch","Expected number, received "+typeof t)}:void 0!==e.min&&n<e.min?{success:!1,error:wn("runtime-error",`Number must be at least ${e.min}`)}:void 0!==e.max&&n>e.max?{success:!1,error:wn("runtime-error",`Number must be at most ${e.max}`)}:{success:!0,data:n}}})}(e||{}),boolean:()=>zn?En():xn({validate:e=>"boolean"!=typeof e?{success:!1,error:wn("type-mismatch","Expected boolean, received "+typeof e)}:{success:!0,data:e}}),object:e=>Sn(e),array:e=>function(e){return zn?En():xn({validate:t=>{if(!Array.isArray(t))return{success:!1,error:wn("type-mismatch","Expected array, received "+typeof t)};const n=[];for(let r=0;r<t.length;r++){const i=e.validate(t[r]);if(!i.success){const e=i.error.path?`${r}.${i.error.path}`:`${r}`;return{success:!1,error:wn("runtime-error",i.error.message,e)}}n.push(i.data)}return{success:!0,data:n}}})}(e),tuple:e=>function(e){return zn?En():xn({validate:t=>{if(!Array.isArray(t))return{success:!1,error:wn("type-mismatch","Expected array, received "+typeof t)};if(t.length!==e.length)return{success:!1,error:wn("runtime-error",`Expected tuple of length ${e.length}, received length ${t.length}`)};const n=[];for(let r=0;r<e.length;r++){const i=e[r].validate(t[r]);if(!i.success){const e=i.error.path?`${r}.${i.error.path}`:`${r}`;return{success:!1,error:wn("runtime-error",i.error.message,e)}}n.push(i.data)}return{success:!0,data:n}}})}(e),union:e=>function(e){return zn?En():xn({validate:t=>{const n=[];for(const r of e){const e=r.validate(t);if(e.success)return e;n.push(e.error.message)}return{success:!1,error:wn("type-mismatch","Value does not match any union type")}}})}(e),literal:e=>{return t=e,zn?En():xn({validate:e=>e===t?{success:!0,data:e}:{success:!1,error:wn("runtime-error",`Expected ${JSON.stringify(t)}, received ${JSON.stringify(e)}`)}});var t},custom:(e,t)=>Tn(e,t),record:(e,t)=>function(e,t){return zn?En():xn({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:!1,error:wn("type-mismatch","Expected record object, received "+typeof n)};const r=n,i={};for(const[n,a]of Object.entries(r)){const r=e.validate(n);if(!r.success)return{success:!1,error:wn("invalid-argument",`Invalid key "${n}": ${r.error.message}`,n)};const o=t.validate(a);if(!o.success){const e=o.error.path?`${n}.${o.error.path}`:n;return{success:!1,error:wn("runtime-error",o.error.message,e)}}i[n]=o.data}return{success:!0,data:i}}})}(e,t),enum:e=>function(e){return zn?En():xn({validate:t=>"string"!=typeof t&&"number"!=typeof t&&"boolean"!=typeof t?{success:!1,error:wn("type-mismatch","Expected string, received "+typeof t)}:e.includes(t)?{success:!0,data:t}:{success:!1,error:wn("runtime-error",`Expected one of [${e.join(", ")}], received "${t}"`)}})}(e),function:()=>Tn(e=>"function"==typeof e,"Expected function"),unknown:()=>En(),any:()=>En(),null:()=>Tn(e=>null===e,"Expected null"),undefined:()=>Tn(e=>void 0===e,"Expected undefined"),instanceOf:e=>Tn(t=>t instanceof e,`Expected instance of ${e.name}`),instanceof:e=>Tn(t=>t instanceof e,`Expected instance of ${e.name}`)},An=Cn;class jn{trackPerformance(e,t,n,r){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:t,output:n.success?n.value:n.error,timestamp:r,duration:Date.now()-r,success:n.success})}trackSimple(e,t,n,r=(n?"success":"error")){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:r,timestamp:t,duration:Date.now()-t,success:n})}toBoolean(e){return!1!==e&&0!==e&&0n!==e&&""!==e&&null!=e&&(!Kt(e)||!isNaN(e))}success(e,t){return{success:!0,value:e,type:t}}failure(e,t,n,r,i=[]){return{success:!1,error:{name:e,type:t,message:n,code:r,suggestions:i}}}validationSuccess(){return{isValid:!0,errors:[],suggestions:[]}}validationFailure(e,t,n=[]){return{isValid:!1,errors:[{type:e,message:t,suggestions:n}],suggestions:n}}isElement(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName}inferType(e){return null===e?"null":void 0===e?"undefined":this.isElement(e)?"element":Array.isArray(e)?"array":Qt(e)?"object":typeof e}inferEvaluationType(e){return void 0===e?"Undefined":null===e?"Null":Ut(e)?"String":Kt(e)?"Number":Gt(e)?"Boolean":Array.isArray(e)?"Array":this.isElement(e)?"Element":"Object"}normalizeCollection(e){return Array.isArray(e)?e:e instanceof NodeList?Array.from(e):Ut(e)?e.split(""):null==e?[]:Qt(e)&&Symbol.iterator in e?Array.from(e):[]}toNumber(e){if(Kt(e)&&Number.isFinite(e))return e;if(Ut(e)){const t=Number(e);return Number.isFinite(t)?t:null}return Gt(e)?e?1:0:null}}const Ln=Cn.object({selector:Cn.string().min(1),single:Cn.boolean().optional().default(!1)});new class extends jn{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=Cn.undefined(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=e.me,i=this.isElement(r)?r:null,a=this.success(i,"element");return this.trackPerformance(e,t,a,n),a}catch(r){const i=this.failure("MeExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "me"',"ME_EVALUATION_FAILED",["Ensure element context is properly set",'Check if "me" is available in current scope']);return this.trackPerformance(e,t,i,n),i}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"me" expression takes no arguments',['Use "me" without any parameters']):this.validationSuccess()}},new class extends jn{constructor(){super(...arguments),this.name="you",this.category="Reference",this.syntax="you",this.description="References the target element (usually event target or command target)",this.inputSchema=Cn.undefined(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=e.you,i=this.isElement(r)?r:null,a=this.success(i,"element");return this.trackPerformance(e,t,a,n),a}catch(r){const i=this.failure("YouExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "you"',"YOU_EVALUATION_FAILED",["Ensure target element is available in context",'Check if "you" is set by event or command']);return this.trackPerformance(e,t,i,n),i}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"you" expression takes no arguments',['Use "you" without any parameters']):this.validationSuccess()}},new class extends jn{constructor(){super(...arguments),this.name="it",this.category="Reference",this.syntax="it",this.description="References the current context variable (result of previous operation or loop item)",this.inputSchema=Cn.undefined(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=e.it,i={success:!0,value:r,type:this.inferType(r)};return this.trackPerformance(e,t,i,n),i}catch(r){const i=this.failure("ItExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "it"',"IT_EVALUATION_FAILED",['Ensure "it" is set by previous operation',"Check if context variable is available"]);return this.trackPerformance(e,t,i,n),i}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"it" expression takes no arguments',['Use "it" without any parameters']):this.validationSuccess()}},new class extends jn{constructor(){super(...arguments),this.name="css-selector",this.category="Reference",this.syntax="<selector/> or <selector/> (single)",this.description="Queries DOM elements using CSS selectors with validation",this.inputSchema=Ln,this.outputType="ElementList",this.metadata={category:"Reference",complexity:"medium"}}async evaluate(e,t){const n=Date.now();try{if(!this.isValidCSSSelector(t.selector)){const r=this.failure("CSSSelectorError","invalid-argument",`Invalid CSS selector: "${t.selector}"`,"INVALID_CSS_SELECTOR",["Check selector syntax","Use valid CSS selector patterns like .class, #id, tag[attr]","Avoid special characters that need escaping"]);return this.trackPerformance(e,t,r,n),r}let r;if(t.single){r=document.querySelector(t.selector)}else{const e=Array.from(document.querySelectorAll(t.selector));r=e.length>0?e:null}const i={success:!0,value:r,type:Array.isArray(r)?"element-list":"element"};return this.trackPerformance(e,t,i,n),i}catch(r){const i=this.failure("CSSSelectorError","runtime-error",r instanceof Error?r.message:"CSS selector evaluation failed","CSS_SELECTOR_EVALUATION_FAILED",["Check if selector is valid CSS","Ensure DOM is ready when query executes","Verify elements exist in document"]);return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);if(!t.success)return{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:`Invalid input: ${e.message}`,suggestions:this.getValidationSuggestion(e.code??"unknown")}))??[],suggestions:["Provide valid CSS selector string","Check selector syntax"]};const{selector:n}=t.data;return this.isValidCSSSelector(n)?this.validationSuccess():this.validationFailure("syntax-error",`Invalid CSS selector syntax: "${n}"`,["Use .class for class selectors","Use #id for ID selectors","Use tag for element selectors","Use [attr] for attribute selectors"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Ensure input matches expected format"])}}isValidCSSSelector(e){try{return document.querySelector(e),!0}catch{return!1}}getValidationSuggestion(e){return[{too_small:"CSS selector cannot be empty",invalid_type:"Selector must be a string",required:"CSS selector is required"}[e]||"Check input format and types"]}};const Pn={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me instanceof HTMLElement?e.me:null,validate:gn},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.you instanceof HTMLElement?e.you:null,validate:gn},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:gn},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:gn},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.result,validate:gn},querySelector:{name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const[n]=t;if("string"!=typeof n)throw new Error("querySelector requires a string selector");return document.querySelector(n)},validate:e=>yn(e,"querySelector","selector")},querySelectorAll:{name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw new Error("querySelectorAll requires a string selector");const r=document.querySelectorAll(n);return Array.from(r)},validate:e=>yn(e,"querySelectorAll","selector")},getElementById:{name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw new Error("getElementById requires a string ID");return document.getElementById(n)},validate:e=>yn(e,"getElementById","ID")},getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw new Error("getElementsByClassName requires a string class name");const r=document.getElementsByClassName(n);return Array.from(r)},validate:e=>yn(e,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){let n=t[0];if(n&&"object"==typeof n&&"type"in n){const e=n;"identifier"===e.type&&e.name?n=e.name:"literal"===e.type&&"string"==typeof e.value&&(n=e.value)}if("string"!=typeof n)throw new Error("closest requires a string selector");return e.me?e.me.closest(n):null},validate(e){if(1!==e.length)return"closest requires exactly 1 argument (selector)";const t=e[0];if("string"==typeof t)return null;if(t&&"object"==typeof t&&"type"in t){const e=t;if("identifier"===e.type||"literal"===e.type)return null}return"closest selector must be a string or identifier"}},parent:{name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me?e.me.parentElement:null,validate:gn},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async e=>window,validate:gn},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async e=>document,validate:gn},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw new Error("Selector must be a string");const r=document.querySelectorAll(n);return Array.from(r)},validate:e=>yn(e,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const n=t[0],r=t[1];if("string"!=typeof n)throw new Error("StyleRef requires a string property name");const i=r||e.me;if(!(i&&i instanceof HTMLElement))return;if(n.startsWith("computed-")){const e=n.substring(9);return getComputedStyle(i).getPropertyValue(e)||""}return i.style.getPropertyValue(n)||void 0},validate:e=>kn(e,1,2,"styleRef","property, optional element")??fn(e,0,"styleRef","property")??(2===e.length&&e[1]&&"object"!=typeof e[1]?"styleRef element must be an HTMLElement":null)},possessiveStyleRef:{name:"possessiveStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const n=t[0],r=t[1];if("string"!=typeof n||"string"!=typeof r)throw new Error("Possessive styleRef requires possessor and property strings");let i=null;if("my"===n&&e.me?i=e.me instanceof HTMLElement?e.me:null:"its"===n&&e.it&&(i=e.it instanceof HTMLElement?e.it:null),!i)return;if(r.startsWith("computed-")){const e=r.substring(9);return getComputedStyle(i).getPropertyValue(e)||""}return i.style.getPropertyValue(r)||void 0},validate:e=>hn(e,2,"possessiveStyleRef","possessor, property")??fn(e,0,"possessiveStyleRef","possessor")??fn(e,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const n=t[0],r=t[1];if("string"!=typeof n||"string"!=typeof r)throw new Error("Of styleRef requires property and reference strings");let i=null;if("me"===r&&e.me?i=e.me instanceof HTMLElement?e.me:null:"it"===r&&e.it&&(i=e.it instanceof HTMLElement?e.it:null),!i)return;if(n.startsWith("computed-")){const e=n.substring(9);return getComputedStyle(i).getPropertyValue(e)||""}return i.style.getPropertyValue(n)||void 0},validate:e=>hn(e,2,"ofStyleRef","property, reference")??fn(e,0,"ofStyleRef","property")??fn(e,1,"ofStyleRef","reference")}};class In{constructor(e=100,t=5e3){this.maxSize=e,this.ttl=t,this.cache=new Map,this.accessOrder=new Map,this.accessCounter=0}get(e){const t=this.cache.get(e);if(t){if(!(Date.now()-t.timestamp>this.ttl))return t.accessCount++,this.accessOrder.set(e,++this.accessCounter),t.result;this.delete(e)}}set(e,t){this.cache.size>=this.maxSize&&!this.cache.has(e)&&this.evictLRU();const n={result:t,timestamp:Date.now(),accessCount:1};this.cache.set(e,n),this.accessOrder.set(e,++this.accessCounter)}delete(e){return this.accessOrder.delete(e),this.cache.delete(e)}clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}size(){return this.cache.size}evictLRU(){let e,t=1/0;for(const[n,r]of this.accessOrder)r<t&&(t=r,e=n);void 0!==e&&this.delete(e)}getStats(){const e=Array.from(this.cache.values()),t=Date.now();return{size:this.cache.size,maxSize:this.maxSize,hitRate:e.length>0?e.filter(e=>e.accessCount>1).length/e.length:0,avgAge:e.length>0?e.reduce((e,n)=>e+(t-n.timestamp),0)/e.length:0,totalAccesses:e.reduce((e,t)=>e+t.accessCount,0)}}}const Nn=new class{constructor(){this.domQueryCache=new In(200,3e3),this.exprResultCache=new In(500,2e3),this.cssMatchCache=new In(100,5e3),this.formValueCache=new In(50,1e3),this.hits=0,this.misses=0}querySelector(e){const t=`querySelector:${e}`,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.querySelector(e);return this.domQueryCache.set(t,r),r}querySelectorAll(e){const t=`querySelectorAll:${e}`,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.querySelectorAll(e));return this.domQueryCache.set(t,r),r}getElementById(e){const t=`getElementById:${e}`,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.getElementById(e);return this.domQueryCache.set(t,r),r}getElementsByClassName(e){const t=`getElementsByClassName:${e}`,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.getElementsByClassName(e));return this.domQueryCache.set(t,r),r}matches(e,t){const n=`matches:${this.getElementCacheKey(e)}:${t}`,r=this.cssMatchCache.get(n);if(void 0!==r)return this.hits++,r;this.misses++;const i=e.matches(t);return this.cssMatchCache.set(n,i),i}getExpressionResult(e){const t=this.exprResultCache.get(e);if(void 0!==t)return this.hits++,t;this.misses++}setExpressionResult(e,t){this.exprResultCache.set(e,t)}getFormValue(e){const t=`formValue:${this.getElementCacheKey(e)}`,n=this.formValueCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++}setFormValue(e,t){const n=`formValue:${this.getElementCacheKey(e)}`;this.formValueCache.set(n,t)}invalidateElementCache(e){const t=this.getElementCacheKey(e);for(const e of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const n of Array.from(e.cache.keys()))"string"==typeof n&&n.includes(t)&&e.delete(n)}invalidateAll(){this.domQueryCache.clear(),this.exprResultCache.clear(),this.cssMatchCache.clear(),this.formValueCache.clear(),this.hits=0,this.misses=0}getElementCacheKey(e){if(e.id)return`#${e.id}`;const t=Array.from(e.classList).sort().join("."),n=this.getElementPosition(e);return`${e.tagName.toLowerCase()}${t?"."+t:""}@${n}`}getElementPosition(e){return`${Array.from(e.parentElement?.children||[]).indexOf(e)}`}getPerformanceStats(){const e=this.hits+this.misses,t=e>0?this.hits/e*100:0;return{hits:this.hits,misses:this.misses,hitRate:Math.round(100*t)/100,domQueryCache:this.domQueryCache.getStats(),exprResultCache:this.exprResultCache.getStats(),cssMatchCache:this.cssMatchCache.getStats(),formValueCache:this.formValueCache.getStats()}}cleanup(){const e=Date.now();[this.domQueryCache,this.exprResultCache,this.cssMatchCache,this.formValueCache].forEach(t=>{Array.from(t.cache.entries()).forEach(([n,r])=>{e-r.timestamp>t.ttl&&t.delete(n)})})}};"undefined"!=typeof window&&setInterval(()=>{Nn.cleanup()},1e4);const On=new class{constructor(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0},this.startTimes=new Map}startTimer(e){this.startTimes.set(e,performance.now())}endTimer(e){const t=this.startTimes.get(e);if(t){const n=performance.now()-t;return this.startTimes.delete(e),n}return 0}recordTokenization(e){this.metrics.tokenizationTime+=e}recordEvaluation(e){this.metrics.evaluationTime+=e}updateCacheMetrics(){const e=Nn.getPerformanceStats();this.metrics.cacheHitRate=e.hitRate}getMetrics(){return this.updateCacheMetrics(),{...this.metrics}}reset(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0}}};function Rn(){Nn.cleanup();On.getMetrics().memoryUsage>52428800&&On.reset()}let Mn=null;function Wn(e,t){if("number"==typeof e){if(!Number.isFinite(e))throw new Error(`${t} must be a finite number, got ${e}`);return e}if("string"==typeof e){const n=e.trim();if(""===n)return 0;const r=parseFloat(n);if(isNaN(r))throw new Error(`${t} cannot be converted to number: "${e}"`);return r}if("boolean"==typeof e)return e?1:0;if(null==e)return 0;if("object"==typeof e&&null!==e){if(Array.isArray(e)&&1===e.length){const n=e[0];if(Array.isArray(n))throw new Error(`${t} is a nested array, cannot convert to number`);return Wn(n,t)}const n=e;if("string"==typeof n.textContent||"value"in n){const e=n.value??n.textContent;if(null!=e){const t=String(e).trim();if(""===t)return 0;const n=parseFloat(t);if(!isNaN(n))return n}}const r=e.valueOf();if("number"==typeof r&&Number.isFinite(r))return r}throw new Error(`${t} cannot be converted to number: ${typeof e}`)}function $n(e){if("number"==typeof e)return Number.isFinite(e)?e:null;if("string"==typeof e){const t=e.trim();if(""===t)return 0;const n=parseFloat(t);return isNaN(n)?null:n}return"boolean"==typeof e?e?1:0:null==e?0:null}function Hn(e,t,n){if("==="===n)return e===t;if("!=="===n)return e!==t;if(null==e||null==t)return function(e,t,n){const r=null==e,i=null==t;if(r&&i)switch(n){case"==":case">=":case"<=":return!0;default:return!1}switch(n){case"==":case">":case"<":case">=":case"<=":default:return!1;case"!=":return!0}}(e,t,n);const[r,i]=function(e,t){if("number"==typeof e&&"number"==typeof t)return[e,t];if("string"==typeof e&&"string"==typeof t){const n=parseFloat(e),r=parseFloat(t);return isNaN(n)||isNaN(r)?[e,t]:[n,r]}const n=$n(e),r=$n(t);if(null!==n&&null!==r)return[n,r];return[String(e),String(t)]}(e,t);switch(n){case">":return r>i;case"<":return r<i;case">=":return r>=i;case"<=":return r<=i;case"==":return qn(e,t);case"!=":return!qn(e,t);default:return!1}}function qn(e,t){if(e===t)return!0;if(typeof e==typeof t)return("string"==typeof e||"number"==typeof e)&&e===t;if("number"==typeof e&&"string"==typeof t){const n=parseFloat(t);return!isNaN(n)&&e===n}if("string"==typeof e&&"number"==typeof t){const n=parseFloat(e);return!isNaN(n)&&n===t}return"boolean"==typeof e?qn(e?1:0,t):"boolean"==typeof t?qn(e,t?1:0):String(e)===String(t)}function Dn(e,t,n,r,i,a=!0,o){return t&&"object"==typeof t&&"evaluationHistory"in t&&Array.isArray(t.evaluationHistory)&&t.evaluationHistory.push({expressionName:e.name,category:e.category,input:n,output:r,timestamp:i,duration:Date.now()-i,success:a,...void 0!==o&&{error:o}}),r}"undefined"!=typeof window&&function(e=3e4){Mn&&clearInterval(Mn),Mn=setInterval(Rn,e)}();const _n=Cn.object({left:Cn.unknown().describe("Left operand value"),right:Cn.unknown().describe("Right operand value")}).strict(),Vn=Cn.object({operand:Cn.unknown().describe("Operand value to negate")}).strict();class Bn extends jn{constructor(){super(...arguments),this.name="and",this.category="Logical",this.syntax="left and right",this.description="Logical AND operation with comprehensive boolean type coercion",this.inputSchema=_n,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=this.toBoolean(t.left);if(!i)return this.trackSimple(e,n,!0,"boolean"),this.success(!1,"boolean");const a=this.toBoolean(t.right),o=i&&a;return this.trackSimple(e,n,!0,"boolean"),this.success(o,"boolean")}catch(t){return this.trackSimple(e,n,!1),this.failure("AndExpressionError","runtime-error",`Logical AND operation failed: ${t instanceof Error?t.message:String(t)}`,"AND_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:`Invalid AND operation input: ${e.message}`,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class Fn extends jn{constructor(){super(...arguments),this.name="or",this.category="Logical",this.syntax="left or right",this.description="Logical OR operation with comprehensive boolean type coercion",this.inputSchema=_n,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=this.toBoolean(t.left);if(i)return this.trackSimple(e,n,!0,"boolean"),this.success(!0,"boolean");const a=this.toBoolean(t.right),o=i||a;return this.trackSimple(e,n,!0,"boolean"),this.success(o,"boolean")}catch(t){return this.trackSimple(e,n,!1),this.failure("OrExpressionError","runtime-error",`Logical OR operation failed: ${t instanceof Error?t.message:String(t)}`,"OR_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:`Invalid OR operation input: ${e.message}`,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class Un extends jn{constructor(){super(...arguments),this.name="not",this.category="Logical",this.syntax="not operand",this.description="Logical NOT operation with comprehensive boolean type coercion",this.inputSchema=Vn,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=!this.toBoolean(t.operand);return this.trackSimple(e,n,!0,"boolean"),this.success(i,"boolean")}catch(t){return this.trackSimple(e,n,!1),this.failure("NotExpressionError","runtime-error",`Logical NOT operation failed: ${t instanceof Error?t.message:String(t)}`,"NOT_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:`Invalid NOT operation input: ${e.message}`,suggestions:[]}))??[],suggestions:["Provide a single operand","Ensure operand is a valid value"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}function Kn(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType}new Bn,new Fn,new Un;const Gn=Cn.tuple([Cn.unknown(),Cn.unknown()]),Qn=Cn.tuple([Cn.unknown(),Cn.string()]),Jn={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(e,t,n){const r=Date.now();try{return Dn(this,e,[t,n],t==n,r)}catch(i){throw Dn(this,e,[t,n],!1,r,!1,i instanceof Error?i:new Error(String(i))),i}},validate:e=>vn(e,"equals"),inputSchema:Gn,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"value is 5",description:"Check if value equals 5 using loose equality",expectedOutput:!0,context:{result:5}},{input:'"5" == 5',description:'String "5" equals number 5 with type coercion',expectedOutput:!0}],relatedExpressions:["strictEquals","notEquals"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Compares two values for loose equality, allowing type coercion",parameters:[{name:"left",type:"unknown",description:"Left operand for comparison",optional:!1,examples:["5",'"hello"',"true","null"]},{name:"right",type:"unknown",description:"Right operand for comparison",optional:!1,examples:["5",'"hello"',"true","null"]}],returns:{type:"Boolean",description:"True if values are loosely equal, false otherwise",examples:["true","false"]},examples:[{title:"Basic equality check",code:"if my.value is 10",explanation:"Check if element value equals 10",output:"Boolean result"},{title:"Type coercion",code:'if "5" == 5',explanation:'String "5" equals number 5 with automatic type conversion',output:"true"},{title:"Null checks",code:"if value is null",explanation:"Check if value is null or undefined",output:"Boolean result"}],seeAlso:["strictEquals","notEquals","matches"],tags:["comparison","equality","logic","type-coercion"]}},Yn={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,a=t===n;return r&&Dn(this,e,[t,n],a,i),a},validate:e=>vn(e,"strictEquals")},Zn={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,a=t!=n;return r&&Dn(this,e,[t,n],a,i),a},validate:e=>vn(e,"notEquals")},Xn={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,a=t!==n;return r&&Dn(this,e,[t,n],a,i),a},validate:e=>vn(e,"strictNotEquals")},er={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,a=Hn(t,n,"<");return r&&Dn(this,e,[t,n],a,i),a},validate:e=>vn(e,"lessThan")},tr={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,a=Hn(t,n,"<=");return r&&Dn(this,e,[t,n],a,i),a},validate:e=>vn(e,"lessThanOrEqual")},nr={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,a=Hn(t,n,">");return r&&Dn(this,e,[t,n],a,i),a},validate:e=>vn(e,"greaterThan")},rr={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,a=Hn(t,n,">=");return r&&Dn(this,e,[t,n],a,i),a},validate:e=>vn(e,"greaterThanOrEqual")},ir={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(e,t,n){const r=Date.now();try{return Dn(this,e,[t,n],t&&n,r)}catch(i){throw Dn(this,e,[t,n],!1,r,!1,i instanceof Error?i:new Error(String(i))),i}},validate:e=>vn(e,"and"),inputSchema:Gn,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"true and false",description:"Logical AND of boolean values",expectedOutput:!1},{input:"name and age",description:"Both name and age must be truthy",expectedOutput:!0,context:{variables:new Map([["name","John"],["age",25]])}}],relatedExpressions:["or","not"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Logical AND operation that returns true only if both operands are truthy",parameters:[{name:"left",type:"unknown",description:"Left operand (evaluated for truthiness)",optional:!1,examples:["true","name","5",'"hello"']},{name:"right",type:"unknown",description:"Right operand (evaluated for truthiness)",optional:!1,examples:["false","age","0",'""']}],returns:{type:"Boolean",description:"True if both operands are truthy, false otherwise",examples:["true","false"]},examples:[{title:"Form validation",code:"if name and email",explanation:"Check if both name and email have values",output:"Boolean result"},{title:"Multiple conditions",code:"if age > 18 and hasLicense",explanation:"Combine multiple conditions",output:"Boolean result"},{title:"Short-circuit evaluation",code:"if element and element.value",explanation:"Check element exists before accessing properties",output:"Boolean result"}],seeAlso:["or","not","exists"],tags:["logic","boolean","conditions","validation"]}},ar={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,a=t||n;return r&&Dn(this,e,[t,n],a,i),a},validate:e=>vn(e,"or")},or={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0,i=!t;return n&&Dn(this,e,[t],i,r),i},validate:e=>hn(e,1,"not","operand")},sr={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0;let i;return i=null==t||(Ut(t)||Array.isArray(t)||t instanceof NodeList?0===t.length:!(t instanceof Node||t instanceof Element)&&(!!Qt(t)&&0===Object.keys(t).length)),n&&Dn(this,e,[t],i,r),i},validate:e=>hn(e,1,"isEmpty","value")},lr={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0;let i;return i=null==t||(!1===t||(Array.isArray(t)||t instanceof NodeList?0===t.length:!Ut(t)&&(!(t instanceof Node||t instanceof Element)&&(!!Qt(t)&&0===Object.keys(t).length)))),n&&Dn(this,e,[t],i,r),i},validate:e=>hn(e,1,"no","value")},cr={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0,i=!await sr.evaluate(e,t);return n&&Dn(this,e,[t],i,r),i},validate:e=>hn(e,1,"isNotEmpty","value")},ur={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0,i=null!=t;return n&&Dn(this,e,[t],i,r),i},validate:e=>hn(e,1,"exists","value")},pr={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0,i=null==t;return n&&Dn(this,e,[t],i,r),i},validate:e=>hn(e,1,"doesNotExist","value")},mr={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0;let a;if(t&&n){if(Kn(t)&&Kn(n))return a=t.contains(n),r&&Dn(this,e,[t,n],a,i),a;if(Ut(t)&&t.match(/^[.#][\w-]+$/)){const o=document.querySelector(t);if(o&&Kn(n))return a=o.contains(n),r&&Dn(this,e,[t,n],a,i),a;if(o&&Ut(n)&&n.match(/^[.#][\w-]+$/)){const s=document.querySelector(n);return a=!!s&&o.contains(s),r&&Dn(this,e,[t,n],a,i),a}}if(Ut(n)&&n.match(/^[.#][\w-]+$/)&&Kn(t)){const o=document.querySelector(n);return a=!!o&&t.contains(o),r&&Dn(this,e,[t,n],a,i),a}}return a=Ut(t)&&Ut(n)||Array.isArray(t)?t.includes(n):"undefined"!=typeof NodeList&&t instanceof NodeList?Array.from(t).includes(n):!(!Qt(t)||!Ut(n))&&n in t,r&&Dn(this,e,[t,n],a,i),a},validate:e=>hn(e,2,"contains","container, value")},dr={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,a=!await mr.evaluate(e,t,n);return r&&Dn(this,e,[t,n],a,i),a},validate:e=>hn(e,2,"doesNotContain","container, value")},hr={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,a=!(!Ut(t)||!Ut(n))&&t.startsWith(n);return r&&Dn(this,e,[t,n],a,i),a},validate:e=>hn(e,2,"startsWith","str, prefix")},fr={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,a=!(!Ut(t)||!Ut(n))&&t.endsWith(n);return r&&Dn(this,e,[t,n],a,i),a},validate:e=>hn(e,2,"endsWith","str, suffix")},yr={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(e,t,n){const r=Date.now();try{let i;if(t instanceof Element&&Ut(n)){const e=n;if(e.startsWith(".")||e.startsWith("#")||e.startsWith(":")||e.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(e))try{i=function(e,t){return Nn.matches(e,t)}(t,e)}catch(e){i=!1}else i=!1}else if(Ut(t)&&Ut(n)){const e=t,r=n;try{i=(r.startsWith("/")&&r.endsWith("/")?new RegExp(r.slice(1,-1)):new RegExp(r)).test(e)}catch(t){i=e.includes(r)}}else i=!1;return Dn(this,e,[t,n],i,r)}catch(i){throw Dn(this,e,[t,n],!1,r,!1,i instanceof Error?i:new Error(String(i))),i}},validate:e=>hn(e,2,"matches","element, selector"),inputSchema:Qn,metadata:{category:"Logical",complexity:"medium",sideEffects:["dom-query"],dependencies:[],returnTypes:["Boolean"],examples:[{input:'element matches ".active"',description:"Check if element has active class",expectedOutput:!0},{input:'text matches "/^hello/"',description:'Check if text starts with "hello" using regex',expectedOutput:!0,context:{variables:new Map([["text","hello world"]])}}],relatedExpressions:["contains","startsWith","endsWith"],performance:{averageTime:.5,complexity:"O(n)"}},documentation:{summary:"Tests if element matches CSS selector or string matches regex pattern",parameters:[{name:"element",type:"Element | string",description:"DOM element or string to test",optional:!1,examples:["<div>",'"hello world"',"me","target"]},{name:"selector",type:"string",description:"CSS selector or regex pattern to match against",optional:!1,examples:['".active"','"#navbar"','"/^hello/"','"\\\\d+"']}],returns:{type:"Boolean",description:"True if element matches selector/pattern",examples:["true","false"]},examples:[{title:"CSS class matching",code:'if me matches ".active"',explanation:'Check if current element has "active" class',output:"Boolean result"},{title:"Attribute matching",code:'if target matches "[data-role=\\"button\\"]"',explanation:"Check if element has specific data attribute",output:"Boolean result"},{title:"Regex pattern matching",code:'if email matches "/^[^@]+@[^@]+\\\\.[^@]+$/"',explanation:"Validate email format with regex",output:"Boolean result"},{title:"Complex CSS selector",code:'if element matches ".card:hover .button"',explanation:"Match complex CSS selector with pseudo-classes",output:"Boolean result"}],seeAlso:["contains","startsWith","endsWith","querySelector"],tags:["pattern","css","regex","validation","dom"]}},vr={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0;let a=!1;if(t instanceof Element&&Ut(n)){const e=n;e.startsWith(".")?a=t.classList.contains(e.slice(1)):e.startsWith("[")&&e.endsWith("]")&&(a=t.hasAttribute(e.slice(1,-1)))}return r&&Dn(this,e,[t,n],a,i),a},validate:e=>hn(e,2,"has","element, selector")},gr={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,a=!await vr.evaluate(e,t,n);return r&&Dn(this,e,[t,n],a,i),a},validate:e=>hn(e,2,"doesNotHave","element, selector")},br={equals:Jn,strictEquals:Yn,notEquals:Zn,strictNotEquals:Xn,lessThan:er,lessThanOrEqual:tr,greaterThan:nr,greaterThanOrEqual:rr,and:ir,or:ar,not:or,no:lr,isEmpty:sr,isNotEmpty:cr,exists:ur,doesNotExist:pr,contains:mr,doesNotContain:dr,startsWith:hr,endsWith:fr,matches:yr,has:vr,doesNotHave:gr};function kr(e,t,n,r,i="runtime-error"){return{success:!1,error:{name:`${e}ConversionError`,type:i,message:n,code:t,suggestions:r}}}function wr(e,t){return{success:!0,value:e,type:t}}function zr(e,t){return`${e}: ${t instanceof Error?t.message:String(t)}`}const xr={Array:(e,t)=>{try{return Array.isArray(e)?wr(e,"array"):e instanceof NodeList?wr(Array.from(e),"array"):wr(null==e?[]:[e],"array")}catch(e){return kr("Array","ARRAY_CONVERSION_FAILED",zr("Failed to convert value to Array",e),["Check if value is iterable","Ensure value is not circular reference"])}},String:(e,t)=>{try{return null==e?wr("","string"):Ut(e)?wr(e,"string"):Qt(e)?wr(JSON.stringify(e),"string"):wr(String(e),"string")}catch(e){return kr("String","STRING_CONVERSION_FAILED",zr("Failed to convert value to String",e),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(e,t)=>{try{if(Gt(e))return wr(e,"boolean");if(null==e)return wr(!1,"boolean");if(Ut(e)){const t=e.toLowerCase().trim();return wr("false"!==t&&"0"!==t&&""!==t,"boolean")}return Kt(e)?wr(0!==e&&!isNaN(e),"boolean"):wr(Boolean(e),"boolean")}catch(e){return kr("Boolean","BOOLEAN_CONVERSION_FAILED",zr("Failed to convert value to Boolean",e),["Use explicit true/false values","Check for unexpected data types"])}},Number:(e,t)=>{try{if(Kt(e))return wr(e,"number");if(null==e)return wr(0,"number");const t=Number(e);return isNaN(t)?kr("Number","INVALID_NUMBER",`Cannot convert "${e}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):wr(t,"number")}catch(e){return kr("Number","NUMBER_CONVERSION_FAILED",zr("Failed to convert value to Number",e),["Ensure value is convertible to number","Check for special characters"])}},Int:(e,t)=>{const n=xr.Number(e,t);return n.success?wr(Math.trunc(n.value),"number"):n},Float:(e,t)=>{const n=xr.Number(e,t);return n.success?wr(parseFloat(n.value.toString()),"number"):n},Date:(e,t)=>{try{if(e instanceof Date)return wr(e,"object");if(null==e)return wr(new Date(""),"object");if(Ut(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,n,r]=e.split("-").map(Number);return wr(new Date(t,n-1,r),"object")}const t=new Date(e);return isNaN(t.getTime())?kr("Date","INVALID_DATE",`Cannot convert "${e}" to a valid date`,["Use ISO 8601 format (YYYY-MM-DD)","Check date string format","Ensure date values are valid"],"invalid-argument"):wr(t,"object")}catch(e){return kr("Date","DATE_CONVERSION_FAILED",zr("Failed to convert value to Date",e),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(e,t)=>{try{return wr(JSON.stringify(e),"string")}catch(e){return kr("JSON","JSON_STRINGIFY_FAILED",zr("Failed to convert value to JSON",e),["Check for circular references","Ensure all properties are serializable","Remove functions and undefined values"])}},Object:(e,t)=>{try{if(Qt(e))return wr(e,"object");if(Ut(e))try{return wr(JSON.parse(e),"object")}catch(e){return kr("Object","JSON_PARSE_FAILED",zr("Cannot parse JSON string",e),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return wr({},"object")}catch(e){return kr("Object","OBJECT_CONVERSION_FAILED",zr("Failed to convert value to Object",e),["Ensure value is valid JSON string or object","Check for syntax errors"])}},Values:(e,t)=>{try{if(e instanceof HTMLFormElement)return wr(function(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const n=e;if(n.name){const e=Tr(n);void 0!==e&&(void 0!==t[n.name]?(Array.isArray(t[n.name])||(t[n.name]=[t[n.name]]),t[n.name].push(e)):t[n.name]=e)}}),t}(e),"object");if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),n={};return t.forEach(e=>{const t=e;if(t.name){const e=Tr(t);void 0!==e&&(n[t.name]=e)}}),wr(n,"object")}return wr({},"object")}catch(e){return kr("FormValues","FORM_VALUES_EXTRACTION_FAILED",zr("Failed to extract form values",e),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}}},Er=Cn.object({value:Cn.any(),type:Cn.string().min(1)});const Sr=Cn.object({value:Cn.any(),type:Cn.string().min(1)});function Tr(e){if(e instanceof HTMLInputElement)switch(e.type){case"checkbox":return e.checked;case"radio":return e.checked?e.value:void 0;case"number":case"range":return e.valueAsNumber;case"date":case"datetime-local":return e.valueAsDate;case"file":return e.files;default:return e.value}return e instanceof HTMLSelectElement&&e.multiple?Array.from(e.selectedOptions).map(e=>e.value):e.value}new class extends jn{constructor(){super(...arguments),this.name="as",this.category="Conversion",this.syntax="value as Type",this.description='Converts values between different types using the "as" keyword',this.outputType="Any",this.inputSchema=Er,this.metadata={category:"Conversion",complexity:"medium",sideEffects:[],dependencies:[],returnTypes:["Any"],examples:[{input:'"123" as Int',description:"Convert string to integer",expectedOutput:123},{input:"form as Values",description:"Extract form values as object",expectedOutput:{name:"John",age:"25"}},{input:"[1,2,3] as JSON",description:"Convert array to JSON string",expectedOutput:"[1,2,3]"},{input:'"2023-12-25" as Date',description:"Parse date string",expectedOutput:new Date(2023,11,25)}],relatedExpressions:["is","Object","Array"],performance:{averageTime:1,complexity:"O(n)"}},this.documentation={summary:'Converts values between different types using the "as" keyword with comprehensive type safety',parameters:[{name:"value",type:"object",description:"The value to convert",optional:!1,examples:['"123"',"form","[1,2,3]","true","null"]},{name:"type",type:"string",description:"Target conversion type",optional:!1,examples:["Int","String","Boolean","Array","JSON","Object","Date","Values","HTML","Fragment"]}],returns:{type:"object",description:"Structured result with converted value or detailed error information",examples:['{ success: true, value: 123, type: "number" }',"{ success: false, error: { ... } }"]},examples:[{title:"String to number conversion",code:"if my.value as Int > 100",explanation:"Convert form input to integer for comparison",output:"Boolean result"},{title:"Form data extraction",code:"put closest <form /> as Values into result",explanation:"Extract all form values as structured object",output:'{ name: "John", age: "25", ... }'},{title:"Array to JSON serialization",code:"put items as JSON into storage",explanation:"Convert array to JSON string for storage",output:'"[1,2,3]"'},{title:"Date parsing with validation",code:"put my.dateInput as Date into event.detail.date",explanation:"Parse date input with automatic validation",output:"Date object or validation error"},{title:"Boolean conversion with smart parsing",code:'if "false" as Boolean then hide else show',explanation:"Parse string boolean values correctly",output:"false (not true like naive conversion)"}],seeAlso:["is","Values","JSON","Array","Object"],tags:["conversion","types","validation","forms","json","parsing"]}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:{name:"AsExpressionValidationError",type:"validation-error",message:r.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:r.suggestions}};const{value:i,type:a}=t;if(a.startsWith("Fixed")){const r=a.match(/^Fixed:(\d+)$/),o=r?parseInt(r[1],10):2,s=xr.Number(i,e);if(!s.success)return s;const l={success:!0,value:s.value.toFixed(o),type:"string"};return this.trackPerformance(e,t,l,n),l}let o=xr[a];if(o){const r=o(i,e);return this.trackPerformance(e,t,r,n),r}const s=a.toLowerCase(),l={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON"}[s];if(l&&(o=xr[l],o)){const r=o(i,e);return this.trackPerformance(e,t,r,n),r}const c={success:!1,error:{name:"UnknownConversionTypeError",type:"validation-error",message:`Unknown conversion type: ${a}`,code:"UNKNOWN_CONVERSION_TYPE",suggestions:["Use supported types: String, Number, Boolean, Array, Object, Date, JSON, Values","Check type spelling and capitalization","See documentation for complete list of conversion types"]}};return this.trackPerformance(e,t,c,n),c}catch(r){const i={success:!1,error:{name:"AsExpressionError",type:"runtime-error",message:`Conversion failed: ${r instanceof Error?r.message:String(r)}`,code:"CONVERSION_FAILED",suggestions:["Check value and type compatibility","Ensure value is convertible to target type"]}};return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:e.message,suggestions:[`Expected valid input structure, got: ${e.code}`]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(e){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}},new class extends jn{constructor(){super(...arguments),this.name="is",this.category="Conversion",this.syntax="value is Type",this.description="Checks if a value is of a specific type",this.outputType="Boolean",this.inputSchema=Sr,this.metadata={category:"Conversion",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"42 is number",description:"Check if value is a number",expectedOutput:!0},{input:"null is empty",description:"Check if value is empty/null",expectedOutput:!0},{input:"element is Element",description:"Check if value is DOM element",expectedOutput:!0,context:{element:"<div>...</div>"}}],relatedExpressions:["as","empty","exists"],performance:{averageTime:.1,complexity:"O(1)"}},this.documentation={summary:"Checks if a value is of a specific type with comprehensive type detection",parameters:[{name:"value",type:"object",description:"The value to check",optional:!1,examples:["42","null","element",'"text"',"[]"]},{name:"type",type:"string",description:"Type name to check against",optional:!1,examples:["number","string","boolean","array","object","element","empty","null"]}],returns:{type:"object",description:"Boolean result indicating type match",examples:['{ success: true, value: true, type: "boolean" }']},examples:[{title:"Number validation",code:"if my.age is number then proceed",explanation:"Check if form input is valid number",output:"Boolean result"},{title:"Empty check",code:"if result is empty then show message",explanation:"Check if result is null, undefined, or empty",output:"Boolean result"},{title:"Element validation",code:"if target is element then addClass",explanation:"Ensure target is valid DOM element before manipulation",output:"Boolean result"}],seeAlso:["as","empty","exists","null"],tags:["validation","types","checking","guards"]}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:{name:"IsExpressionValidationError",type:"validation-error",message:r.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:r.suggestions}};const{value:i,type:a}=t,o=a.toLowerCase();let s;switch(o){case"null":s=null===i;break;case"undefined":s=void 0===i;break;case"string":s=Ut(i);break;case"number":s=Kt(i)&&!isNaN(i);break;case"boolean":s=Gt(i);break;case"object":s=Qt(i);break;case"array":s=Array.isArray(i);break;case"function":s=Jt(i);break;case"date":s=i instanceof Date;break;case"element":s=i instanceof Element;break;case"node":s=i instanceof Node;break;case"node-list":s=i instanceof NodeList;break;case"empty":s=null==i||""===i||Array.isArray(i)&&0===i.length||Qt(i)&&0===Object.keys(i).length;break;default:s=i?.constructor?.name?.toLowerCase()===o}const l=this.success(s,"boolean");return this.trackPerformance(e,t,l,n),l}catch(r){const i=this.failure("IsExpressionError","type-mismatch",`Type check failed: ${r instanceof Error?r.message:String(r)}`,"TYPE_CHECK_FAILED",["Check type name spelling","Ensure value is accessible"]);return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:e.message,suggestions:[`Expected valid input structure, got: ${e.code}`]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(e){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}};const Cr={Array:e=>Array.isArray(e)?e:e instanceof NodeList?Array.from(e):null==e?[]:[e],String:e=>null==e?"":Ut(e)?e:Qt(e)?JSON.stringify(e):String(e),Boolean:e=>{if(Gt(e))return e;if(null==e)return!1;if(Ut(e)){const t=e.toLowerCase().trim();return"false"!==t&&"0"!==t&&""!==t}return Kt(e)?0!==e&&!isNaN(e):Boolean(e)},Number:e=>{if(Kt(e))return e;if(null==e)return 0;const t=Number(e);return isNaN(t)?0:t},Math:e=>{if(Kt(e))return e;if(null==e)return 0;const t=String(e).trim();if(!t)return 0;try{return function(e){if(e=e.replace(/\s/g,""),!/^[0-9+\-*/().]+$/.test(e))throw new Error("Invalid characters in math expression");try{const t=new Function(`"use strict"; return (${e})`)();if(!Kt(t)||!isFinite(t))throw new Error("Expression did not evaluate to a finite number");return t}catch(e){throw new Error(`Math expression evaluation failed: ${e instanceof Error?e.message:String(e)}`)}}(t)}catch(e){return console.warn("Math conversion failed:",e),0}},Int:e=>{const t=Cr.Number(e);return Math.trunc(t)},Float:e=>{const t=Cr.Number(e);return parseFloat(t.toString())},Date:e=>{if(e instanceof Date)return e;if(null==e)return new Date(NaN);if(Ut(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,n,r]=e.split("-").map(Number);return new Date(t,n-1,r)}return new Date(e)},JSON:e=>{try{return JSON.stringify(e)}catch(e){return"{}"}},Object:e=>{if(Qt(e))return e;if(Ut(e))try{return JSON.parse(e)}catch(e){return{}}return{}},Fragment:e=>{Ut(e)||(e=Cr.String(e));const t=document.createElement("template");return t.innerHTML=String(e),t.content},HTML:e=>Ut(e)?e:e instanceof NodeList?Array.from(e).map(e=>e instanceof Element?e.outerHTML:e.textContent||"").join(""):Array.isArray(e)?e.map(e=>e instanceof Element?e.outerHTML:Cr.String(e)).join(""):e instanceof Element?e.outerHTML:Cr.String(e),Values:(e,t)=>{if(e instanceof HTMLFormElement)return function(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const n=e;if(n.name){const e=Ar(n);void 0!==e&&(void 0!==t[n.name]?(Array.isArray(t[n.name])||(t[n.name]=[t[n.name]]),t[n.name].push(e)):t[n.name]=e)}}),t}(e);if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),n={};return t.forEach(e=>{const t=e;t.name&&(n[t.name]=Ar(t))}),n}return{}},"Values:Form":(e,t)=>{const n=Cr.Values(e,t);return new URLSearchParams(n).toString()},"Values:JSON":(e,t)=>{const n=Cr.Values(e,t);return JSON.stringify(n)}};function Ar(e){if(e instanceof HTMLInputElement)switch(e.type){case"checkbox":return e.checked;case"radio":return e.checked?e.value:void 0;case"number":case"range":return e.valueAsNumber;case"date":case"datetime-local":return e.valueAsDate;case"file":return e.files;default:return e.value}return e instanceof HTMLSelectElement&&e.multiple?Array.from(e.selectedOptions).map(e=>e.value):e.value}const jr={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(e,...t){const[n,r]=t;if("string"!=typeof r)throw new Error("Conversion type must be a string");if(r.startsWith("Fixed")){const{precision:e}=function(e){const t=e.match(/^Fixed(?::(\d+))?$/);return t?{precision:t[1]?parseInt(t[1],10):2}:{}}(r);return Cr.Number(n).toFixed(e||2)}let i=Cr[r];if(i)return i(n,e);const a={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON"}[r.toLowerCase()];return a&&(i=Cr[a],i)?i(n,e):(console.warn(`Unknown conversion type: ${r}`),n)},validate:e=>hn(e,2,"as","value, type")??fn(e,1,"as","conversion type")},is:{name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(e,...t){const[n,r]=t;if(!Ut(r))throw new Error("Type check requires a string type");switch(r.toLowerCase()){case"null":return null===n;case"undefined":return void 0===n;case"string":return Ut(n);case"number":return Kt(n)&&!isNaN(n);case"boolean":return Gt(n);case"object":return Qt(n);case"array":return Array.isArray(n);case"function":return Jt(n);case"date":return n instanceof Date;case"element":return n instanceof Element;case"node":return n instanceof Node;case"nodelist":return n instanceof NodeList;case"empty":return null==n||""===n||Array.isArray(n)&&0===n.length||Qt(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:e=>hn(e,2,"is","value, type")??fn(e,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(e,t)=>t,validate:e=>hn(e,1,"async","expression")}},Lr={String:"string",Number:"number",Boolean:"boolean",Element:"element",ElementList:"element-list",Array:"array",Object:"object",Promise:"promise",Context:"object",Null:"null",Undefined:"undefined",Any:"object"},Pr=Cn.object({collection:Cn.unknown().describe("Collection to operate on (array, NodeList, or string)")}).strict(),Ir=Cn.object({collection:Cn.unknown().describe("Collection to access"),index:Cn.number().describe("Index position to access")}).strict(),Nr=Cn.object({collection:Cn.unknown().describe("Collection to select random item from")}).strict();class Or extends jn{constructor(){super(...arguments),this.name="first",this.category="Positional",this.syntax="first in collection",this.description="Gets the first element from a collection",this.inputSchema=Pr,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=this.normalizeCollection(t.collection),a=i.length>0?i[0]:void 0,o={success:!0,value:a,type:Lr[this.inferEvaluationType(a)]};return this.trackPerformance(e,t,o,n),o}catch(r){const i=this.failure("FirstExpressionError","runtime-error",`First operation failed: ${r instanceof Error?r.message:String(r)}`,"FIRST_OPERATION_FAILED");return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:`Invalid first input: ${e.message}`,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class Rr extends jn{constructor(){super(...arguments),this.name="last",this.category="Positional",this.syntax="last in collection",this.description="Gets the last element from a collection",this.inputSchema=Pr,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=this.normalizeCollection(t.collection),a=i.length>0?i[i.length-1]:void 0,o={success:!0,value:a,type:Lr[this.inferEvaluationType(a)]};return this.trackPerformance(e,t,o,n),o}catch(r){const i=this.failure("LastExpressionError","runtime-error",`Last operation failed: ${r instanceof Error?r.message:String(r)}`,"LAST_OPERATION_FAILED");return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:`Invalid last input: ${e.message}`,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class Mr extends jn{constructor(){super(...arguments),this.name="at",this.category="Positional",this.syntax="collection[index] or collection at index",this.description="Gets element at specific index from a collection",this.inputSchema=Ir,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=this.normalizeCollection(t.collection),a=this.normalizeIndex(t.index,i.length),o=a>=0&&a<i.length?i[a]:void 0,s={success:!0,value:o,type:Lr[this.inferEvaluationType(o)]};return this.trackPerformance(e,t,s,n),s}catch(r){const i=this.failure("AtExpressionError","runtime-error",`At operation failed: ${r instanceof Error?r.message:String(r)}`,"AT_OPERATION_FAILED");return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:`Invalid at input: ${e.message}`,suggestions:[]}))??[],suggestions:["Provide collection and index parameters","Ensure index is a number"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}normalizeIndex(e,t){return e<0?t+e:e}}class Wr extends jn{constructor(){super(...arguments),this.name="random",this.category="Positional",this.syntax="random in collection",this.description="Gets a random element from a collection",this.inputSchema=Nr,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=this.normalizeCollection(t.collection);if(0===i.length){const r={success:!0,value:void 0,type:"undefined"};return this.trackPerformance(e,t,r,n),r}const a=i[this.getSecureRandomIndex(i.length)],o={success:!0,value:a,type:Lr[this.inferEvaluationType(a)]};return this.trackPerformance(e,t,o,n),o}catch(r){const i=this.failure("RandomExpressionError","runtime-error",`Random operation failed: ${r instanceof Error?r.message:String(r)}`,"RANDOM_OPERATION_FAILED");return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:`Invalid random input: ${e.message}`,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}getSecureRandomIndex(e){if("undefined"!=typeof crypto&&crypto.getRandomValues){const t=new Uint32Array(1);return crypto.getRandomValues(t),t[0]%e}return Math.floor(Math.random()*e)}}new Or,new Rr,new Mr,new Wr;const $r={name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(e,t){const n=void 0!==t?t:e.it;if(null==n)return null;if(Array.isArray(n))return n.length>0?n[0]:null;if(n instanceof NodeList||n instanceof HTMLCollection)return n.length>0?n[0]:null;if(n instanceof Element)return n.children.length>0?n.children[0]:null;if(Ut(n)){const e=n;return e.length>0?e[0]:null}if(Qt(n)&&"length"in n&&Kt(n.length)){const e=n;return e.length>0?e[0]:null}return null},validate:e=>bn(e,1,"first","collection")},Hr={name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(e,t){const n=void 0!==t?t:e.it;if(null==n)return null;if(Array.isArray(n))return n.length>0?n[n.length-1]:null;if(n instanceof NodeList||n instanceof HTMLCollection)return n.length>0?n[n.length-1]:null;if(n instanceof Element){const e=n.children;return e.length>0?e[e.length-1]:null}if(Ut(n)){const e=n;return e.length>0?e[e.length-1]:null}if(Qt(n)&&"length"in n&&Kt(n.length)){const e=n;return e.length>0?e[e.length-1]:null}return null},validate:e=>bn(e,1,"last","collection")},qr={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(e,...t){const[n,r]=t;if(!Kt(n))throw new Error("Index must be a number");const i=n,a=void 0!==r?r:e.it;if(null==a)return null;if(Array.isArray(a)){const e=i<0?a.length+i:i;return e>=0&&e<a.length?a[e]:null}if(a instanceof NodeList||a instanceof HTMLCollection){const e=i<0?a.length+i:i;return e>=0&&e<a.length?a[e]:null}if(a instanceof Element){const e=a.children,t=i<0?e.length+i:i;return t>=0&&t<e.length?e[t]:null}if(Ut(a)){const e=a,t=i<0?e.length+i:i;return t>=0&&t<e.length?e[t]:null}if(Qt(a)&&"length"in a&&Kt(a.length)){const e=a,t=i<0?e.length+i:i;return t>=0&&t<e.length?e[t]:null}return null},validate:e=>kn(e,1,2,"at","index, optional collection")??function(e,t,n,r){if("number"!=typeof e[t])return`${n} ${r} must be a number`;return null}(e,0,"at","index")};function Dr(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;const e=n.querySelector(t);if(e)return e;n=n.nextElementSibling}const r=e.parentElement;return r&&r!==document.documentElement?Dr(r,t):null}function _r(e,t){let n=e.previousElementSibling;for(;n;){const e=Array.from(n.querySelectorAll(t)).reverse();if(e.length>0)return e[0];if(n.matches(t))return n;n=n.previousElementSibling}const r=e.parentElement;return r&&r!==document.documentElement?_r(r,t):null}function Vr(e){let t=0,n=e;for(;n&&n.parentElement;){t+=Array.from(n.parentElement.children).indexOf(n),n=n.parentElement,t+=1e3}return t}const Br={first:$r,last:Hr,at:qr,next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(e,...t){const[n,r]=t,i=r||e.me;return i&&i instanceof Element?n?Dr(i,n):i.nextElementSibling:null},validate(e){const t=bn(e,2,"next","optional selector, optional fromElement");return t||(e.length>=1&&null!=e[0]&&"string"!=typeof e[0]?"selector must be a string":e.length>=2&&null!=e[1]&&!(e[1]instanceof Element)?"fromElement must be an Element":null)}},previous:{name:"previous",category:"Reference",evaluatesTo:"Element",operators:["previous","prev"],async evaluate(e,...t){const[n,r]=t,i=r||e.me;return i&&i instanceof Element?n?_r(i,n):i.previousElementSibling:null},validate(e){const t=bn(e,2,"previous","optional selector, optional fromElement");return t||(e.length>=1&&null!=e[0]&&"string"!=typeof e[0]?"selector must be a string":e.length>=2&&null!=e[1]&&!(e[1]instanceof Element)?"fromElement must be an Element":null)}},nextWithin:{name:"nextWithin",category:"Reference",evaluatesTo:"Element",operators:["next within"],async evaluate(e,...t){const[n,r,i]=t,a=i||e.me;if(!(a&&a instanceof Element))return null;const o=a.closest(r);return o?function(e,t,n){const r=Array.from(n.querySelectorAll(t)),i=Vr(e);for(const e of r){if(Vr(e)>i)return e}return null}(a,n,o):null},validate(e){const t=kn(e,2,3,"nextWithin","selector, withinSelector, optional fromElement");return t||("string"!=typeof e[0]?"selector must be a string":"string"!=typeof e[1]?"withinSelector must be a string":e.length>=3&&null!=e[2]&&!(e[2]instanceof Element)?"fromElement must be an Element":null)}},previousWithin:{name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(e,...t){const[n,r,i]=t,a=i||e.me;if(!(a&&a instanceof Element))return null;const o=a.closest(r);return o?function(e,t,n){const r=Array.from(n.querySelectorAll(t)),i=Vr(e);for(let e=r.length-1;e>=0;e--){const t=r[e];if(Vr(t)<i)return t}return null}(a,n,o):null},validate(e){const t=kn(e,2,3,"previousWithin","selector, withinSelector, optional fromElement");return t||("string"!=typeof e[0]?"selector must be a string":"string"!=typeof e[1]?"withinSelector must be a string":e.length>=3&&null!=e[2]&&!(e[2]instanceof Element)?"fromElement must be an Element":null)}}},Fr=new Set(["__proto__","constructor","prototype"]),Ur={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(e,...t){const[n,r]=t;if(null!=n){if("string"!=typeof r)throw new Error("Property name must be a string");if(n instanceof Element)return nn(n,r);if(Qt(n)){if(Fr.has(r))return;return n[r]}return n[r]}},validate:e=>hn(e,2,"possessive","element, property")??fn(e,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(e,...t){const[n]=t;if(e.me){if("string"!=typeof n)throw new Error("Property name must be a string");if(e.me instanceof Element)return nn(e.me,n);if(Qt(e.me)){if(Fr.has(n))return;return e.me[n]}return e.me[n]}},validate:e=>yn(e,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(e,...t){const[n]=t;if(null==e.it)return;if("string"!=typeof n)throw new Error("Property name must be a string");const r=e.it;if(r instanceof Element)return nn(r,n);if(Qt(r)){if(Fr.has(n))return;return r[n]}return r[n]},validate:e=>yn(e,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(e,...t){const[n]=t;if(e.you){if("string"!=typeof n)throw new Error("Property name must be a string");if(e.you instanceof Element)return nn(e.you,n);if(Qt(e.you)){if(Fr.has(n))return;return e.you[n]}return e.you[n]}},validate:e=>yn(e,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(e,...t){const[n,r]=t;if(null!=r){if("string"!=typeof n)throw new Error("Property name must be a string");if(r instanceof Element)return nn(r,n);if(Qt(r)){if(Fr.has(n))return;return r[n]}return r[n]}},validate:e=>hn(e,2,"of","property, object")??fn(e,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(e,...t){const[n,r]=t;if("string"!=typeof n)throw new Error("Attribute name must be a string");const i=r||e.me;return i&&i instanceof Element?i.getAttribute(n):null},validate:e=>kn(e,1,2,"attribute","attributeName, optional element")??fn(e,0,"attribute","attribute name")??(e.length>=2&&null!=e[1]&&!(e[1]instanceof Element)?"attribute element must be an Element":null)},attributeWithValue:{name:"attributeWithValue",category:"Reference",evaluatesTo:"Boolean",operators:["@="],async evaluate(e,...t){const[n,r,i]=t;if("string"!=typeof n)throw new Error("Attribute name must be a string");if("string"!=typeof r)throw new Error("Expected value must be a string");const a=i||e.me;if(!(a&&a instanceof Element))return!1;return a.getAttribute(n)===r},validate:e=>kn(e,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??fn(e,0,"attributeWithValue","attribute name")??fn(e,1,"attributeWithValue","expected value")??(e.length>=3&&null!=e[2]&&!(e[2]instanceof Element)?"attributeWithValue element must be an Element":null)},classReference:{name:"classReference",category:"Reference",evaluatesTo:"Array",operators:["."],async evaluate(e,...t){const[n]=t;if("string"!=typeof n)throw new Error("Class name must be a string");const r=n.startsWith(".")?n.slice(1):n,i=document.getElementsByClassName(r);return Array.from(i)},validate:e=>yn(e,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(e,...t){const[n]=t;if("string"!=typeof n)throw new Error("ID value must be a string");const r=n.startsWith("#")?n.slice(1):n;return document.getElementById(r)},validate:e=>yn(e,"idReference","idValue")}},Kr=Cn.object({value:Cn.string().describe("String literal value")}).strict(),Gr=Cn.object({value:Cn.number().describe("Number literal value")}).strict(),Qr=Cn.object({value:Cn.boolean().describe("Boolean literal value")}).strict(),Jr=Cn.object({left:Cn.unknown().describe("Left operand"),right:Cn.unknown().describe("Right operand")}).strict();class Yr extends jn{constructor(){super(...arguments),this.name="stringLiteral",this.category="Special",this.syntax="\"string\" or 'string'",this.description="String literals with template interpolation support",this.outputType="String",this.inputSchema=Kr,this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid){const t=this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions);return this.trackSimple(e,n,!1),t}let i=t.value;(i.includes("${")||i.includes("$"))&&(i=this.interpolateString(i,e));const a=this.success(i,"string");return this.trackSimple(e,n,!0,i),a}catch(t){return this.trackSimple(e,n,!1),this.failure("StringEvaluationError","runtime-error",`String literal evaluation failed: ${t instanceof Error?t.message:String(t)}`,"STRING_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid string literal input",["Provide a value parameter","Ensure value is a string"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}interpolateString(e,t){let n=e.replace(/\$\{([^}]+)\}/g,(e,n)=>{try{const e=this.resolveExpression(n.trim(),t);return void 0!==e?String(e):""}catch(e){return""}});return n=n.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(e,n)=>{try{const e=this.resolveVariable(n,t);return void 0!==e?String(e):""}catch(e){return""}}),n}resolveExpression(e,t){if(e.includes(".")){const n=e.split(".");let r=this.resolveVariable(n[0],t);for(let e=1;e<n.length&&null!=r;e++)r=r[n[e]];return r}return this.resolveVariable(e,t)}resolveVariable(e,t){return"me"===e&&t.me?t.me:"you"===e&&t.you?t.you:"it"===e&&t.it?t.it:"result"===e&&t.result?t.result:t.locals?.has(e)?t.locals.get(e):t.globals?.has(e)?t.globals.get(e):void 0}}class Zr extends jn{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Gr,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);return r.isValid?Number.isFinite(t.value)?(this.trackSimple(e,n,!0,t.value),this.success(t.value,"number")):(this.trackSimple(e,n,!1),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(t){return this.trackSimple(e,n,!1),this.failure("NumberEvaluationError","runtime-error",`Number literal evaluation failed: ${t instanceof Error?t.message:String(t)}`,"NUMBER_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?Number.isFinite(t.data.value)?this.validationSuccess():this.validationFailure("invalid-argument","Number literal value must be finite",["Use finite numbers only","Avoid Infinity and NaN values"]):this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid number literal input",["Provide a value parameter","Ensure value is a number"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class Xr extends jn{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Qr,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);return r.isValid?(this.trackSimple(e,n,!0,t.value),this.success(t.value,"boolean")):(this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(t){return this.trackSimple(e,n,!1),this.failure("BooleanEvaluationError","runtime-error",`Boolean literal evaluation failed: ${t instanceof Error?t.message:String(t)}`,"BOOLEAN_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class ei extends jn{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=Jr,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions);const i=Wn(t.left,"left operand"),a=i+Wn(t.right,"right operand");return this.trackSimple(e,n,!0,a),this.success(a,"number")}catch(t){return this.trackSimple(e,n,!1),this.failure("AdditionError","runtime-error",`Addition failed: ${t instanceof Error?t.message:String(t)}`,"ADDITION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid addition input",["Provide left and right operands"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class ti extends jn{constructor(){super(...arguments),this.name="stringConcatenation",this.category="Special",this.syntax="left + right (string concatenation)",this.description="Concatenation of two values into a string",this.inputSchema=Jr,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",r.suggestions);const i=this.convertToString(t.left),a=i+this.convertToString(t.right);return this.trackSimple(e,n,!0,a),this.success(a,"string")}catch(t){return this.trackSimple(e,n,!1),this.failure("StringConcatenationError","runtime-error",t instanceof Error?t.message:"String concatenation failed","STRING_CONCATENATION_ERROR",["Check that operands can be converted to strings"])}}validate(e){const t=Jr.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid string concatenation input",["Provide left and right operands for concatenation"])}convertToString(e){if(null===e)return"null";if(void 0===e)return"undefined";if(Ut(e))return e;if(Kt(e))return e.toString();if(Gt(e))return e.toString();if(e instanceof Date)return e.toString();try{return String(e)}catch{return"[object Object]"}}}class ni extends jn{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=Jr,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions);const i=Wn(t.left,"left operand"),a=i*Wn(t.right,"right operand");return this.trackSimple(e,n,!0,a),this.success(a,"number")}catch(t){return this.trackSimple(e,n,!1),this.failure("MultiplicationError","runtime-error",`Multiplication failed: ${t instanceof Error?t.message:String(t)}`,"MULTIPLICATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid multiplication input",["Provide left and right operands"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}const ri={stringLiteral:new Yr,numberLiteral:new Zr,booleanLiteral:new Xr,addition:new ei,stringConcatenation:new ti,multiplication:new ni};class ii extends mn{constructor(){super(),this.registerExpressions()}registerExpressions(){this.registerCategory(Pn),this.registerCategory(br),this.registerCategory(jr),this.registerCategory(Br),this.registerCategory(Ur),this.registerCategory(ri)}}class ai{static toTyped(e){return{me:e.me,it:e.it,you:e.you,result:e.result,...void 0!==e.event&&{event:e.event},variables:e.variables||new Map,locals:e.locals||new Map,globals:e.globals||new Map,...void 0!==e.events&&{events:e.events},meta:e.meta||{},expressionStack:[],evaluationDepth:0,validationMode:"strict",evaluationHistory:[]}}static fromTyped(e,t){return{...t,me:e.me,it:e.it,you:e.you,result:e.result,...void 0!==e.event&&{event:e.event},...void 0!==e.variables&&{variables:e.variables},locals:e.locals,globals:e.globals,...void 0!==e.events&&{events:e.events},...void 0!==e.meta&&{meta:e.meta}}}}class oi{constructor(e,t,n){this.impl=e,this.expressionEvaluator=t??new ii,this.hookRegistry=n??null}setHookRegistry(e){this.hookRegistry=e}createHookContext(e,t,n={}){return{commandName:this.name,element:e.me instanceof Element?e.me:null,args:t,modifiers:n,event:e.event??void 0,executionContext:e}}get name(){return this.impl.name||this.impl.metadata?.name}get metadata(){return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:this.impl.metadata?.syntax||""}}async execute(e,...t){const n=t[0],r=n&&"object"==typeof n&&"modifiers"in n&&n.modifiers||{},i=this.createHookContext(e,t,r);try{if(we(`CommandAdapterV2: Executing '${this.name}' with args:`,t),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(i),this.hookRegistry?.shouldIntercept(this.name,i))return void we(`CommandAdapterV2: '${this.name}' intercepted by hook`);e.locals||(e.locals=new Map),e.locals.set("__evaluator",this.expressionEvaluator);const r=ai.toTyped(e);let a,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(we(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),n&&"object"==typeof n&&("args"in n||"modifiers"in n)){const t=n.modifiers,r=t?.when||t?.where;if(r){if(!await this.expressionEvaluator.evaluate(r,e))return void we(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`)}a=await this.impl.parseInput({args:n.args||[],modifiers:t||{},commandName:n.commandName},this.expressionEvaluator,e)}else a=t;else we(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),a=t;return we("CommandAdapterV2: Calling execute with parsed input:",a),o=2===this.impl.execute.length?await this.impl.execute(a,r):await this.impl.execute(r,...a),we("CommandAdapterV2: Command result:",o),Object.assign(e,ai.fromTyped(r,e)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(i,o),o}catch(e){if(di(e)||we(`CommandAdapterV2: Error executing '${this.name}':`,e),this.hookRegistry&&e instanceof Error){throw await this.hookRegistry.runOnError(i,e)}throw e}}validate(e){return this.impl.validate?this.impl.validate(e):{isValid:!0,errors:[],suggestions:[]}}}class si{constructor(e,t){this.adapters=new Map,this.implementations=new Map,this.sharedEvaluator=e,this.hookRegistry=t}setHookRegistry(e){this.hookRegistry=e;for(const t of this.adapters.values())t.setHookRegistry(e);Se(`CommandRegistryV2: Hook registry set and propagated to ${this.adapters.size} adapters`)}getHookRegistry(){return this.hookRegistry}register(e){const t=e.name||e.metadata?.name;if(!t||"string"!=typeof t)throw new Error("Cannot register command: no name found. Provide a 'name' property or 'metadata.name' on the implementation.");const n=t.toLowerCase();Se(`CommandRegistryV2: Registering command '${n}'`),this.implementations.set(n,e);const r=new oi(e,this.sharedEvaluator,this.hookRegistry);this.adapters.set(n,r),j.add(n);const i=e.metadata?.aliases;if(i&&Array.isArray(i))for(const t of i){const n=t.toLowerCase();this.implementations.set(n,e),this.adapters.set(n,r),j.add(n)}}getAdapter(e){return this.adapters.get(e.toLowerCase())}has(e){return this.adapters.has(e.toLowerCase())}getCommandNames(){return Array.from(this.adapters.keys())}getImplementation(e){return this.implementations.get(e.toLowerCase())}getAdapters(){return new Map(this.adapters)}validateCommand(e,t){const n=this.getAdapter(e);return n?n.validate(t):{isValid:!1,errors:[{type:"runtime-error",message:`Unknown command: ${e}`,suggestions:[`Available commands: ${this.getCommandNames().join(", ")}`]}],suggestions:[`Available commands: ${this.getCommandNames().join(", ")}`]}}}function li(e){const t=e?.commands??new si,n=e?.eventSources??new Vt,r=e?.context??new Bt,i=new Set,a={commands:t,eventSources:n,context:r,use(e){if(i.has(e.name))console.warn(`[LokaScriptRegistry] Plugin '${e.name}' is already installed`);else{if(e.commands)for(const n of e.commands)t.register(n);if(e.eventSources)for(const t of e.eventSources)n.register(t.name,t);if(e.contextProviders)for(const{name:t,provide:n,options:i}of e.contextProviders)r.register(t,n,i);e.setup?.(a),i.add(e.name)}},reset(){i.clear()}};return a}let ci=null;function ui(){return ci||(ci=li()),ci}class pi{constructor(e={}){this.contextCache=new WeakMap;const t=ui();this.options={enableContextProviders:e.enableContextProviders??!0,enableEventSources:e.enableEventSources??!0,registry:e.registry??{}},this.contextRegistry=this.options.registry.context??t.context,this.eventSourceRegistry=this.options.registry.eventSources??t.eventSources,Se(`[RegistryIntegration] Initialized (context=${this.options.enableContextProviders}, events=${this.options.enableEventSources})`)}enhanceContext(e){if(!this.options.enableContextProviders)return e;const t=this.contextCache.get(e);if(t)return t;try{const t=this.contextRegistry.enhance(e);return this.contextCache.set(e,t),Se(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),t}catch(t){return Se(`[RegistryIntegration] Failed to enhance context: ${t instanceof Error?t.message:String(t)}`),e}}getEventSource(e){if(!this.options.enableEventSources)return;const t=this.eventSourceRegistry.get(e);if(t)return Se(`[RegistryIntegration] Found event source for '${e}'`),t;const n=this.eventSourceRegistry.findSourceForEvent(e);if(n){const t=this.eventSourceRegistry.get(n);return Se(`[RegistryIntegration] Found event source '${n}' supporting '${e}'`),t}}hasEventSource(e){return void 0!==this.getEventSource(e)}subscribeToEventSource(e,t,n){if(!this.options.enableEventSources)throw new Error("Event sources are disabled in this runtime");const r=this.eventSourceRegistry.subscribe(e,t,n);if(!r)throw new Error(`Failed to subscribe to event source '${e}'`);return Se(`[RegistryIntegration] Subscribed to '${e}' event '${t.event}' (id: ${r.id})`),r}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,Se("[RegistryIntegration] Destroyed")}}function mi(e){const t=new Error(e.type.toUpperCase()+"_EXECUTION");return t["is"+e.type.charAt(0).toUpperCase()+e.type.slice(1)]=!0,"returnValue"in e&&(t.returnValue=e.returnValue),t}function di(e){return e instanceof Error&&(null!==Rt(e)||"HALT_EXECUTION"===e.message||"EXIT_COMMAND"===e.message||"EXIT_EXECUTION"===e.message)}function hi(e){if(void 0===e)return;let t=e;if(t&&"object"==typeof t){const e=t;if("result"in e&&"wasAsync"in e)t=e.result;else if("result"in e&&"executed"in e){if(t=e.result,e.preserveArrayResult)return void 0!==t?t:void 0}else if("lastResult"in e&&"type"in e)t=e.lastResult;else if("conditionResult"in e&&"executedBranch"in e){if(void 0===e.result)return;t=e.result}else"value"in e&&1===Object.keys(e).length||"value"in e&&"target"in e&&"targetType"in e?t=e.value:"data"in e&&"status"in e&&"headers"in e&&(t=e.data)}return Array.isArray(t)&&t.length>0&&(t=t[0]),t}function fi(e){return null!==e&&"object"==typeof e&&"command"in e&&"selector"in e}const yi=new WeakMap;class vi{constructor(e){if(this.autoCleanupObserver=null,this.registryIntegration=null,this.options={commandTimeout:1e4,enableErrorReporting:!0,enableResultPattern:!0,enableAutoCleanup:!0,...e},this.registry=e.registry,this.expressionEvaluator=e.expressionEvaluator,this.behaviorRegistry=new Map,this.globalVariables=qt,this.hookRegistry=new Ot,e.hooks&&this.hookRegistry.register("default",e.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new Ht,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==e.registryIntegration){const t="object"==typeof e.registryIntegration?e.registryIntegration:{};this.registryIntegration=new pi(t),Se("RuntimeBase: Registry integration enabled")}this.behaviorAPI={has:e=>this.behaviorRegistry.has(e),get:e=>this.behaviorRegistry.get(e),install:async(e,t,n)=>await this.installBehaviorOnElement(e,t,n)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(e=>{const t=[];for(const n of e)for(const e of n.removedNodes)e instanceof Element&&t.push(e);t.length>0&&queueMicrotask(()=>{for(const e of t)if(!e.isConnected){const t=this.cleanupRegistry.cleanupElementTree(e);t>0&&Se(`RuntimeBase: Auto-cleaned ${t} resources for removed element`)}})}),document.body?this.autoCleanupObserver.observe(document.body,{childList:!0,subtree:!0}):document.addEventListener("DOMContentLoaded",()=>{this.autoCleanupObserver?.observe(document.body,{childList:!0,subtree:!0})},{once:!0}))}registerHooks(e,t){this.hookRegistry.register(e,t)}unregisterHooks(e){return this.hookRegistry.unregister(e)}getRegisteredHooks(){return this.hookRegistry.getRegisteredNames()}cleanup(e){return this.cleanupRegistry.cleanupElement(e)}cleanupTree(e){return this.cleanupRegistry.cleanupElementTree(e)}getCleanupStats(){return this.cleanupRegistry.getStats()}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),Se("RuntimeBase: Destroyed")}async execute(e,t){Se(`RUNTIME BASE: execute() called with node type: '${e.type}'`),t.locals.has("_behaviors")||t.locals.set("_behaviors",this.behaviorAPI),t.locals.has("_runtimeExecute")||t.locals.set("_runtimeExecute",(e,n)=>this.execute(e,n||t));try{switch(e.type){case"command":if(this.options.enableResultPattern)try{const n=await this.processCommandWithResult(e,t);if(!$t(n))throw mi(n.error);return n.value}catch(e){throw e}return await this.processCommand(e,t);case"eventHandler":return await this.executeEventHandler(e,t);case"event":{const n={type:"eventHandler",event:e.event,events:[e.event],commands:e.body||[],target:e.filter,modifiers:e.modifiers||{}};return await this.executeEventHandler(n,t)}case"behavior":return await this.executeBehaviorDefinition(e,t);case"Program":return await this.executeProgram(e,t);case"initBlock":case"block":return await this.executeBlock(e,t);case"sequence":case"CommandSequence":if(this.options.enableResultPattern){const n=e,r=await this.executeCommandSequenceWithResult(n.commands||[],t);if(!$t(r))throw mi(r.error);return r.value}return await this.executeCommandSequence(e,t);case"objectLiteral":return await this.executeObjectLiteral(e,t);default:if(this.options.enableResultPattern){const n=await this.evaluateExpressionWithResult(e,t);if(!$t(n))throw mi(n.error);return n.value}return await this.evaluateExpression(e,t)}}catch(e){throw this.options.enableErrorReporting,e}}async processCommand(e,t){const{name:n,args:r,modifiers:i}=e,a=n.toLowerCase();if(we(`RUNTIME BASE: Processing command '${a}'`),this.registry.has(a)){const e=await this.registry.getAdapter(a);if(!e)throw new Error(`Command '${a}' is registered but failed to load adapter.`);try{return await e.execute(t,{args:r||[],modifiers:i||{},commandName:a,runtime:this})}catch(e){throw di(e)||console.error(`Error executing command '${a}':`,e),e}}const o=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.options.enableErrorReporting&&console.warn(o),new Error(o)}toSignal(e){const t=Rt(e);if(t){if(t.isHalt||"HALT_EXECUTION"===t.message)return{type:"halt"};if(t.isExit||"EXIT_COMMAND"===t.message)return{type:"exit",returnValue:t.returnValue};if(t.isBreak)return{type:"break"};if(t.isContinue)return{type:"continue"};if(t.isReturn)return{type:"return",returnValue:t.returnValue}}if(e instanceof Error){if("HALT_EXECUTION"===e.message)return{type:"halt"};if("EXIT_COMMAND"===e.message)return{type:"exit"}}return null}async processCommandWithResult(e,t){const{name:n,args:r,modifiers:i}=e,a=n.toLowerCase();if(we(`RUNTIME BASE (Result): Processing command '${a}'`),!this.registry.has(a)){const e=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.options.enableErrorReporting&&console.warn(e),new Error(e)}const o=await this.registry.getAdapter(a);if(!o)throw new Error(`Command '${a}' is registered but failed to load adapter.`);try{return Mt(await o.execute(t,{args:r||[],modifiers:i||{},commandName:a,runtime:this}))}catch(e){const t=this.toSignal(e);if(t)return Wt(t);throw console.error(`Error executing command '${a}':`,e),e}}async executeCommandSequenceWithResult(e,t){let n;for(const r of e)if("command"===r.type){const e=await this.processCommandWithResult(r,t);if(!$t(e)){const n=e.error;switch(n.type){case"halt":case"exit":case"break":case"continue":return e;case"return":return void 0!==n.returnValue&&Object.assign(t,{it:n.returnValue,result:n.returnValue}),Mt(n.returnValue)}}n=e.value}else{const e=await this.evaluateExpressionWithResult(r,t);if(!$t(e))return e;n=e.value}return Mt(n)}async evaluateExpression(e,t){const n=await this.expressionEvaluator.evaluate(e,t);return fi(n)?await this.executeCommandFromPattern(n.command,n.selector,t):n}async evaluateExpressionWithResult(e,t){const n=await this.expressionEvaluator.evaluateWithResult(e,t);if(!$t(n))return n;const r=n.value;if(fi(r)){if(this.options.enableResultPattern){const e={type:"command",name:r.command,args:[{type:"literal",value:r.selector}]};return this.processCommandWithResult(e,t)}try{return Mt(await this.executeCommandFromPattern(r.command,r.selector,t))}catch(e){const t=this.toSignal(e);if(t)return Wt(t);throw e}}return Mt(r)}async executeCommandFromPattern(e,t,n){const r={type:"command",name:e,args:[{type:"literal",value:t}]};return this.processCommand(r,n)}async executeProgram(e,t){if(!e.statements||!Array.isArray(e.statements))return;let n;const r=[],i=[],a=[];for(const t of e.statements)"eventHandler"===t.type?r.push(t):"initBlock"===t.type?i.push(t):a.push(t);for(const e of r)try{await this.execute(e,t)}catch(e){if(di(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of i)try{n=await this.execute(e,t)}catch(e){if(di(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of a)try{n=await this.execute(e,t)}catch(e){if(di(e)&&(e.isHalt||e.isExit))break;throw e}return n}async executeBlock(e,t){if(e.commands&&Array.isArray(e.commands))for(const n of e.commands)try{await this.execute(n,t)}catch(e){if(di(e)&&e.isHalt)break;throw e}}async executeCommandSequence(e,t){if(!e.commands||!Array.isArray(e.commands))return;let n;for(const r of e.commands)try{n=await this.execute(r,t)}catch(e){if(di(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){if(void 0!==e.returnValue)return Object.assign(t,{it:e.returnValue,result:e.returnValue}),e.returnValue;break}if(e.isBreak)throw e}throw e}return n}async executeObjectLiteral(e,t){const n={};if(!e.properties)return n;for(const r of e.properties){let e;if("identifier"===r.key.type)e=r.key.name;else if("literal"===r.key.type)e=String(r.key.value);else{const n=await this.execute(r.key,t);e=String(n)}const i=await this.execute(r.value,t);n[e]=i}return n}enhanceContext(e){return this.registryIntegration?this.registryIntegration.enhanceContext(e):e}async executeBehaviorDefinition(e,t){const{name:n,parameters:r,eventHandlers:i,initBlock:a}=e;this.behaviorRegistry.set(n,{name:n,parameters:r,eventHandlers:i,initBlock:a}),Se(`RUNTIME BASE: Registered behavior '${n}'`)}async installBehaviorOnElement(e,t,n){Se(`BEHAVIOR: installBehaviorOnElement called: ${e}`);const r=this.behaviorRegistry.get(e);if(!r)throw new Error(`Behavior "${e}" not found`);Se(`BEHAVIOR: Found behavior, eventHandlers count: ${r.eventHandlers?.length||0}`);const i={me:t,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,halted:!1,returned:!1,broke:!1,continued:!1,async:!1},a=this.enhanceContext(i);if(r.parameters)for(const e of r.parameters){const t=e in n?n[e]:void 0;a.locals.set(e,t)}for(const[e,t]of Object.entries(n))r.parameters?.includes(e)||a.locals.set(e,t);if(r.initBlock){Se(`BEHAVIOR: Running init block for ${e}`);const t=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(r.initBlock,a),new Promise((n,r)=>setTimeout(()=>r(new Error(`Behavior "${e}" init block timed out after ${t}ms`)),t))]),Se(`BEHAVIOR: Init block completed for ${e}`)}catch(t){if(Se(`BEHAVIOR: Init block error for ${e}:`,t),!(t instanceof Error&&di(t)))throw t}}if(Se(`BEHAVIOR: About to attach ${r.eventHandlers?.length||0} handlers for ${e}`),r.eventHandlers){const t=this.options.commandTimeout??1e4;for(const n of r.eventHandlers)await Promise.race([this.executeEventHandler(n,a),new Promise((n,r)=>setTimeout(()=>r(new Error(`Behavior "${e}" handler attachment timed out after ${t}ms`)),t))])}Se(`BEHAVIOR: Finished installing ${e}`)}async executeEventHandler(e,t){const{event:n,events:r,commands:i,target:a,args:o,selector:s,attributeName:l,watchTarget:c,modifiers:u}=e,p=r&&r.length>0?r:[n];Se(`BEHAVIOR: executeEventHandler: event='${n}', target='${a}'`);let m=[],d=null;if(a){const e="string"==typeof a?a.toLowerCase():"";if("window"===e||"the window"===e)d=window;else if("document"===e||"the document"===e||"body"===e)d=document;else if("me"===e||"myself"===e)m=t.me?[t.me]:[];else if("string"==typeof a&&t.locals.has(a)){const e=t.locals.get(a);Se(`BEHAVIOR: Target resolution: found local '${a}', isElement: ${this.isElement(e)}`),this.isElement(e)?m=[e]:Array.isArray(e)?m=e.filter(e=>this.isElement(e)):"string"==typeof e&&(m=this.queryElements(e,t))}else Se(`BEHAVIOR: Target resolution: querying for '${a}'`),m=this.queryElements(a,t)}else m=t.me?[t.me]:[];if(0===m.length&&!d)return void Se(`BEHAVIOR: executeEventHandler - No targets found for event '${n}', returning early`);if("mutation"===n&&l)return void this.setupMutationObserver(m,l,i,t);if("change"===n&&c)return void this.setupChangeObserver(c,i,t);const h=e.customEventSource;if(h&&this.registryIntegration){Se(`BEHAVIOR: executeEventHandler - Using custom event source '${h}' for event '${n}'`);const e=async e=>{const r=new Map(t.locals),a={...t,locals:r,it:e,event:e},o=this.enhanceContext(a);Se(`CUSTOM EVENT: Executing commands for event '${n}'`);try{await this.execute({type:"program",commands:i},o)}catch(e){console.error(`[HyperFixi] Error executing commands for custom event '${n}':`,e)}};try{const r=this.registryIntegration.subscribeToEventSource(h,{event:n,handler:e,target:a,selector:s},t);Se(`BEHAVIOR: Subscribed to custom event source '${h}' (id: ${r.id})`),this.cleanupRegistry.registerGlobal(()=>r.unsubscribe(),"listener",`Custom event source '${h}' subscription ${r.id}`)}catch(e){console.error(`[HyperFixi] Failed to subscribe to custom event source '${h}':`,e)}return}const f=vi.createEventHandler(this,i,t,s,o);let y,v=null;if(u){let e=f;if(u.prevent){const t=e;e=async e=>(e.preventDefault(),t(e))}if(u.stop){const t=e;e=async e=>(e.stopPropagation(),t(e))}if(u.debounce){const t=u.debounce;let n;y=r=>{n&&clearTimeout(n),n=setTimeout(()=>e(r),t)},v=()=>{n&&(clearTimeout(n),n=void 0)}}else if(u.throttle){const t=u.throttle;let n=0;y=r=>{const i=Date.now();i-n>=t&&(n=i,e(r))}}else y=e}else y=f;const g=u?.once?{once:!0}:void 0;if(d){for(const e of p)d.addEventListener(e,y,g),m.length>0?this.cleanupRegistry.registerListener(m[0],d,e,y):this.cleanupRegistry.registerGlobal(()=>d.removeEventListener(e,y),"listener",`Global ${e} listener`);v&&(m.length>0?this.cleanupRegistry.registerCustom(m[0],v,"debounce-timeout"):this.cleanupRegistry.registerGlobal(v,"timeout","debounce-timeout"))}else for(const e of m){for(const t of p)e.addEventListener(t,y,g),this.cleanupRegistry.registerListener(e,e,t,y);v&&this.cleanupRegistry.registerCustom(e,v,"debounce-timeout")}}static createEventHandler(e,t,n,r,i){return async a=>{const o=yi.get(a)??0;if(o>=100)return;if(yi.set(a,o+1),r&&a.target instanceof Element)try{if(!a.target.matches(r)&&!a.target.closest(r))return}catch{Se(`Event delegation: invalid CSS selector '${r}', skipping filter`)}const s=new Map(n.locals),l={...n,locals:s,it:a,event:a};s.has("target")||l.locals.set("target",a.target);const c=e.enhanceContext(l);if(i&&i.length>0){const e=a,t=e.detail;for(const n of i){const r=e[n]??t?.[n]??null;c.locals.set(n,r)}}for(const n of t)try{const t=hi(await e.execute(n,c));void 0!==t&&Object.assign(c,{it:t,result:t})}catch(e){if(di(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){void 0!==e.returnValue&&Object.assign(c,{it:e.returnValue,result:e.returnValue});break}}throw console.error("COMMAND FAILED:",e),e}}}setupMutationObserver(e,t,n,r){Se(`RUNTIME BASE: Setting up MutationObserver for attribute '${t}' on ${e.length} elements`);for(const i of e){const e=new MutationObserver(async e=>{for(const a of e)if("attributes"===a.type&&a.attributeName===t){ze(`MUTATION DETECTED: attribute '${t}' changed on`,i);const e={...r,me:i,it:a,locals:new Map(r.locals)},o=a.oldValue,s=i.getAttribute(t);e.locals.set("oldValue",o),e.locals.set("newValue",s);const l=this.enhanceContext(e);for(const e of n)try{await this.execute(e,l)}catch(e){if(di(e)){if(e.isHalt||e.isExit||e.isReturn)break}else console.error("Error executing mutation handler command:",e)}}});e.observe(i,{attributes:!0,attributeOldValue:!0,attributeFilter:[t]}),this.cleanupRegistry.registerObserver(i,e),Se("RUNTIME BASE: MutationObserver attached to",i,`for attribute '${t}'`)}}async setupChangeObserver(e,t,n){Se("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const r=await this.execute(e,n);let i=[];this.isElement(r)?i=[r]:Array.isArray(r)&&(i=r.filter(e=>this.isElement(e))),Se(`RUNTIME BASE: Watching ${i.length} target elements for content changes`);for(const e of i){const r=new MutationObserver(async r=>{for(const i of r)if("childList"===i.type||"characterData"===i.type){ze("CONTENT CHANGE DETECTED on",e,"mutation type:",i.type);const r={...n,me:n.me,it:i,locals:new Map(n.locals)};r.locals.set("target",e);const a=i.oldValue,o=e.textContent;null!==a&&r.locals.set("oldValue",a),r.locals.set("newValue",o);const s=this.enhanceContext(r);for(const e of t)try{await this.execute(e,s)}catch(e){if(di(e)){if(e.isHalt||e.isExit||e.isReturn)break}else console.error("Error executing change handler command:",e)}}});r.observe(e,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(e,r),Se("RUNTIME BASE: MutationObserver attached to",e,"for content changes")}}queryElements(e,t){const n=t.me,r=(n instanceof Element?n.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!r)return[];let i=e;i.startsWith("<")&&i.endsWith("/>")&&(i=i.slice(1,-2).trim());try{return Array.from(r.querySelectorAll(i))}catch{return Se(`queryElements: invalid CSS selector '${i}'`),[]}}isElement(e){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return!0;if(e&&"object"==typeof e){const t=e;return!!t.style&&!!t.classList}return!1}}function gi(e,t,n,r,i,a){function o(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var s,l=r.kind,c="getter"===l?"get":"setter"===l?"set":"value",u=!t&&e?r.static?e:e.prototype:null,p=t||(u?Object.getOwnPropertyDescriptor(u,r.name):{}),m=!1,d=n.length-1;d>=0;d--){var h={};for(var f in r)h[f]="access"===f?{}:r[f];for(var f in r.access)h.access[f]=r.access[f];h.addInitializer=function(e){if(m)throw new TypeError("Cannot add initializers after decoration has completed");a.push(o(e||null))};var y=(0,n[d])("accessor"===l?{get:p.get,set:p.set}:p[c],h);if("accessor"===l){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw new TypeError("Object expected");(s=o(y.get))&&(p.get=s),(s=o(y.set))&&(p.set=s),(s=o(y.init))&&i.unshift(s)}else(s=o(y))&&("field"===l?i.unshift(s):p[c]=s)}u&&Object.defineProperty(u,r.name,p),m=!0}function bi(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0}function ki(e,t,n){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:n?"".concat(n," ",t):t})}"function"==typeof SuppressedError&&SuppressedError;const wi=Symbol("command:name"),zi=Symbol("command:category"),xi=Symbol("command:metadata");function Ei(e){return function(t,n){const r=t;r[wi]=e.name,r[zi]=e.category,Object.defineProperty(t.prototype,"name",{value:e.name,writable:!1,enumerable:!0})}}function Si(e){return function(t,n){const r=t,i=r[zi];if(!i)throw new Error(`@meta decorator requires @command decorator to be applied first on ${t.name}`);const a={description:e.description,syntax:e.syntax,examples:e.examples,category:i,sideEffects:e.sideEffects,deprecated:e.deprecated,deprecationMessage:e.deprecationMessage,aliases:e.aliases,relatedCommands:e.relatedCommands,isBlocking:e.isBlocking??!1,hasBody:e.hasBody??!1,version:"1.0.0",compatibility:e.compatibility};r[xi]=a,Object.defineProperty(t,"metadata",{value:a,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(t.prototype,"metadata",{get:()=>a,enumerable:!0,configurable:!1})}}function Ti(e){return()=>new e}function Ci(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName&&"classList"in e}function Ai(e,t){if(Ci(e))return e;if(!e){const e=t.me;if(!e)throw new Error("No target element - provide explicit target or ensure context.me is set");return Li(e)}if("string"==typeof e){const n=e.trim();if("me"===n){if(!t.me)throw new Error('Context reference "me" is not available');return Li(t.me)}if("it"===n){if(!Ci(t.it))throw new Error('Context reference "it" is not an HTMLElement');return t.it}if("you"===n){if(!t.you)throw new Error('Context reference "you" is not available');return Li(t.you)}const r=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw new Error("DOM not available - cannot resolve element selector");const i=r.querySelector(n);if(!i)throw new Error(`Element not found with selector: ${n}`);if(!Ci(i))throw new Error(`Element found but is not an HTMLElement: ${n}`);return i}throw new Error("Invalid target type: "+typeof e)}function ji(e,t){if(Array.isArray(e))return e.filter(Ci);if(e instanceof NodeList)return Array.from(e).filter(Ci);if(Ci(e))return[e];if(!e){const e=t.me;return e&&Ci(e)?[e]:[]}if("string"==typeof e){const n=e.trim();if("me"===n)return t.me&&Ci(t.me)?[t.me]:[];if("it"===n)return Ci(t.it)?[t.it]:[];if("you"===n)return t.you&&Ci(t.you)?[t.you]:[];const r=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(r){let e=n;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=r.querySelectorAll(e);return Array.from(t).filter(Ci)}}return[]}function Li(e){if(Ci(e))return e;throw new Error("Value is not an HTMLElement")}function Pi(e,t){switch(e.toLowerCase()){case"my":case"me":if(!t.me)throw new Error('No "me" element in context');if(!Ci(t.me))throw new Error("context.me is not an HTMLElement");return t.me;case"its":case"it":if(!t.it)throw new Error('No "it" value in context');if(!Ci(t.it))throw new Error("context.it is not an HTMLElement");return t.it;case"your":case"you":if(!t.you)throw new Error('No "you" element in context');if(!Ci(t.you))throw new Error("context.you is not an HTMLElement");return t.you;default:throw new Error(`Unknown possessive: ${e}`)}}const Ii=["on","from","to","in","with","at"];async function Ni(e,t,n,r,i={},a){let o=e;if(i.filterPrepositions&&e&&(o=e.filter(e=>{const t=e;return"identifier"!==t?.type||"string"!=typeof t.name||!Ii.includes(t.name.toLowerCase())})),(!o||0===o.length)&&i.fallbackModifierKey&&a){const e=a[i.fallbackModifierKey];e&&(o=[e])}if(!o||0===o.length){if(!n.me)throw new Error(`${r} command: no target specified and context.me is null`);if(!Ci(n.me))throw new Error(`${r} command: context.me must be an HTMLElement`);return[n.me]}const s=[];for(const e of o){const i=await t.evaluate(e,n);if(""!==i&&("string"!=typeof i||""!==i.trim()))if(Ci(i))s.push(i);else if(i instanceof NodeList){const e=Array.from(i).filter(Ci);s.push(...e)}else if(Array.isArray(i)){const e=i.filter(Ci);s.push(...e)}else{if("string"!=typeof i)throw new Error(`Invalid ${r} target: expected HTMLElement or CSS selector, got ${typeof i}`);try{let e=i;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=n.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!t)throw new Error("DOM not available - cannot resolve element selector");const r=t.querySelectorAll(e),a=Array.from(r).filter(Ci);s.push(...a)}catch(e){throw new Error(`Invalid CSS selector: "${i}" - ${e instanceof Error?e.message:String(e)}`)}}}if(0===s.length){if(!n.me)throw new Error(`${r} command: no target specified and context.me is null`);if(!Ci(n.me))throw new Error(`${r} command: context.me must be an HTMLElement`);return[n.me]}return s}class Oi{async parseInput(e,t,n){const{targets:r}=await async function(e,t,n,r){return{targets:await Ni(e.args,t,n,r)}}(e,t,n,this.mode);return{targets:r,mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&(!!t.targets.every(e=>Ci(e))&&(("show"===t.mode||"hide"===t.mode)&&("show"!==t.mode||"string"==typeof t.defaultDisplay)))}showElement(e,t="block"){const n=e.dataset.originalDisplay;void 0!==n?(e.style.display=n||t,delete e.dataset.originalDisplay):"none"===e.style.display&&(e.style.display=t),e.classList.add("show")}hideElement(e){if(!e.dataset.originalDisplay){const t=e.style.display;e.dataset.originalDisplay="none"===t?"":t}e.style.display="none",e.classList.remove("show")}}let Ri=(()=>{let e,t,n=[Si({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),Ei({name:"hide",category:"dom"})],r=[],i=Oi;return t=class extends i{constructor(){super(...arguments),this.mode="hide"}async execute(e,t){for(const t of e.targets)this.hideElement(t)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>Ci(e))}},ki(t,"HideCommand"),(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:a},null,r),t=e.value,a&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a}),bi(t,r)})(),t})();const Mi=Ti(Ri);let Wi=(()=>{let e,t,n=[Si({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),Ei({name:"show",category:"dom"})],r=[],i=Oi;return t=class extends i{constructor(){super(...arguments),this.mode="show"}async execute(e,t){const n=e.defaultDisplay||"block";for(const t of e.targets)this.showElement(t,n)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&(!!t.targets.every(e=>Ci(e))&&"string"==typeof t.defaultDisplay)}},ki(t,"ShowCommand"),(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:a},null,r),t=e.value,a&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a}),bi(t,r)})(),t})();const $i=Ti(Wi);function Hi(e){const t=e.trim();return!(!t.startsWith("[@")||!t.endsWith("]"))||!!t.startsWith("@")}function qi(e){const t=e.trim();if(t.startsWith("[@")&&t.endsWith("]")){const e=t.slice(2,-1),n=e.indexOf("=");if(-1===n)return{name:e.trim()};const r=e.slice(0,n).trim();let i=e.slice(n+1).trim();return(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),{name:r,value:i}}if(t.startsWith("@"))return{name:t.substring(1).trim()};throw new Error(`Invalid attribute syntax: ${e}`)}function Di(e,t){for(const n of e)t(n);return e}function _i(e,t,n){for(const r of e)for(const e of t)n(r,e);return e}function Vi(e,t,n){const r=e.hasAttribute(t);void 0!==n?r&&e.getAttribute(t)===n?e.removeAttribute(t):e.setAttribute(t,n):r?e.removeAttribute(t):e.setAttribute(t,"")}function Bi(e){if(!e)return[];if("string"==typeof e)return e.trim().split(/[\s,]+/).map(e=>{const t=e.trim();return t.startsWith(".")?t.substring(1):t}).filter(e=>e.length>0&&Ui(e));if(Array.isArray(e))return e.map(e=>{const t=String(e).trim();return t.startsWith(".")?t.substring(1):t}).filter(e=>e.length>0&&Ui(e));const t=String(e).trim(),n=t.startsWith(".")?t.substring(1):t;return n.length>0&&Ui(n)?[n]:[]}function Fi(e){const t=e.trim();return/^\{[^}]+\}$/.test(t)}function Ui(e){if(!e||0===e.trim().length)return!1;const t=e.trim();if(Fi(t))return!0;return/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t)}function Ki(e,t){return e.map(e=>{if(Fi(e)){const n=function(e){const t=e.trim(),n=t.match(/^\{(.+)\}$/);return n?n[1].trim():t}(e),r=t.locals.get(n)??t.globals.get(n);return null!=r?String(r):(console.warn(`Dynamic class variable '${n}' not found in context`),"")}return e}).filter(e=>e.length>0)}function Gi(e){return"string"==typeof e&&e.trim().startsWith("*")}function Qi(e,t,n){e.style.setProperty(t,n)}const Ji=["dialog","details","summary","select"];function Yi(e){if(!e||"object"!=typeof e)return null;const t=e;return"string"==typeof t.selector?t.selector:"string"==typeof t.value?t.value:"string"==typeof t.name?t.name:null}function Zi(e){const t=e;return"attributeAccess"===t.type?`@${t.attributeName}`:Yi(e)}function Xi(e){if(!e||"object"!=typeof e)return!1;const t=e;if("identifier"!==t.type)return!1;const n=t.name;return"string"==typeof n&&function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return Ji.includes(t)}(n)}async function ea(e,t,n){return function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"classSelector"!==t)return!1;const n=Yi(e);return"string"==typeof n&&n.startsWith(".")}(e)||function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"cssProperty"!==t)return!1;const n=Yi(e);return"string"==typeof n&&n.startsWith("*")}(e)?{value:Yi(e),extractedFromNode:!0}:function(e){if(!e||"object"!=typeof e)return!1;const t=e;if("attributeAccess"===t.type)return!0;if("selector"===t.type||"cssSelector"===t.type){const t=Yi(e);return"string"==typeof t&&t.startsWith("@")}return!1}(e)?{value:Zi(e),extractedFromNode:!0}:{value:await t.evaluate(e,n),extractedFromNode:!1}}class ta{async resolveTargets(e,t,n,r){return Ni(e,t,n,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},r)}async evaluateFirst(e,t,n){return ea(e,t,n)}parseClassNames(e){return Bi(e)}isAttribute(e){return Hi(e.trim())}isCSSProperty(e){return Gi(e.trim())}validateTargets(e){return Array.isArray(e)&&function(e){return Array.isArray(e)&&e.length>0&&e.every(e=>Ci(e))}(e)}validateType(e,t){return function(e,t){return"string"==typeof e&&t.includes(e)}(e,t)}validateStringArray(e,t=1){return Array.isArray(e)&&function(e,t=1){return Array.isArray(e)&&e.length>=t&&e.every(e=>"string"==typeof e&&e.length>0)}(e,t)}}let na=(()=>{let e,t,n=[Si({description:"Add CSS classes, attributes, or styles to elements",syntax:"add <classes|@attr|{styles}> [to <target>]",examples:["add .active to me",'add "active selected" to <button/>',"add .highlighted to #modal",'add [@data-test="value"] to #element'],sideEffects:["dom-mutation"]}),Ei({name:"add",category:"dom"})],r=[],i=ta;return t=class extends i{constructor(){super(...arguments),this.mode="add",this.preposition="to"}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw new Error("add command requires an argument");const{value:r}=await this.evaluateFirst(e.args[0],t,n);if("object"==typeof r&&null!==r&&!Array.isArray(r)){return{type:"styles",styles:r,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}if("string"==typeof r){const i=r.trim();if(this.isAttribute(i)){const{name:r,value:a}=function(e){const t=qi(e);return{name:t.name,value:t.value??""}}(i);return{type:"attribute",name:r,value:a,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}if(this.isCSSProperty(i)){const r=i.substring(1).trim();if(e.args.length<2)throw new Error("add *property requires a value argument");const a=await t.evaluate(e.args[1],n);return{type:"styles",styles:{[r]:String(a)},targets:await this.resolveTargets(e.args.slice(2),t,n,e.modifiers)}}}const i=this.parseClassNames(r);if(0===i.length)throw new Error("add command: no valid class names found");return{type:"classes",classes:i,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}async execute(e,t){switch(e.type){case"classes":{const n=Ki(e.classes,t);n.length>0&&_i(e.targets,n,(e,t)=>{e.classList.contains(t)||e.classList.add(t)});break}case"attribute":!function(e,t,n){Di(e,e=>{e.setAttribute(t,n)})}(e.targets,e.name,e.value);break;case"styles":!function(e,t){_i(e,Object.entries(t),(e,[t,n])=>{e.style.setProperty(t,n)})}(e.targets,e.styles)}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){const t=e;if(!this.validateStringArray(t.classes,1))return!1}else if("attribute"===t.type){const t=e;if("string"!=typeof t.name||0===t.name.length)return!1;if("string"!=typeof t.value)return!1}else if("styles"===t.type){const t=e;if("object"!=typeof t.styles||null===t.styles)return!1;if(Array.isArray(t.styles))return!1;const n=t.styles;if(0===Object.keys(n).length)return!1;if(!Object.values(n).every(e=>"string"==typeof e))return!1}return!0}},ki(t,"AddCommand"),(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:a},null,r),t=e.value,a&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a}),bi(t,r)})(),t})();const ra=Ti(na);function ia(e){return!!e.parentNode&&(e.remove(),!0)}let aa=(()=>{let e,t,n=[Si({description:"Remove CSS classes, attributes, styles, or elements from the DOM",syntax:"remove <classes|@attr|*prop|element> [from <target>]",examples:["remove .active from me",'remove "active selected" from <button/>',"remove .highlighted from #modal","remove me","remove closest .item"],sideEffects:["dom-mutation"]}),Ei({name:"remove",category:"dom"})],r=[],i=ta;return t=class extends i{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw new Error("remove command requires an argument");const{value:r}=await this.evaluateFirst(e.args[0],t,n);if(Ci(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&Ci(r[0]))return{type:"element",targets:r.filter(e=>Ci(e))};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i)){return{type:"attribute",name:qi(i).name,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}if(this.isCSSProperty(i)){return{type:"styles",properties:[i.substring(1).trim()],targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}}const i=this.parseClassNames(r);if(0===i.length)throw new Error("remove command: no valid class names found");return{type:"classes",classes:i,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}execute(e,t){switch(e.type){case"classes":{const n=Ki(e.classes,t);n.length>0&&_i(e.targets,n,(e,t)=>{e.classList.remove(t)});break}case"attribute":!function(e,t){Di(e,e=>{e.removeAttribute(t)})}(e.targets,e.name);break;case"styles":!function(e,t){_i(e,t,(e,t)=>{e.style.removeProperty(t)})}(e.targets,e.properties);break;case"element":for(const t of e.targets)ia(t)}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles","element"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){const t=e;if(!this.validateStringArray(t.classes,1))return!1}else if("attribute"===t.type){const t=e;if("string"!=typeof t.name||0===t.name.length)return!1}else if("styles"===t.type){const t=e;if(!this.validateStringArray(t.properties,1))return!1}return!0}},ki(t,"RemoveCommand"),(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:a},null,r),t=e.value,a&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a}),bi(t,r)})(),t})();const oa=Ti(aa);function sa(e){const t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!t)return null;const n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();return"ms"===r||"millisecond"===r||"milliseconds"===r?{number:n,milliseconds:Math.floor(n)}:"s"===r||"sec"===r||"second"===r||"seconds"===r?{number:n,milliseconds:Math.floor(1e3*n)}:null}function la(e,t=300){if("number"==typeof e)return Math.max(0,Math.floor(e));if("string"==typeof e){const n=sa(e);return n?n.milliseconds:t}return t}function ca(e){if("number"==typeof e){if(e<0)throw new Error("Duration must be >= 0");return Math.floor(e)}if("string"==typeof e){const t=sa(e);if(!t)throw new Error(`Invalid duration format: "${e}"`);return t.milliseconds}throw new Error("Invalid duration type: "+typeof e)}function ua(e){return e&&"none"!==e?e.split(",").map(e=>{const t=parseFloat(e.trim());return isNaN(t)?0:e.includes("s")&&!e.includes("ms")?1e3*t:t}):[0]}function pa(e,t){let n=0;for(let r=0;r<e.length;r++){const i=(e[r]||0)+(t[r]||0);n=Math.max(n,i)}return n}function ma(e){if(0===e.length)return[];return"SUMMARY"===e[0].tagName?e.map(e=>e.closest("details")).filter(e=>null!==e):e}function da(e,t,n){return()=>{"class"===t?e.classList.toggle(n):"attribute"===t&&Vi(e,n)}}function ha(e,t,n,r){const i=da(e,t,n),a=setTimeout(i,r);return()=>{clearTimeout(a)}}function fa(e,t,n,r){const i=da(e,t,n),a=()=>{i(),e.removeEventListener(r,a)};return e.addEventListener(r,a,{once:!0}),()=>{e.removeEventListener(r,a)}}function ya(e,t,n){if(t.startsWith("@")){const r=t.substring(1);return void(!1===n?e.removeAttribute(r):!0===n?e.setAttribute(r,""):e.setAttribute(r,String(n)))}const r=String(n);switch(t){case"textContent":return void(e.textContent=r);case"innerHTML":return void(e.innerHTML=r);case"innerText":return void(e.innerText=r);case"id":return void(e.id=r);case"className":return void(e.className=r);case"value":return void("value"in e&&(e.value=r));case"checked":return void("checked"in e&&(e.checked=Boolean(n)))}if(t.includes(".")){const r=t.split(".");let i=e;for(let e=0;e<r.length-1;e++)if(i=i[r[e]],null==i)return;return void(i[r[r.length-1]]=n)}if(t.includes("-")||t in e.style)e.style.setProperty(t,r);else try{e[t]=n}catch(e){if(!(e instanceof TypeError&&(e.message.includes("only a getter")||e.message.includes("read only"))))throw new Error(`Cannot set property '${t}': ${e instanceof Error?e.message:"Unknown error"}`)}}function va(e){return null==e||""===e}const ga=/^the\s+(.+?)\s+of\s+(.+)$/i,ba=new Set(["disabled","checked","hidden","readOnly","readonly","required","multiple","selected","autofocus","autoplay","controls","loop","muted","open","reversed","async","defer","noValidate","novalidate","formNoValidate","formnovalidate","draggable","spellcheck","contentEditable"]);function ka(e){return"string"==typeof e&&ga.test(e)}function wa(e,t){const n=e.match(ga);if(!n)return null;try{return{element:Ai(n[2].trim(),t),property:n[1].trim()}}catch{return null}}async function za(e,t,n){if(function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"propertyOfExpression"===t.type&&"object"==typeof t.property&&null!==t.property}(e))return async function(e,t,n){const r=e.property?.name;if(!r)return null;let i=await t.evaluate(e.target,n);return Array.isArray(i)&&(i=i[0]),Ci(i)?{element:i,property:r}:null}(e,t,n);if(function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"propertyAccess"===t.type&&("string"==typeof t.property||"object"==typeof t.property&&null!==t.property&&"string"==typeof t.property.name)}(e))return async function(e,t,n){const r="string"==typeof e.property?e.property:e.property?.name;if(!r)return null;let i=await t.evaluate(e.object,n);return Array.isArray(i)&&(i=i[0]),Ci(i)?{element:i,property:r}:null}(e,t,n);const r=e;if("possessiveExpression"===r?.type||"memberExpression"===r?.type){const e=r.object,i=r.property;let a=await t.evaluate(e,n);if(Array.isArray(a)&&(a=a[0]),!Ci(a))return null;const o=i?.name||i?.value;return o&&(o.startsWith("@")||o.startsWith("*"))?{element:a,property:o}:null}return null}function xa(e){const{element:t,property:n}=e;if(n.startsWith("*")){return function(e,t){return window.getComputedStyle(e).getPropertyValue(t)}(t,n.substring(1))}return nn(t,n)}function Ea(e,t){const{element:n,property:r}=e;if(r.startsWith("*")){return void Qi(n,r.substring(1),String(t))}ya(n,r,t)}async function Sa(e,t,n){let r,i;if(e?.for){const i=await t.evaluate(e.for,n);r="number"==typeof i?i:"string"==typeof i?la(i):void 0}if(e?.until){const r=await t.evaluate(e.until,n);"string"==typeof r&&(i=r)}return{duration:r,untilEvent:i}}function Ta(e,t){const n=t?.name,r=Xi(t);if(Ci(e)||Array.isArray(e)&&e.every(e=>Ci(e)))return{type:"element",expression:""};if(r&&n)return{type:"element",expression:n};if("string"==typeof e){const t=e.trim();return t.startsWith("@")||t.startsWith("[@")?{type:"attribute",expression:t}:t.startsWith("*")?{type:"css-property",expression:t}:t.startsWith(".")?{type:"class",expression:t}:t.startsWith("#")||function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return Ji.some(e=>t.includes(e))}(t)?{type:"element",expression:t}:{type:"class",expression:t}}return{type:"class",expression:""}}let Ca=(()=>{let e,t,n=[Si({description:"Toggle classes, attributes, or interactive elements",syntax:["toggle <class> [on <target>]","toggle @attr","toggle <element> [as modal]","toggle <expr> for <duration>"],examples:["toggle .active on me","toggle @disabled","toggle #myDialog as modal","toggle .loading for 2s"],sideEffects:["dom-mutation"]}),Ei({name:"toggle",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw new Error("toggle command requires an argument");const r=e.args[0],i=r?.name;if("between"===i&&e.args.length>=4){const{duration:r,untilEvent:i}=await Sa(e.modifiers,t,n),a=await t.evaluate(e.args[1],n),o=await t.evaluate(e.args[3],n),s=[];for(let t=4;t<e.args.length;t++){const n=e.args[t]?.name;"on"!==n&&"from"!==n&&s.push(e.args[t])}const l={filterPrepositions:!0,fallbackModifierKey:"on"},c=await Ni(s,t,n,"toggle",l,e.modifiers);return{type:"classes-between",classA:String(a).replace(/^\./,""),classB:String(o).replace(/^\./,""),targets:c,duration:r,untilEvent:i}}const a=await za(r,t,n);if(a)return{type:"property",target:a};const{duration:o,untilEvent:s}=await Sa(e.modifiers,t,n),{value:l}=await ea(r,t,n);if(ka(l)){const e=wa(l,n);if(e)return{type:"property",target:e}}const{type:c,expression:u}=Ta(l,r),p={filterPrepositions:!0,fallbackModifierKey:"on"};switch(c){case"attribute":{const{name:r,value:i}=qi(u);return{type:"attribute",name:r,value:i,targets:await Ni(e.args.slice(1),t,n,"toggle",p,e.modifiers),duration:o,untilEvent:s}}case"css-property":{const r=function(e){const t=function(e){const t=e.trim();if(!t.startsWith("*"))return null;const n=t.substring(1).trim();return n?{property:n}:null}(e);if(!t)return null;const n=t.property.toLowerCase();return["display","visibility","opacity"].includes(n)?n:null}(u);if(!r)throw new Error(`Invalid CSS property: ${u}`);return{type:"css-property",property:r,targets:await Ni(e.args.slice(1),t,n,"toggle",p,e.modifiers)}}case"element":{let i;if(Ci(l))i=[l];else if(Array.isArray(l)&&l.every(e=>Ci(e)))i=l;else if(u){const e=document.querySelectorAll(u);i=Array.from(e).filter(e=>Ci(e))}else i=await Ni([r],t,n,"toggle",p,e.modifiers);const a=function(e){if(0===e.length)return null;const t=e[0].tagName;if(!e.every(e=>e.tagName===t))return null;switch(t){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return e.map(e=>e.closest("details")).filter(e=>null!==e).length>0?"details":null;default:return null}}(i);if("dialog"===a){const r=await async function(e,t,n,r){if(t?.as){const e=await n.evaluate(t.as,r);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}if(e.length>=2){const t=await n.evaluate(e[1],r);if("string"==typeof t){const i=t.toLowerCase();if("modal"===i||"as modal"===i)return"modal";if("as"===i&&e.length>=3){const t=await n.evaluate(e[2],r);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}}}return"non-modal"}(e.args,e.modifiers,t,n);return{type:"dialog",mode:r,targets:i}}if("details"===a)return{type:"details",targets:ma(i)};if("select"===a)return{type:"select",targets:i};return{type:"classes",classes:Bi(u),targets:i,duration:o,untilEvent:s}}default:{const r=Bi(u||l);if(!r.length)throw new Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await Ni(e.args.slice(1),t,n,"toggle",p,e.modifiers),duration:o,untilEvent:s}}}}async execute(e,t){switch(e.type){case"classes":{const n=Ki(e.classes,t);if(0===n.length)return[...e.targets];if(_i(e.targets,n,(e,t)=>{e.classList.toggle(t)}),(e.duration||e.untilEvent)&&n.length)for(const t of e.targets)e.duration&&ha(t,"class",n[0],e.duration),e.untilEvent&&fa(t,"class",n[0],e.untilEvent);return[...e.targets]}case"attribute":if(function(e,t,n){Di(e,e=>{Vi(e,t,n)})}(e.targets,e.name,e.value),e.duration||e.untilEvent)for(const t of e.targets)e.duration&&ha(t,"attribute",e.name,e.duration),e.untilEvent&&fa(t,"attribute",e.name,e.untilEvent);return[...e.targets];case"css-property":return Di(e.targets,t=>function(e,t){const n=window.getComputedStyle(e);switch(t){case"display":if("none"===n.display){const t=e.dataset.previousDisplay||"block";e.style.display=t,delete e.dataset.previousDisplay}else e.dataset.previousDisplay=n.display,e.style.display="none";break;case"visibility":e.style.visibility="hidden"===n.visibility?"visible":"hidden";break;case"opacity":e.style.opacity=0===parseFloat(n.opacity)?"1":"0"}}(t,e.property));case"property":return function(e){const t=xa(e),n=e.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof t||ba.has(r)||ba.has(r.toLowerCase())){const n=!t;return Ea(e,n),n}if("number"==typeof t){const n=0===t?1:0;return Ea(e,n),n}if("string"==typeof t){const r=`__ht_${n}`,i=e.element[r];return""===t&&void 0!==i?(Ea(e,i),i):(e.element[r]=t,Ea(e,""),"")}const i=!t;Ea(e,i)}(e.target),[e.target.element];case"dialog":return Di(e.targets,t=>{return n=t,r=e.mode,void(n.open?n.close():"modal"===r?n.showModal():n.show());var n,r});case"details":return Di(e.targets,e=>{var t;(t=e).open=!t.open});case"select":return Di(e.targets,e=>function(e){if(document.activeElement===e)e.blur();else{if(e.focus(),"showPicker"in e&&"function"==typeof e.showPicker)try{return void e.showPicker()}catch{}const t=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0});e.dispatchEvent(t)}}(e));case"classes-between":for(const t of e.targets){const n=t.classList.contains(e.classA),r=t.classList.contains(e.classB);n?(t.classList.remove(e.classA),t.classList.add(e.classB)):r?(t.classList.remove(e.classB),t.classList.add(e.classA)):t.classList.add(e.classA)}if(e.duration||e.untilEvent)for(const t of e.targets)e.duration&&ha(t,"class",e.classA,e.duration),e.untilEvent&&fa(t,"class",e.classA,e.untilEvent);return[...e.targets]}}},ki(t,"ToggleCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})();const Aa=Ti(Ca);let ja=(()=>{let e,t,n=[Si({description:"Insert content into elements or properties",syntax:["put <value> into <target>","put <value> before <target>","put <value> after <target>"],examples:['put "Hello World" into me',"put <div>Content</div> before #target","put value into #elem's innerHTML"],sideEffects:["dom-mutation"]}),Ei({name:"put",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw new Error("put requires arguments");const r=e=>e?.type||"unknown",i=["into","before","after","at","at start of","at end of"];let a=-1,o=null;for(let t=0;t<e.args.length;t++){const n=e.args[t],s=r(n),l="literal"===s?n.value:n.name;if(("literal"===s||"identifier"===s)&&i.includes(l)){a=t,o=l;break}}let s=null,l=null;if(-1===a)if(e.modifiers.into||e.modifiers.before||e.modifiers.after){const t=e.modifiers.into?"into":e.modifiers.before?"before":"after";s=e.args[0],o=t,l=e.modifiers[t]}else if(e.args.length>=3)s=e.args[0],o=e.args[1]?.value||e.args[1]?.name||null,l=e.args[2];else{if(!(e.args.length>=2))throw new Error("put requires content and position");s=e.args[0],o=e.args[1]?.value||e.args[1]?.name||"into"}else s=e.args.slice(0,a)[0]||null,l=e.args.slice(a+1)[0]||null;if(!s)throw new Error("put requires content");if(!o)throw new Error("put requires position keyword");const c=await t.evaluate(s,n),u=this.mapPosition(o);let p,m,d=null;if(l){const e=r(l),i=await za(l,t,n);if(i)return{value:c,targets:[i.element],position:"replace",memberPath:i.property};if("memberExpression"===e){const e=l.object,r=l.property;if("selector"===e?.type?d=e.value:"identifier"===e?.type&&(d=e.name),d&&r?.name)p=r.name;else{const e=await t.evaluate(l,n);"string"==typeof e&&(d=e)}}else if("identifier"===e&&"me"===l.name)d=null;else if("selector"===e||"cssSelector"===e)d=l.value||l.selector;else if("literal"===e){const e=l.value;if("string"==typeof e&&ka(e)){const t=wa(e,n);if(t)return{value:c,targets:[t.element],position:"replace",memberPath:t.property}}"string"==typeof e&&this.looksLikeCss(e)?d=e:m=String(e)}else if("identifier"===e){const e=l.name;if(this.looksLikeCss(e))d=e;else{const r=await t.evaluate(l,n),i=this.resolveEvaluatedAsElements(r);if(i)return{value:c,targets:i,position:u,memberPath:p};m=e}}else{const e=await t.evaluate(l,n),r=this.resolveEvaluatedAsElements(e);if(r)return{value:c,targets:r,position:u,memberPath:p};"string"==typeof e&&(this.looksLikeCss(e)?d=e:m=e)}}if(m)return{value:c,targets:[],position:u,memberPath:p,variableName:m};return{value:c,targets:await this.resolveTargets(d,n),position:u,memberPath:p}}async execute(e,t){const{value:n,targets:r,position:i,memberPath:a,variableName:o}=e;if(o)return t.locals&&t.locals.set(o,n),t[o]=n,void Object.assign(t,{it:n});if(a)for(const e of r)this.setProperty(e,a,n);else for(const e of r){const t=this.parseValue(n);this.insertContent(e,t,i)}return r}mapPosition(e){switch(e){case"into":return"replace";case"before":return"beforebegin";case"after":return"afterend";case"at start of":return"afterbegin";case"at end of":return"beforeend";default:throw new Error(`Invalid position: ${e}`)}}async resolveTargets(e,t){if(!e||"me"===e){if(!t.me||!Ci(t.me))throw new Error("put: no target and context.me is null");return[t.me]}const n=Array.from(document.querySelectorAll(e)).filter(e=>Ci(e));if(!n.length)throw new Error(`No elements: "${e}"`);return n}parseValue(e){return Ci(e)?e:null==e?"":String(e)}insertContent(e,t,n){if("replace"!==n)if(Ci(t)){const r=t;switch(n){case"beforebegin":e.parentElement?.insertBefore(r,e);break;case"afterbegin":e.insertBefore(r,e.firstChild);break;case"beforeend":e.appendChild(r);break;case"afterend":e.parentElement?.insertBefore(r,e.nextSibling)}}else{t.includes("<")&&t.includes(">")?e.insertAdjacentHTML(n,t):e.insertAdjacentText(n,t)}else if(Ci(t))e.innerHTML="",e.appendChild(t);else{t.includes("<")&&t.includes(">")?e.innerHTML=t:e.textContent=t}}resolveEvaluatedAsElements(e){if(Ci(e))return[e];if(Array.isArray(e)){const t=e.filter(Ci);return t.length>0?t:null}if("undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e).filter(Ci);return t.length>0?t:null}return null}looksLikeCss(e){if(!e)return!1;if(/^[#.\[]/.test(e))return!0;if(/[>+~\s]/.test(e)&&e.length>1)return!0;return["div","span","p","a","button","input","form","ul","li","ol","table","tr","td","th","img","h1","h2","h3","h4","h5","h6","section","article","header","footer","nav","main","aside","dialog","label","select","option","textarea"].includes(e.toLowerCase())}setProperty(e,t,n){const r=t.split(".");let i=e;for(let e=0;e<r.length-1;e++){if(!i[r[e]])throw new Error(`Property path "${t}" does not exist`);i=i[r[e]]}i[r[r.length-1]]=n}},ki(t,"PutCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})();const La=Ti(ja);function Pa(e){if(null==e)return 0;if("number"==typeof e)return isFinite(e)?e:0;if("string"==typeof e){return parseFloat(e)}if("boolean"==typeof e)return e?1:0;if(Array.isArray(e))return e.length;if("object"==typeof e){if("length"in e&&"number"==typeof e.length)return e.length;if("function"==typeof e.valueOf){const t=e.valueOf();if("number"==typeof t)return t}return NaN}return 0}function Ia(e,t,n){return"global"===n&&t.globals&&t.globals.has(e)?t.globals.get(e):"global"!==n&&t.locals&&t.locals.has(e)?t.locals.get(e):t.globals&&t.globals.has(e)?t.globals.get(e):t.variables&&t.variables.has(e)?t.variables.get(e):"global"===n&&t.locals&&t.locals.has(e)?t.locals.get(e):"undefined"!=typeof window&&e in window?window[e]:"undefined"!=typeof globalThis&&e in globalThis?globalThis[e]:void 0}function Na(e,t,n,r){if("global"===r)return n.globals.set(e,t),void("undefined"!=typeof window&&(window[e]=t));if(n.locals&&n.locals.has(e))n.locals.set(e,t);else{if(n.globals&&n.globals.has(e))return n.globals.set(e,t),void("undefined"!=typeof window&&e in window&&(window[e]=t));if(!n.variables||!n.variables.has(e))return"undefined"!=typeof window&&e in window?(window[e]=t,void n.globals.set(e,t)):void n.locals.set(e,t);n.variables.set(e,t)}}function Oa(e,t){return"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:Ia(e,t)}function Ra(e,t,n,r){if("number"==typeof e)return e;if(Ci(e)){const n=e;if(t){if(t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)){return Pa(n.getAttribute(t))}return Pa(n[t])}return Pa(n.value||n.textContent)}if("string"==typeof e){if("global"===n){return Pa(Ia(e,r,"global"))}if(e.includes("."))return function(e,t){const n=e.split("."),r=n[0],i=n[1],a=Oa(r,t);return a?Pa(a[i]):0}(e,r);if("me"===e&&r.me)return Pa(r.me.value||0);if("it"===e)return Pa(r.it||0);if("you"===e&&r.you)return Pa(r.you.value||0);return Pa(Ia(e,r))}return Pa(e)}function Ma(e,t,n,r,i){if(Ci(e)){const n=e;return void(t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?n.setAttribute(t,String(r)):n[t]=r:"value"in n&&void 0!==n.value?n.value=String(r):n.textContent=String(r))}if("string"==typeof e){if("global"===n)return void Na(e,r,i,"global");if(e.includes("."))return void function(e,t,n){const r=e.split("."),i=r[0],a=r[1],o=Oa(i,n);o&&(o[a]=t)}(e,r,i);if("me"===e&&i.me)return void(i.me.value=r);if("it"===e)return void Object.assign(i,{it:r});if("you"===e&&i.you)return void(i.you.value=r);Na(e,r,i)}}const Wa=Ti((()=>{let e,t,n=[Si({description:"Create DOM elements or class instances",syntax:["make a <tag#id.class1.class2/>","make a <ClassName> from <args> called <identifier>"],examples:["make an <a.navlink/> called linkElement",'make a URL from "/path/", "https://origin.example.com"'],sideEffects:["dom-creation","data-mutation"]}),Ei({name:"make",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){const r=e.args.length>0?await t.evaluate(e.args[0],n):void 0;if(!r)throw new Error("Make command requires class name or DOM element expression");const i=void 0!==e.modifiers.an?"an":"a",a=await async function(e,t,n){if(!e)return[];if("arrayLiteral"===e.type&&Array.isArray(e.args)){const r=[];for(const i of e.args)r.push(await t.evaluate(i,n));return r}const r=await t.evaluate(e,n);return Array.isArray(r)?r:[r]}(e.modifiers.from,t,n),o=await async function(e,t,n){if(!e)return;if("symbol"===e.type&&"string"==typeof e.name)return e.name;const r=await t.evaluate(e,n);return"string"==typeof r?r:String(r)}(e.modifiers.called,t,n);return{article:i,expression:r,constructorArgs:a,variableName:o}}async execute(e,t){const{expression:n,constructorArgs:r=[],variableName:i}=e,a="string"==typeof n&&n.startsWith("<")&&n.endsWith("/>")?function(e){const t=e.slice(1,-2);let n="div",r=t;const i=t.match(/^([a-zA-Z][a-zA-Z0-9]*)/);i&&(n=i[1],r=t.slice(i[0].length));const a=document.createElement(n),o=r.split(/(?=[.#])/);for(const e of o)if(e.startsWith("#")){const t=e.slice(1);t&&(a.id=t)}else if(e.startsWith(".")){const t=e.slice(1);t&&a.classList.add(t)}return a}(n):function(e,t,n){if(Ci(e))return e;const r=String(e);let i;if("undefined"!=typeof window&&(i=window[r]),i||"undefined"==typeof global||(i=global[r]),!i&&n.variables?.has(r)&&(i=n.variables.get(r)),!i||"function"!=typeof i)throw new Error(`Constructor '${r}' not found or is not a function`);return 0===t.length?new i:new i(...t)}(n,r,t);return Object.assign(t,{it:a}),i&&Na(i,a,t),a}},ki(t,"MakeCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})());var $a="moveBefore"in Element.prototype,Ha=[0,1,0,0,0,0,0,0,0,1,0,1,0],qa=0,Da=1,_a=2,Va=new Set,Ba=new Set,Fa=new Set,Ua=new Set,Ka=new Set;function Ga(e){for(const t of e.querySelectorAll("input"))(t.name&&t.value!==t.defaultValue||t.checked!==t.defaultChecked)&&t.setAttribute("morphlex-dirty","");for(const t of e.querySelectorAll("option"))t.value&&t.selected!==t.defaultSelected&&t.setAttribute("morphlex-dirty","");for(const t of e.querySelectorAll("textarea"))t.value!==t.defaultValue&&t.setAttribute("morphlex-dirty","")}function Qa(e){const t=document.createElement("template");return t.innerHTML=e.trim(),t.content}function Ja(e,t,n){if(t!==n){if(t.parentNode===e){if(t.nextSibling===n)return;if($a)return void e.moveBefore(t,n)}e.insertBefore(t,n)}}class Ya{#e=new WeakMap;#t=new WeakMap;#n;constructor(e={}){this.#n=e}morph(e,t){eo(e)&&this.#r(e),t instanceof NodeList?(this.#i(t),this.#a(e,t)):eo(t)&&(this.#o(t),this.#s(e,t))}#a(e,t){const n=t.length;if(0===n)this.#l(e);else if(1===n)this.#s(e,t[0]);else if(n>1){const n=[...t];this.#s(e,n.shift());const r=e.nextSibling,i=e.parentNode||document;for(let e=0;e<n.length;e++){const t=n[e];(this.#n.beforeNodeAdded?.(i,t,r)??1)&&(i.insertBefore(t,r),this.#n.afterNodeAdded?.(t))}}}#s(e,t){e!==t&&(e.isEqualNode(t)||(1===e.nodeType&&1===t.nodeType?e.localName===t.localName?this.#c(e,t):this.#u(e,t):this.#p(e,t)))}#c(e,t){(this.#n.beforeNodeVisited?.(e,t)??1)&&((e.hasAttributes()||t.hasAttributes())&&this.#m(e,t),"textarea"===e.localName&&"textarea"===t.localName?this.#d(e,t):(e.hasChildNodes()||t.hasChildNodes())&&this.visitChildNodes(e,t),this.#n.afterNodeVisited?.(e,t))}#u(e,t){(this.#n.beforeNodeVisited?.(e,t)??1)&&(this.#h(e,t),this.#n.afterNodeVisited?.(e,t))}#p(e,t){(this.#n.beforeNodeVisited?.(e,t)??1)&&(e.nodeType===t.nodeType&&null!==e.nodeValue&&null!==t.nodeValue?e.nodeValue=t.nodeValue:this.#h(e,t),this.#n.afterNodeVisited?.(e,t))}#m(e,t){e.hasAttribute("morphlex-dirty")&&e.removeAttribute("morphlex-dirty");for(const{name:n,value:r}of t.attributes){"value"===n&&Za(e)&&e.value!==r&&(this.#n.preserveChanges&&e.value!==e.defaultValue||(e.value=r)),"selected"===n&&Xa(e)&&!e.selected&&(this.#n.preserveChanges&&e.selected!==e.defaultSelected||(e.selected=!0)),"checked"===n&&Za(e)&&!e.checked&&(this.#n.preserveChanges&&e.checked!==e.defaultChecked||(e.checked=!0));const t=e.getAttribute(n);t!==r&&(this.#n.beforeAttributeUpdated?.(e,n,r)??1)&&(e.setAttribute(n,r),this.#n.afterAttributeUpdated?.(e,n,t))}for(const{name:n,value:r}of e.attributes)t.hasAttribute(n)||("selected"===n&&Xa(e)&&e.selected&&(this.#n.preserveChanges&&e.selected!==e.defaultSelected||(e.selected=!1)),"checked"===n&&Za(e)&&e.checked&&(this.#n.preserveChanges&&e.checked!==e.defaultChecked||(e.checked=!1)),(this.#n.beforeAttributeUpdated?.(e,n,null)??1)&&(e.removeAttribute(n),this.#n.afterAttributeUpdated?.(e,n,r)))}#d(e,t){const n=t.textContent||"",r=e.value!==e.defaultValue;e.textContent!==n&&(e.textContent=n),this.#n.preserveChanges&&r||(e.value=e.defaultValue)}visitChildNodes(e,t){if(!(this.#n.beforeChildrenVisited?.(e)??1))return;const n=e,r=[...e.childNodes],i=[...t.childNodes];Va.clear(),Ba.clear(),Fa.clear(),Ua.clear(),Ka.clear();const a=[],o=[],s=[],l=[],c=[],u=[];for(let e=0;e<r.length;e++){const t=r[e],n=t.nodeType;l[e]=n,1===n?(u[e]=t.localName,Ba.add(e)):3===n&&""===t.textContent?.trim()?Ka.add(e):Va.add(e)}for(let e=0;e<i.length;e++){const t=i[e],n=t.nodeType;if(s[e]=n,1===n)c[e]=t.localName,Ua.add(e);else{if(3===n&&""===t.textContent?.trim())continue;Fa.add(e)}}for(const e of Ua){const t=c[e],n=i[e];for(const i of Ba){if(t!==u[i])continue;if(r[i].isEqualNode(n)){a[e]=i,o[e]=qa,Ba.delete(i),Ua.delete(e);break}}}for(const e of Ua){const t=i[e],n=t.id,s=this.#e.get(t);if(""!==n||s)e:for(const t of Ba){const i=r[t];if(c[e]===u[t]){if(""!==n&&n===i.id){a[e]=t,o[e]=Da,Ba.delete(t),Ua.delete(e);break e}if(s){const n=this.#t.get(i);if(n)for(let r=0;r<s.length;r++){const i=s[r];if(n.has(i)){a[e]=t,o[e]=Da,Ba.delete(t),Ua.delete(e);break e}}}}}}for(const e of Ua){const t=i[e],n=t.getAttribute("name"),s=t.getAttribute("href"),l=t.getAttribute("src");for(const t of Ba){const i=r[t];if(c[e]===u[t]&&(n&&n===i.getAttribute("name")||s&&s===i.getAttribute("href")||l&&l===i.getAttribute("src"))){a[e]=t,o[e]=Da,Ba.delete(t),Ua.delete(e);break}}}for(const e of Ua){const t=i[e],n=c[e];for(const i of Ba){const s=r[i];if(n===u[i]){if("input"===n&&s.type!==t.type)continue;a[e]=i,o[e]=Da,Ba.delete(i),Ua.delete(e);break}}}for(const e of Fa){const t=i[e];for(const n of Va){if(r[n].isEqualNode(t)){a[e]=n,o[e]=qa,Va.delete(n),Fa.delete(e);break}}}for(const e of Fa){const t=s[e];for(const n of Va)if(t===l[n]){a[e]=n,o[e]=_a,Va.delete(n),Fa.delete(e);break}}for(const e of Va)this.#l(r[e]);for(const e of Ka)this.#l(r[e]);for(const e of Ba)this.#l(r[e]);const p=function(e){const t=e.length;if(0===t)return[];const n=[],r=[],i=new Array(t);for(let a=0;a<t;a++){const t=e[a];if(void 0===t)continue;let o=0,s=n.length;for(;o<s;){const e=Math.floor((o+s)/2);n[e]<t?o=e+1:s=e}i[a]=o>0?r[o-1]:-1,o===n.length?(n.push(t),r.push(a)):(n[o]=t,r[o]=a)}const a=[];if(0===r.length)return a;let o=r[r.length-1];for(;void 0!==o&&-1!==o;)a.unshift(o),o=i[o];return a}(a),m=new Array(r.length);for(let e=0;e<p.length;e++)m[a[p[e]]]=!0;let d=n.firstChild;for(let e=0;e<i.length;e++){const t=i[e],s=a[e];if(void 0!==s){const i=r[s],a=o[e];m[s]||Ja(n,i,d),a===qa||(a===Da?this.#c(i,t):this.#s(i,t)),d=i.nextSibling}else(this.#n.beforeNodeAdded?.(n,t,d)??1)&&(n.insertBefore(t,d),this.#n.afterNodeAdded?.(t),d=t.nextSibling)}this.#n.afterChildrenVisited?.(e)}#h(e,t){const n=e.parentNode||document,r=e;(this.#n.beforeNodeRemoved?.(e)??1)&&(this.#n.beforeNodeAdded?.(n,t,r)??1)&&(n.insertBefore(t,r),this.#n.afterNodeAdded?.(t),e.remove(),this.#n.afterNodeRemoved?.(e))}#l(e){(this.#n.beforeNodeRemoved?.(e)??1)&&(e.remove(),this.#n.afterNodeRemoved?.(e))}#i(e){for(const t of e)eo(t)&&this.#o(t)}#o(e){const t=this.#e;for(const n of e.querySelectorAll("[id]")){const r=n.id;if(""===r)continue;let i=n;for(;i;){const n=t.get(i);if(n?n.push(r):t.set(i,[r]),i===e)break;i=i.parentElement}}}#r(e){const t=this.#t;for(const n of e.querySelectorAll("[id]")){const r=n.id;if(""===r)continue;let i=n;for(;i;){const n=t.get(i);if(n?n.add(r):t.set(i,new Set([r])),i===e)break;i=i.parentElement}}}}function Za(e){return"input"===e.localName}function Xa(e){return"option"===e.localName}function eo(e){return!!Ha[e.nodeType]}const to=function(e,t,n={}){"string"==typeof t&&(t=Qa(t).childNodes),!n.preserveChanges&&eo(e)&&Ga(e),new Ya(n).morph(e,t)},no=function(e,t,n={}){if("string"==typeof t){const e=Qa(t);if(!e.firstChild||1!==e.childNodes.length||1!==e.firstChild.nodeType)throw new Error("[Morphlex] The string was not a valid HTML element.");t=e.firstChild}if(1!==e.nodeType||1!==t.nodeType||e.localName!==t.localName)throw new Error("[Morphlex] You can only do an inner morph with matching elements.");eo(e)&&Ga(e),new Ya(n).visitChildNodes(e,t)};function ro(e){return e?{preserveChanges:e.preserveChanges??!0,beforeNodeVisited:e.beforeNodeVisited,afterNodeVisited:e.afterNodeVisited,beforeNodeAdded:e.beforeNodeAdded?t=>e.beforeNodeAdded(t.parentNode,t,null):void 0,afterNodeAdded:e.afterNodeAdded,beforeNodeRemoved:e.beforeNodeRemoved,afterNodeRemoved:e.afterNodeRemoved}:{preserveChanges:!0}}let io={morph(e,t,n){const r=ro(n);to(e,t,r)},morphInner(e,t,n){const r=ro(n);let i;if("string"==typeof t){const n=document.createElement(e.tagName);n.innerHTML=t,i=n}else i=t;no(e,i,r)}};const ao={morph(e,t,n){io.morph(e,t,n)},morphInner(e,t,n){io.morphInner(e,t,n)}};function oo(){return"undefined"!=typeof document&&"function"==typeof document.startViewTransition}let so={enabled:oo(),defaultTimeout:5e3},lo=[],co=!1;async function uo(e,t){const{skipTransition:n=!1,timeout:r=so.defaultTimeout}=t;if(!so.enabled||!oo()||n)return void await e();const i=document.startViewTransition(async()=>{await e()}),a=new Promise((e,t)=>{setTimeout(()=>t(new Error("View transition timed out")),r)});try{await Promise.race([i.finished,a])}catch(e){}}function po(e,t={}){return new Promise((n,r)=>{lo.push({callback:e,options:t,resolve:n,reject:r}),async function(){if(!co&&0!==lo.length){for(co=!0;lo.length>0;){const e=lo.shift();try{await uo(e.callback,e.options),e.resolve()}catch(t){e.reject(t)}}co=!1}}().catch(r)})}const mo={html:{category:"document-root",message:"The <html> element is the document root and cannot be part of a partial",suggestion:"Remove the <html> element. Return only the content that should replace the target."},body:{category:"document-root",message:"The <body> element is the document body and cannot be part of a partial",suggestion:"Remove the <body> element. Return only the content for the target."},head:{category:"document-root",message:"The <head> element contains document metadata and cannot be part of a partial",suggestion:"Remove the <head> element. Styles/scripts should be loaded separately."}},ho={header:{category:"semantic-landmark",message:"The <header> element is a semantic landmark. Swapping may create duplicate landmarks.",suggestion:"Consider if <header> is appropriate in this partial, or if the page already has this landmark."},footer:{category:"semantic-landmark",message:"The <footer> element is a semantic landmark. Swapping may create duplicate landmarks.",suggestion:"Consider if <footer> is appropriate in this partial, or if the page already has this landmark."},main:{category:"semantic-landmark",message:"The <main> element should be unique per page. Swapping may create duplicates.",suggestion:"Consider if <main> is appropriate. Pages should have exactly one <main> element."},nav:{category:"semantic-landmark",message:"The <nav> element is a semantic landmark. Consider if navigation should be in a partial.",suggestion:"Consider if <nav> is appropriate in this partial, or if navigation should be static."},aside:{category:"semantic-landmark",message:"The <aside> element is a semantic landmark. Swapping may affect accessibility.",suggestion:"Consider if <aside> is appropriate in this partial."}},fo={title:{category:"metadata",message:"The <title> element should only appear in <head>. This may be ignored by browsers.",suggestion:"Move <title> to the document <head> or remove from partial."},meta:{category:"metadata",message:"The <meta> element should only appear in <head>. This may be ignored by browsers.",suggestion:"Move <meta> to the document <head> or remove from partial."},link:{category:"metadata",message:"The <link> element for stylesheets should typically be in <head>.",suggestion:"Consider if <link> should be in document <head> for proper loading order."},base:{category:"metadata",message:"The <base> element should only appear once in <head>.",suggestion:"Remove <base> from partial. It must be in document <head>."}};const yo={enabled:!("undefined"!=typeof window&&window.__HYPERFIXI_PROD__||"undefined"!=typeof process&&"production"===process.env?.NODE_ENV),showWarnings:!0,strictness:"standard",additionalCriticalElements:[],additionalStructuralElements:[],ignoredElements:[],ignoredTargets:[],targetOverrides:[]};let vo={...yo};function go(){return{...vo}}function bo(e,t){if("*"===t)return!0;if(t.includes("*")){const n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp("^"+n+"$").test(e)}return e===t}function ko(e,t=""){const n=function(e){const t={...vo};if(vo.targetOverrides)for(const n of vo.targetOverrides)if(bo(e,n.target))return{...t,...n.config};return t}(t);if(!n.enabled)return{valid:!0,issues:[],bySeverity:{critical:[],structural:[],warning:[]},totalIssues:0,shouldProceed:!0};if(n.ignoredTargets?.some(e=>bo(t,e)))return{valid:!0,issues:[],bySeverity:{critical:[],structural:[],warning:[]},totalIssues:0,shouldProceed:!0};const r=[];if(e.match(/<!DOCTYPE[^>]*>/i)&&!n.ignoredElements?.includes("doctype")&&r.push({severity:"critical",category:"document-root",element:"DOCTYPE",message:"DOCTYPE declarations cannot be part of a partial",suggestion:"Remove DOCTYPE declaration. Partials should only contain content fragments.",targetSelector:t,count:1}),"undefined"==typeof document)return function(e,t,n){const r=[];for(const[i,a]of Object.entries(mo)){if(n.ignoredElements?.includes(i))continue;const o=new RegExp(`<${i}[\\s>]`,"gi"),s=e.match(o),l=s?.length||0;l>0&&r.push({severity:"critical",category:a.category,element:i,message:a.message,suggestion:a.suggestion||`Remove the <${i}> element from the partial.`,targetSelector:t,count:l})}if("relaxed"!==n.strictness)for(const[i,a]of Object.entries(ho)){if(n.ignoredElements?.includes(i))continue;const o=new RegExp(`<${i}[\\s>]`,"gi"),s=e.match(o),l=s?.length||0;l>0&&r.push({severity:"strict"===n.strictness?"critical":"structural",category:a.category,element:i,message:a.message,suggestion:a.suggestion||`Consider if <${i}> is appropriate in this partial.`,targetSelector:t,count:l})}return wo(r)}(e,t,n);for(const[i,a]of Object.entries(mo)){if(n.ignoredElements?.includes(i))continue;const o=new RegExp(`<${i}[\\s>]`,"gi"),s=e.match(o),l=s?.length||0;l>0&&r.push({severity:"critical",category:a.category,element:i,message:a.message,suggestion:a.suggestion||`Remove the <${i}> element from the partial.`,targetSelector:t,count:l})}const i=document.createElement("div");if(i.innerHTML=e,"relaxed"!==n.strictness)for(const[e,a]of Object.entries(ho)){if(n.ignoredElements?.includes(e))continue;const o=i.querySelectorAll(e).length;o>0&&r.push({severity:"strict"===n.strictness?"critical":"structural",category:a.category,element:e,message:a.message,suggestion:a.suggestion||`Consider if <${e}> is appropriate in this partial.`,targetSelector:t,count:o})}if("strict"===n.strictness)for(const[e,a]of Object.entries(fo)){if(n.ignoredElements?.includes(e))continue;const o=i.querySelectorAll(e).length;o>0&&r.push({severity:"warning",category:a.category,element:e,message:a.message,suggestion:a.suggestion||`Move <${e}> to document <head> or remove from partial.`,targetSelector:t,count:o})}if(n.additionalCriticalElements)for(const e of n.additionalCriticalElements){if(n.ignoredElements?.includes(e))continue;const a=i.querySelectorAll(e).length;a>0&&r.push({severity:"critical",category:"document-root",element:e,message:`The <${e}> element is configured as a critical layout element.`,suggestion:`Remove <${e}> from the partial content.`,targetSelector:t,count:a})}if(n.additionalStructuralElements)for(const e of n.additionalStructuralElements){if(n.ignoredElements?.includes(e))continue;const a=i.querySelectorAll(e).length;a>0&&r.push({severity:"structural",category:"semantic-landmark",element:e,message:`The <${e}> element is configured as a structural element.`,suggestion:`Consider if <${e}> is appropriate in this partial.`,targetSelector:t,count:a})}if(n.customValidator){const i=n.customValidator(e,t);r.push(...i)}return wo(r)}function wo(e){const t={critical:e.filter(e=>"critical"===e.severity),structural:e.filter(e=>"structural"===e.severity),warning:e.filter(e=>"warning"===e.severity)};return{valid:0===t.critical.length,issues:e,bySeverity:t,totalIssues:e.length,shouldProceed:!0}}const zo="font-weight: bold; font-size: 13px; color: #6366f1;",xo="color: #dc2626; font-weight: bold;",Eo="color: #ea580c; font-weight: bold;",So="color: #ca8a04; font-weight: bold;",To="color: #7c3aed; font-weight: bold;",Co="color: #16a34a; font-style: italic;",Ao="color: #0891b2;",jo="color: inherit;",Lo="color: #6b7280;",Po={critical:"🚨",structural:"⚠️",warning:"💡"},Io={critical:"CRITICAL",structural:"STRUCTURAL",warning:"WARNING"};function No(e){0!==e.totalIssues&&("undefined"!=typeof window&&"undefined"!=typeof console?function(e){if(console.groupCollapsed(`%c[HyperFixi] Partial Template Validation: ${e.totalIssues} issue(s) found`,zo),function(e){const t=[],n=[];e.bySeverity.critical.length>0&&(t.push(`%c${e.bySeverity.critical.length} critical%c`),n.push(xo,jo));e.bySeverity.structural.length>0&&(t.length>0&&t.push(", "),t.push(`%c${e.bySeverity.structural.length} structural%c`),n.push(Eo,jo));e.bySeverity.warning.length>0&&(t.length>0&&t.push(", "),t.push(`%c${e.bySeverity.warning.length} warning(s)%c`),n.push(So,jo));t.length>0&&console.log(`Found: ${t.join("")}`,...n)}(e),e.bySeverity.critical.length>0){console.group(`%c${Po.critical} Critical Issues (${e.bySeverity.critical.length})`,xo);for(const t of e.bySeverity.critical)Oo(t);console.groupEnd()}if(e.bySeverity.structural.length>0){console.group(`%c${Po.structural} Structural Issues (${e.bySeverity.structural.length})`,Eo);for(const t of e.bySeverity.structural)Oo(t);console.groupEnd()}if(e.bySeverity.warning.length>0){console.group(`%c${Po.warning} Warnings (${e.bySeverity.warning.length})`,So);for(const t of e.bySeverity.warning)Oo(t);console.groupEnd()}console.groupEnd()}(e):function(e){console.warn(`[HyperFixi] Partial Template Validation: ${e.totalIssues} issue(s) found`);const t=[];e.bySeverity.critical.length>0&&t.push(`${e.bySeverity.critical.length} critical`);e.bySeverity.structural.length>0&&t.push(`${e.bySeverity.structural.length} structural`);e.bySeverity.warning.length>0&&t.push(`${e.bySeverity.warning.length} warning(s)`);console.warn(` Found: ${t.join(", ")}`);for(const t of e.issues){const e=Po[t.severity],n=Io[t.severity],r=t.count>1?` (${t.count}x)`:"",i=t.targetSelector?` [target: ${t.targetSelector}]`:"";console.warn(` ${e} [${n}] <${t.element}>${r}${i}`),console.warn(` ${t.message}`),console.warn(` Fix: ${t.suggestion}`)}}(e))}function Oo(e){const t=e.count>1?` %c(${e.count} instances)%c`:"",n=e.count>1?[Lo,jo]:[];console.log(` %c<${e.element}>${t}: %c${e.message}`,To,...n,jo),console.log(` %c💡 ${e.suggestion}`,Co),e.targetSelector&&console.log(` %cTarget: %c${e.targetSelector}`,jo,Ao)}function Ro(e){const t=e.count>1?` (${e.count}x)`:"",n=e.targetSelector?` [target: ${e.targetSelector}]`:"";return`${Po[e.severity]} [${Io[e.severity]}] <${e.element}>${t}${n}: ${e.message}`}function Mo(e){return e.issues.map(Ro)}const Wo={into:"innerHTML",over:"outerHTML",innerhtml:"innerHTML",outerhtml:"outerHTML",beforebegin:"beforeBegin",afterbegin:"afterBegin",beforeend:"beforeEnd",afterend:"afterEnd",delete:"delete",none:"none",morph:"morph",innermorph:"morph",outermorph:"morphOuter"};function $o(e,t,n,r){const i=null===t||Ci(t)?"":t,a=Ci(t)?t:null;switch(n){case"morph":if(null!==t)try{ao.morphInner(e,a||i,r)}catch(t){console.warn("[HyperFixi] Morph failed, falling back to innerHTML:",t),a?(e.innerHTML="",e.appendChild(a)):e.innerHTML=i}break;case"morphOuter":if(null!==t)try{ao.morph(e,a||i,r)}catch(t){console.warn("[HyperFixi] Morph failed, falling back to outerHTML:",t),a?e.replaceWith(a):e.outerHTML=i}break;case"innerHTML":a?(e.innerHTML="",e.appendChild(a)):e.innerHTML=i;break;case"outerHTML":a?e.replaceWith(a):e.outerHTML=i;break;case"beforeBegin":a?e.parentElement?.insertBefore(a,e):e.insertAdjacentHTML("beforebegin",i);break;case"afterBegin":a?e.insertBefore(a,e.firstChild):e.insertAdjacentHTML("afterbegin",i);break;case"beforeEnd":a?e.appendChild(a):e.insertAdjacentHTML("beforeend",i);break;case"afterEnd":a?e.parentElement?.insertBefore(a,e.nextSibling):e.insertAdjacentHTML("afterend",i);break;case"delete":e.remove();break;case"none":break;default:throw new Error(`[HyperFixi] swap: unknown strategy "${n}"`)}}async function Ho(e,t,n,r={}){const{morphOptions:i,useViewTransition:a=!1,validateContent:o=!1,targetSelector:s}=r;if(o&&"string"==typeof t){const n=go();if(n.enabled){const r=s||function(e){if(!e)return"";if(e.id)return`#${e.id}`;if(e.className){const t=e.className.split(" ")[0];if(t)return`.${t}`}return e.tagName.toLowerCase()}(e[0]),i=ko(t,r);i.totalIssues>0&&n.showWarnings&&No(i)}}const l=()=>{for(const r of e)$o(r,t,n,i)};a&&oo()?await po(l):l()}function qo(e){if(null==e)return null;if(Ci(e))return e;if(function(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&11===e.nodeType&&"childNodes"in e}(e)){const t=e,n=document.createElement("div");return n.appendChild(t.cloneNode(!0)),n.innerHTML}return String(e)}async function Do(e,t){const n=ji(e||void 0,t);if(0===n.length){throw new Error(`[HyperFixi] swap: no elements found${e?` matching "${e}"`:""}`)}return n}let _o=(()=>{let e,t,n=[Si({description:"Swap content into target elements with intelligent morphing support",syntax:["swap <target> with <content>","swap [strategy] of <target> with <content>","swap into <target> with <content>","swap over <target> with <content>","swap delete <target>","swap <target> with <content> using view transition"],examples:["swap #target with it","swap innerHTML of #target with it","swap over #modal with fetchedContent","swap delete #notification"],sideEffects:["dom-mutation"]}),Ei({name:"swap",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){const r=e.args;if(!r||0===r.length)throw new Error("[HyperFixi] swap: command requires arguments");const i=r.map(e=>{if(!e||"object"!=typeof e)return null;const t=e,n=t.type;return"literal"===n&&"string"==typeof t.value?t.value.toLowerCase():"identifier"===n&&"string"==typeof t.name?t.name.toLowerCase():null}),a=i.findIndex(e=>"with"===e),o=i.findIndex(e=>"of"===e),s=i.findIndex(e=>"delete"===e),l=i.findIndex(e=>"using"===e);let c=!1;if(-1!==l){const e=i.slice(l+1);e.includes("view")&&e.includes("transition")&&(c=!0)}let u="morph",p=null,m=null;if(-1!==s)u="delete",p=r[s+1],m=null;else if(-1!==o&&-1!==a){const e=i[0];e&&Wo[e]&&(u=Wo[e]),p=r[o+1],m=r[a+1]}else if(-1!==a){const e=i.slice(0,a),t=e.findIndex(e=>"into"===e),n=e.findIndex(e=>"over"===e);if(-1!==t)u="innerHTML",p=r[t+1];else if(-1!==n)u="outerHTML",p=r[n+1];else{const e=i[0];e&&Wo[e]?(u=Wo[e],p=r[1]||r[a-1]):p=r[a-1]}m=r[a+1]}else{if(!(r.length>=2))throw new Error('[HyperFixi] swap: could not parse arguments. Expected "swap <target> with <content>"');{const e=i[0];e&&Wo[e]&&(u=Wo[e]),p=r[r.length-2],m=r[r.length-1]}}let d=null,h=null;if(p){const e=p.type,r=p.value;if("selector"===e&&"string"==typeof r)d=r;else if("binaryExpression"===e&&"of"===p.operator){const e=p.left,r=p.right;if(e&&"identifier"===e.type&&"string"==typeof e.name){const t=e.name.toLowerCase();Wo[t]&&(u=Wo[t])}r&&"selector"===r.type&&"string"==typeof r.value?d=r.value:r&&(d=await t.evaluate(r,n))}else d=await t.evaluate(p,n)}m&&(h=await t.evaluate(m,n));let f=null;if("string"==typeof d)f=d;else if(Ci(d))return{targets:[d],content:qo(h),strategy:u,morphOptions:{preserveChanges:!0},useViewTransition:c};return{targets:await Do(f,n),content:qo(h),strategy:u,morphOptions:{preserveChanges:!0},useViewTransition:c}}async execute(e,t){const{targets:n,content:r,strategy:i,morphOptions:a,useViewTransition:o}=e;await Ho(n,r,i,{morphOptions:a,useViewTransition:o})}},ki(t,"SwapCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})(),Vo=(()=>{let e,t,n=[Si({description:"Morph content into target elements (intelligent diffing, preserves state)",syntax:["morph <target> with <content>","morph over <target> with <content>"],examples:["morph #target with it","morph over #modal with fetchedContent"],sideEffects:["dom-mutation"]}),Ei({name:"morph",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){const r=e.args;if(!r||0===r.length)throw new Error("[HyperFixi] morph: command requires arguments");const i=r.map(e=>{const t=e;return"identifier"===t.type&&"string"==typeof t.name?t.name.toLowerCase():null}),a=i.findIndex(e=>"with"===e),o=i.findIndex(e=>"over"===e),s=i.findIndex(e=>"using"===e);let l=!1;if(-1!==s){const e=i.slice(s+1);e.includes("view")&&e.includes("transition")&&(l=!0)}let c="morph",u=null,p=null;if(-1!==o&&o<(-1===a?1/0:a)?(c="morphOuter",u=r[o+1],-1!==a&&(p=r[a+1])):-1!==a?(u=r[a-1],p=r[a+1]):r.length>=2&&(u=r[0],p=r[1]),!u)throw new Error("[HyperFixi] morph: could not determine target");let m=null;const d=u;m="selector"===d.type&&"string"==typeof d.value?d.value:await t.evaluate(u,n);let h,f=null;if(p&&(f=await t.evaluate(p,n)),!m)throw new Error("[HyperFixi] morph: could not determine target");if("string"==typeof m)h=await Do(m,n);else{if(!Ci(m))throw new Error("[HyperFixi] morph: target must be a selector or element");h=[m]}return{targets:h,content:qo(f),strategy:c,morphOptions:{preserveChanges:!0},useViewTransition:l}}async execute(e,t){const{targets:n,content:r,strategy:i,morphOptions:a,useViewTransition:o}=e;if(o)await Ho(n,r,i,{morphOptions:a,useViewTransition:o});else for(const e of n)$o(e,r,i,a)}},ki(t,"MorphCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})();const Bo=Ti(_o),Fo=Ti(Vo);function Uo(e,t,n={}){return new CustomEvent(e,{detail:void 0!==t?t:{},bubbles:void 0===n.bubbles||n.bubbles,cancelable:void 0===n.cancelable||n.cancelable,composed:void 0!==n.composed&&n.composed})}function Ko(e){const t=e.trim();return/^\d+$/.test(t)?parseInt(t,10):/^\d*\.\d+$/.test(t)?parseFloat(t):"true"===t||"false"!==t&&("null"===t?null:"undefined"!==t?t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t:void 0)}function Go(e,t,n={},r={}){const i=Uo(t,n,r);return e.dispatchEvent(i),i}function Qo(e,t,n={},r={}){return{lokascript:Go(e,`lokascript:${t}`,n,r),hyperfixi:Go(e,`hyperfixi:${t}`,n,r)}}Bo(),Fo();const Jo={morph:"morph",morphouter:"morphOuter",innerhtml:"innerHTML",outerhtml:"outerHTML",beforebegin:"beforeBegin",afterbegin:"afterBegin",beforeend:"beforeEnd",afterend:"afterEnd",delete:"delete",none:"none"};function Yo(e,t){const{target:n,strategy:r,content:i}=e,a=document.querySelector(n);if(!a||!Ci(a))return{success:!1,error:`Target "${n}" not found`};try{switch(r){case"morph":ao.morphInner(a,i,t);break;case"morphOuter":ao.morph(a,i,t);break;case"innerHTML":a.innerHTML=i;break;case"outerHTML":a.outerHTML=i;break;case"beforeBegin":a.insertAdjacentHTML("beforebegin",i);break;case"afterBegin":a.insertAdjacentHTML("afterbegin",i);break;case"beforeEnd":a.insertAdjacentHTML("beforeend",i);break;case"afterEnd":a.insertAdjacentHTML("afterend",i);break;case"delete":a.remove();break;case"none":break;default:return{success:!1,error:`Unknown strategy "${r}"`}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}function Zo(e,t){const n=function(e){const t=[],n=document.createElement("div");n.innerHTML=e;const r=n.querySelectorAll("hx-partial");for(const e of r){const n=e.getAttribute("target");if(!n){console.warn("hx-partial element missing target attribute, skipping");continue}const r=e.getAttribute("strategy")?.toLowerCase()||"morph",i=Jo[r]||"morph",a=e.innerHTML;t.push({target:n,strategy:i,content:a})}return t}(e),r=go(),i={count:0,targets:[],errors:[],validationWarnings:[],validationDetails:{}};for(const e of n){if(r.enabled){const t=ko(e.content,e.target);t.totalIssues>0&&(r.showWarnings&&No(t),i.validationWarnings.push(...Mo(t)),i.validationDetails[e.target]=t)}const n=Yo(e,t);n.success?(i.count++,i.targets.push(e.target)):n.error&&i.errors.push(`${e.target}: ${n.error}`)}return i}const Xo=Ti((()=>{let e,t,n=[Si({description:"Process <hx-partial> elements for multi-target swaps",syntax:["process partials in <content>","process partials in <content> using view transition"],examples:["process partials in it","process partials in fetchedHtml","process partials in it using view transition"],sideEffects:["dom-mutation"]}),Ei({name:"process",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){const r=e.args;if(!r||0===r.length)throw new Error("process partials command requires content argument");const i=[],a=[];for(const e of r){const r=await t.evaluate(e,n);i.push(r),"string"==typeof r&&a.push(r.toLowerCase())}const o=a.findIndex(e=>"partials"===e);if(-1===o)throw new Error('process command expects "partials" keyword: process partials in <content>');const s=a.findIndex(e=>"in"===e);if(-1===s||s<=o)throw new Error('process partials command expects "in" keyword: process partials in <content>');const l=i[s+1];let c;if("string"==typeof l)c=l;else if(Ci(l))c=l.outerHTML;else{if(!l||"function"!=typeof l.text)throw new Error("process partials: content must be an HTML string or element");c=await l.text()}const u=a.findIndex(e=>"using"===e);let p=!1;if(-1!==u){const e=a.slice(u+1).join(" ");e.includes("view")&&e.includes("transition")&&(p=!0)}return{html:c,useViewTransition:p,morphOptions:{preserveChanges:!0}}}async execute(e,t){const{html:n,useViewTransition:r,morphOptions:i}=e,a=()=>Zo(n,i);let o;return r&&oo()?await po(()=>{o=a()}):o=a(),t.it=o,Qo(window,"partials",o),o.errors.length>0&&console.warn("Some partials failed to process:",o.errors),o}},ki(t,"ProcessPartialsCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})());function es(e,t,n){return e?new Promise(n=>{const r=ns(()=>{e.removeEventListener(t,i)},n),i=e=>{r({event:e,timedOut:!1,cancelled:!1})};e.addEventListener(t,i)}):Promise.reject(new Error("waitForEvent: no target provided"))}function ts(e){return new Promise(t=>setTimeout(t,e))}function ns(e,t){let n=!1;return r=>{n||(n=!0,e(),t(r))}}Xo();let rs=(()=>{let e,t,n=[Si({description:"Wait for time delay, event, or race condition",syntax:["wait <time>","wait for <event>","wait for <event> or <condition>"],examples:["wait 2s","wait for click","wait for click or 1s","wait for mousemove(clientX, clientY)"],sideEffects:["time","event-listening"]}),Ei({name:"wait",category:"async"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw new Error("wait command requires an argument");if(e.modifiers.or)return this.parseRaceCondition(e,t,n);if(e.modifiers.for)return this.parseEventWait(e.modifiers.for,e.modifiers.from,t,n);const r=e.args[0];return"arrayLiteral"===r.type&&r.elements?this.parseEventArrayWait(r.elements,e.args[1],t,n):this.parseTimeWait(e.args[0],t,n)}async execute(e,t){const n=Date.now();if("time"===e.type)return await ts(e.milliseconds),{type:"time",result:e.milliseconds,duration:Date.now()-n};if("event"===e.type){const r=e.target??t.me??document,i=(await es(r,e.eventName)).event;if(Object.assign(t,{it:i}),e.destructure)for(const n of e.destructure)n in i&&t.locals.set(n,i[n]);return{type:"event",result:i,duration:Date.now()-n}}const{result:r,winningCondition:i}=await this.executeRace(e.conditions,t);if(Object.assign(t,{it:r}),r instanceof Event&&"event"===i?.type&&i.destructure)for(const e of i.destructure)e in r&&t.locals.set(e,r[e]);return{type:r instanceof Event?"event":"time",result:r,duration:Date.now()-n}}async parseTimeWait(e,t,n){return{type:"time",milliseconds:ca(await t.evaluate(e,n))}}async parseEventWait(e,t,n,r){const i=await n.evaluate(e,r);if("string"!=typeof i)throw new Error("wait for: event name must be a string");const a=i.match(/^(\w+)\(([^)]+)\)$/),o=a?a[1]:i,s=a?a[2].split(",").map(e=>e.trim()):void 0;let l;if(t){const e=await n.evaluate(t,r);if(!e||"object"!=typeof e||!("addEventListener"in e))throw new Error("wait for from: target must be an EventTarget");l=e}else l=r.me??void 0;return{type:"event",eventName:o,target:l,destructure:s}}async parseEventArrayWait(e,t,n,r){const i=[];for(const t of e){const e=t;if("objectLiteral"===e.type&&e.properties){let t="",n=[];for(const r of e.properties){const e=r.key?.name||r.key?.value;"name"===e&&r.value?t=r.value.value||"":"args"===e&&r.value?.elements&&(n=r.value.elements.map(e=>e.value||e.name||""))}t&&i.push({name:t,params:n})}}let a;if(t){const e=await n.evaluate(t,r);e&&"object"==typeof e&&"addEventListener"in e&&(a=e)}return a||(a=r.me??void 0),1===i.length?{type:"event",eventName:i[0].name,target:a,destructure:i[0].params.length>0?i[0].params:void 0}:{type:"race",conditions:i.map(e=>({type:"event",eventName:e.name,target:a,destructure:e.params.length>0?e.params:void 0}))}}async parseRaceCondition(e,t,n){const r=[];e.modifiers.for?r.push(await this.parseEventWait(e.modifiers.for,e.modifiers.from,t,n)):e.args[0]&&r.push(await this.parseTimeWait(e.args[0],t,n));const i=await t.evaluate(e.modifiers.or,n),a=Array.isArray(i)?i:[i];for(const e of a)try{r.push({type:"time",milliseconds:ca(e)})}catch{if("string"==typeof e){const t=e.match(/^(\w+)\(([^)]+)\)$/);r.push(t?{type:"event",eventName:t[1],target:n.me??void 0,destructure:t[2].split(",").map(e=>e.trim())}:{type:"event",eventName:e,target:n.me??void 0})}}if(r.length<2)throw new Error("wait: race requires at least 2 conditions");return{type:"race",conditions:r}}async executeRace(e,t){const n=e.map(e=>{if("time"===e.type)return ts(e.milliseconds).then(()=>({result:e.milliseconds,winningCondition:e}));return es(e.target??t.me??document,e.eventName).then(t=>({result:t.event,winningCondition:e}))});return Promise.race(n)}},ki(t,"WaitCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})();const is=Ti(rs),as=new Map;let os=(()=>{let e,t,n=[Si({description:"Make HTTP requests with lifecycle event support",syntax:["fetch <url>","fetch <url> as <type>","fetch <url> with <options>"],examples:['fetch "/api/data"','fetch "/api/users" as json','fetch "/api/save" with { method:"POST" }'],sideEffects:["network","event-dispatching"]}),Ei({name:"fetch",category:"async"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw new Error("fetch requires a URL");return{url:await this.parseURL(e.args[0],t,n),responseType:this.parseResponseType(e.modifiers.as),options:await this.parseRequestOptions(e.modifiers.with,t,n)}}async execute(e,t){const n=Date.now(),{url:r,responseType:i,options:a}=e,o=new AbortController;let s;t.me&&(s=()=>o.abort(),t.me.addEventListener("fetch:abort",s,{once:!0}));const l={...a,signal:o.signal},c=as.get(i);if(c?.accept){const e=new Headers(l.headers);e.has("Accept")||e.set("Accept",c.accept),l.headers=e}if(t.me){const e={...l,sender:t.me,headers:l.headers||{}};this.dispatchEvent(t.me,"fetch:beforeRequest",e),l.headers=e.headers}let u;a.timeout&&(u=setTimeout(()=>o.abort(),a.timeout));try{let e=await fetch(r,l);if(t.me){const n={response:e};this.dispatchEvent(t.me,"fetch:afterResponse",n),e=n.response}const a=await this.handleResponse(e,i,t);t.me&&this.dispatchEvent(t.me,"fetch:afterRequest",{result:a});const o={status:e.status,statusText:e.statusText,headers:e.headers,data:a,url:e.url,duration:Date.now()-n};return Object.assign(t,{it:a}),o}catch(e){if(t.me&&this.dispatchEvent(t.me,"fetch:error",{reason:e instanceof Error?e.message:String(e),error:e}),e instanceof Error&&"AbortError"===e.name)throw new Error(`Fetch aborted for ${r}`);throw new Error(`Fetch failed for ${r}: ${e instanceof Error?e.message:String(e)}`)}finally{u&&clearTimeout(u),t.me&&s&&t.me.removeEventListener("fetch:abort",s)}}async parseURL(e,t,n){const r=await t.evaluate(e,n);if("string"!=typeof r||!r)throw new Error("fetch: URL must be a non-empty string");return r}parseResponseType(e){if(!e)return"text";const t=e;if(("identifier"===t.type||"expression"===t.type)&&t.name){const e=t.name.toLowerCase();if("object"===e)return"json";if(["text","json","html","response","blob","arraybuffer"].includes(e))return"arraybuffer"===e?"arrayBuffer":e;if(as.has(e))return e;throw new Error(`fetch: invalid response type "${e}"`)}return"text"}async parseRequestOptions(e,t,n){if(!e)return{};const r=await t.evaluate(e,n);if("object"!=typeof r||null===r)throw new Error('fetch: "with" options must be an object');const i={};return"method"in r&&(i.method=String(r.method).toUpperCase()),"headers"in r&&(i.headers=this.parseHeaders(r.headers)),"body"in r&&(i.body=this.parseBody(r.body)),"credentials"in r&&(i.credentials=r.credentials),"mode"in r&&(i.mode=r.mode),"cache"in r&&(i.cache=r.cache),i}parseHeaders(e){if(e instanceof Headers)return e;const t=new Headers;if("object"==typeof e&&null!==e)for(const[n,r]of Object.entries(e))t.set(n,String(r));return t}parseBody(e){return null==e?null:e instanceof FormData||e instanceof Blob||e instanceof ArrayBuffer||e instanceof URLSearchParams||"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):String(e)}async handleResponse(e,t,n){switch(t){case"response":return e;case"json":return e.json();case"html":return this.parseHTML(await e.text());case"blob":return e.blob();case"arrayBuffer":return e.arrayBuffer();case"text":return e.text();default:{const r=as.get(t);return r?r.handler(e,n):e.text()}}}parseHTML(e){const t=(new DOMParser).parseFromString(e,"text/html"),n=document.createDocumentFragment();return Array.from(t.body.childNodes).forEach(e=>n.appendChild(e.cloneNode(!0))),1===n.childNodes.length&&Ci(n.firstChild)?n.firstChild:n}dispatchEvent(e,t,n){e.dispatchEvent(new CustomEvent(t,{detail:n,bubbles:!0,cancelable:!0}))}},ki(t,"FetchCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})();const ss=Ti(os);const ls=Ti((()=>{let e,t,n=[Si({description:"Set values to variables, attributes, or properties",syntax:["set <target> to <value>"],examples:['set myVar to "value"','set @data-theme to "dark"','set my innerHTML to "content"'],sideEffects:["state-mutation","dom-mutation"]}),Ei({name:"set",category:"data"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw new Error("set command requires a target");const r=e.args[0],i=r?.name||r?.value,a=await za(r,t,n);if(a){const r=await this.extractValue(e,t,n);if(a.property.startsWith("*")){const e=a.property.substring(1);return{type:"style",element:a.element,property:e,value:String(r)}}return{type:"property",element:a.element,property:a.property,value:r}}if("memberExpression"===r?.type||"propertyAccess"===r?.type){const i=await this.tryParseMemberExpression(r,e,t,n);if(i)return i}let o;if(o="identifier"!==r?.type&&"variable"!==r?.type||"string"!=typeof i?await t.evaluate(r,n):i,function(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if(Ci(e)||e instanceof Node)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(o)){return{type:"object-literal",properties:o,targets:await this.resolveTargets(e.modifiers.on,t,n)}}if(ka(o)){const r=wa(o,n);if(r){const i=await this.extractValue(e,t,n);return{type:"property",element:r.element,property:r.property,value:i}}return this.parseTheXofY(o,e,t,n)}if("string"==typeof o&&Gi(o)){const r=o.substring(1).trim(),i=await this.extractValue(e,t,n);return{type:"style",element:await this.resolveElement(e.modifiers.on,t,n),property:r,value:String(i)}}if("string"==typeof o&&Hi(o)){const r=o.substring(1).trim(),i=await this.extractValue(e,t,n);return{type:"attribute",element:await this.resolveElement(e.modifiers.on,t,n),name:r,value:i}}if("string"==typeof o){const r=o.match(/^(my|me|its?|your?)\s+(.+)$/i);if(r){const i=Pi(r[1],n),a=await this.extractValue(e,t,n);return{type:"property",element:i,property:r[2],value:a}}}if(Ci(o)){return{type:"property",element:o,property:"textContent",value:await this.extractValue(e,t,n)}}if(Array.isArray(o)&&o.length>0&&Ci(o[0])){const r=await this.extractValue(e,t,n);return{type:"property",element:o[0],property:"textContent",value:r}}if("string"!=typeof o)throw new Error("set command target must be a string or object literal");return{type:"variable",name:o,value:await this.extractValue(e,t,n)}}async execute(e,t){switch(e.type){case"variable":return t.locals.set(e.name,e.value),"result"!==e.name&&"it"!==e.name||Object.assign(t,{[e.name]:e.value}),Object.assign(t,{it:e.value}),{target:e.name,value:e.value,targetType:"variable"};case"attribute":return e.element.setAttribute(e.name,String(e.value)),Object.assign(t,{it:e.value}),{target:`@${e.name}`,value:e.value,targetType:"attribute"};case"property":return ya(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"style":return Qi(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"object-literal":for(const t of e.targets)for(const[n,r]of Object.entries(e.properties))ya(t,n,r);return Object.assign(t,{it:e.properties}),{target:e.targets[0]||"unknown",value:e.properties,targetType:"property"};case"member-assignment":return e.container[e.property]=e.value,Object.assign(t,{it:e.value}),{target:e.property,value:e.value,targetType:"property"};default:throw new Error(`Unknown input type: ${e.type}`)}}async tryParseMemberExpression(e,t,n,r){const i=e.object,a=e.property;if(i?.name&&a?.name){const e=i.name.toLowerCase();if(["me","my","it","its","you","your"].includes(e)){const i=Pi(e,r),o=await this.extractValue(t,n,r);return{type:"property",element:i,property:a.name,value:o}}}const o=e.object,s=e.computed;if(o){const i=await n.evaluate(o,r);if(null!=i&&"object"==typeof i){const o=s?String(await n.evaluate(e.property,r)):a?.name||"";if(o){return{type:"member-assignment",container:i,property:o,value:await this.extractValue(t,n,r)}}}}return null}async extractValue(e,t,n){if(e.modifiers.to)return t.evaluate(e.modifiers.to,n);const r=e.args.findIndex(e=>"identifier"===e.type&&"to"===e.name);if(r>=0&&e.args.length>r+1)return t.evaluate(e.args[r+1],n);if(e.args.length>=2)return t.evaluate(e.args[1],n);throw new Error('set command requires a value (use "to" keyword)')}async resolveElement(e,t,n){if(!e)return Ai(void 0,n);return Ai(await t.evaluate(e,n),n)}async resolveTargets(e,t,n){if(!e)return ji(void 0,n);return ji(await t.evaluate(e,n),n)}async parseTheXofY(e,t,n,r){const i=e.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!i)throw new Error('Invalid "the X of Y" syntax');const[,a,o]=i,s=Ai(o,r),l=await this.extractValue(t,n,r);return{type:"property",element:s,property:a.trim(),value:l}}validate(e){if(!e||"object"!=typeof e)return!1;const t=e;if(!t.type||"string"!=typeof t.type)return!1;if(!["variable","attribute","property","style","object-literal"].includes(t.type))return!1;switch(t.type){case"variable":return"string"==typeof t.name&&"value"in t;case"attribute":return"string"==typeof t.name&&Ci(t.element)&&"value"in t;case"property":return"string"==typeof t.property&&Ci(t.element)&&"value"in t;case"style":return"string"==typeof t.property&&""!==t.property&&Ci(t.element)&&"string"==typeof t.value;case"object-literal":return null!==t.properties&&"object"==typeof t.properties&&Array.isArray(t.targets)&&t.targets.length>0;default:return!1}}},ki(t,"SetCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})());const cs=Ti((()=>{let e,t,n=[Si({description:"Evaluate an expression and store the result in it",syntax:"get <expression>",examples:["get #my-dialog","get <button/>","get me.parentElement"],sideEffects:["context-mutation"]}),Ei({name:"get",category:"data"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args||0===e.args.length)throw new Error("get command requires an expression argument");const r=e.args[0],i=await t.evaluate(r,n);return i instanceof NodeList&&1===i.length||Array.isArray(i)&&1===i.length?{value:i[0]}:{value:i}}execute(e,t){return t.it=e.value,Object.assign(t,{result:e.value}),{value:e.value}}validate(e){return"object"==typeof e&&null!==e&&"value"in e}},ki(t,"GetCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})());let us=(()=>{let e,t,n=[Si({description:"Modify a variable or property by a specified amount (default: 1)",syntax:["increment <target> [by <number>]","decrement <target> [by <number>]"],examples:["increment counter","increment counter by 5","decrement counter","decrement counter by 5"],sideEffects:["data-mutation","context-modification"],aliases:["decrement"]}),Ei({name:"increment",category:"data"})],r=[];return t=class{async parseInput(e,t,n){const r="decrement"===e.commandName?.toLowerCase()?"decrement":"increment",i=await async function(e,t,n,r){if(!e.args||0===e.args.length)throw new Error(`${r} command requires a target`);const i=e.args[0];let a,o;const s=(l=i)&&"object"==typeof l&&l.type||"unknown";var l;if("identifier"===s)a=i.name,i.scope&&(o=i.scope);else if("literal"===s)a=i.value;else{const e=await t.evaluate(i,n);a=Array.isArray(e)&&e.length>0?e[0]:e}let c=1,u=o;for(let r=1;r<e.args.length;r++){const i=e.args[r];if(i&&"literal"===i.type){const e=i.value;"global"===e?u="global":"number"==typeof e&&(c=e)}else if(i&&"literal"!==i.type){const e=await t.evaluate(i,n);"number"==typeof e&&(c=e)}}return{target:a,amount:c,...u&&{scope:u}}}(e,t,n,r);return{...i,operation:r}}async execute(e,t){const{target:n,property:r,scope:i,amount:a=1,operation:o="increment"}=e,s=Ra(n,r,i,t);let l;if(isNaN(s))l=NaN;else{const e=isFinite(a)?a:1;l="increment"===o?s+e:s-e}return Ma(n,r,i,l,t),Object.assign(t,{it:l}),l}},ki(t,"NumericModifyCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})();const ps=Ti(us),ms=Ti(us);const ds=Ti((()=>{let e,t,n=[Si({description:"Log values to the console",syntax:"log [<values...>]",examples:['log "Hello World"',"log me.value","log x y z",'log "Result:" result'],sideEffects:["console-output"]}),Ei({name:"log",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args||0===e.args.length)return{values:[]};return{values:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}}async execute(e,t){const n="undefined"!=typeof window?window.console:console;0===e.values.length?n.log():n.log(...e.values)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return Array.isArray(t.values)}},ki(t,"LogCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})());let hs=(()=>{let e,t,n=[Si({description:"Dispatch events on elements",syntax:["trigger <event> on <target>","trigger <event>(<detail>) on <target>","send <event> to <target>","send <event>(<detail>) to <target>"],examples:["trigger click on #button","trigger customEvent on me","send dataEvent to #target","send myEvent(count: 42) to me"],sideEffects:["event-dispatch"],aliases:["send"]}),Ei({name:"trigger",category:"event"})],r=[];return t=class{async parseInput(e,t,n){const r="send"===e.commandName?.toLowerCase()?"send":"trigger",i=r;if(!e.args?.length)throw new Error(`${i} command requires an event name`);const a=e=>e?.type||"unknown",o=e.args[0];let s,l,c;if("functionCall"===a(o)||"callExpression"===a(o)){s=o.name||o.callee?.name;const e=o.args||o.arguments;e?.length&&(l=await this.parseEventDetail(e,t,n))}else if("identifier"===a(o)||"keyword"===a(o))s=o.name;else{const e=await t.evaluate(o,n);s="string"==typeof e?e:String(e)}const u=e.modifiers?.on||e.modifiers?.to;if(u)c=await this.resolveTargets([u],t,n,i);else{const r=e.args.findIndex((e,t)=>{if(0===t)return!1;const n=e.name||e.value;return"on"===n||"to"===n});if(-1===r||r>=e.args.length-1){if(!n.me)throw new Error(`${i}: no target specified and context.me is null`);c=[n.me]}else{const a=e.args.slice(r+1),o=a.findIndex(e=>"with"===(e.name||e.value)),s=-1===o?a:a.slice(0,o);c=await this.resolveTargets(s,t,n,i)}}return{eventName:s,detail:l,targets:c,options:await this.parseEventOptions(e.args,t,n),mode:r}}async execute(e,t){const n=Uo(e.eventName,e.detail,e.options);for(const t of e.targets)t.dispatchEvent(n);t.it=n}async resolveTargets(e,t,n,r){const i=[];for(const r of e){const e=await t.evaluate(r,n);if("window"!==e&&e!==window)if("document"!==e&&e!==document)if("me"===e&&n.me)i.push(n.me);else if("you"===e&&n.you)i.push(n.you);else if("it"===e&&n.it)i.push(n.it);else if(Ci(e))i.push(e);else if(e instanceof NodeList)i.push(...Array.from(e).filter(Ci));else if(Array.isArray(e))i.push(...e.filter(Ci));else{if("string"==typeof e){const t=document.querySelectorAll(e);if(0===t.length)throw new Error(`No elements found: "${e}"`);i.push(...Array.from(t).filter(Ci));continue}if(!e||"object"!=typeof e||!("addEventListener"in e))throw new Error("Invalid target: "+typeof e);i.push(e)}else i.push(document);else i.push(window)}if(!i.length)throw new Error(`${r}: no valid targets`);return i}async parseEventDetail(e,t,n){if(!e?.length)return;if(1===e.length){const r=e[0];if("objectLiteral"!==r?.type)return await t.evaluate(r,n)}const r={};for(const i of e){const e=await t.evaluate(i,n);if("object"!=typeof e||null===e||Array.isArray(e)){if("string"==typeof e&&e.includes(":")){const[t,n]=e.split(":",2);r[t.trim()]=Ko(n.trim())}}else Object.assign(r,e)}return Object.keys(r).length?r:void 0}async parseEventOptions(e,t,n){const r={bubbles:!0,cancelable:!0,composed:!1},i=e.findIndex(e=>"with"===(e.name||e.value));if(-1===i)return r;for(const a of e.slice(i+1)){const e=await t.evaluate(a,n);if("string"==typeof e){const t=e.toLowerCase();"bubbles"===t?r.bubbles=!0:"nobubbles"===t?r.bubbles=!1:"cancelable"===t?r.cancelable=!0:"nocancelable"===t?r.cancelable=!1:"composed"===t&&(r.composed=!0)}}return r}},ki(t,"EventDispatchCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})();const fs=Ti(hs),ys=Ti(hs);let vs=(()=>{let e,t,n=[Si({description:"Navigation functionality including URL navigation, element scrolling, and browser history",syntax:["go back","go to url <url> [in new window]","go to [position] [of] <element>"],examples:["go back",'go to url "https://example.com"',"go to top of #header"],sideEffects:["navigation","scrolling"]}),Ei({name:"go",category:"navigation"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args||0===e.args.length)return{args:[]};return{args:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}}async execute(e,t){const{args:n}=e;if(0===n.length)throw new Error("Go command requires arguments");if("string"==typeof n[0]&&"back"===n[0].toLowerCase())return await this.goBack(),{result:"back",type:"back"};if(this.isUrlNavigation(n)){return{result:await this.navigateToUrl(n,t),type:"url"}}return{result:await this.scrollToElement(n,t),type:"scroll"}}isUrlNavigation(e){return-1!==e.findIndex(e=>"url"===e)}async goBack(){if("undefined"==typeof window||!window.history)throw new Error("Browser history API not available");window.history.back()}async navigateToUrl(e,t){const n=e.findIndex(e=>"url"===e),r=e[n+1];if(!r)throw new Error('URL is required after "url" keyword');const i="string"==typeof r?r:String(r),a=e.includes("new")&&e.includes("window");if(!this.isValidUrl(i))throw new Error(`Invalid URL: "${i}"`);if(a){if("undefined"!=typeof window&&window.open){const e=window.open(i,"_blank");e?.focus&&e.focus()}}else i.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=i):"undefined"!=typeof window&&(window.location.assign?.(i)??(window.location.href=i));return i}isValidUrl(e){try{return e.startsWith("/")||e.startsWith("#")||new URL(e),!0}catch{return!1}}async scrollToElement(e,t){const n=this.parseScrollPosition(e),r=this.parseScrollTarget(e),i=this.parseScrollOffset(e),a=!e.includes("instantly"),o=this.resolveScrollTarget(r,t);if(!o)throw new Error(`Target element not found: ${r}`);if("undefined"!=typeof window){const e=a?"smooth":"instant",t=this.mapVerticalPosition(n.vertical),r=this.mapHorizontalPosition(n.horizontal);if(0!==i){o.scrollIntoView?.({behavior:e,block:t,inline:r});const{x:a,y:s}=this.calculateScrollPosition(o,n,i);window.scrollTo?.({left:a,top:s,behavior:e})}else o.scrollIntoView?.({behavior:e,block:t,inline:r})}return o}mapVerticalPosition(e){return{top:"start",middle:"center",bottom:"end",nearest:"nearest"}[e]||"start"}mapHorizontalPosition(e){return{left:"start",center:"center",right:"end",nearest:"nearest"}[e]||"nearest"}parseScrollPosition(e){const t={vertical:"top",horizontal:"nearest"},n=["top","middle","bottom"],r=["left","center","right"];let i=!1,a=!1;for(const o of e)"string"==typeof o&&(n.includes(o)?(t.vertical=o,i=!0):r.includes(o)&&(t.horizontal=o,a=!0));return a&&!i&&(t.vertical="nearest"),t}parseScrollTarget(e){const t=e.findIndex(e=>"of"===e);if(-1!==t&&t+1<e.length){let n=e[t+1];return"the"===n&&t+2<e.length&&(n=e[t+2]),n}for(const t of e)if("object"==typeof t&&t&&t.nodeType)return t;const n=["top","middle","bottom","left","center","right","of","the","to","smoothly","instantly"];for(const t of e)if("string"==typeof t&&!n.includes(t)&&(t.startsWith("#")||t.startsWith(".")||t.includes("[")||/^[a-zA-Z][a-zA-Z0-9-]*$/.test(t)))return t;return"body"}parseScrollOffset(e){for(let t=0;t<e.length;t++){const n=e[t];if("string"==typeof n){const e=n.match(/^([+-]?\d+)(px)?$/);if(e)return parseInt(e[1],10)}if(("+"===n||"-"===n)&&t+1<e.length){const r=e[t+1],i="number"==typeof r?r:parseInt(String(r).replace("px",""),10);if(!isNaN(i))return"-"===n?-i:i}}return 0}resolveScrollTarget(e,t){if("object"==typeof e&&e&&e.nodeType)return e;const n="string"==typeof e?e:String(e);if("body"===n&&"undefined"!=typeof document)return document.body;if("html"===n&&"undefined"!=typeof document)return document.documentElement;if("me"===n&&Ci(t.me))return t.me;if("it"===n&&Ci(t.it))return t.it;if("you"===n&&Ci(t.you))return t.you;const r=Ia(n,t);if(Ci(r))return r;if("undefined"!=typeof document)try{const e=document.querySelector(n);if(e)return e}catch{try{const e=document.getElementsByTagName(n);if(e.length>0)return e[0]}catch{}}return null}calculateScrollPosition(e,t,n){if("undefined"==typeof window||!e.getBoundingClientRect)return{x:0,y:0};const r=e.getBoundingClientRect(),i=window.pageXOffset||document.documentElement?.scrollLeft||0,a=window.pageYOffset||document.documentElement?.scrollTop||0,o=window.innerWidth||800,s=window.innerHeight||600;let l=i,c=a;switch(t.horizontal){case"left":l=r.left+i;break;case"center":l=r.left+i+r.width/2-o/2;break;case"right":l=r.right+i-o}switch(t.vertical){case"top":c=r.top+a+n;break;case"middle":c=r.top+a+r.height/2-s/2+n;break;case"bottom":c=r.bottom+a-s+n}return{x:Math.max(0,l),y:Math.max(0,c)}}},ki(t,"GoCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})();const gs=Ti(vs);const bs=["url","with","title"];async function ks(e,t,n,r){if(!e||0===e.length)throw new Error(`${r} command requires a URL argument`);const i=[],a=[];for(let r=0;r<e.length;r++){const o=e[r],s=o,l=s?.type||"unknown",c=s?.name;if("identifier"===l&&c&&bs.includes(c.toLowerCase()))i.push(c.toLowerCase()),a.push(c.toLowerCase());else{const e=await t.evaluate(o,n);i.push(e),"string"==typeof e&&a.push(e.toLowerCase())}}const o=a.findIndex(e=>"url"===e),s=a.findIndex(e=>"with"===e),l=a.findIndex(e=>"title"===e),c=`urlKeywordIndex=${o}, argCount=${i.length}`;let u,p;if(-1!==o&&i.length>o+1)u=String(i[o+1]);else{if(!(i.length>=1))throw new Error(`${r} command: URL is required. Debug: ${c}`);u=String(i[0])}-1!==s&&-1!==l&&l>s&&i.length>l+1&&(p=String(i[l+1]));const m=function(e,t,n){const r=n?` Debug: ${n}`:"";if(null==e)throw new Error(`[HyperFixi] ${t}: URL is required.${r}`);if("string"!=typeof e)throw new Error(`[HyperFixi] ${t}: URL must be a string (got ${typeof e}: ${String(e)}).${r}`);if(""===e.trim())throw new Error(`[HyperFixi] ${t}: URL cannot be empty.${r}`);if("undefined"===e)throw new Error(`[HyperFixi] ${t}: URL evaluated to string 'undefined' - check your expression.${r}`);if("null"===e)throw new Error(`[HyperFixi] ${t}: URL evaluated to string 'null' - check your expression.${r}`);return e}(u,r,c);return{url:m,title:p}}let ws=(()=>{let e,t,n=[Si({description:"Modify browser history URL without page reload",syntax:["push url <url>","push url <url> with title <title>","replace url <url>","replace url <url> with title <title>"],examples:['push url "/page/2"','push url "/search" with title "Search Results"','replace url "/search?q=test"','replace url "/page" with title "Updated Page"'],sideEffects:["navigation"],aliases:["replace"]}),Ei({name:"push",category:"navigation"})],r=[];return t=class{async parseInput(e,t,n){const r=e.commandName?.toLowerCase().includes("replace")?"replace":"push";return{...await ks(e.args,t,n,`${r} url`),mode:r}}async execute(e,t){const{url:n,title:r,state:i,mode:a}=e;"push"===a?window.history.pushState(i||null,"",n):window.history.replaceState(i||null,"",n),r&&(document.title=r);return Qo(window,"push"===a?"pushurl":"replaceurl",{url:n,title:r,state:i}),{url:n,title:r,mode:a}}},ki(t,"HistoryCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})();const zs=Ti(ws),xs=Ti(ws);function Es(e,t){if("boolean"==typeof e)return e;if("function"==typeof e)return!0;if(e instanceof Promise)throw new Error("Condition must be awaited - use await in the condition expression");if("string"==typeof e){if("me"===e)return Boolean(t.me);if("it"===e)return Boolean(t.it);if("you"===e)return Boolean(t.you);const n=Ia(e,t);return void 0!==n?Boolean(n):Boolean(e)}return Boolean(e)}const Ss=Ti((()=>{let e,t,n=[Si({description:"Conditional execution based on boolean expressions",syntax:["if <condition> then <commands>","if <condition> then <commands> else <commands>","unless <condition> <commands>"],examples:["if x > 5 then add .active","if user.isAdmin then show #adminPanel else hide #adminPanel","unless user.isLoggedIn showLoginForm"],sideEffects:["conditional-execution"],aliases:["unless"]}),Ei({name:"if",category:"control-flow"})],r=[];return t=class{async parseInput(e,t,n){const r="unless"===e.commandName?.toLowerCase()?"unless":"if";if(!e.args||0===e.args.length)throw new Error(`${r} command requires a condition to evaluate`);let i,a;if("unless"===r){if(e.args.length<2)throw new Error("unless command requires a condition and at least one command");i=e.args.slice(1)}else if(e.args.length>=2&&e.args[1]?(i=e.args[1],a=e.args.length>=3?e.args[2]:void 0):e.modifiers?.then&&(i=e.modifiers.then,a=e.modifiers.else),!i)throw new Error('if command requires "then" branch with commands');return{mode:r,condition:await t.evaluate(e.args[0],n),thenCommands:i,elseCommands:a}}async execute(e,t){const{mode:n,condition:r,thenCommands:i,elseCommands:a}=e,o=Es(r,t);let s,l;return("unless"===n?!o:o)?(s="then",l=await this.executeCommandsOrBlock(i,t),"unless"===n&&Object.assign(t,{it:l})):a&&"if"===n?(s="else",l=await this.executeCommandsOrBlock(a,t)):s="none",{mode:n,conditionResult:o,executedBranch:s,result:l}}async executeCommandsOrBlock(e,t){return"block"===e?.type?this.executeBlock(e,t):Array.isArray(e)?this.executeCommands(e,t):e}async executeBlock(e,t){const n=t.locals.get("_runtimeExecute");if(!n)throw new Error("Runtime execute function not available");let r;if(e.commands?.length)for(const i of e.commands)r=await n(i,t);return r}async executeCommands(e,t){let n;for(const r of e)n=r?.execute?await r.execute(t):"function"==typeof r?await r():r;return n}},ki(t,"ConditionalCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})()),Ts=Ss,Cs=Ss;let As=(()=>{let e,t,n=[Si({description:"Iteration in hyperscript - for-in, counted, conditional, event-driven, and infinite loops",syntax:["repeat for <var> in <collection> { <commands> }","repeat <count> times { <commands> }","repeat while <condition> { <commands> }","repeat until <condition> { <commands> }","repeat forever { <commands> }"],examples:["repeat for item in items { log item }",'repeat 5 times { log "hello" }'],sideEffects:["iteration","conditional-execution"]}),Ei({name:"repeat",category:"control-flow"})],r=[];return t=class{async parseInput(e,t,n){let r;if(e.modifiers?.index){const i=await t.evaluate(e.modifiers.index,n);"string"==typeof i&&(r=i)}let i=e.modifiers?.block||e.modifiers?.commands;if(!i)for(let t=e.args.length-1;t>=0;t--){const n=e.args[t];if("block"===n?.type&&n.commands){i=n;break}}const a=e.args[0],o="identifier"===a?.type?a.name:null;if("for"===o||e.modifiers?.for){const a=e.args[1],o=a?.value||a?.name,s=e.args[2]?await t.evaluate(e.args[2],n):void 0;if(!o||void 0===s)throw new Error("for loops require variable and collection");return{type:"for",variable:o,collection:Array.isArray(s)?s:[s],indexVariable:r,commands:i}}if("times"===o||e.modifiers?.times){const a=e.args[1],o=a?await t.evaluate(a,n):void 0,s="number"==typeof o?o:parseInt(String(o),10);if(isNaN(s))throw new Error("times loops require a count number");return{type:"times",count:s,indexVariable:r,commands:i}}if("while"===o||e.modifiers?.while){const t=e.args[1]||e.modifiers?.while;if(!t)throw new Error("while loops require a condition");return{type:"while",condition:t,indexVariable:r,commands:i}}if("until"===o&&e.modifiers?.from||"until-event"===o){const a=e.args[1],o=a?.value||a?.name;if(!o)throw new Error("until-event loops require an event name");let s=n.me;if(e.args[2]){const r=await t.evaluate(e.args[2],n);r instanceof EventTarget?s=r:"document"===r&&(s=document)}return{type:"until-event",eventName:o,eventTarget:s,indexVariable:r,commands:i}}if("until"===o||e.modifiers?.until){const t=e.args[1]||e.modifiers?.until;if(!t)throw new Error("until loops require a condition");return{type:"until",condition:t,indexVariable:r,commands:i}}if("forever"===o||e.modifiers?.forever)return{type:"forever",indexVariable:r,commands:i};throw new Error("repeat command requires a loop type (for/times/while/until/forever)")}async execute(e,t){const{type:n,variable:r,collection:i,condition:a,count:o,indexVariable:s,commands:l,eventName:c,eventTarget:u}=e;let p,m;switch(n){case"for":({config:p,iterCtx:m}=function(e,t,n){return{config:{type:"for",shouldContinue:e=>e.index<(e.collection?.length??0),beforeIteration:(e,t)=>{e.item=e.collection?.[e.index],e.itemVariable&&t.locals&&t.locals.set(e.itemVariable,e.item)}},iterCtx:{index:0,collection:e,itemVariable:t,indexVariable:n}}}(i,r,s));break;case"times":({config:p,iterCtx:m}=function(e,t){return{config:{type:"times",shouldContinue:e=>e.index<(e.count??0),beforeIteration:(e,t)=>{Object.assign(t,{it:e.index+1})}},iterCtx:{index:0,count:e,indexVariable:t}}}(o,s));break;case"while":({config:p,iterCtx:m}=function(e,t,n,r){return{config:{type:"while",shouldContinue:()=>t(e,n)},iterCtx:{index:0,conditionExpr:e,indexVariable:r}}}(a,Es,t,s));break;case"until":({config:p,iterCtx:m}=function(e,t,n,r){return{config:{type:"until",shouldContinue:()=>!t(e,n)},iterCtx:{index:0,conditionExpr:e,indexVariable:r}}}(a,Es,t,s));break;case"until-event":({config:p,iterCtx:m}=function(e,t,n){const r={index:0,eventFired:!1,indexVariable:n};return{config:{type:"until-event",shouldContinue:e=>!e.eventFired,eventSetup:{eventName:e,target:t,onEvent:()=>{r.eventFired=!0}}},iterCtx:r}}(c,u,s));break;case"forever":({config:p,iterCtx:m}=function(e,t=1e4){return{config:{type:"forever",maxIterations:t,shouldContinue:()=>!0},iterCtx:{index:0,indexVariable:e}}}(s));break;default:throw new Error(`Unknown repeat type: ${n}`)}try{const e=await async function(e,t,n,r,i){const a=e.maxIterations??1e4;let o,s=0,l=!1;e.eventSetup&&e.eventSetup.target.addEventListener(e.eventSetup.eventName,e.eventSetup.onEvent,{once:!0});try{for(;s<a&&await e.shouldContinue(r);){e.beforeIteration&&await e.beforeIteration(r,n),r.indexVariable&&n.locals&&n.locals.set(r.indexVariable,s);try{o=await i(t,n)}catch(t){if(t instanceof Error){if(t.message.includes("BREAK")){l=!0;break}if(t.message.includes("CONTINUE")){s++,r.index=s,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0));continue}}throw t}s++,r.index=s,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0))}}finally{e.eventSetup&&!r.eventFired&&e.eventSetup.target.removeEventListener(e.eventSetup.eventName,e.eventSetup.onEvent)}return{iterations:s,lastResult:o,interrupted:l}}(p,l,t,m,this.executeCommands.bind(this));return Object.assign(t,{it:e.lastResult}),{type:n,iterations:e.iterations,completed:!e.interrupted,lastResult:e.lastResult,interrupted:e.interrupted}}catch(e){if(e instanceof Error&&(e.message.includes("BREAK")||e.message.includes("CONTINUE")))return{type:n,iterations:0,completed:!0,interrupted:e.message.includes("BREAK")};throw e}}async executeCommands(e,t){if(e&&"object"==typeof e&&"block"===e.type){const n=e,r=t.locals.get("_runtimeExecute");if(!r)throw new Error("Runtime execute function not available");let i;if(n.commands)for(const e of n.commands)i=await r(e,t);return i}if(Array.isArray(e)){let n;for(const r of e)n="function"==typeof r?await r(t):r&&"function"==typeof r.execute?await r.execute(t):r;return n}return"function"==typeof e?await e(t):e}},ki(t,"RepeatCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})();const js=Ti(As);class Ls{async parseInput(e,t,n){return{signalType:this.signalType}}async execute(e,t){const n=new Error(this.errorMessage);throw n[this.errorFlag]=!0,"exit"===this.signalType&&(n.returnValue=void 0,n.timestamp=Date.now()),n}}let Ps=(()=>{let e,t,n=[Si({description:"Exit from the current loop (repeat, for, while, until)",syntax:["break"],examples:["break","if found then break","repeat for item in items { if item == target then break }"],sideEffects:["control-flow"]}),Ei({name:"break",category:"control-flow"})],r=[],i=Ls;return t=class extends i{constructor(){super(...arguments),this.signalType="break",this.errorMessage="BREAK_LOOP",this.errorFlag="isBreak"}},ki(t,"BreakCommand"),(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:a},null,r),t=e.value,a&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a}),bi(t,r)})(),t})();const Is=Ti(Ps);let Ns=(()=>{let e,t,n=[Si({description:"Skip to the next iteration of the current loop",syntax:["continue"],examples:["continue","if item.isInvalid then continue","repeat for item in items { if item.skip then continue; process item }"],sideEffects:["control-flow"]}),Ei({name:"continue",category:"control-flow"})],r=[],i=Ls;return t=class extends i{constructor(){super(...arguments),this.signalType="continue",this.errorMessage="CONTINUE_LOOP",this.errorFlag="isContinue"}},ki(t,"ContinueCommand"),(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:a},null,r),t=e.value,a&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a}),bi(t,r)})(),t})();const Os=Ti(Ns);const Rs=Ti((()=>{let e,t,n=[Si({description:"Stop command execution or prevent event defaults",syntax:["halt","halt the event"],examples:["halt","halt the event","if error then halt",'on click halt the event then log "clicked"'],sideEffects:["control-flow","event-prevention"]}),Ei({name:"halt",category:"control-flow"})],r=[];return t=class{async parseInput(e,t,n){if(e.args&&e.args.length>0){const r=e.args[0],i=e.args.length>1?e.args[1]:null;if("identifier"===r.type&&"the"===r.name&&i&&"identifier"===i.type&&"event"===i.name)return{target:n.event};return{target:await t.evaluate(e.args[0],n)}}return{}}async execute(e,t){let n=e.target;if(("the"===n&&t.event||"object"==typeof n&&null!==n&&"the"===n.target&&t.event)&&(n=t.event),this.isEvent(n)){const e=n;return e.preventDefault(),e.stopPropagation(),{halted:!0,timestamp:Date.now(),eventHalted:!0}}"halted"in t&&(t.halted=!0);const r=new Error("HALT_EXECUTION");throw r.isHalt=!0,r}isEvent(e){return null!==e&&"object"==typeof e&&"preventDefault"in e&&"stopPropagation"in e}},ki(t,"HaltCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})());const Ms=Ti((()=>{let e,t,n=[Si({description:"Return a value from a command sequence or function, terminating execution",syntax:["return","return <value>"],examples:["return","return 42","return user.name","if found then return result"],sideEffects:["control-flow","context-mutation"]}),Ei({name:"return",category:"control-flow"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args||0===e.args.length)return{value:void 0};return{value:await t.evaluate(e.args[0],n)}}async execute(e,t){const{value:n}=e;"returnValue"in t&&(t.returnValue=n),Object.assign(t,{it:n});const r=new Error("RETURN_VALUE");throw r.isReturn=!0,r.returnValue=n,r}},ki(t,"ReturnCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})());let Ws=(()=>{let e,t,n=[Si({description:"Immediately terminate execution of the current event handler or behavior",syntax:["exit"],examples:["exit","if no draggedItem exit","on click if disabled exit"],sideEffects:["control-flow"]}),Ei({name:"exit",category:"control-flow"})],r=[],i=Ls;return t=class extends i{constructor(){super(...arguments),this.signalType="exit",this.errorMessage="EXIT_COMMAND",this.errorFlag="isExit"}},ki(t,"ExitCommand"),(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:a},null,r),t=e.value,a&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a}),bi(t,r)})(),t})();const $s=Ti(Ws);const Hs=Ti((()=>{let e,t,n=[Si({description:"Evaluate an expression and store the result in the it variable",syntax:["call <expression>"],examples:["call myFunction()",'call fetch("/api/data")',"call element.focus()"],sideEffects:["function-execution","context-mutation"]}),Ei({name:"call",category:"execution"})],r=[];return t=class{parseInput(e,t,n){if(!e.args?.length)throw new Error("call command requires an expression");return Promise.resolve({expression:e.args[0]})}async execute(e,t){const{expression:n}=e,r=t.locals?.get("__evaluator");if(!r)throw new Error("[CALL.execute] No evaluator available in context");const i=await r.evaluate(n,t);let a,o,s=!1;return"function"==typeof i?(o="function",a=i(),a instanceof Promise&&(s=!0,a=await a)):i instanceof Promise?(o="promise",s=!0,a=await i):(o="value",a=i),Object.assign(t,{it:a,result:a}),{result:a,wasAsync:s,expressionType:o}}},ki(t,"CallCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})());const qs=Ti((()=>{let e,t,n=[Si({description:"Add content to the end of a string, array, or HTML element",syntax:["append <content>","append <content> to <target>"],examples:['append "Hello"','append "World" to greeting',"append item to myArray",'append "<p>New</p>" to #content'],sideEffects:["data-mutation","dom-mutation"]}),Ei({name:"append",category:"content"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw new Error("append requires content");const r=await t.evaluate(e.args[0],n);let i;return e.modifiers?.to?i=await t.evaluate(e.modifiers.to,n):e.target&&(i=e.target),{content:r,target:i}}async execute(e,t){const{content:n,target:r}=e,i=String(n);if(!r)return void 0===t.it?Object.assign(t,{it:i}):Object.assign(t,{it:String(t.it)+i}),{result:t.it,targetType:"result"};if("string"==typeof r){if(r.startsWith("#")||r.startsWith(".")||r.includes("[")){const e=this.resolveDOMElement(r);return e.innerHTML+=i,{result:e,targetType:"element",target:e}}if("me"===r||"it"===r||"you"===r){const e=this.resolveContextRef(r,t);if(Ci(e))return e.innerHTML+=i,{result:e,targetType:"element",target:e}}const e=Ia(r,t);if(void 0!==e){if(Array.isArray(e))return e.push(n),{result:e,targetType:"array",target:r};const a=(null==e?"":String(e))+i;return Na(r,a,t),{result:a,targetType:"variable",target:r}}return Na(r,i,t),{result:i,targetType:"variable",target:r}}if(Array.isArray(r))return r.push(n),{result:r,targetType:"array"};if(Ci(r))return r.innerHTML+=i,{result:r,targetType:"element",target:r};{const e=String(r)+i;return Object.assign(t,{it:e}),{result:e,targetType:"string"}}}resolveDOMElement(e){if("undefined"==typeof document)throw new Error("DOM not available");const t=document.querySelector(e);if(!t)throw new Error(`Element not found: ${e}`);return t}resolveContextRef(e,t){switch(e){case"me":return t.me;case"it":return t.it;case"you":return t.you;default:throw new Error(`Unknown context ref: ${e}`)}}},ki(t,"AppendCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})());const Ds=Ti((()=>{let e,t,n=[Si({description:"Animate CSS properties using CSS transitions",syntax:"transition <property> to <value> [over <duration>] [with <timing>]",examples:["transition opacity to 0.5","transition left to 100px over 500ms","transition background-color to red over 1s with ease-in-out"],sideEffects:["style-change","timing"]}),Ei({name:"transition",category:"animation"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw new Error("transition requires property and value");let r,i;const a=await t.evaluate(e.args[0],n);if(Ci(a)||"string"==typeof a&&/^[#.]|^(?:me|it|you)$/.test(a)?(i=a,r=String(await t.evaluate(e.args[1],n))):r=String(a),!r)throw new Error("transition requires a CSS property");if(!e.modifiers?.to)throw new Error('transition requires "to <value>"');let o=await t.evaluate(e.modifiers.to,n);void 0===o&&"identifier"===e.modifiers.to.type&&(o=e.modifiers.to.name);const s={property:r,value:o};return void 0!==i&&(s.target=i),e.modifiers?.over&&(s.duration=await t.evaluate(e.modifiers.over,n)),e.modifiers?.with&&(s.timingFunction=String(await t.evaluate(e.modifiers.with,n))),s}async execute(e,t){let{property:n}=e;const{target:r,value:i,duration:a,timingFunction:o}=e;n.startsWith("*")&&(n=n.substring(1)),n=n.replace(/([A-Z])/g,"-$1").toLowerCase();const s=Ai(r,t),l=la(a,300),c=getComputedStyle(s).getPropertyValue(n),u=s.style.transition,p=`${n} ${l}ms ${o||"ease"}`;s.style.transition=u?`${u}, ${p}`:p;let m=String(i),d=!1;if("initial"===m||"inherit"===m||"unset"===m||"revert"===m){const e=s.style.getPropertyValue(n);s.style.removeProperty(n),m=getComputedStyle(s).getPropertyValue(n),e&&s.style.setProperty(n,e),d=!0}s.style.setProperty(n,m);const h=await function(e,t,n){return new Promise(r=>{const i=n=>{n.target===e&&n.propertyName===t&&o({completed:!0,cancelled:!1})},a=n=>{n.target===e&&n.propertyName===t&&o({completed:!1,cancelled:!0})},o=ns(()=>{e.removeEventListener("transitionend",i),e.removeEventListener("transitioncancel",a),clearTimeout(s)},r);e.addEventListener("transitionend",i),e.addEventListener("transitioncancel",a);const s=setTimeout(()=>{o({completed:!0,cancelled:!1})},n+50)})}(s,n,l);return s.style.transition=u,d&&s.style.removeProperty(n),Object.assign(t,{it:s}),{element:s,property:n,fromValue:c,toValue:m,duration:l,completed:h.completed}}},ki(t,"TransitionCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})());const _s=Ti((()=>{let e,t,n=[Si({description:"Measure DOM element dimensions, positions, and properties",syntax:["measure","measure <property>","measure <target> <property>"],examples:["measure","measure width","measure #element height","measure x and set dragX"],sideEffects:["data-mutation"]}),Ei({name:"measure",category:"animation"})],r=[];return t=class{async parseInput(e,t,n){let r,i,a;if(e.args?.length){const a=e.args[0];if("identifier"===a.type&&a.name){const o=a.name.toLowerCase();if("me"===o||"it"===o||"you"===o){const o=await t.evaluate(a,n);if(Ci(o)&&(r=o,e.args.length>1)){const r=e.args[1];i="identifier"===r.type?r.name:String(await t.evaluate(r,n))}}else i=a.name}else{const o=await t.evaluate(a,n);if(Ci(o)||"string"==typeof o&&/^[#.]/.test(o)){if(r=o,e.args.length>1){const r=e.args[1];i="identifier"===r.type?r.name:String(await t.evaluate(r,n))}}else"string"==typeof o&&(i=o)}}e.modifiers?.set&&(a=String(await t.evaluate(e.modifiers.set,n)));const o={};return void 0!==r&&(o.target=r),void 0!==i&&(o.property=i),void 0!==a&&(o.variable=a),o}async execute(e,t){const n=Ai(e.target,t),r=e.property||"width",i=this.getMeasurement(n,r);return e.variable&&t.locals&&t.locals.set(e.variable,i.value),Object.assign(t,{it:i.value}),{result:i.value,wasAsync:!1,element:n,property:r,value:i.value,unit:i.unit,stored:!!e.variable}}getMeasurement(e,t){const n=getComputedStyle(e);if(t.startsWith("*")){const e=n.getPropertyValue(t.substring(1)),r=parseFloat(e);if(!isNaN(r)){const t=e.match(/([a-zA-Z%]+)$/);return{value:r,unit:t?t[1]:""}}return{value:e,unit:""}}const r=t.toLowerCase(),i=e.getBoundingClientRect(),a={width:()=>i.width,height:()=>i.height,top:()=>i.top,left:()=>i.left,right:()=>i.right,bottom:()=>i.bottom,x:()=>e.offsetLeft,y:()=>e.offsetTop,clientwidth:()=>e.clientWidth,"client-width":()=>e.clientWidth,clientheight:()=>e.clientHeight,"client-height":()=>e.clientHeight,offsetwidth:()=>e.offsetWidth,"offset-width":()=>e.offsetWidth,offsetheight:()=>e.offsetHeight,"offset-height":()=>e.offsetHeight,scrollwidth:()=>e.scrollWidth,"scroll-width":()=>e.scrollWidth,scrollheight:()=>e.scrollHeight,"scroll-height":()=>e.scrollHeight,scrolltop:()=>e.scrollTop,"scroll-top":()=>e.scrollTop,scrollleft:()=>e.scrollLeft,"scroll-left":()=>e.scrollLeft,offsettop:()=>e.offsetTop,"offset-top":()=>e.offsetTop,offsetleft:()=>e.offsetLeft,"offset-left":()=>e.offsetLeft};if(a[r])return{value:a[r](),unit:"px"};const o=n.getPropertyValue(t),s=parseFloat(o);if(!isNaN(s)){const e=o.match(/([a-zA-Z%]+)$/);return{value:s,unit:e?e[1]:"px"}}return{value:0,unit:"px"}}},ki(t,"MeasureCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})());const Vs=Ti((()=>{let e,t,n=[Si({description:"Wait for CSS transitions and animations to complete",syntax:"settle [<target>] [for <timeout>]",examples:["settle","settle #animated-element","settle for 3000"],sideEffects:["timing"]}),Ei({name:"settle",category:"animation"})],r=[];return t=class{async parseInput(e,t,n){let r,i;if(e.args&&e.args.length>0){const i=await t.evaluate(e.args[0],n);(Ci(i)||"string"==typeof i&&(i.startsWith("#")||i.startsWith(".")||"me"===i||"it"===i||"you"===i))&&(r=i)}e.modifiers?.for&&(i=await t.evaluate(e.modifiers.for,n));const a={};return void 0!==r&&(a.target=r),void 0!==i&&(a.timeout=i),a}async execute(e,t){const{target:n,timeout:r}=e,i=Ai(n,t),a=la(r,5e3),o=Date.now(),s=getComputedStyle(i),l=ua(s.transitionDuration),c=ua(s.transitionDelay),u=ua(s.animationDuration),p=ua(s.animationDelay),m=pa(l,c),d=pa(u,p),h=Math.max(m,d),f=await(y=i,v=h,g=a,v<=0?Promise.resolve({completed:!0,type:"timeout"}):new Promise(e=>{const t=e=>{e.target===y&&r({completed:!0,type:"transition"})},n=e=>{e.target===y&&r({completed:!0,type:"animation"})},r=ns(()=>{y.removeEventListener("transitionend",t),y.removeEventListener("animationend",n),clearTimeout(i),clearTimeout(a)},e);y.addEventListener("transitionend",t),y.addEventListener("animationend",n);const i=setTimeout(()=>{r({completed:!0,type:"timeout"})},v+50),a=setTimeout(()=>{r({completed:!1,type:"timeout"})},g)}));var y,v,g;const b=Date.now()-o;return Object.assign(t,{it:i}),{element:i,settled:f.completed,timeout:a,duration:b}}},ki(t,"SettleCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})());const Bs=Ti((()=>{let e,t,n=[Si({description:"Execute inline JavaScript code with access to hyperscript context",syntax:["js <code> end","js(param1, param2) <code> end"],examples:['js console.log("Hello") end',"js(x, y) return x + y end",'js me.style.color = "red" end'],sideEffects:["code-execution","data-mutation"]}),Ei({name:"js",category:"advanced"})],r=[];return t=class{async parseInput(e,t,n){let r,i;if(0===e.args.length)throw new Error("js command requires JavaScript code");const a=e.args[0],o=e.args[1];if(a&&"literal"===a.type&&"string"==typeof a.value)r=a.value;else{if(!a||void 0===a.value)throw new Error("js command requires JavaScript code");r=String(a.value)}o&&"arrayLiteral"===o.type&&Array.isArray(o.elements)&&(i=o.elements.map(e=>"string"==typeof e.value?e.value:String(e.value)).filter(e=>e&&e.length>0));const s={code:r};return i&&i.length>0&&(s.parameters=i),s}async execute(e,t){const{code:n,parameters:r=[]}=e;if(!n.trim())return{result:void 0,executed:!1,codeLength:n.length,parameters:r,preserveArrayResult:!0};try{const e=this.createExecutionContext(t,r),i=new Function(...Object.keys(e),n),a=await i(...Object.values(e));return void 0!==a&&Object.assign(t,{it:a}),{result:a,executed:!0,codeLength:n.length,parameters:r,preserveArrayResult:!0}}catch(e){throw new Error(`JavaScript execution failed: ${e instanceof Error?e.message:"Unknown error"}`)}}createExecutionContext(e,t){return{me:e.me,it:e.it,you:e.you,locals:e.locals,globals:e.globals,variables:e.variables,console:console,document:"undefined"!=typeof document?document:void 0,window:"undefined"!=typeof window?window:void 0,...t.reduce((t,n)=>{let r=e.locals?.get(n);return void 0===r&&(r=e.variables?.get(n)),void 0===r&&(r=e[n]),t[n]=r,t},{})}}},ki(t,"JsCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})());const Fs=Ti((()=>{let e,t,n=[Si({description:"Execute commands asynchronously without blocking",syntax:["async <command> [<command> ...]"],examples:["async command1 command2","async fetchData processData","async animateIn showContent"],sideEffects:["async-execution"]}),Ei({name:"async",category:"advanced"})],r=[];return t=class{async parseInput(e,t,n){if(e.args.length<1)throw new Error("async command requires at least one command to execute");return{commands:e.args}}async execute(e,t){const{commands:n}=e,r=Date.now();try{const e=await this.executeCommandsAsync(t,n),i=Date.now()-r;return e.length>0&&Object.assign(t,{it:e[e.length-1]}),{commandCount:n.length,results:e,executed:!0,duration:i}}catch(e){throw new Error(`Async command execution failed: ${e instanceof Error?e.message:"Unknown error"}`)}}async executeCommandsAsync(e,t){const n=[];for(let r=0;r<t.length;r++){const i=t[r];try{const t=await this.executeCommand(i,e);n.push(t),Object.assign(e,{it:t})}catch(e){const n=this.getCommandName(i);throw new Error(`Command '${n}' (${r+1}/${t.length}) failed: ${e instanceof Error?e.message:"Unknown error"}`)}}return n}async executeCommand(e,t){if("function"==typeof e)return await e(t);if(e&&"object"==typeof e&&"function"==typeof e.execute)return await e.execute(t);throw new Error("Invalid command: must be a function or object with execute method")}getCommandName(e){return"function"==typeof e?e.name||"anonymous function":e&&"object"==typeof e?e.name||"unnamed command":"unknown"}},ki(t,"AsyncCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})());const Us=Ti((()=>{let e,t,n=[Si({description:"Set a value only if it doesn't already exist",syntax:["default <expression> to <expression>"],examples:['default myVar to "fallback"','default @data-theme to "light"','default my innerHTML to "No content"'],sideEffects:["data-mutation","dom-mutation"]}),Ei({name:"default",category:"data"})],r=[];return t=class{async parseInput(e,t,n){if(e.args.length<1)throw new Error("default command requires a target");const r=await t.evaluate(e.args[0],n);let i;if(e.modifiers?.to)i=await t.evaluate(e.modifiers.to,n);else{if(!(e.args.length>=2))throw new Error('default command requires a value (use "to <value>")');i=await t.evaluate(e.args[1],n)}return{target:r,value:i}}async execute(e,t){const{target:n,value:r}=e;if("string"==typeof n){if(n.startsWith("@"))return this.defaultAttribute(t,n.substring(1),r);const e=n.match(/^(my|its?|your?)\s+(.+)$/);if(e){const[,n,i]=e;return this.defaultElementProperty(t,n,i,r)}return this.defaultVariable(t,n,r)}if(Ci(n))return this.defaultElementValue(t,n,r);throw new Error("Invalid target type: "+typeof n)}defaultVariable(e,t,n){const r=Ia(t,e);return void 0!==r?{target:t,value:n,wasSet:!1,existingValue:r,targetType:"variable"}:(Na(t,n,e),Object.assign(e,{it:n}),{target:t,value:n,wasSet:!0,targetType:"variable"})}defaultAttribute(e,t,n){if(!e.me)throw new Error("No element context available for attribute default");const r=e.me.getAttribute(t);return null!==r?{target:`@${t}`,value:n,wasSet:!1,existingValue:r,targetType:"attribute"}:(e.me.setAttribute(t,String(n)),Object.assign(e,{it:n}),{target:`@${t}`,value:n,wasSet:!0,targetType:"attribute"})}defaultElementProperty(e,t,n,r){const i=Pi(t,e),a=function(e,t){if(t.startsWith("@"))return e.getAttribute(t.substring(1));switch(t){case"textContent":return e.textContent;case"innerHTML":return e.innerHTML;case"innerText":return e.innerText;case"id":return e.id;case"className":return e.className;case"value":return"value"in e?e.value:void 0;case"checked":return"checked"in e?e.checked:void 0}if(t.includes(".")){const n=t.split(".");let r=e;for(const e of n){if(null==r)break;r=r[e]}return r}return t.includes("-")||t in e.style?e.style.getPropertyValue(t)||e.style[t]:e[t]}(i,n),o=`${t} ${n}`;return va(a)?(ya(i,n,r),Object.assign(e,{it:r}),{target:o,value:r,wasSet:!0,targetType:"property"}):{target:o,value:r,wasSet:!1,existingValue:a,targetType:"property"}}defaultElementValue(e,t,n){const r=function(e){return"value"in e?e.value:e.textContent}(t);return va(r)?(function(e,t){"value"in e?e.value=String(t):e.textContent=String(t)}(t,n),Object.assign(e,{it:n}),{target:"element",value:n,wasSet:!0,targetType:"element"}):{target:"element",value:n,wasSet:!1,existingValue:r,targetType:"element"}}},ki(t,"DefaultCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})());class Ks{constructor(){this.name="pseudo-command"}get metadata(){return Ks.metadata}async parseInput(e,t,n){if(1===e.args.length&&"objectLiteral"===e.args[0].type){const r=e.args[0].properties||[];let i,a,o="",s=[];for(const e of r){const r=e.key?.name||e.key?.value,l=e.value;switch(r){case"methodName":o=l?.value||String(await t.evaluate(l,n));break;case"methodArgs":"arrayLiteral"===l?.type&&l.elements?s=await Promise.all(l.elements.map(e=>t.evaluate(e,n))):"literal"===l?.type&&Array.isArray(l.value)&&(s=await Promise.all(l.value.map(e=>t.evaluate(e,n))));break;case"preposition":const e=l?.value;e&&"null"!==e&&(i=e);break;case"target":case"targetExpression":a=await t.evaluate(l,n)}}if(!o)throw new Error("pseudo-command requires method name");if(null==a)throw new Error("pseudo-command requires a target expression");return{methodName:o,methodArgs:s,preposition:i,targetExpression:a}}if(e.args.length<2)throw new Error("pseudo-command requires method name and target expression");const r=String(await t.evaluate(e.args[0],n)),i=Array.isArray(e.args[1])?await Promise.all(e.args[1].map(e=>t.evaluate(e,n))):[];let a,o;const s=["from","on","with","into","at","to"];for(const r of s)if(e.modifiers?.[r]){o=r,a=await t.evaluate(e.modifiers[r],n);break}if(!a&&e.args.length>=3&&(a=await t.evaluate(e.args[2],n)),!a)throw new Error("pseudo-command requires a target expression");return{methodName:r,methodArgs:i,preposition:o,targetExpression:a}}async execute(e,t){const{methodName:n,methodArgs:r,targetExpression:i}=e;try{const e=await this.resolveTarget(i,t);if(null==e)throw new Error(`Target expression resolved to ${e}`);const a=this.resolveMethod(e,n);if(!a)throw new Error(`Method "${n}" not found on target object`);if("function"!=typeof a)throw new Error(`"${n}" is not a function (it's a ${typeof a})`);const o=await this.executeMethod(a,e,r);return t.locals.set("result",o),Object.assign(t,{it:o}),{result:o,methodName:n,target:e}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`Pseudo-command failed: ${t}`)}}async resolveTarget(e,t){return"object"==typeof e&&null!==e?e:"string"==typeof e?t.locals.has(e)?t.locals.get(e):t.variables?.has(e)?t.variables.get(e):t.globals.has(e)?t.globals.get(e):"me"===e&&t.me?t.me:"it"===e&&t.it?t.it:"document"===e?"undefined"!=typeof document?document:null:"window"===e?"undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null:this.resolvePropertyPath(e,t):e}resolvePropertyPath(e,t){const n=e.split(".");let r="undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null;t.locals.has(n[0])?(r=t.locals.get(n[0]),n.shift()):t.variables?.has(n[0])?(r=t.variables.get(n[0]),n.shift()):t.globals.has(n[0])&&(r=t.globals.get(n[0]),n.shift());for(const e of n){if(null==r)return null;r=r[e]}return r}resolveMethod(e,t){if(!e)return null;if(t in e)return e[t];const n=t.split(".");let r=e;for(let e=0;e<n.length;e++){const t=n[e];if(null==r)return null;if(!(t in r))return null;if(r=r[t],e===n.length-1&&"function"==typeof r)return r}return null}async executeMethod(e,t,n){try{const r=e.apply(t,n);return r&&"object"==typeof r&&"then"in r?await r:r}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`Method execution failed: ${t}`)}}}Ks.metadata={description:"Treat a method on an object as a top-level command",syntax:["<method>(<args>) [(to|on|with|into|from|at)] <expression>"],examples:['getElementById("d1") from the document',"reload() the location of the window",'setAttribute("foo", "bar") on me',"foo() on me"],category:"execution",sideEffects:["method-execution"]};const Gs=Ti((()=>{let e,t,n=[Si({description:"Execute commands in the context of target elements",syntax:["tell <target> <command> [<command> ...]"],examples:["tell #sidebar hide","tell .buttons add .disabled","tell closest <form/> submit"],sideEffects:["context-switching","command-execution"]}),Ei({name:"tell",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){if(e.args.length<2)throw new Error("tell command requires a target and at least one command");return{target:await t.evaluate(e.args[0],n),commands:e.args.slice(1)}}async execute(e,t){const{target:n,commands:r}=e,i=ji(n,t);if(0===i.length)throw new Error("tell command found no target elements");const a=t.locals.get("_runtimeExecute"),o=[];for(const e of i){const n={...t,me:e,you:e};for(const e of r)try{const t=await this.executeCommand(e,n,a);o.push(t),Object.assign(n,{it:t})}catch(e){throw new Error(`Command execution failed in tell block: ${e instanceof Error?e.message:"Unknown error"}`)}}return{targetElements:i,commandResults:o,executionCount:i.length*r.length}}async executeCommand(e,t,n){if(e&&"object"==typeof e&&"command"===e.type&&n)return await n(e,t);if("function"==typeof e)return await e(t);if(e&&"object"==typeof e&&"function"==typeof e.execute)return await e.execute(t);throw new Error("Invalid command: must be a function or object with execute method")}},ki(t,"TellCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})());let Qs=(()=>{let e,t,n=[Si({description:"Copy text or element content to the clipboard",syntax:["copy <source>","copy <source> to clipboard"],examples:['copy "Hello World"',"copy #code-snippet","copy my textContent"],sideEffects:["clipboard-write","custom-events"]}),Ei({name:"copy",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){if(e.args.length<1)throw new Error("copy command requires a source (text or element)");const r=await t.evaluate(e.args[0],n);let i="text";if(e.modifiers?.format){const r=await t.evaluate(e.modifiers.format,n);"html"!==r&&"text"!==r||(i=r)}return{source:r,format:i}}async execute(e,t){const{source:n,format:r="text"}=e,i=this.extractText(n,r,t);if("undefined"!=typeof navigator&&navigator.clipboard)try{return await navigator.clipboard.writeText(i),this.dispatchCopyEvent(t,"copy:success",{text:i,method:"clipboard-api"}),{success:!0,text:i,format:r,method:"clipboard-api"}}catch{}try{if(this.copyUsingExecCommand(i))return this.dispatchCopyEvent(t,"copy:success",{text:i,method:"execCommand"}),{success:!0,text:i,format:r,method:"execCommand"}}catch{}return this.dispatchCopyEvent(t,"copy:error",{text:i,error:"All copy methods failed"}),{success:!1,text:i,format:r,method:"fallback"}}extractText(e,t,n){if("string"==typeof e)return e;if(Ci(e))return"html"===t?e.outerHTML:e.textContent||"";if(e===n.me&&Ci(n.me)){const e=n.me;return"html"===t?e.outerHTML:e.textContent||""}return String(e)}copyUsingExecCommand(e){if("undefined"==typeof document)return!1;const t=document.createElement("textarea");t.value=e,t.style.cssText="position:fixed;top:0;left:-9999px",t.setAttribute("readonly",""),document.body.appendChild(t);try{t.select(),t.setSelectionRange(0,e.length);const n=document.execCommand("copy");return document.body.removeChild(t),n}catch{return t.parentNode?.removeChild(t),!1}}dispatchCopyEvent(e,t,n){if(Ci(e.me)){const r=new CustomEvent(t,{detail:n,bubbles:!0,cancelable:!1});e.me.dispatchEvent(r)}}},ki(t,"CopyCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})();const Js=Ti(Qs);const Ys=Ti((()=>{let e,t,n=[Si({description:"Select a random element from a collection",syntax:["pick <item1>, <item2>, ...","pick from <array>"],examples:['pick "red", "green", "blue"',"pick from colors","pick 1, 2, 3, 4, 5"],sideEffects:["random-selection"]}),Ei({name:"pick",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){if(e.modifiers?.from){const r=await t.evaluate(e.modifiers.from,n);if(!Array.isArray(r))throw new Error("pick from requires an array");if(0===r.length)throw new Error("Cannot pick from empty array");return{array:r}}if(0===e.args.length)throw new Error("pick command requires items to choose from");return{items:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}}async execute(e,t){const{items:n,array:r}=e,i=n||r,a=n?"items":"array",o=Math.floor(Math.random()*i.length),s=i[o];return Object.assign(t,{it:s}),{selectedItem:s,selectedIndex:o,sourceLength:i.length,sourceType:a}}},ki(t,"PickCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})());const Zs=Ti((()=>{let e,t,n=[Si({description:"Throw an error with a specified message",syntax:["throw <message>"],examples:['throw "Invalid input"','if not valid then throw "Validation failed"'],sideEffects:["error-throwing","execution-termination"]}),Ei({name:"throw",category:"control-flow"})],r=[];return t=class{async parseInput(e,t,n){if(e.args.length<1)throw new Error("throw command requires a message or error object");return{message:await t.evaluate(e.args[0],n)}}async execute(e,t){const{message:n}=e;let r;throw r=n instanceof Error?n:"string"==typeof n?new Error(n):new Error(String(n)),r}},ki(t,"ThrowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})());let Xs=(()=>{let e,t,n=[Si({description:"Debug output for expressions with type information",syntax:["beep!","beep! <expression>","beep! <expression>, <expression>, ..."],examples:["beep!","beep! myValue","beep! me.id, me.className"],sideEffects:["console-output","debugging"]}),Ei({name:"beep",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){if(0===e.args.length)return{expressions:[]};return{expressions:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}}async execute(e,t){const n=e.expressions||[];if(0===n.length)return this.debugContext(t),{expressionCount:0,debugged:!0,outputs:[]};const r=[];console.group("🔔 beep! Debug Output");for(const e of n){const t=this.debugExpression(e);r.push(t),console.log("Value:",e),console.log("Type:",t.type),console.log("Representation:",t.representation),console.log("---")}return console.groupEnd(),{expressionCount:n.length,debugged:!0,outputs:r}}debugContext(e){console.group("🔔 beep! Context Debug"),console.log("me:",e.me),console.log("it:",e.it),console.log("you:",e.you),console.log("locals:",e.locals),console.log("globals:",e.globals),console.log("variables:",e.variables),console.groupEnd()}debugExpression(e){return{value:e,type:this.getType(e),representation:this.getRepresentation(e)}}getType(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":Ci(e)?"HTMLElement":e instanceof Element?"Element":e instanceof Node?"Node":e instanceof Error?"Error":e instanceof Date?"Date":e instanceof RegExp?"RegExp":typeof e}getRepresentation(e){if(null===e)return"null";if(void 0===e)return"undefined";if(Array.isArray(e))return`Array(${e.length}) [${e.slice(0,3).map(e=>this.getRepresentation(e)).join(", ")}${e.length>3?"...":""}]`;if(Ci(e)){const t=e;return`<${t.tagName.toLowerCase()}${t.id?`#${t.id}`:""}${t.className?`.${t.className.split(" ").join(".")}`:""}/>`}if(e instanceof Error)return`Error: ${e.message}`;if("string"==typeof e)return e.length>50?`"${e.substring(0,47)}..."`:`"${e}"`;if("object"==typeof e)try{const t=Object.keys(e);return`Object {${t.slice(0,3).join(", ")}${t.length>3?"...":""}}`}catch{return"[Object]"}return String(e)}},ki(t,"BeepCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})();const el=Ti(Xs);class tl{constructor(){this.name="install"}get metadata(){return tl.metadata}async parseInput(e,t,n){if(e.args.length<1)throw new Error("install command requires a behavior name");const r=e.args[0];let i,a,o;if(i="identifier"===r?.type&&"string"==typeof r.name?r.name:String(await t.evaluate(r,n)),!/^[A-Z][a-zA-Z0-9_]*$/.test(i))throw new Error(`Behavior name must be PascalCase (start with uppercase): "${i}"`);if(e.args.length>=2){const r=await t.evaluate(e.args[1],n);if(r&&"object"==typeof r&&!Array.isArray(r)){a=r;for(const e of Object.keys(a))if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e))throw new Error(`Invalid parameter name: "${e}"`)}}return e.modifiers?.on&&(o=await t.evaluate(e.modifiers.on,n)),{behaviorName:i,parameters:a,target:o}}async execute(e,t){const{behaviorName:n,parameters:r={},target:i}=e;try{const e=this.resolveTarget(i,t);if(0===e.length)throw new Error("No target elements found to install behavior on");if(!this.behaviorExists(n,t))throw new Error(`Behavior "${n}" is not defined. Define it using the 'behavior' keyword before installing.`);const a=[];for(const i of e){const e=await this.installBehavior(n,i,r,t);a.push(e)}return{success:!0,behaviorName:n,installedCount:a.length,instances:a}}catch(e){throw new Error(`Failed to install behavior "${n}": ${e instanceof Error?e.message:String(e)}`)}}resolveTarget(e,t){if(null==e){const e=t.me||t.locals.get("me");if(Ci(e))return[e];throw new Error('No target specified and "me" is not available in context')}if(Ci(e))return[e];if(Array.isArray(e)){const t=e.filter(e=>Ci(e));if(0===t.length)throw new Error("Target array contains no valid HTMLElements");return t}if("string"==typeof e){if("me"===e){const e=t.me||t.locals.get("me");if(Ci(e))return[e];throw new Error('"me" is not available in context')}if("undefined"!=typeof document){const t=document.querySelectorAll(e),n=Array.from(t).filter(e=>Ci(e));if(0===n.length)throw new Error(`No elements found matching selector: "${e}"`);return n}throw new Error("document is not available (not in browser environment)")}if(e&&"object"==typeof e&&"length"in e){const t=Array.from(e).filter(e=>Ci(e));if(0===t.length)throw new Error("Target collection contains no valid HTMLElements");return t}if("object"==typeof e&&"element"in e){const t=e.element;if(Ci(t))return[t]}throw new Error(`Cannot resolve target to HTMLElement(s): ${String(e)}`)}behaviorExists(e,t){const n=t.locals.get("_behaviors");if(n&&"object"==typeof n){return n.has(e)}if("undefined"!=typeof globalThis){const t=globalThis._hyperscript;if(t?.behaviors)return t.behaviors.has(e)}return!1}async installBehavior(e,t,n,r){const i=r.locals.get("_behaviors");if(i&&"object"==typeof i){const r=i;if(r.install&&"function"==typeof r.install)return await r.install(e,t,n)}if("undefined"!=typeof globalThis){const r=globalThis._hyperscript;if(r?.behaviors?.install)return await r.behaviors.install(e,t,n)}throw new Error("Behavior system not available in context")}}tl.metadata={description:"Install a behavior on an element with optional parameters",syntax:["install <BehaviorName>","install <BehaviorName> on <element>","install <BehaviorName>(param: value)","install <BehaviorName>(param: value) on <element>"],examples:["install Removable","install Draggable on #box",'install Tooltip(text: "Help", position: "top")','install Sortable(axis: "y") on .list',"install MyBehavior(foo: 42) on the first <div/>"],category:"behaviors",sideEffects:["behavior-installation","element-modification"]};let nl=(()=>{let e,t,n=[Si({description:"Move classes, attributes, and properties from one element to another",syntax:["take <property> from <source>","take <property> from <source> and put it on <target>"],examples:["take class from <#source/>","take @data-value from <.source/> and put it on <#target/>"],sideEffects:["dom-mutation","property-transfer"]}),Ei({name:"take",category:"animation"})],r=[];return t=class{async parseInput(e,t,n){if(e.args.length<3)throw new Error('take requires property, "from", and source');const r=String(await t.evaluate(e.args[0],n));if("from"!==await t.evaluate(e.args[1],n))throw new Error("take syntax: take <property> from <source>");const i=await t.evaluate(e.args[2],n);let a;if(e.args.length>=8){const r=await Promise.all([3,4,5,6].map(r=>t.evaluate(e.args[r],n)));"and"===r[0]&&"put"===r[1]&&"it"===r[2]&&"on"===r[3]&&e.args[7]&&(a=await t.evaluate(e.args[7],n))}else e.args.length>3&&(a=await t.evaluate(e.args[3],n));return!a&&e.modifiers?.on&&(a=await t.evaluate(e.modifiers.on,n)),{property:r,source:i,target:a}}async execute(e,t){const n=Ai(e.source,t),r=e.target?Ai(e.target,t):Ai(void 0,t),i=this.takeProperty(n,e.property);return this.putProperty(r,e.property,i),{targetElement:r,property:e.property,value:i}}takeProperty(e,t){const n=t.trim(),r=n.toLowerCase();if("class"===r||"classes"===r){const t=Array.from(e.classList);return e.className="",t}if(n.startsWith(".")){const t=n.substring(1);return e.classList.contains(t)?(e.classList.remove(t),t):null}if(n.startsWith("@")){const t=n.substring(1),r=e.getAttribute(t);return e.removeAttribute(t),r}if(n.startsWith("data-")){const t=e.getAttribute(n);return e.removeAttribute(n),t}if("id"===r){const t=e.id;return e.id="",t}if("title"===r){const t=e.title;return e.title="",t}if("value"===r&&"value"in e){const t=e.value;return e.value="",t}const i=n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());if(n.includes("-")||i in e.style||n in e.style){let t;return i in e.style?(t=e.style[i],e.style[i]=""):n in e.style?(t=e.style[n],e.style[n]=""):(t=e.style.getPropertyValue(n),e.style.removeProperty(n)),t}const a=e.getAttribute(t);return null!==a?(e.removeAttribute(t),a):null}putProperty(e,t,n){if(null==n)return;const r=t.trim(),i=r.toLowerCase();if("class"===i||"classes"===i)return void(Array.isArray(n)?n.forEach(t=>t&&"string"==typeof t&&e.classList.add(t)):"string"==typeof n&&(e.className=n));if(r.startsWith("."))return void(n&&e.classList.add(r.substring(1)));if(r.startsWith("@"))return void e.setAttribute(r.substring(1),String(n));if(r.startsWith("data-"))return void e.setAttribute(r,String(n));if("id"===i)return void(e.id=String(n));if("title"===i)return void(e.title=String(n));if("value"===i&&"value"in e)return void(e.value=String(n));const a=r.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());r.includes("-")||a in e.style||r in e.style?a in e.style?e.style[a]=String(n):r in e.style?e.style[r]=String(n):e.style.setProperty(r,String(n)):e.setAttribute(t,String(n))}},ki(t,"TakeCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;gi(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),bi(t,r)})(),t})();const rl=Ti(nl);class il{constructor(){this.name="render"}get metadata(){return il.metadata}async parseInput(e,t,n){if(e.args.length<1)throw new Error("render command requires a template");const r=await t.evaluate(e.args[0],n);let i;if(e.args.length>=3){if("with"===await t.evaluate(e.args[1],n)){const r=await t.evaluate(e.args[2],n);r&&"object"==typeof r&&(i=r)}}if(!i&&e.modifiers?.with){const r=await t.evaluate(e.modifiers.with,n);r&&"object"==typeof r&&(i=r)}return{template:r,variables:i}}async execute(e,t){const{template:n,variables:r={}}=e,i=this.extractTemplateContent(n,t),a=this.createTemplateContext(t,r),o=[],s=await this.processTemplate(i,a,o),l=this.createDOMElement(s);return Object.assign(t,{it:l}),{element:l,rendered:s,directivesProcessed:o}}extractTemplateContent(e,t){if(e instanceof HTMLTemplateElement)return e.innerHTML;if("string"==typeof e){let n=e;if(!n.includes("<")&&!n.includes("$")){const e=this.resolveVariable(n,t);if(e instanceof HTMLTemplateElement)return e.innerHTML;"string"==typeof e&&(n=e)}const r=n.match(/<template[^>]*>([\s\S]*?)<\/template>/i);return r?r[1]:n}if(e&&"object"==typeof e&&"innerHTML"in e)return e.innerHTML;throw new Error("Invalid template format")}createTemplateContext(e,t){return{...e,locals:new Map([...Array.from(e.locals.entries()),...Object.entries(t)])}}async processTemplate(e,t,n){const r=e.split("\n"),i=[];let a=0;for(;a<r.length;){const e=r[a].trim();if(e.startsWith("@repeat ")){const{nextIndex:e,rendered:o}=await this.processRepeatDirective(r,a,t);i.push(o),a=e,n.push("@repeat")}else if(e.startsWith("@if ")){const{nextIndex:e,rendered:o}=await this.processIfDirective(r,a,t,n);i.push(o),a=e,n.push("@if")}else if("@else"===e||"@end"===e)a++;else{const n=this.processVariableInterpolation(e,t);i.push(n),a++}}return i.join("\n")}async processRepeatDirective(e,t,n){const r=e[t].trim(),i=r.match(/^@repeat\s+in\s+(.+)$/);if(!i)throw new Error(`Invalid @repeat syntax: ${r}`);const a=i[1],o=this.evaluateExpression(a,n),{endIndex:s,blockContent:l}=this.extractDirectiveBlock(e,t+1),c=[];if(Array.isArray(o))for(const e of o){const t={...n,locals:new Map([...n.locals.entries(),["it",e]])},r=await this.processTemplate(l.join("\n"),t,[]);c.push(r)}return{nextIndex:s+1,rendered:c.join("\n")}}async processIfDirective(e,t,n,r){const i=e[t].trim(),a=i.match(/^@if\s+(.+)$/);if(!a)throw new Error(`Invalid @if syntax: ${i}`);const o=a[1],s=Boolean(this.evaluateExpression(o,n)),{endIndex:l,blockContent:c,elseContent:u}=this.extractIfElseBlock(e,t+1);let p="";return s?p=await this.processTemplate(c.join("\n"),n,[]):u.length>0&&(p=await this.processTemplate(u.join("\n"),n,[]),r.push("@else")),{nextIndex:l+1,rendered:p}}extractDirectiveBlock(e,t){const n=[];let r=1,i=t;for(;i<e.length&&r>0;){const t=e[i].trim();t.startsWith("@repeat ")||t.startsWith("@if ")?(r++,n.push(e[i])):"@end"===t?(r--,r>0&&n.push(e[i])):n.push(e[i]),i++}return{endIndex:i-1,blockContent:n}}extractIfElseBlock(e,t){const n=[],r=[];let i=1,a=t,o=!1;for(;a<e.length&&i>0;){const t=e[a].trim();if(t.startsWith("@if "))i++;else{if("@else"===t&&1===i){o=!0,a++;continue}if("@end"===t&&(i--,0===i))break}o?r.push(e[a]):n.push(e[a]),a++}return{endIndex:a,blockContent:n,elseContent:r}}processVariableInterpolation(e,t){return e.replace(/\$\{([^}]+)\}/g,(e,n)=>{try{const e=n.trim();if(e.startsWith("unescaped ")){const n=e.substring(10).trim(),r=this.evaluateExpression(n,t);return String(r||"")}const r=this.evaluateExpression(e,t);return this.escapeHtml(String(r||""))}catch(t){return console.warn(`Template interpolation error for ${n}:`,t),e}})}evaluateExpression(e,t){if("true"===e)return!0;if("false"===e)return!1;if("null"===e)return null;if("undefined"===e)return;const n=Number(e);if(!isNaN(n)&&""!==e.trim())return n;if(e.startsWith("[")&&e.endsWith("]"))try{return JSON.parse(e)}catch{}if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if(e.includes(".")){const n=e.split(".");let r=this.resolveVariable(n[0],t);for(let e=1;e<n.length&&null!=r;e++){if("object"!=typeof r||null===r)return;r=r[n[e]]}return r}return this.resolveVariable(e,t)}resolveVariable(e,t){return t.locals?.has(e)?t.locals.get(e):"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:"result"===e?t.result:t.globals?.has(e)?t.globals.get(e):void 0}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}createDOMElement(e){if("undefined"==typeof document)return null;const t=document.createElement("div");return t.innerHTML=e,1===t.children.length?t.firstElementChild:t}}il.metadata={description:"Render templates with @if, @else, and @repeat directives",syntax:["render <template>","render <template> with <variables>","render <template> with (key: value, ...)"],examples:["render myTemplate",'render myTemplate with (name: "Alice")','render "<template>Hello ${name}!</template>" with (name: "World")',"render template with (items: data)"],category:"templates",sideEffects:["dom-creation","template-execution"]};class al extends vi{constructor(e={}){const t=e.registry||new si;e.registry||(t.register(Mi()),t.register($i()),t.register(ra()),t.register(oa()),t.register(Aa()),t.register(La()),t.register(Wa()),t.register(Bo()),t.register(Fo()),t.register(Xo()),t.register(is()),t.register(ss()),t.register(ls()),t.register(cs()),t.register(ps()),t.register(ms()),t.register(ds()),t.register(fs()),t.register(ys()),t.register(gs()),t.register(zs()),t.register(xs()),t.register(Ts()),t.register(js()),t.register(Is()),t.register(Os()),t.register(Rs()),t.register(Ms()),t.register($s()),t.register(Hs()),t.register(qs()),t.register(Ds()),t.register(_s()),t.register(Vs()),t.register(Bs()),t.register(Fs()),t.register(Cs()),t.register(Us()),t.register(new Ks),t.register(Gs()),t.register(Js()),t.register(Ys()),t.register(Zs()),t.register(el()),t.register(new tl),t.register(rl()),t.register(new il));const n={registry:t,expressionEvaluator:new ii};void 0!==e.enableAsyncCommands&&(n.enableAsyncCommands=e.enableAsyncCommands),void 0!==e.commandTimeout&&(n.commandTimeout=e.commandTimeout),void 0!==e.enableErrorReporting&&(n.enableErrorReporting=e.enableErrorReporting),super(n)}getRegistry(){return this.registry}}var ol,sl,ll,cl,ul,pl=Object.defineProperty,ml=Object.getOwnPropertyDescriptor,dl=Object.getOwnPropertyNames,hl=Object.prototype.hasOwnProperty,fl=(e,t)=>function(){return e&&(t=(0,e[dl(e)[0]])(e=0)),t},yl=(e,t)=>{for(var n in t)pl(e,n,{get:t[n],enumerable:!0})},vl=e=>((e,t,n,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of dl(t))hl.call(e,i)||i===n||pl(e,i,{get:()=>t[i],enumerable:!(r=ml(t,i))||r.enumerable});return e})(pl({},"__esModule",{value:!0}),e);function gl(e,t){const n={...e};for(const r of Object.keys(t)){const i=t[r],a=e[r];void 0!==i&&("object"!=typeof i||null===i||Array.isArray(i)||"object"!=typeof a||null===a||Array.isArray(a)?n[r]=i:n[r]=gl(a,i))}return n}function bl(e,t){return gl(e,t)}function kl(e){if(!e.extends)return e;const t=sl.get(e.extends);if(!t)return console.warn(`[Registry] Profile '${e.code}' extends '${e.extends}' but base is not registered. Make sure to import the base language before the variant.`),e;return bl(kl(t),e)}function wl(e,t,n){ol.set(e,t),sl.set(e,n),ll.delete(e)}function zl(e,t){ul.set(e,t),ll.delete(e)}function xl(e){return e.split("-")[0]}function El(e){return e.includes("-")}function Sl(e){let t=sl.get(e);return!t&&El(e)&&(t=sl.get(xl(e))),t?kl(t):void 0}function Tl(){return Array.from(ol.keys())}function Cl(e){if(ol.has(e)&&sl.has(e))return!0;if(El(e)){const t=xl(e);return ol.has(t)&&sl.has(t)}return!1}function Al(e,t){return function(e){let t=ol.get(e);if(!t&&El(e)){const n=xl(e);t=ol.get(n)}if(!t){const t=Array.from(ol.keys()).join(", ");throw new Error(`Language '${e}' is not registered. Registered languages: ${t||"none"}. Import the language module first: import '@lokascript/semantic/languages/${e}';`)}return t}(t).tokenize(e)}function jl(e){let t=ll.get(e);if(!t&&El(e)&&(t=ll.get(xl(e))),t)return t;let n=ul.get(e);if(!n&&El(e)&&(n=ul.get(xl(e))),n)return ll.set(e,n),n;if(!cl)throw new Error(`No patterns registered for language '${e}'. Either import the language module or set a pattern generator.`);const r=function(e){let t=sl.get(e);if(!t&&El(e)){const n=xl(e);t=sl.get(n)}if(!t){const t=Array.from(sl.keys()).join(", ");throw new Error(`Language profile '${e}' is not registered. Registered languages: ${t||"none"}. Import the language module first: import '@lokascript/semantic/languages/${e}';`)}return kl(t)}(e),i=cl(r);return ll.set(e,i),i}var Ll,Pl=fl({"src/registry.ts"(){ol=new Map,sl=new Map,ll=new Map,cl=null,ul=new Map}});function Il(e,t){return{start:e,end:t}}function Nl(e,t,n,r){if("string"==typeof r)return{value:e,kind:t,position:n,normalized:r};if(r){const{normalized:i,stem:a,stemConfidence:o}=r;return{value:e,kind:t,position:n,...void 0!==i&&{normalized:i},...void 0!==a&&{stem:a},...void 0!==o&&{stemConfidence:o}}}return{value:e,kind:t,position:n}}function Ol(e){return/\s/.test(e)}function Rl(e){return"#"===e||"."===e||"["===e||"@"===e||"*"===e||"<"===e}function Ml(e){return'"'===e||"'"===e||"`"===e||"「"===e||"」"===e}function Wl(e){return/\d/.test(e)}function $l(e){return/[a-zA-Z0-9_-]/.test(e)}var Hl=fl({"src/tokenizers/token-utils.ts"(){Ll=class{constructor(e,t){this.pos=0,this.tokens=e,this.language=t}peek(e=0){const t=this.pos+e;return t<0||t>=this.tokens.length?null:this.tokens[t]}advance(){if(this.isAtEnd())throw new Error("Unexpected end of token stream");return this.tokens[this.pos++]}isAtEnd(){return this.pos>=this.tokens.length}mark(){return{position:this.pos}}reset(e){this.pos=e.position}position(){return this.pos}remaining(){return this.tokens.slice(this.pos)}takeWhile(e){const t=[];for(;!this.isAtEnd()&&e(this.peek());)t.push(this.advance());return t}skipWhile(e){for(;!this.isAtEnd()&&e(this.peek());)this.advance()}}}});function ql(e){return t=>{const n=t.charCodeAt(0);return e.some(([e,t])=>n>=e&&n<=t)}}function Dl(...e){return t=>e.some(e=>e(t))}function _l(e){const t=t=>e.test(t);return{isLetter:t,isIdentifierChar:e=>t(e)||/[0-9_-]/.test(e)}}var Vl=fl({"src/tokenizers/char-classifiers.ts"(){}});function Bl(e,t){if(t>=e.length||"'"!==e[t])return!1;if(t+1>=e.length)return!1;if("s"!==e[t+1].toLowerCase())return!1;if(t+2>=e.length)return!0;const n=e[t+2];return Ol(n)||"*"===n||!$l(n)}function Fl(e,t){if(t>=e.length)return!1;const n=e[t],r=e[t+1]||"",i=e[t+2]||"";if("/"===n&&"/"!==r&&/[a-zA-Z0-9._-]/.test(r))return!0;if("/"===n&&"/"===r&&/[a-zA-Z]/.test(i))return!0;if("."===n&&("/"===r||"."===r&&"/"===i))return!0;const a=e.slice(t,t+8).toLowerCase();return!(!a.startsWith("http://")&&!a.startsWith("https://"))}var Ul,Kl,Gl=fl({"src/tokenizers/extractors.ts"(){Hl()}}),Ql=fl({"src/tokenizers/base-tokenizer.ts"(){Hl(),Gl(),Ul=class e{constructor(){this.profileKeywords=[],this.profileKeywordMap=new Map}tryPropertyAccess(e,t,n){if("."!==e[t])return!1;const r=n[n.length-1],i=r&&r.position.end<t;if(r&&!i&&("identifier"===r.kind||"keyword"===r.kind||"selector"===r.kind))return n.push(Nl(".","operator",Il(t,t+1))),!0;let a=t+1;for(;a<e.length&&$l(e[a]);)a++;return a<e.length&&"("===e[a]&&(n.push(Nl(".","operator",Il(t,t+1))),!0)}initializeKeywordsFromProfile(e,t=[]){const n=new Map;if(e.keywords)for(const[t,r]of Object.entries(e.keywords))if(n.set(r.primary,{native:r.primary,normalized:r.normalized||t}),r.alternatives)for(const e of r.alternatives)n.set(e,{native:e,normalized:r.normalized||t});if(e.references){for(const[t,r]of Object.entries(e.references))n.set(r,{native:r,normalized:t});for(const t of Object.keys(e.references))n.has(t)||n.set(t,{native:t,normalized:t})}if(e.roleMarkers)for(const[t,r]of Object.entries(e.roleMarkers))if(r.primary&&n.set(r.primary,{native:r.primary,normalized:t}),r.alternatives)for(const e of r.alternatives)n.set(e,{native:e,normalized:t});for(const e of t)n.set(e.native,e);this.profileKeywords=Array.from(n.values()).sort((e,t)=>t.native.length-e.native.length),this.profileKeywordMap=new Map;for(const e of this.profileKeywords){this.profileKeywordMap.set(e.native.toLowerCase(),e);const t=this.removeDiacritics(e.native);t===e.native||this.profileKeywordMap.has(t.toLowerCase())||this.profileKeywordMap.set(t.toLowerCase(),e)}}removeDiacritics(e){return e.replace(/[\u064B-\u0652\u0670]/g,"")}tryProfileKeyword(e,t){for(const n of this.profileKeywords)if(e.slice(t).startsWith(n.native))return Nl(n.native,"keyword",Il(t,t+n.native.length),n.normalized);return null}isKeywordStart(e,t){const n=e.slice(t);return this.profileKeywords.some(e=>n.startsWith(e.native))}lookupKeyword(e){return this.profileKeywordMap.get(e.toLowerCase())}isKeyword(e){return this.profileKeywordMap.has(e.toLowerCase())}setNormalizer(e){this.normalizer=e}tryNormalize(e){if(!this.normalizer)return null;const t=this.normalizer.normalize(e);return t.stem!==e&&t.confidence>=.7?t:null}tryMorphKeywordMatch(e,t,n){const r=this.tryNormalize(e);if(!r)return null;const i=this.lookupKeyword(r.stem);if(!i)return null;const a={normalized:i.normalized,stem:r.stem,stemConfidence:r.confidence};return Nl(e,"keyword",Il(t,n),a)}trySelector(e,t){const n=function(e,t){if(t>=e.length)return null;const n=e[t];if(!Rl(n))return null;let r=t,i="";if("#"===n||"."===n){for(i+=e[r++];r<e.length&&$l(e[r]);)i+=e[r++];if(i.length<=1)return null;if(r<e.length&&"."===e[r]&&"#"===n){let t=r+1;for(;t<e.length&&$l(e[t]);)t++;if(t<e.length&&"("===e[t])return i}}else if("["===n){let t=1,n=!1,a=null,o=!1;for(i+=e[r++];r<e.length&&t>0;){const s=e[r];i+=s,o?o=!1:"\\"===s?o=!0:n?s===a&&(n=!1,a=null):'"'===s||"'"===s||"`"===s?(n=!0,a=s):"["===s?t++:"]"===s&&t--,r++}if(0!==t)return null}else if("@"===n){for(i+=e[r++];r<e.length&&$l(e[r]);)i+=e[r++];if(i.length<=1)return null}else if("*"===n){for(i+=e[r++];r<e.length&&$l(e[r]);)i+=e[r++];if(i.length<=1)return null}else if("<"===n){if(i+=e[r++],r>=e.length||!function(e){return/[a-zA-Z]/.test(e)}(e[r]))return null;for(;r<e.length&&$l(e[r]);)i+=e[r++];for(;r<e.length;){const t=e[r];if("."===t){if(i+=e[r++],r>=e.length||!$l(e[r]))return null;for(;r<e.length&&$l(e[r]);)i+=e[r++]}else if("#"===t){if(i+=e[r++],r>=e.length||!$l(e[r]))return null;for(;r<e.length&&$l(e[r]);)i+=e[r++]}else{if("["!==t)break;{let t=1,n=!1,a=null,o=!1;for(i+=e[r++];r<e.length&&t>0;){const s=e[r];i+=s,o?o=!1:"\\"===s?o=!0:n?s===a&&(n=!1,a=null):'"'===s||"'"===s||"`"===s?(n=!0,a=s):"["===s?t++:"]"===s&&t--,r++}if(0!==t)return null}}}for(;r<e.length&&Ol(e[r]);)i+=e[r++];if(r<e.length&&"/"===e[r])for(i+=e[r++];r<e.length&&Ol(e[r]);)i+=e[r++];if(r>=e.length||">"!==e[r])return null;i+=e[r++]}return i||null}(e,t);return n?Nl(n,"selector",Il(t,t+n.length)):null}tryEventModifier(e,t){if("."!==e[t])return null;const n=e.slice(t).match(/^\.(?:once|debounce|throttle|queue)(?:\(([^)]+)\))?(?:\s|$|\.)/);if(!n)return null;const r=n[0].replace(/(\s|\.)$/,""),i=r.slice(1).split("(")[0],a=n[1];return{...Nl(r,"event-modifier",Il(t,t+r.length)),metadata:{modifierName:i,value:a?"queue"===i?a:parseInt(a,10):void 0}}}tryString(e,t){const n=function(e,t){if(t>=e.length)return null;const n=e[t];if(!Ml(n))return null;if("'"===n&&Bl(e,t))return null;const r={'"':'"',"'":"'","`":"`","「":"」"}[n];if(!r)return null;let i=t+1,a=n,o=!1;for(;i<e.length;){const t=e[i];if(a+=t,o)o=!1;else if("\\"===t)o=!0;else if(t===r)return a;i++}return a}(e,t);return n?Nl(n,"literal",Il(t,t+n.length)):null}tryNumber(e,t){const n=function(e,t){if(t>=e.length)return null;const n=e[t];if(!Wl(n)&&"-"!==n&&"+"!==n)return null;let r=t,i="";if("-"!==e[r]&&"+"!==e[r]||(i+=e[r++]),r>=e.length||!Wl(e[r]))return null;for(;r<e.length&&Wl(e[r]);)i+=e[r++];if(r<e.length&&"."===e[r])for(i+=e[r++];r<e.length&&Wl(e[r]);)i+=e[r++];r<e.length&&("ms"===e.slice(r,r+2)?i+="ms":"s"!==e[r]&&"m"!==e[r]&&"h"!==e[r]||(i+=e[r]));return i}(e,t);return n?Nl(n,"literal",Il(t,t+n.length)):null}tryMatchTimeUnit(e,t,n,r=!1){let i=t;if(r)for(;i<e.length&&Ol(e[i]);)i++;const a=e.slice(i);for(const e of n){const t=a.slice(0,e.length);if(e.caseInsensitive?t.toLowerCase()===e.pattern.toLowerCase():t===e.pattern){if(e.notFollowedBy){if((a[e.length]||"")===e.notFollowedBy)continue}if(e.checkBoundary){if($l(a[e.length]||""))continue}return{suffix:e.suffix,endPos:i+e.length}}}return null}parseBaseNumber(e,t,n=!0){let r=t,i="";if(!n||"-"!==e[r]&&"+"!==e[r]||(i+=e[r++]),r>=e.length||!Wl(e[r]))return null;for(;r<e.length&&Wl(e[r]);)i+=e[r++];if(r<e.length&&"."===e[r])for(i+=e[r++];r<e.length&&Wl(e[r]);)i+=e[r++];return i&&"-"!==i&&"+"!==i?{number:i,endPos:r}:null}tryNumberWithTimeUnits(t,n,r,i={}){const{allowSign:a=!0,skipWhitespace:o=!1}=i,s=this.parseBaseNumber(t,n,a);if(!s)return null;let{number:l,endPos:c}=s;const u=[...r,...e.STANDARD_TIME_UNITS],p=this.tryMatchTimeUnit(t,c,u,o);return p&&(l+=p.suffix,c=p.endPos),Nl(l,"literal",Il(n,c))}tryUrl(e,t){const n=function(e,t){if(!Fl(e,t))return null;let n=t,r="";const i=/[a-zA-Z0-9/:._\-?&=%@+~!$'()*,;[\]]/;for(;n<e.length;){const t=e[n];if("#"===t){if(r.length>0&&/[a-zA-Z0-9/.]$/.test(r))for(r+=t,n++;n<e.length&&/[a-zA-Z0-9_-]/.test(e[n]);)r+=e[n++];break}if(!i.test(t))break;r+=t,n++}return r.length<2?null:r}(e,t);return n?Nl(n,"url",Il(t,t+n.length)):null}tryVariableRef(e,t){if(":"!==e[t])return null;if(t+1>=e.length)return null;if(!$l(e[t+1]))return null;let n=t+1;for(;n<e.length&&$l(e[n]);)n++;return Nl(e.slice(t,n),"identifier",Il(t,n))}tryOperator(e,t){const n=e.slice(t,t+2);if(["==","!=","<=",">=","&&","||","->"].includes(n))return Nl(n,"operator",Il(t,t+2));const r=e[t];return["<",">","!","+","-","*","/","="].includes(r)?Nl(r,"operator",Il(t,t+1)):["(",")","{","}",",",";",":"].includes(r)?Nl(r,"punctuation",Il(t,t+1)):null}tryMultiCharParticle(e,t,n){for(const r of n)if(e.slice(t,t+r.length)===r)return Nl(r,"particle",Il(t,t+r.length));return null}},Ul.STANDARD_TIME_UNITS=[{pattern:"ms",suffix:"ms",length:2},{pattern:"s",suffix:"s",length:1,checkBoundary:!0},{pattern:"m",suffix:"m",length:1,checkBoundary:!0,notFollowedBy:"s"},{pattern:"h",suffix:"h",length:1,checkBoundary:!0}],Kl=Ul}}),Jl=fl({"src/tokenizers/base.ts"(){Hl(),Vl(),Gl(),Ql()}});function Yl(e){return{stem:e,confidence:1}}function Zl(e,t,n){return n?{stem:e,confidence:t,metadata:n}:{stem:e,confidence:t}}var Xl,ec,tc,nc,rc,ic=fl({"src/tokenizers/morphology/types.ts"(){}});function ac(e){const t=e.charCodeAt(0);return t>=1536&&t<=1791||t>=1872&&t<=1919||t>=2208&&t<=2303||t>=64336&&t<=65023||t>=65136&&t<=65279}var oc,sc=fl({"src/tokenizers/morphology/arabic-normalizer.ts"(){ic(),Xl=[{pattern:"وال",confidencePenalty:.15,prefixType:"conjunction"},{pattern:"فال",confidencePenalty:.15,prefixType:"conjunction"},{pattern:"بال",confidencePenalty:.15,prefixType:"preposition"},{pattern:"كال",confidencePenalty:.15,prefixType:"preposition"},{pattern:"لل",confidencePenalty:.12,prefixType:"preposition"}],ec=[{pattern:"ال",confidencePenalty:.08,prefixType:"article",minRemaining:2},{pattern:"و",confidencePenalty:.08,prefixType:"conjunction",minRemaining:3},{pattern:"ف",confidencePenalty:.08,prefixType:"conjunction",minRemaining:3},{pattern:"ب",confidencePenalty:.1,prefixType:"preposition",minRemaining:3},{pattern:"ل",confidencePenalty:.1,prefixType:"preposition",minRemaining:3},{pattern:"ك",confidencePenalty:.1,prefixType:"preposition",minRemaining:3}],tc=[{pattern:"ي",confidencePenalty:.12,prefixType:"verb-marker",minRemaining:3},{pattern:"ت",confidencePenalty:.12,prefixType:"verb-marker",minRemaining:3},{pattern:"ن",confidencePenalty:.12,prefixType:"verb-marker",minRemaining:3},{pattern:"أ",confidencePenalty:.12,prefixType:"verb-marker",minRemaining:3},{pattern:"ا",confidencePenalty:.12,prefixType:"verb-marker",minRemaining:3}],nc=[{pattern:"ون",confidencePenalty:.1,type:"masculine-plural"},{pattern:"ين",confidencePenalty:.1,type:"masculine-plural-accusative"},{pattern:"ات",confidencePenalty:.1,type:"feminine-plural"},{pattern:"ان",confidencePenalty:.1,type:"dual-nominative"},{pattern:"ين",confidencePenalty:.1,type:"dual-accusative"},{pattern:"ها",confidencePenalty:.1,type:"pronoun-her"},{pattern:"هم",confidencePenalty:.1,type:"pronoun-them"},{pattern:"هن",confidencePenalty:.1,type:"pronoun-them-f"},{pattern:"نا",confidencePenalty:.1,type:"pronoun-us"},{pattern:"كم",confidencePenalty:.1,type:"pronoun-you-pl"},{pattern:"ك",confidencePenalty:.08,type:"pronoun-you"},{pattern:"ه",confidencePenalty:.08,type:"pronoun-him"},{pattern:"ي",confidencePenalty:.08,type:"pronoun-me"},{pattern:"ة",confidencePenalty:.08,type:"feminine"}],new(rc=class{constructor(){this.language="ar"}isNormalizable(e){return!!function(e){for(const t of e)if(ac(t))return!0;return!1}(e)&&!(e.length<2)}normalize(e){let t=function(e){return e.replace(/[\u064B-\u0652\u0670]/g,"")}(e),n=1;const r=[],i=[];for(const e of Xl)if(t.startsWith(e.pattern)){const i=t.slice(e.pattern.length);if(i.length>=2){t=i,n-=e.confidencePenalty,r.push(e.pattern);break}}if(0===r.length)for(const e of ec)if(t.startsWith(e.pattern)){const i=t.slice(e.pattern.length),a=e.minRemaining??2;if(i.length>=a){t=i,n-=e.confidencePenalty,r.push(e.pattern);break}}if(!(t.endsWith("ات")||t.endsWith("ة")||t.endsWith("ون")||t.endsWith("ين")||t.endsWith("ها")||t.endsWith("هم")||t.endsWith("هن")||t.endsWith("نا")||t.endsWith("كم"))&&(0===r.length||"و"===r[0]||"ف"===r[0]))for(const e of tc)if(t.startsWith(e.pattern)){const i=t.slice(e.pattern.length),a=e.minRemaining??3;if(i.length>=a){t=i,n-=e.confidencePenalty,r.push(e.pattern);break}}for(const e of nc)if(t.endsWith(e.pattern)){const r=t.slice(0,-e.pattern.length);r.length>=2&&(t=r,n-=e.confidencePenalty,i.push(e.pattern))}return n=Math.max(.5,n),0===r.length&&0===i.length?Yl(e):Zl(t,n,{removedPrefixes:r,removedSuffixes:i})}})}}),lc={};yl(lc,{arabicProfile:()=>oc});var cc,uc,pc,mc,dc,hc,fc,yc,vc,gc=fl({"src/generators/profiles/arabic.ts"(){oc={code:"ar",name:"Arabic",nativeName:"العربية",direction:"rtl",wordOrder:"VSO",markingStrategy:"preposition",usesSpaces:!0,verb:{position:"start",subjectDrop:!0},references:{me:"أنا",it:"هو",you:"أنت",result:"النتيجة",event:"الحدث",target:"الهدف",body:"الجسم"},possessive:{marker:"",markerPosition:"after-object",usePossessiveAdjectives:!0,specialForms:{me:"لي",it:"له",you:"لك"},keywords:{"لي":"me","لك":"you","له":"it","لها":"it"}},roleMarkers:{destination:{primary:"على",alternatives:["في","إلى","ب","قبل","بعد"],position:"before"},source:{primary:"من",position:"before"},patient:{primary:"",position:"before"},style:{primary:"بـ",alternatives:["باستخدام"],position:"before"}},keywords:{toggle:{primary:"بدّل",alternatives:["بدل","غيّر","غير"],normalized:"toggle"},add:{primary:"أضف",alternatives:["اضف","زِد"],normalized:"add"},remove:{primary:"احذف",alternatives:["أزل","امسح"],normalized:"remove"},put:{primary:"ضع",alternatives:["اجعل"],normalized:"put"},append:{primary:"ألحق",normalized:"append"},prepend:{primary:"سبق",normalized:"prepend"},take:{primary:"خذ",normalized:"take"},make:{primary:"اصنع",alternatives:["أنشئ"],normalized:"make"},clone:{primary:"استنسخ",alternatives:["انسخ"],normalized:"clone"},swap:{primary:"استبدل",alternatives:["تبادل"],normalized:"swap"},morph:{primary:"حوّل",alternatives:["غيّر"],normalized:"morph"},set:{primary:"اضبط",alternatives:["عيّن","حدد"],normalized:"set"},get:{primary:"احصل",normalized:"get"},increment:{primary:"زِد",alternatives:["زد","ارفع"],normalized:"increment"},decrement:{primary:"أنقص",alternatives:["انقص","قلل"],normalized:"decrement"},log:{primary:"سجل",normalized:"log"},show:{primary:"اظهر",alternatives:["أظهر","اعرض"],normalized:"show"},hide:{primary:"اخف",alternatives:["أخفِ","اخفي","أخف"],normalized:"hide"},transition:{primary:"انتقال",alternatives:["انتقل"],normalized:"transition"},on:{primary:"على",alternatives:["عند","لدى","حين"],normalized:"on"},trigger:{primary:"تشغيل",alternatives:["أطلق","فعّل"],normalized:"trigger"},send:{primary:"أرسل",normalized:"send"},focus:{primary:"تركيز",alternatives:["ركز"],normalized:"focus"},blur:{primary:"ضبابية",alternatives:["شوش"],normalized:"blur"},go:{primary:"اذهب",alternatives:["انتقل"],normalized:"go"},wait:{primary:"انتظر",normalized:"wait"},fetch:{primary:"احضر",alternatives:["جلب"],normalized:"fetch"},settle:{primary:"استقر",normalized:"settle"},if:{primary:"إذا",normalized:"if"},when:{primary:"عندما",normalized:"when"},where:{primary:"أين",normalized:"where"},else:{primary:"وإلا",alternatives:["خلاف ذلك"],normalized:"else"},repeat:{primary:"كرر",normalized:"repeat"},for:{primary:"لكل",normalized:"for"},while:{primary:"بينما",normalized:"while"},continue:{primary:"واصل",normalized:"continue"},halt:{primary:"أوقف",alternatives:["توقف"],normalized:"halt"},throw:{primary:"ارم",alternatives:["ارمِ"],normalized:"throw"},call:{primary:"استدع",alternatives:["نادِ"],normalized:"call"},return:{primary:"ارجع",alternatives:["عُد"],normalized:"return"},then:{primary:"ثم",alternatives:["بعدها","ثمّ"],normalized:"then"},and:{primary:"وأيضاً",alternatives:["أيضاً"],normalized:"and"},end:{primary:"نهاية",alternatives:["انتهى","آخر"],normalized:"end"},js:{primary:"جافاسكربت",alternatives:["js"],normalized:"js"},async:{primary:"متزامن",normalized:"async"},tell:{primary:"أخبر",normalized:"tell"},default:{primary:"افتراضي",normalized:"default"},init:{primary:"تهيئة",alternatives:["بدء"],normalized:"init"},behavior:{primary:"سلوك",normalized:"behavior"},install:{primary:"تثبيت",alternatives:["ثبّت"],normalized:"install"},measure:{primary:"قياس",alternatives:["قِس"],normalized:"measure"},beep:{primary:"صفّر",normalized:"beep"},break:{primary:"توقف",normalized:"break"},copy:{primary:"انسخ",normalized:"copy"},exit:{primary:"اخرج",normalized:"exit"},pick:{primary:"اختر",normalized:"pick"},render:{primary:"ارسم",normalized:"render"},into:{primary:"في",alternatives:["إلى"],normalized:"into"},before:{primary:"قبل",normalized:"before"},after:{primary:"بعد",normalized:"after"},until:{primary:"حتى",normalized:"until"},event:{primary:"حدث",normalized:"event"},from:{primary:"من",normalized:"from"}},tokenization:{prefixes:["ال","و","ف","ب","ك","ل"]},eventHandler:{eventMarker:{primary:"عند",alternatives:["في","لدى","عندما","حين","حينما","لمّا","لما"],position:"before"},temporalMarkers:["عندما","حين","لمّا"],negationMarker:{primary:"عدم",alternatives:["عدم"],position:"before"}}}}}),bc={};yl(bc,{ArabicTokenizer:()=>yc,arabicTokenizer:()=>vc});var kc,wc=fl({"src/tokenizers/arabic.ts"(){Jl(),sc(),gc(),cc=ql([[1536,1791],[1872,1919],[2208,2303],[64336,65023],[65136,65279]]),uc=new Set(["بـ","لـ","كـ","وـ"]),pc=new Map([["و",{normalized:"and",type:"conjunction"}],["ف",{normalized:"then",type:"conjunction"}],["ب",{normalized:"with",type:"preposition"}],["ل",{normalized:"to",type:"preposition"}],["ك",{normalized:"like",type:"preposition"}],["ول",{normalized:"and-to",type:"conjunction"}],["وب",{normalized:"and-with",type:"conjunction"}],["وك",{normalized:"and-like",type:"conjunction"}],["فل",{normalized:"then-to",type:"conjunction"}],["فب",{normalized:"then-with",type:"conjunction"}],["فك",{normalized:"then-like",type:"conjunction"}]]),mc=new Map([["عندما",{normalized:"on",formality:"formal",confidence:.95,description:"when (formal MSA)"}],["حينما",{normalized:"on",formality:"formal",confidence:.93,description:"when/whenever (formal)"}],["عند",{normalized:"on",formality:"neutral",confidence:.88,description:"at/when (neutral)"}],["حين",{normalized:"on",formality:"neutral",confidence:.85,description:"when/time (neutral)"}],["لمّا",{normalized:"on",formality:"dialectal",confidence:.7,description:"when (dialectal, with shadda)"}],["لما",{normalized:"on",formality:"dialectal",confidence:.68,description:"when (dialectal, no diacritic)"}],["لدى",{normalized:"on",formality:"neutral",confidence:.82,description:"at/with (temporal)"}]]),dc=new Set(["في","على","من","إلى","الى","مع","عن","قبل","بعد","بين"]),hc=[{native:"صحيح",normalized:"true"},{native:"خطأ",normalized:"false"},{native:"null",normalized:"null"},{native:"فارغ",normalized:"null"},{native:"غير معرف",normalized:"undefined"},{native:"الأول",normalized:"first"},{native:"أول",normalized:"first"},{native:"الأخير",normalized:"last"},{native:"آخر",normalized:"last"},{native:"التالي",normalized:"next"},{native:"السابق",normalized:"previous"},{native:"الأقرب",normalized:"closest"},{native:"الأب",normalized:"parent"},{native:"النقر",normalized:"click"},{native:"نقر",normalized:"click"},{native:"الإدخال",normalized:"input"},{native:"إدخال",normalized:"input"},{native:"التغيير",normalized:"change"},{native:"تغيير",normalized:"change"},{native:"الإرسال",normalized:"submit"},{native:"إرسال",normalized:"submit"},{native:"التركيز",normalized:"focus"},{native:"فقدان التركيز",normalized:"blur"},{native:"ضغط",normalized:"keydown"},{native:"رفع",normalized:"keyup"},{native:"تمرير الفأرة",normalized:"mouseover"},{native:"مغادرة الفأرة",normalized:"mouseout"},{native:"تحميل",normalized:"load"},{native:"تمرير",normalized:"scroll"},{native:"هي",normalized:"it"},{native:"ثانية",normalized:"s"},{native:"ثواني",normalized:"s"},{native:"ملي ثانية",normalized:"ms"},{native:"دقيقة",normalized:"m"},{native:"دقائق",normalized:"m"},{native:"ساعة",normalized:"h"},{native:"ساعات",normalized:"h"}],fc=[{pattern:"ملي ثانية",suffix:"ms",length:9,caseInsensitive:!1},{pattern:"ملي_ثانية",suffix:"ms",length:8,caseInsensitive:!1},{pattern:"دقائق",suffix:"m",length:5,caseInsensitive:!1},{pattern:"دقيقة",suffix:"m",length:5,caseInsensitive:!1},{pattern:"ثواني",suffix:"s",length:5,caseInsensitive:!1},{pattern:"ثانية",suffix:"s",length:5,caseInsensitive:!1},{pattern:"ساعات",suffix:"h",length:5,caseInsensitive:!1},{pattern:"ساعة",suffix:"h",length:4,caseInsensitive:!1}],vc=new(yc=class extends Kl{constructor(){super(),this.language="ar",this.direction="rtl",this.initializeKeywordsFromProfile(oc,hc),this.normalizer=new rc}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])){const r=this.extractArabicNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}const i=this.tryPreposition(e,n);if(i)t.push(i),n=i.position.end;else{if(cc(e[n])){const r=this.tryProclitic(e,n);if(r){t.push(r.conjunction),n=r.conjunction.position.end;continue}const i=this.extractArabicWord(e,n);if(i){t.push(i),n=i.position.end;continue}}if($l(e[n])){const r=this.extractAsciiWord(e,n);if(r){t.push(r),n=r.position.end;continue}}n++}}return new Ll(t,"ar")}classifyToken(e){return dc.has(e)?"particle":this.isKeyword(e)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||/^\d/.test(e)?"literal":"identifier"}tryPreposition(e,t){const n=Array.from(dc).sort((e,t)=>t.length-e.length);for(const r of n)if(e.slice(t,t+r.length)===r){const n=t+r.length;if(n>=e.length||Ol(e[n])||!cc(e[n])){return{...Nl(r,"particle",Il(t,n)),metadata:{prepositionValue:r}}}}return null}tryProclitic(e,t){let n=t;for(;n<e.length&&(cc(e[n])||"ـ"===e[n]);)n++;const r=e.slice(t,n);if(this.lookupKeyword(r))return null;if(mc.has(r))return null;if(dc.has(r))return null;if(t+2<=e.length){const r=e.slice(t,t+2),i=pc.get(r);if(i){const a=t+2;if(a<e.length&&cc(e[a])){let o=0,s=a;for(;s<e.length&&cc(e[s]);)o++,s++;if(o>=2){if(!pc.get(e[t])){return{conjunction:Nl(r,"conjunction"===i.type?"conjunction":"particle",Il(t,a),i.normalized)}}{const o=e.slice(t+1,n);if(!this.lookupKeyword(o)){return{conjunction:Nl(r,"conjunction"===i.type?"conjunction":"particle",Il(t,a),i.normalized)}}}}}}}const i=e[t],a=pc.get(i);if(!a)return null;const o=t+1;if(o>=e.length||!cc(e[o]))return null;let s=0,l=o;for(;l<e.length&&cc(e[l]);)s++,l++;if(s<2)return null;return{conjunction:Nl(i,"conjunction"===a.type?"conjunction":"particle",Il(t,o),a.normalized)}}extractArabicWord(e,t){let n=t,r="";for(const t of uc){const r=t.replace("ـ","");e.slice(n,n+r.length)}for(;n<e.length&&(cc(e[n])||"ـ"===e[n]);)r+=e[n++];if(!r)return null;const i=mc.get(r);if(i){return{...Nl(r,"keyword",Il(t,n),i.normalized),metadata:{temporalFormality:i.formality,temporalConfidence:i.confidence}}}const a=this.lookupKeyword(r);if(a)return Nl(r,"keyword",Il(t,n),a.normalized);if(dc.has(r)){return{...Nl(r,"particle",Il(t,n)),metadata:{prepositionValue:r}}}const o=this.tryMorphKeywordMatch(r,t,n);return o||Nl(r,"identifier",Il(t,n))}extractAsciiWord(e,t){let n=t,r="";for(;n<e.length&&$l(e[n]);)r+=e[n++];return r?Nl(r,"identifier",Il(t,n)):null}extractArabicNumber(e,t){return this.tryNumberWithTimeUnits(e,t,fc,{allowSign:!1,skipWhitespace:!0})}})}}),zc={};yl(zc,{bengaliProfile:()=>kc});var xc,Ec,Sc,Tc,Cc,Ac=fl({"src/generators/profiles/bengali.ts"(){kc={code:"bn",name:"Bengali",nativeName:"বাংলা",direction:"ltr",wordOrder:"SOV",markingStrategy:"postposition",usesSpaces:!0,defaultVerbForm:"imperative",verb:{position:"end",suffixes:["ুন","ো","া","ে","ি"],subjectDrop:!0},references:{me:"আমি",it:"এটি",you:"আপনি",result:"ফলাফল",event:"ঘটনা",target:"লক্ষ্য",body:"বডি"},possessive:{marker:"র",markerPosition:"between",keywords:{"আমার":"me","তোমার":"you","আপনার":"you","তার":"it","এর":"it"}},roleMarkers:{patient:{primary:"কে",position:"after"},destination:{primary:"তে",alternatives:["এ"],position:"after"},source:{primary:"থেকে",position:"after"},style:{primary:"দিয়ে",position:"after"},event:{primary:"তে",position:"after"}},keywords:{toggle:{primary:"টগল",alternatives:["পরিবর্তন"],normalized:"toggle"},add:{primary:"যোগ",alternatives:["যোগ করুন"],normalized:"add"},remove:{primary:"সরান",alternatives:["সরিয়ে ফেলুন","মুছুন"],normalized:"remove"},put:{primary:"রাখুন",alternatives:["রাখ"],normalized:"put"},append:{primary:"শেষে যোগ",alternatives:[],normalized:"append"},prepend:{primary:"শুরুতে যোগ",alternatives:[],normalized:"prepend"},take:{primary:"নিন",alternatives:["নে"],normalized:"take"},make:{primary:"তৈরি করুন",alternatives:["বানান"],normalized:"make"},clone:{primary:"কপি",alternatives:["প্রতিলিপি"],normalized:"clone"},swap:{primary:"বদল",alternatives:[],normalized:"swap"},morph:{primary:"রূপান্তর",alternatives:[],normalized:"morph"},set:{primary:"সেট",alternatives:["নির্ধারণ"],normalized:"set"},get:{primary:"পান",alternatives:["নিন"],normalized:"get"},increment:{primary:"বৃদ্ধি",alternatives:["বাড়ান"],normalized:"increment"},decrement:{primary:"হ্রাস",alternatives:["কমান"],normalized:"decrement"},log:{primary:"লগ",alternatives:["রেকর্ড"],normalized:"log"},show:{primary:"দেখান",alternatives:["দেখাও"],normalized:"show"},hide:{primary:"লুকান",alternatives:["লুকাও"],normalized:"hide"},transition:{primary:"সংক্রমণ",alternatives:[],normalized:"transition"},on:{primary:"তে",alternatives:["এ","যখন"],normalized:"on"},trigger:{primary:"ট্রিগার",alternatives:[],normalized:"trigger"},send:{primary:"পাঠান",alternatives:["পাঠাও"],normalized:"send"},focus:{primary:"ফোকাস",alternatives:["মনোযোগ"],normalized:"focus"},blur:{primary:"ঝাপসা",alternatives:["ফোকাস_সরান"],normalized:"blur"},click:{primary:"ক্লিক",normalized:"click"},hover:{primary:"হোভার",alternatives:["উপরে_রাখুন"],normalized:"hover"},submit:{primary:"সাবমিট",alternatives:["জমা"],normalized:"submit"},input:{primary:"ইনপুট",alternatives:["প্রবেশ"],normalized:"input"},change:{primary:"পরিবর্তন",normalized:"change"},go:{primary:"যান",alternatives:["যাও"],normalized:"go"},wait:{primary:"অপেক্ষা",alternatives:["থামুন"],normalized:"wait"},fetch:{primary:"আনুন",alternatives:[],normalized:"fetch"},settle:{primary:"স্থির",alternatives:[],normalized:"settle"},if:{primary:"যদি",alternatives:[],normalized:"if"},when:{primary:"যখন",normalized:"when"},where:{primary:"কোথায়",normalized:"where"},else:{primary:"নতুবা",alternatives:["না হলে"],normalized:"else"},repeat:{primary:"পুনরাবৃত্তি",alternatives:["বার বার"],normalized:"repeat"},for:{primary:"জন্য",alternatives:[],normalized:"for"},while:{primary:"যতক্ষণ",alternatives:[],normalized:"while"},continue:{primary:"চালিয়ে যান",alternatives:[],normalized:"continue"},halt:{primary:"থামুন",alternatives:["থামাও"],normalized:"halt"},throw:{primary:"নিক্ষেপ",alternatives:["ছুঁড়ে দিন"],normalized:"throw"},call:{primary:"কল",alternatives:["ডাকুন"],normalized:"call"},return:{primary:"ফিরুন",alternatives:["ফেরত দিন"],normalized:"return"},then:{primary:"তারপর",alternatives:["তখন"],normalized:"then"},and:{primary:"এবং",alternatives:[],normalized:"and"},end:{primary:"শেষ",alternatives:["সমাপ্ত"],normalized:"end"},js:{primary:"জেএস",alternatives:["js"],normalized:"js"},async:{primary:"অ্যাসিঙ্ক",alternatives:[],normalized:"async"},tell:{primary:"বলুন",alternatives:["বল"],normalized:"tell"},default:{primary:"ডিফল্ট",alternatives:[],normalized:"default"},init:{primary:"শুরু",alternatives:[],normalized:"init"},behavior:{primary:"আচরণ",alternatives:[],normalized:"behavior"},install:{primary:"ইনস্টল",alternatives:[],normalized:"install"},measure:{primary:"মাপুন",alternatives:[],normalized:"measure"},beep:{primary:"বীপ",alternatives:[],normalized:"beep"},break:{primary:"থামুন",alternatives:[],normalized:"break"},copy:{primary:"কপি",alternatives:[],normalized:"copy"},exit:{primary:"বের",alternatives:[],normalized:"exit"},pick:{primary:"বাছুন",alternatives:[],normalized:"pick"},render:{primary:"রেন্ডার",alternatives:[],normalized:"render"},into:{primary:"তে",alternatives:["এ"],normalized:"into"},before:{primary:"আগে",alternatives:[],normalized:"before"},after:{primary:"পরে",alternatives:[],normalized:"after"},until:{primary:"পর্যন্ত",alternatives:[],normalized:"until"},event:{primary:"ঘটনা",alternatives:[],normalized:"event"},from:{primary:"থেকে",normalized:"from"}},tokenization:{particles:["কে","তে","থেকে","র","এর","দিয়ে","জন্য","পর্যন্ত"],boundaryStrategy:"space"},eventHandler:{keyword:{primary:"তে",alternatives:["এ","যখন"],normalized:"on"},sourceMarker:{primary:"থেকে",position:"after"},eventMarker:{primary:"তে",alternatives:["এ"],position:"after"},temporalMarkers:["যখন","যখনই"]}}}}),jc={};yl(jc,{BengaliTokenizer:()=>Tc,bengaliTokenizer:()=>Cc});var Lc,Pc=fl({"src/tokenizers/bengali.ts"(){Jl(),Ac(),xc=ql([[2432,2559]]),Ec=new Set(["কে","তে","থেকে","র","এর","দিয়ে","জন্য","পর্যন্ত","এ","মধ্যে"]),Sc=[{native:"সত্য",normalized:"true"},{native:"মিথ্যা",normalized:"false"},{native:"শূন্য",normalized:"null"},{native:"অনির্ধারিত",normalized:"undefined"},{native:"প্রথম",normalized:"first"},{native:"পরবর্তী",normalized:"next"},{native:"আগের",normalized:"previous"},{native:"নিকটতম",normalized:"closest"},{native:"মূল",normalized:"parent"},{native:"ক্লিক",normalized:"click"},{native:"জমা",normalized:"submit"},{native:"ইনপুট",normalized:"input"},{native:"লোড",normalized:"load"},{native:"স্ক্রোল",normalized:"scroll"},{native:"কে",normalized:"to"},{native:"সাথে",normalized:"with"}],Cc=new(Tc=class extends Kl{constructor(){super(),this.language="bn",this.direction="ltr",this.initializeKeywordsFromProfile(kc,Sc)}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])||"-"===e[n]&&n+1<e.length&&Wl(e[n+1])){const r=this.extractNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}if(":"===e[n]){const r=n;n++;let i="";for(;n<e.length&&($l(e[n])||xc(e[n]));)i+=e[n],n++;if(i){t.push(Nl(":"+i,"identifier",Il(r,n),":"+i));continue}n=r}if(xc(e[n])){const r=n;let i="";for(;n<e.length&&xc(e[n]);)i+=e[n],n++;if(Ec.has(i))t.push(Nl(i,"particle",Il(r,n)));else{const e=this.lookupKeyword(i);e?t.push(Nl(i,"keyword",Il(r,n),e.normalized)):t.push(Nl(i,"identifier",Il(r,n)))}continue}if($l(e[n])){const r=n;let i="";for(;n<e.length&&$l(e[n]);)i+=e[n],n++;const a=this.lookupKeyword(i),o=a?"keyword":"identifier";t.push(Nl(i,o,Il(r,n),a?.normalized||i.toLowerCase()));continue}const r=n;t.push(Nl(e[n],"operator",Il(r,n+1))),n++}return new Ll(t,this.language)}classifyToken(e){return this.isKeyword(e)?"keyword":Ec.has(e)?"particle":e.startsWith(".")||e.startsWith("#")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith(":")?"identifier":e.startsWith('"')||e.startsWith("'")||/^-?\d/.test(e)?"literal":"identifier"}extractNumber(e,t){let n=t,r="";for("-"===e[n]&&(r+="-",n++);n<e.length&&Wl(e[n]);)r+=e[n],n++;if(n<e.length&&"."===e[n])for(r+=".",n++;n<e.length&&Wl(e[n]);)r+=e[n],n++;return"-"===r?null:Nl(r,"literal",Il(t,n))}})}}),Ic={};yl(Ic,{germanProfile:()=>Lc});var Nc,Oc,Rc,Mc,Wc,$c=fl({"src/generators/profiles/german.ts"(){Lc={code:"de",name:"German",nativeName:"Deutsch",direction:"ltr",wordOrder:"SVO",markingStrategy:"preposition",usesSpaces:!0,defaultVerbForm:"infinitive",verb:{position:"start",subjectDrop:!1},references:{me:"ich",it:"es",you:"du",result:"Ergebnis",event:"Ereignis",target:"Ziel",body:"Körper"},possessive:{marker:"",markerPosition:"before-property",usePossessiveAdjectives:!0,specialForms:{me:"mein",it:"sein",you:"dein"},keywords:{mein:"me",meine:"me",meinen:"me",dein:"you",deine:"you",deinen:"you",sein:"it",seine:"it",seinen:"it"}},roleMarkers:{destination:{primary:"auf",alternatives:["zu","in"],position:"before"},source:{primary:"von",alternatives:["aus"],position:"before"},patient:{primary:"",position:"before"},style:{primary:"mit",position:"before"}},keywords:{toggle:{primary:"umschalten",alternatives:["wechseln"],normalized:"toggle"},add:{primary:"hinzufügen",normalized:"add"},remove:{primary:"entfernen",alternatives:["löschen"],normalized:"remove"},put:{primary:"setzen",alternatives:["stellen","platzieren"],normalized:"put"},append:{primary:"anhängen",normalized:"append"},prepend:{primary:"voranstellen",normalized:"prepend"},take:{primary:"nehmen",normalized:"take"},make:{primary:"machen",alternatives:["erstellen","erzeugen"],normalized:"make"},clone:{primary:"klonen",alternatives:["kopieren"],normalized:"clone"},swap:{primary:"austauschen",alternatives:["tauschen","wechseln"],normalized:"swap"},morph:{primary:"verwandeln",alternatives:["transformieren"],normalized:"morph"},set:{primary:"festlegen",alternatives:["definieren"],normalized:"set"},get:{primary:"holen",alternatives:["bekommen"],normalized:"get"},increment:{primary:"erhöhen",normalized:"increment"},decrement:{primary:"verringern",alternatives:["vermindern"],normalized:"decrement"},log:{primary:"protokollieren",alternatives:["ausgeben"],normalized:"log"},show:{primary:"zeigen",alternatives:["anzeigen"],normalized:"show"},hide:{primary:"verbergen",alternatives:["verstecken"],normalized:"hide"},transition:{primary:"übergang",alternatives:["animieren"],normalized:"transition"},on:{primary:"bei",alternatives:["wenn","auf"],normalized:"on"},trigger:{primary:"auslösen",normalized:"trigger"},send:{primary:"senden",alternatives:["schicken"],normalized:"send"},focus:{primary:"fokussieren",normalized:"focus"},blur:{primary:"defokussieren",alternatives:["entfokussieren"],normalized:"blur"},go:{primary:"gehen",alternatives:["navigieren"],normalized:"go"},wait:{primary:"warten",normalized:"wait"},fetch:{primary:"abrufen",alternatives:["laden"],normalized:"fetch"},settle:{primary:"stabilisieren",normalized:"settle"},if:{primary:"wenn",alternatives:["falls"],normalized:"if"},when:{primary:"wenn",normalized:"when"},where:{primary:"wo",normalized:"where"},else:{primary:"sonst",alternatives:["ansonsten"],normalized:"else"},repeat:{primary:"wiederholen",normalized:"repeat"},for:{primary:"für",normalized:"for"},while:{primary:"solange",alternatives:["während"],normalized:"while"},continue:{primary:"fortfahren",alternatives:["weiter"],normalized:"continue"},halt:{primary:"anhalten",alternatives:["stoppen"],normalized:"halt"},throw:{primary:"werfen",normalized:"throw"},call:{primary:"aufrufen",normalized:"call"},return:{primary:"zurückgeben",normalized:"return"},then:{primary:"dann",alternatives:["danach","anschließend"],normalized:"then"},and:{primary:"und",alternatives:["sowie","auch"],normalized:"and"},end:{primary:"ende",alternatives:["beenden","fertig"],normalized:"end"},js:{primary:"js",alternatives:["javascript"],normalized:"js"},async:{primary:"asynchron",normalized:"async"},tell:{primary:"sagen",normalized:"tell"},default:{primary:"standard",normalized:"default"},init:{primary:"initialisieren",normalized:"init"},behavior:{primary:"verhalten",normalized:"behavior"},install:{primary:"installieren",normalized:"install"},measure:{primary:"messen",normalized:"measure"},beep:{primary:"piepton",normalized:"beep"},break:{primary:"unterbrechen",normalized:"break"},copy:{primary:"kopieren",normalized:"copy"},exit:{primary:"beenden",normalized:"exit"},pick:{primary:"auswählen",normalized:"pick"},render:{primary:"rendern",normalized:"render"},into:{primary:"hinein",normalized:"into"},before:{primary:"vor",normalized:"before"},after:{primary:"nach",normalized:"after"},click:{primary:"Klick",alternatives:["Klicken"],normalized:"click"},hover:{primary:"Hover",alternatives:["Schweben"],normalized:"hover"},submit:{primary:"Absenden",alternatives:["Senden"],normalized:"submit"},input:{primary:"Eingabe",normalized:"input"},change:{primary:"Änderung",alternatives:["Ändern"],normalized:"change"},until:{primary:"bis",normalized:"until"},event:{primary:"Ereignis",alternatives:["Event"],normalized:"event"},from:{primary:"von",alternatives:["aus"],normalized:"from"}},eventHandler:{keyword:{primary:"bei",alternatives:["auf"],normalized:"on"},sourceMarker:{primary:"von",alternatives:["aus"],position:"before"},conditionalKeyword:{primary:"wenn",alternatives:["falls"]},eventMarker:{primary:"bei",alternatives:["beim"],position:"before"},temporalMarkers:["wenn","bei"]}}}});var Hc,qc,Dc,_c,Vc,Bc,Fc,Uc=fl({"src/tokenizers/morphology/german-normalizer.ts"(){ic(),Nc=["an","auf","aus","ein","mit","vor","zu","ab","bei","nach","weg","um","her","hin"],Oc=[{ending:"end",stem:"en",confidence:.88,type:"gerund"},{ending:"e",stem:"en",confidence:.75,type:"present"},{ending:"st",stem:"en",confidence:.8,type:"present"},{ending:"t",stem:"en",confidence:.78,type:"present"},{ending:"en",stem:"en",confidence:.85,type:"dictionary"},{ending:"test",stem:"en",confidence:.85,type:"past"},{ending:"ten",stem:"en",confidence:.82,type:"past"},{ending:"tet",stem:"en",confidence:.85,type:"past"},{ending:"te",stem:"en",confidence:.82,type:"past"},{ending:"test",stem:"en",confidence:.8,type:"subjunctive"},{ending:"ten",stem:"en",confidence:.78,type:"subjunctive"},{ending:"tet",stem:"en",confidence:.8,type:"subjunctive"},{ending:"te",stem:"en",confidence:.78,type:"subjunctive"},{ending:"e",stem:"en",confidence:.72,type:"imperative"},{ending:"t",stem:"en",confidence:.72,type:"imperative"},{ending:"en",stem:"en",confidence:.75,type:"imperative"}],Rc=[{ending:"le",stem:"eln",confidence:.82,type:"present"},{ending:"elst",stem:"eln",confidence:.85,type:"present"},{ending:"elt",stem:"eln",confidence:.85,type:"present"},{ending:"eln",stem:"eln",confidence:.88,type:"dictionary"},{ending:"re",stem:"ern",confidence:.82,type:"present"},{ending:"erst",stem:"ern",confidence:.85,type:"present"},{ending:"ert",stem:"ern",confidence:.85,type:"present"},{ending:"ern",stem:"ern",confidence:.88,type:"dictionary"}],Mc=[...Oc,...Rc].sort((e,t)=>t.ending.length-e.ending.length),new(Wc=class{constructor(){this.language="de"}isNormalizable(e){return!(e.length<3)&&function(e){const t=e.toLowerCase();return!!(t.endsWith("en")||t.endsWith("eln")||t.endsWith("ern")||t.startsWith("ge")&&t.endsWith("t")||t.startsWith("ge")&&t.endsWith("en")||/[äöüß]/i.test(e))}(e)}normalize(e){const t=e.toLowerCase();if(t.endsWith("en")&&t.length>=4)return Yl(e);if((t.endsWith("eln")||t.endsWith("ern"))&&t.length>=5)return Yl(e);const n=this.tryParticipleNormalization(t);if(n)return n;const r=this.tryConjugationNormalization(t);return r||Yl(e)}tryParticipleNormalization(e){for(const t of Nc)if(e.startsWith(t+"ge")){const n=e.slice(t.length),r=this.trySimpleParticipleNormalization(n);if(r){const e={removedPrefixes:["ge"],conjugationType:"participle"};return r.metadata?.removedSuffixes&&(e.removedSuffixes=r.metadata.removedSuffixes),Zl(t+r.stem,.95*r.confidence,e)}}return this.trySimpleParticipleNormalization(e)}trySimpleParticipleNormalization(e){if(!e.startsWith("ge"))return null;const t=e.slice(2);if(t.endsWith("t")&&t.length>=3){return Zl(t.slice(0,-1)+"en",.85,{removedPrefixes:["ge"],removedSuffixes:["t"],conjugationType:"participle"})}return t.endsWith("en")&&t.length>=4?Zl(t,.82,{removedPrefixes:["ge"],conjugationType:"participle"}):null}tryConjugationNormalization(e){for(const t of Mc)if(e.endsWith(t.ending)){const n=e.slice(0,-t.ending.length);if(n.length<2)continue;return Zl(n+t.stem,t.confidence,{removedSuffixes:[t.ending],conjugationType:t.type})}return null}})}}),Kc={};yl(Kc,{GermanTokenizer:()=>Bc,germanTokenizer:()=>Fc});var Gc,Qc=fl({"src/tokenizers/german.ts"(){Jl(),$c(),Uc(),({isLetter:Hc,isIdentifierChar:qc}=_l(/[a-zA-ZäöüÄÖÜß]/)),Dc=new Set(["an","auf","aus","bei","durch","für","fur","gegen","in","mit","nach","ohne","seit","über","uber","um","unter","von","vor","zu","zwischen","bis","gegenüber","gegenuber","während","wahrend","wegen","trotz","statt","innerhalb","außerhalb","ausserhalb"]),_c=[{native:"wahr",normalized:"true"},{native:"falsch",normalized:"false"},{native:"null",normalized:"null"},{native:"undefiniert",normalized:"undefined"},{native:"erste",normalized:"first"},{native:"erster",normalized:"first"},{native:"erstes",normalized:"first"},{native:"letzte",normalized:"last"},{native:"letzter",normalized:"last"},{native:"letztes",normalized:"last"},{native:"nächste",normalized:"next"},{native:"nachste",normalized:"next"},{native:"vorherige",normalized:"previous"},{native:"nächste",normalized:"closest"},{native:"eltern",normalized:"parent"},{native:"klick",normalized:"click"},{native:"click",normalized:"click"},{native:"eingabe",normalized:"input"},{native:"änderung",normalized:"change"},{native:"anderung",normalized:"change"},{native:"absenden",normalized:"submit"},{native:"taste unten",normalized:"keydown"},{native:"taste oben",normalized:"keyup"},{native:"maus drüber",normalized:"mouseover"},{native:"maus druber",normalized:"mouseover"},{native:"maus weg",normalized:"mouseout"},{native:"fokus",normalized:"focus"},{native:"unschärfe",normalized:"blur"},{native:"unscharfe",normalized:"blur"},{native:"scrollen",normalized:"scroll"},{native:"meine",normalized:"my"},{native:"meinen",normalized:"my"},{native:"ergebnis",normalized:"result"},{native:"ziel",normalized:"target"},{native:"sekunde",normalized:"s"},{native:"sekunden",normalized:"s"},{native:"millisekunde",normalized:"ms"},{native:"millisekunden",normalized:"ms"},{native:"minute",normalized:"m"},{native:"minuten",normalized:"m"},{native:"stunde",normalized:"h"},{native:"stunden",normalized:"h"},{native:"hinzufugen",normalized:"add"},{native:"hinzufgen",normalized:"add"},{native:"loschen",normalized:"remove"},{native:"anhangen",normalized:"append"},{native:"erhohen",normalized:"increment"},{native:"ubergang",normalized:"transition"},{native:"auslosen",normalized:"trigger"},{native:"zuruckgeben",normalized:"return"},{native:"anschliessend",normalized:"then"},{native:"erhöhe",normalized:"increment"},{native:"erhohe",normalized:"increment"},{native:"verringere",normalized:"decrement"}],Vc=[{pattern:"millisekunden",suffix:"ms",length:13,caseInsensitive:!0},{pattern:"millisekunde",suffix:"ms",length:12,caseInsensitive:!0},{pattern:"sekunden",suffix:"s",length:8,caseInsensitive:!0},{pattern:"sekunde",suffix:"s",length:7,caseInsensitive:!0},{pattern:"minuten",suffix:"m",length:7,caseInsensitive:!0},{pattern:"minute",suffix:"m",length:6,caseInsensitive:!0},{pattern:"stunden",suffix:"h",length:7,caseInsensitive:!0},{pattern:"stunde",suffix:"h",length:6,caseInsensitive:!0}],Fc=new(Bc=class extends Kl{constructor(){super(),this.language="de",this.direction="ltr",this.initializeKeywordsFromProfile(Lc,_c),this.normalizer=new Wc}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])||"-"===e[n]&&n+1<e.length&&Wl(e[n+1])){const r=this.extractNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}if(Hc(e[n])){const r=this.extractWord(e,n);if(r){t.push(r),n=r.position.end;continue}}const i=this.tryOperator(e,n);i?(t.push(i),n=i.position.end):n++}return new Ll(t,"de")}classifyToken(e){const t=e.toLowerCase();return Dc.has(t)?"particle":this.isKeyword(t)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||/^\d/.test(e)?"literal":"identifier"}extractWord(e,t){let n=t,r="";for(;n<e.length&&qc(e[n]);)r+=e[n++];if(!r)return null;const i=r.toLowerCase(),a=this.lookupKeyword(i);return a?Nl(r,"keyword",Il(t,n),a.normalized):Dc.has(i)?Nl(r,"particle",Il(t,n)):Nl(r,"identifier",Il(t,n))}extractNumber(e,t){return this.tryNumberWithTimeUnits(e,t,Vc,{allowSign:!0,skipWhitespace:!0})}})}}),Jc={};yl(Jc,{englishProfile:()=>Gc});var Yc,Zc,Xc,eu=fl({"src/generators/profiles/english.ts"(){Gc={code:"en",name:"English",nativeName:"English",direction:"ltr",wordOrder:"SVO",markingStrategy:"preposition",usesSpaces:!0,defaultVerbForm:"base",verb:{position:"start",subjectDrop:!1},references:{me:"me",it:"it",you:"you",result:"result",event:"event",target:"target",body:"body"},possessive:{marker:"'s",markerPosition:"after-object",specialForms:{me:"my",it:"its",you:"your"},keywords:{my:"me",your:"you",its:"it"}},roleMarkers:{destination:{primary:"on",alternatives:["to","from"],position:"before"},source:{primary:"from",position:"before"},patient:{primary:"",position:"before"},style:{primary:"with",alternatives:["by","using"],position:"before"},responseType:{primary:"as",position:"before"},method:{primary:"via",alternatives:["using"],position:"before"}},keywords:{toggle:{primary:"toggle"},add:{primary:"add"},remove:{primary:"remove"},put:{primary:"put"},append:{primary:"append"},prepend:{primary:"prepend"},take:{primary:"take"},make:{primary:"make"},clone:{primary:"clone"},swap:{primary:"swap"},morph:{primary:"morph"},set:{primary:"set"},get:{primary:"get"},increment:{primary:"increment"},decrement:{primary:"decrement"},log:{primary:"log"},show:{primary:"show"},hide:{primary:"hide"},transition:{primary:"transition"},on:{primary:"on"},trigger:{primary:"trigger"},send:{primary:"send"},focus:{primary:"focus"},blur:{primary:"blur"},go:{primary:"go"},wait:{primary:"wait"},fetch:{primary:"fetch"},settle:{primary:"settle"},if:{primary:"if"},when:{primary:"when",normalized:"when"},where:{primary:"where",normalized:"where"},else:{primary:"else"},repeat:{primary:"repeat"},for:{primary:"for"},while:{primary:"while"},continue:{primary:"continue"},halt:{primary:"halt"},throw:{primary:"throw"},call:{primary:"call"},return:{primary:"return"},then:{primary:"then"},and:{primary:"and"},end:{primary:"end"},js:{primary:"js"},async:{primary:"async"},tell:{primary:"tell"},default:{primary:"default"},init:{primary:"init"},behavior:{primary:"behavior"},install:{primary:"install"},measure:{primary:"measure"},beep:{primary:"beep"},break:{primary:"break"},copy:{primary:"copy"},exit:{primary:"exit"},pick:{primary:"pick"},render:{primary:"render"},into:{primary:"into"},before:{primary:"before"},after:{primary:"after"},until:{primary:"until"},event:{primary:"event"},from:{primary:"from"}}}}}),tu={};yl(tu,{EnglishTokenizer:()=>Zc,englishTokenizer:()=>Xc});var nu,ru,iu,au=fl({"src/tokenizers/english.ts"(){Jl(),eu(),Yc=[{native:"true",normalized:"true"},{native:"false",normalized:"false"},{native:"null",normalized:"null"},{native:"undefined",normalized:"undefined"},{native:"first",normalized:"first"},{native:"last",normalized:"last"},{native:"next",normalized:"next"},{native:"previous",normalized:"previous"},{native:"closest",normalized:"closest"},{native:"click",normalized:"click"},{native:"dblclick",normalized:"dblclick"},{native:"mousedown",normalized:"mousedown"},{native:"mouseup",normalized:"mouseup"},{native:"mouseover",normalized:"mouseover"},{native:"mouseout",normalized:"mouseout"},{native:"mouseenter",normalized:"mouseenter"},{native:"mouseleave",normalized:"mouseleave"},{native:"mousemove",normalized:"mousemove"},{native:"keydown",normalized:"keydown"},{native:"keyup",normalized:"keyup"},{native:"keypress",normalized:"keypress"},{native:"input",normalized:"input"},{native:"change",normalized:"change"},{native:"submit",normalized:"submit"},{native:"reset",normalized:"reset"},{native:"load",normalized:"load"},{native:"unload",normalized:"unload"},{native:"scroll",normalized:"scroll"},{native:"resize",normalized:"resize"},{native:"dragstart",normalized:"dragstart"},{native:"drag",normalized:"drag"},{native:"dragend",normalized:"dragend"},{native:"dragenter",normalized:"dragenter"},{native:"dragleave",normalized:"dragleave"},{native:"dragover",normalized:"dragover"},{native:"drop",normalized:"drop"},{native:"touchstart",normalized:"touchstart"},{native:"touchmove",normalized:"touchmove"},{native:"touchend",normalized:"touchend"},{native:"touchcancel",normalized:"touchcancel"},{native:"in",normalized:"in"},{native:"to",normalized:"to"},{native:"at",normalized:"at"},{native:"by",normalized:"by"},{native:"with",normalized:"with"},{native:"without",normalized:"without"},{native:"of",normalized:"of"},{native:"as",normalized:"as"},{native:"every",normalized:"every"},{native:"upon",normalized:"upon"},{native:"unless",normalized:"unless"},{native:"forever",normalized:"forever"},{native:"times",normalized:"times"},{native:"and",normalized:"and"},{native:"or",normalized:"or"},{native:"not",normalized:"not"},{native:"is",normalized:"is"},{native:"exists",normalized:"exists"},{native:"empty",normalized:"empty"},{native:"my",normalized:"my"},{native:"your",normalized:"your"},{native:"its",normalized:"its"},{native:"the",normalized:"the"},{native:"a",normalized:"a"},{native:"an",normalized:"an"},{native:"delete",normalized:"delete"},{native:"innerHTML",normalized:"innerHTML"},{native:"outerHTML",normalized:"outerHTML"},{native:"beforebegin",normalized:"beforebegin"},{native:"afterend",normalized:"afterend"},{native:"beforeend",normalized:"beforeend"},{native:"afterbegin",normalized:"afterbegin"},{native:"flip",normalized:"toggle"},{native:"switch",normalized:"toggle"},{native:"increase",normalized:"increment"},{native:"decrease",normalized:"decrement"},{native:"display",normalized:"show"},{native:"reveal",normalized:"show"},{native:"conceal",normalized:"hide"},{native:"colour",normalized:"color"},{native:"grey",normalized:"gray"},{native:"centre",normalized:"center"},{native:"behaviour",normalized:"behavior"},{native:"initialise",normalized:"initialize"},{native:"favourite",normalized:"favorite"}],Xc=new(Zc=class extends Kl{constructor(){super(),this.language="en",this.direction="ltr",this.initializeKeywordsFromProfile(Gc,Yc)}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if("."===e[n]){const r=t[t.length-1],i=r&&r.position.end<n;if(r&&!i&&("identifier"===r.kind||"keyword"===r.kind||"selector"===r.kind)){t.push(Nl(".","operator",Il(n,n+1))),n++;continue}let a=n+1;for(;a<e.length&&$l(e[a]);)a++;if(a<e.length&&"("===e[a]){t.push(Nl(".","operator",Il(n,n+1))),n++;continue}}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){if("'"===e[n]&&Bl(e,n)){t.push(Nl("'s","punctuation",Il(n,n+2))),n+=2;continue}const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])||"-"===e[n]&&n+1<e.length&&Wl(e[n+1])){const r=this.tryNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}if($l(e[n])){const r=this.extractWord(e,n);if(r){t.push(r),n=r.position.end;continue}}const i=this.tryOperator(e,n);i?(t.push(i),n=i.position.end):n++}return new Ll(t,"en")}classifyToken(e){return this.isKeyword(e)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||/^\d/.test(e)?"literal":["==","!=","<=",">=","<",">","&&","||","!"].includes(e)?"operator":e.startsWith("/")||e.startsWith("./")||e.startsWith("http")?"url":"identifier"}extractWord(e,t){let n=t,r="";for(;n<e.length&&$l(e[n]);)r+=e[n++];if(!r)return null;if(n<e.length&&":"===e[n]){const t=n;n++;let i="";for(;n<e.length&&$l(e[n]);)i+=e[n++];i?r=r+":"+i:n=t}const i=this.classifyToken(r),a=this.lookupKeyword(r),o=a&&a.normalized!==a.native?a.normalized:void 0;if("identifier"===i){const t=this.tryConvertToClassSelector(e,n,r);if(t)return t.token}return Nl(r,i,Il(t,n),o)}tryConvertToClassSelector(e,t,n){let r=t;for(;r<e.length&&/\s/.test(e[r]);)r++;if("class"===e.slice(r,r+5).toLowerCase()){const i=r+5;if(i>=e.length||!$l(e[i])){return{token:Nl("."+n,"selector",Il(t-n.length,t)),endPos:t}}}return null}})}});function ou(e,t){return e.replace(/\{(\w+)\}/g,(e,n)=>String(t[n]??`{${n}}`))}function su(e,t,n={},r){const i=ou(ru[e],n),a=iu[e],o=a?ou(a,n):void 0;return{code:e,message:i,severity:t,...r&&{role:r},...o&&{suggestion:o}}}var lu,cu,uu=fl({"src/generators/schema-error-codes.ts"(){nu={AMBIGUOUS_TYPE_LITERAL_SELECTOR:"SCHEMA_AMBIGUOUS_TYPE_LITERAL_SELECTOR",TOO_MANY_EXPECTED_TYPES:"SCHEMA_TOO_MANY_EXPECTED_TYPES",MULTI_TYPE_PATIENT_EXPECTED:"SCHEMA_MULTI_TYPE_PATIENT_EXPECTED",NO_REQUIRED_ROLES:"SCHEMA_NO_REQUIRED_ROLES",NO_REQUIRED_ROLES_EXPECTED:"SCHEMA_NO_REQUIRED_ROLES_EXPECTED",TRANSITION_PATIENT_ACCEPTS_SELECTOR:"SCHEMA_TRANSITION_PATIENT_ACCEPTS_SELECTOR",TRANSITION_MISSING_GOAL:"SCHEMA_TRANSITION_MISSING_GOAL",EVENT_HANDLER_MISSING_EVENT:"SCHEMA_EVENT_HANDLER_MISSING_EVENT",EVENT_HANDLER_EVENT_NOT_REQUIRED:"SCHEMA_EVENT_HANDLER_EVENT_NOT_REQUIRED",CONDITIONAL_MISSING_CONDITION:"SCHEMA_CONDITIONAL_MISSING_CONDITION",CONDITIONAL_CONDITION_NOT_REQUIRED:"SCHEMA_CONDITIONAL_CONDITION_NOT_REQUIRED",FOR_LOOP_MISSING_SOURCE:"SCHEMA_FOR_LOOP_MISSING_SOURCE",WHILE_LOOP_MISSING_CONDITION:"SCHEMA_WHILE_LOOP_MISSING_CONDITION"},ru={[nu.AMBIGUOUS_TYPE_LITERAL_SELECTOR]:"Role '{role}' accepts both 'literal' and 'selector'. This may cause ambiguous type inference for values starting with special characters (* . # etc.).",[nu.TOO_MANY_EXPECTED_TYPES]:"Role '{role}' accepts {count} different types. This may make type inference unreliable.",[nu.MULTI_TYPE_PATIENT_EXPECTED]:"Role '{role}' accepts multiple types (expected for {command} command).",[nu.NO_REQUIRED_ROLES]:"Command has no required roles. Is this intentional?",[nu.NO_REQUIRED_ROLES_EXPECTED]:"Command has no required roles (expected for {command}).",[nu.TRANSITION_PATIENT_ACCEPTS_SELECTOR]:"Transition command 'patient' role (CSS property name) should only accept 'literal', not 'selector'. CSS property names like 'background-color' are strings, not CSS selectors.",[nu.TRANSITION_MISSING_GOAL]:"Transition command requires a 'goal' role for the target value (to <value>). Without it, there's no way to specify what value to transition to.",[nu.EVENT_HANDLER_MISSING_EVENT]:"Event handler command should have an 'event' role to specify which event to listen for.",[nu.EVENT_HANDLER_EVENT_NOT_REQUIRED]:"Event role should be required - every event handler needs an event to listen for.",[nu.CONDITIONAL_MISSING_CONDITION]:"Conditional command should have a 'condition' role for the boolean expression.",[nu.CONDITIONAL_CONDITION_NOT_REQUIRED]:"Condition role should be required - conditionals need a condition to evaluate.",[nu.FOR_LOOP_MISSING_SOURCE]:"For-loop should have a 'source' role for the collection to iterate over.",[nu.WHILE_LOOP_MISSING_CONDITION]:"While-loop should have a 'condition' role for the loop condition."},iu={[nu.AMBIGUOUS_TYPE_LITERAL_SELECTOR]:"Consider being more specific about which type is expected, or use explicit type markers.",[nu.TOO_MANY_EXPECTED_TYPES]:"Consider narrowing the accepted types to improve type inference reliability.",[nu.TRANSITION_PATIENT_ACCEPTS_SELECTOR]:"Remove 'selector' from expectedTypes and only accept 'literal'.",[nu.TRANSITION_MISSING_GOAL]:"Add a 'goal' role with expectedTypes ['literal', 'variable'].",[nu.EVENT_HANDLER_MISSING_EVENT]:"Add an 'event' role with expectedTypes ['literal'].",[nu.EVENT_HANDLER_EVENT_NOT_REQUIRED]:"Set required: true on the 'event' role.",[nu.CONDITIONAL_MISSING_CONDITION]:"Add a 'condition' role with expectedTypes ['expression'].",[nu.CONDITIONAL_CONDITION_NOT_REQUIRED]:"Set required: true on the 'condition' role.",[nu.FOR_LOOP_MISSING_SOURCE]:"Add a 'source' role for the collection to iterate over.",[nu.WHILE_LOOP_MISSING_CONDITION]:"Add a 'condition' role for the loop continuation condition."}}}),pu={};function mu(e){const t=[];for(const n of e.roles)n.expectedTypes.includes("literal")&&n.expectedTypes.includes("selector")&&("patient"===n.role&&lu.has(e.action)?t.push(su(nu.MULTI_TYPE_PATIENT_EXPECTED,"note",{role:n.role,command:e.action},n.role)):t.push(su(nu.AMBIGUOUS_TYPE_LITERAL_SELECTOR,"warning",{role:n.role},n.role))),n.expectedTypes.length>3&&!lu.has(e.action)&&t.push(su(nu.TOO_MANY_EXPECTED_TYPES,"warning",{role:n.role,count:n.expectedTypes.length},n.role));switch(e.action){case"transition":!function(e,t){const n=e.roles.find(e=>"patient"===e.role),r=e.roles.find(e=>"goal"===e.role);n&&n.expectedTypes.includes("selector")&&t.push(su(nu.TRANSITION_PATIENT_ACCEPTS_SELECTOR,"warning",{},"patient"));n&&!r&&t.push(su(nu.TRANSITION_MISSING_GOAL,"error",{}))}(e,t);break;case"on":!function(e,t){const n=e.roles.find(e=>"event"===e.role);n||t.push(su(nu.EVENT_HANDLER_MISSING_EVENT,"warning",{}));n&&!n.required&&t.push(su(nu.EVENT_HANDLER_EVENT_NOT_REQUIRED,"warning",{}))}(e,t);break;case"if":case"unless":!function(e,t){const n=e.roles.find(e=>"condition"===e.role);n||t.push(su(nu.CONDITIONAL_MISSING_CONDITION,"warning",{}));n&&!n.required&&t.push(su(nu.CONDITIONAL_CONDITION_NOT_REQUIRED,"warning",{}))}(e,t);break;case"repeat":case"for":case"while":!function(e,t){if("for"===e.action){e.roles.find(e=>"source"===e.role)||t.push(su(nu.FOR_LOOP_MISSING_SOURCE,"warning",{}))}else if("while"===e.action){e.roles.find(e=>"condition"===e.role)||t.push(su(nu.WHILE_LOOP_MISSING_CONDITION,"warning",{}))}}(e,t)}return 0===e.roles.filter(e=>e.required).length&&(cu.has(e.action)?t.push(su(nu.NO_REQUIRED_ROLES_EXPECTED,"note",{command:e.action})):t.push(su(nu.NO_REQUIRED_ROLES,"warning",{}))),function(e,t){return{action:e,items:t,get notes(){return t.filter(e=>"note"===e.severity).map(e=>e.message)},get warnings(){return t.filter(e=>"warning"===e.severity).map(e=>e.message)},get errors(){return t.filter(e=>"error"===e.severity).map(e=>e.message)}}}(e.action,t)}function du(e,t={}){const n=new Map,{includeNotes:r=!1}=t;for(const[t,i]of Object.entries(e)){const e=mu(i),a=e.items.some(e=>"warning"===e.severity||"error"===e.severity),o=r&&e.items.some(e=>"note"===e.severity);(a||o)&&n.set(t,e)}return n}function hu(e,t={}){const n=[],{showNotes:r=!1,showCodes:i=!0}=t;for(const[t,a]of e){const e=a.items.filter(e=>"error"===e.severity),o=a.items.filter(e=>"warning"===e.severity),s=a.items.filter(e=>"note"===e.severity);if(e.length>0){n.push(` ❌ ${t}:`);for(const t of e){const e=i?` [${t.code}]`:"";n.push(` ERROR${e}: ${t.message}`),t.suggestion&&n.push(` 💡 Suggestion: ${t.suggestion}`)}}if(o.length>0){n.push(` ⚠️ ${t}:`);for(const e of o){const t=i?` [${e.code}]`:"";n.push(` ${t?`${e.code}: `:""}${e.message}`),e.suggestion&&n.push(` 💡 ${e.suggestion}`)}}if(r&&s.length>0){n.push(` ℹ️ ${t}:`);for(const e of s){const t=i?` [${e.code}]`:"";n.push(` ${t?`${e.code}: `:""}${e.message}`)}}}return n.join("\n")}function fu(e){let t=0,n=0,r=0;const i={};for(const a of e.values())for(const e of a.items)"error"===e.severity?t++:"warning"===e.severity?n++:"note"===e.severity&&r++,i[e.code]=(i[e.code]||0)+1;return{totalCommands:e.size,errors:t,warnings:n,notes:r,byCode:i}}yl(pu,{SchemaErrorCodes:()=>nu,formatValidationResults:()=>hu,getValidationStats:()=>fu,validateAllSchemas:()=>du,validateCommandSchema:()=>mu});var yu,vu,gu,bu,ku,wu,zu,xu,Eu,Su,Tu,Cu,Au,ju,Lu,Pu,Iu=fl({"src/generators/schema-validator.ts"(){uu(),lu=new Set(["put","append","prepend","log","throw","make","measure","return","swap","morph","beep","copy"]),cu=new Set(["compound","else","halt","continue","async","init","settle","focus","blur","return","js","measure","break","exit","beep"])}});function Nu(){return Object.values(Pu).filter(e=>e.roles.length>0)}var Ou=fl({"src/generators/command-schemas.ts"(){Pu={toggle:yu={action:"toggle",description:"Toggle a class or attribute on/off",category:"dom-class",primaryRole:"patient",roles:[{role:"patient",description:"The class or attribute to toggle",required:!0,expectedTypes:["selector"],svoPosition:1,sovPosition:2},{role:"destination",description:"The target element (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1}],errorCodes:["MISSING_ARGUMENT","NO_VALID_CLASS_NAMES","INVALID_CSS_PROPERTY"],preconditions:[{condition:"Command has at least one argument",errorCode:"MISSING_ARGUMENT",message:"toggle command requires an argument"},{condition:"Class names are valid CSS identifiers",errorCode:"NO_VALID_CLASS_NAMES",message:"toggle command: no valid class names found"}],recoveryHints:{MISSING_ARGUMENT:"Add a class selector (.classname) or attribute to toggle",NO_VALID_CLASS_NAMES:"Ensure class names start with a dot (.) and are valid CSS identifiers",INVALID_CSS_PROPERTY:"Check CSS property name syntax (use kebab-case)"}},add:vu={action:"add",description:"Add a class or attribute to an element",category:"dom-class",primaryRole:"patient",roles:[{role:"patient",description:"The class or attribute to add",required:!0,expectedTypes:["selector"],svoPosition:1,sovPosition:2},{role:"destination",description:"The target element (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1,markerOverride:{en:"to"}}],errorCodes:["MISSING_ARGUMENT","NO_VALID_CLASS_NAMES","PROPERTY_REQUIRES_VALUE"],preconditions:[{condition:"Command has at least one argument",errorCode:"MISSING_ARGUMENT",message:"add command requires an argument"}],recoveryHints:{MISSING_ARGUMENT:"Add a class selector (.classname) or attribute to add",NO_VALID_CLASS_NAMES:"Ensure class names start with a dot (.) and are valid CSS identifiers",PROPERTY_REQUIRES_VALUE:"When adding a property (*prop), provide a value argument"}},remove:gu={action:"remove",description:"Remove a class or attribute from an element",category:"dom-class",primaryRole:"patient",roles:[{role:"patient",description:"The class or attribute to remove",required:!0,expectedTypes:["selector"],svoPosition:1,sovPosition:2},{role:"source",description:"The element to remove from (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1}],errorCodes:["MISSING_ARGUMENT","NO_VALID_CLASS_NAMES"],preconditions:[{condition:"Command has at least one argument",errorCode:"MISSING_ARGUMENT",message:"remove command requires an argument"}],recoveryHints:{MISSING_ARGUMENT:"Add a class selector (.classname) or attribute to remove",NO_VALID_CLASS_NAMES:"Ensure class names start with a dot (.) and are valid CSS identifiers"}},put:bu={action:"put",description:"Put content into a target element or variable",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The content to put",required:!0,expectedTypes:["literal","selector","reference","expression"],svoPosition:1,sovPosition:1},{role:"destination",description:"Where to put the content",required:!0,expectedTypes:["selector","reference"],svoPosition:2,sovPosition:2,markerOverride:{en:"into"}}],errorCodes:["MISSING_ARGUMENTS","MISSING_CONTENT","MISSING_POSITION","INVALID_POSITION","NO_TARGET","NO_ELEMENTS"],preconditions:[{condition:"Command has content and position arguments",errorCode:"MISSING_ARGUMENTS",message:"put requires arguments"},{condition:"Content to put is specified",errorCode:"MISSING_CONTENT",message:"put requires content"},{condition:"Position keyword is specified (into, before, after, etc.)",errorCode:"MISSING_POSITION",message:"put requires position keyword"}],recoveryHints:{MISSING_ARGUMENTS:"Use syntax: put <content> into/before/after <target>",MISSING_CONTENT:"Add content to put (string, element, or expression)",MISSING_POSITION:"Add position keyword: into, before, after, at start of, at end of",INVALID_POSITION:"Valid positions: into, before, after, at start of, at end of",NO_TARGET:'Ensure target element exists or use "me" reference',NO_ELEMENTS:"Check that the selector matches existing elements"}},set:ku={action:"set",description:"Set a property or variable to a value",category:"variable",primaryRole:"destination",roles:[{role:"destination",description:"The property or variable to set",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:1,sovPosition:1,markerOverride:{en:"",ja:"を",ko:"를",tr:"i",ar:"",sw:"",tl:"",bn:"কে",qu:"ta"}},{role:"patient",description:"The value to set",required:!0,expectedTypes:["literal","expression","reference"],svoPosition:2,sovPosition:2,markerOverride:{en:"to",es:"a",pt:"para",fr:"à",de:"auf",id:"ke",ja:"に",ko:"으로",tr:"e",ar:"إلى",sw:"kwenye",tl:"sa",bn:"তে",qu:"man"}}],errorCodes:["MISSING_TARGET","INVALID_TARGET","MISSING_VALUE","INVALID_SYNTAX"],preconditions:[{condition:"Command has a target variable or property",errorCode:"MISSING_TARGET",message:"set command requires a target"},{condition:"Target is a valid variable or property reference",errorCode:"INVALID_TARGET",message:"set command target must be a string or object literal"},{condition:'Value is specified with "to" keyword',errorCode:"MISSING_VALUE",message:'set command requires a value (use "to" keyword)'}],recoveryHints:{MISSING_TARGET:"Add a target: set :variable to value OR set element.property to value",INVALID_TARGET:'Use local variable (:name), element property (el.prop), or "the X of Y" syntax',MISSING_VALUE:'Add "to <value>" to specify what to set',INVALID_SYNTAX:"Use syntax: set <target> to <value>"}},show:wu={action:"show",description:"Make an element visible",category:"dom-visibility",primaryRole:"patient",roles:[{role:"patient",description:"The element to show",required:!0,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1},{role:"style",description:"Animation style (fade, slide, etc.)",required:!1,expectedTypes:["literal"],svoPosition:2,sovPosition:2}]},hide:zu={action:"hide",description:"Make an element invisible",category:"dom-visibility",primaryRole:"patient",roles:[{role:"patient",description:"The element to hide",required:!0,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1},{role:"style",description:"Animation style (fade, slide, etc.)",required:!1,expectedTypes:["literal"],svoPosition:2,sovPosition:2}]},on:xu={action:"on",description:"Handle an event",category:"event",primaryRole:"event",hasBody:!0,roles:[{role:"event",description:"The event to handle",required:!0,expectedTypes:["literal"],svoPosition:1,sovPosition:2},{role:"source",description:"The element to listen on (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1}]},trigger:Eu={action:"trigger",description:"Trigger/dispatch an event",category:"event",primaryRole:"event",roles:[{role:"event",description:"The event to trigger (supports namespaced events like draggable:start)",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:2},{role:"destination",description:"The target element (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1}]},wait:Su={action:"wait",description:"Wait for a duration or event",category:"async",primaryRole:"patient",roles:[{role:"patient",description:"Duration or event to wait for",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1}]},fetch:Tu={action:"fetch",description:"Fetch data from a URL",category:"async",primaryRole:"source",roles:[{role:"source",description:"The URL to fetch from",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1,renderOverride:{en:""}},{role:"responseType",description:"Response format (json, text, html, blob, etc.)",required:!1,expectedTypes:["literal","expression"],svoPosition:2,sovPosition:2},{role:"method",description:"HTTP method (GET, POST, etc.)",required:!1,expectedTypes:["literal"],svoPosition:3,sovPosition:3},{role:"destination",description:"Where to store the result",required:!1,expectedTypes:["selector","reference"],svoPosition:4,sovPosition:4}]},increment:Cu={action:"increment",description:"Increment a numeric value",category:"variable",primaryRole:"patient",roles:[{role:"patient",description:"The value to increment",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:1,sovPosition:1},{role:"quantity",description:"Amount to increment by (defaults to 1)",required:!1,expectedTypes:["literal"],default:{type:"literal",value:1,dataType:"number"},svoPosition:2,sovPosition:2,markerOverride:{en:"by"}}]},decrement:Au={action:"decrement",description:"Decrement a numeric value",category:"variable",primaryRole:"patient",roles:[{role:"patient",description:"The value to decrement",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:1,sovPosition:1},{role:"quantity",description:"Amount to decrement by (defaults to 1)",required:!1,expectedTypes:["literal"],default:{type:"literal",value:1,dataType:"number"},svoPosition:2,sovPosition:2,markerOverride:{en:"by"}}]},append:ju={action:"append",description:"Append content to an element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The content to append",required:!0,expectedTypes:["literal","selector","expression"],svoPosition:1,sovPosition:2},{role:"destination",description:"The element to append to",required:!0,expectedTypes:["selector","reference"],svoPosition:2,sovPosition:1,markerOverride:{en:"to"}}]},prepend:Lu={action:"prepend",description:"Prepend content to an element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The content to prepend",required:!0,expectedTypes:["literal","selector","expression"],svoPosition:1,sovPosition:2},{role:"destination",description:"The element to prepend to",required:!0,expectedTypes:["selector","reference"],svoPosition:2,sovPosition:1,markerOverride:{en:"to"}}]},log:{action:"log",description:"Log a value to the console",category:"variable",primaryRole:"patient",roles:[{role:"patient",description:"The value to log",required:!0,expectedTypes:["literal","selector","reference","expression"],svoPosition:1,sovPosition:1}]},get:{action:"get",description:"Get a value from a source",category:"variable",primaryRole:"source",roles:[{role:"source",description:"The source to get from",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:1,sovPosition:2,markerOverride:{en:"",es:"",pt:"",fr:"",de:"",ja:"を",zh:"",ko:"를",ar:"على",tr:"i",id:"",sw:"",tl:"",bn:"কে",qu:"ta"}},{role:"destination",description:"Where to store the result (optional)",required:!1,expectedTypes:["reference"],svoPosition:2,sovPosition:1}]},take:{action:"take",description:"Take content from a source element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The class or element to take",required:!0,expectedTypes:["selector"],svoPosition:1,sovPosition:2},{role:"source",description:"The element to take from (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1}]},make:{action:"make",description:"Create a new element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element type or selector to create",required:!0,expectedTypes:["literal","selector"],svoPosition:1,sovPosition:1}]},halt:{action:"halt",description:"Halt/stop execution or event propagation",category:"control-flow",primaryRole:"patient",roles:[{role:"patient",description:"What to halt (event, default, bubbling, etc.)",required:!1,expectedTypes:["literal","reference","expression"],svoPosition:1,sovPosition:1}]},settle:{action:"settle",description:"Wait for animations/transitions to settle",category:"async",primaryRole:"patient",roles:[{role:"patient",description:"The element to settle (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},throw:{action:"throw",description:"Throw an error",category:"control-flow",primaryRole:"patient",roles:[{role:"patient",description:"The error message or object to throw",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1}]},send:{action:"send",description:"Send an event to an element",category:"event",primaryRole:"event",roles:[{role:"event",description:"The event to send",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:2},{role:"destination",description:"The target element (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1,markerOverride:{en:"to",ja:"に",ar:"إلى",es:"a",ko:"에게",zh:"到",tr:"-e",pt:"para",fr:"à",de:"an",id:"ke",qu:"-man",sw:"kwa"}}]},if:{action:"if",description:"Conditional execution",category:"control-flow",primaryRole:"condition",hasBody:!0,roles:[{role:"condition",description:"The condition to evaluate",required:!0,expectedTypes:["expression"],svoPosition:1,sovPosition:1}]},unless:{action:"unless",description:"Negated conditional execution (executes when condition is false)",category:"control-flow",primaryRole:"condition",hasBody:!0,roles:[{role:"condition",description:"The condition to evaluate (body executes when false)",required:!0,expectedTypes:["expression"],svoPosition:1,sovPosition:1}]},else:{action:"else",description:"Else branch of conditional",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[]},repeat:{action:"repeat",description:"Repeat a block of commands",category:"control-flow",primaryRole:"loopType",hasBody:!0,roles:[{role:"loopType",description:"Loop variant: forever, times, for, while, until, until-event",required:!0,expectedTypes:["literal"],svoPosition:0,sovPosition:0},{role:"quantity",description:"Number of times to repeat",required:!1,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1},{role:"event",description:"Event to wait for (terminates loop)",required:!1,expectedTypes:["literal","expression"],svoPosition:2,sovPosition:2},{role:"source",description:"Element to listen for event on",required:!1,expectedTypes:["selector","reference"],svoPosition:3,sovPosition:3}],notes:'Can also use "repeat forever", "repeat until condition", or "repeat until event X from Y"'},for:{action:"for",description:"Iterate over a collection",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[{role:"patient",description:"The iteration variable",required:!0,expectedTypes:["reference"],svoPosition:1,sovPosition:2},{role:"source",description:"The collection to iterate over",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:2,sovPosition:1,markerOverride:{en:"in"}}]},while:{action:"while",description:"Loop while condition is true",category:"control-flow",primaryRole:"condition",hasBody:!0,roles:[{role:"condition",description:"The condition to check",required:!0,expectedTypes:["expression"],svoPosition:1,sovPosition:1}]},continue:{action:"continue",description:"Continue to next loop iteration",category:"control-flow",primaryRole:"patient",roles:[]},go:{action:"go",description:"Navigate to a URL",category:"navigation",primaryRole:"destination",roles:[{role:"destination",description:"The URL to navigate to",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1,markerOverride:{en:"to"},renderOverride:{en:""}}]},transition:{action:"transition",description:"Transition an element with animation",category:"dom-visibility",primaryRole:"patient",roles:[{role:"patient",description:"The property to transition (opacity, *background-color, etc.)",required:!0,expectedTypes:["literal"],svoPosition:1,sovPosition:2,markerOverride:{en:"",ar:"",tl:"",sw:""}},{role:"goal",description:"The target value to transition to",required:!0,expectedTypes:["literal","expression"],svoPosition:2,sovPosition:3,markerOverride:{en:"to",ar:"إلى",tl:"sa",sw:"kwenye",bn:"তে",qu:"man",es:"a",pt:"para",fr:"à",de:"auf",ja:"に",ko:"으로",tr:"e",id:"ke"}},{role:"destination",description:"The target element (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:3,sovPosition:1},{role:"duration",description:"Transition duration (over 500ms, for 2 seconds)",required:!1,expectedTypes:["literal"],svoPosition:4,sovPosition:4,markerOverride:{en:"over"}},{role:"style",description:"Easing function (ease-in, linear, etc.)",required:!1,expectedTypes:["literal"],svoPosition:5,sovPosition:5}]},clone:{action:"clone",description:"Clone an element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element to clone",required:!0,expectedTypes:["selector","reference"],svoPosition:1,sovPosition:2},{role:"destination",description:"Where to put the clone",required:!1,expectedTypes:["selector","reference"],svoPosition:2,sovPosition:1,markerOverride:{en:"into"}}]},focus:{action:"focus",description:"Focus an element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element to focus (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},blur:{action:"blur",description:"Remove focus from an element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element to blur (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},call:{action:"call",description:"Call a function",category:"control-flow",primaryRole:"patient",roles:[{role:"patient",description:"The function to call",required:!0,expectedTypes:["expression","reference"],svoPosition:1,sovPosition:1}]},return:{action:"return",description:"Return a value from a function",category:"control-flow",primaryRole:"patient",roles:[{role:"patient",description:"The value to return",required:!1,expectedTypes:["literal","expression","reference"],svoPosition:1,sovPosition:1}]},js:{action:"js",description:"Execute raw JavaScript code",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[{role:"patient",description:"The JavaScript code to execute",required:!1,expectedTypes:["expression"],svoPosition:1,sovPosition:1}]},async:{action:"async",description:"Execute commands asynchronously",category:"async",primaryRole:"patient",hasBody:!0,roles:[]},tell:{action:"tell",description:"Execute commands in context of another element",category:"control-flow",primaryRole:"destination",hasBody:!0,roles:[{role:"destination",description:"The element to tell",required:!0,expectedTypes:["selector","reference"],svoPosition:1,sovPosition:1,markerOverride:{en:""}}]},default:{action:"default",description:"Set a default value for a variable",category:"variable",primaryRole:"destination",roles:[{role:"destination",description:"The variable to set default for",required:!0,expectedTypes:["reference"],svoPosition:1,sovPosition:1,markerOverride:{en:"",ar:"",tl:"",sw:"",bn:"কে",qu:"ta"}},{role:"patient",description:"The default value",required:!0,expectedTypes:["literal","expression"],svoPosition:2,sovPosition:2,markerOverride:{en:"to",ar:"إلى",tl:"sa",sw:"kwenye",bn:"তে",qu:"man"}}]},init:{action:"init",description:"Initialization block that runs once",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[]},behavior:{action:"behavior",description:"Define a reusable behavior",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[{role:"patient",description:"The behavior name (PascalCase identifier)",required:!0,expectedTypes:["literal","reference","expression"],svoPosition:1,sovPosition:1}]},install:{action:"install",description:"Install a behavior on an element",category:"control-flow",primaryRole:"patient",roles:[{role:"patient",description:"The behavior name to install",required:!0,expectedTypes:["literal","reference","expression"],svoPosition:1,sovPosition:2},{role:"destination",description:"Element to install on (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1}]},measure:{action:"measure",description:"Measure element dimensions (x, y, width, height, etc.)",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"Property to measure (x, y, width, height, top, left, etc.)",required:!1,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1},{role:"source",description:"Element to measure (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:2,markerOverride:{en:"of"}}]},swap:{action:"swap",description:"Swap DOM content using various strategies (innerHTML, outerHTML, delete, etc.)",category:"dom-content",primaryRole:"destination",roles:[{role:"method",description:"The swap strategy (innerHTML, outerHTML, beforebegin, afterend, delete)",required:!1,expectedTypes:["literal"],svoPosition:1,sovPosition:3,markerOverride:{en:""}},{role:"destination",description:"The element to swap content in/for",required:!0,expectedTypes:["selector","reference"],svoPosition:2,sovPosition:1,markerOverride:{en:"of"}},{role:"patient",description:"The content to swap in (optional for delete)",required:!1,expectedTypes:["literal","expression","selector"],svoPosition:3,sovPosition:2,markerOverride:{en:"with"}}]},morph:{action:"morph",description:"Morph an element into another using DOM diffing",category:"dom-content",primaryRole:"destination",roles:[{role:"destination",description:"The element to morph",required:!0,expectedTypes:["selector","reference"],svoPosition:1,sovPosition:1,markerOverride:{en:""}},{role:"patient",description:"The target content/element to morph into",required:!0,expectedTypes:["literal","expression","selector"],svoPosition:2,sovPosition:2,markerOverride:{en:"to"}}]},beep:{action:"beep",description:"Debug output for expressions with type information",category:"variable",primaryRole:"patient",roles:[{role:"patient",description:"The expression(s) to debug",required:!1,expectedTypes:["literal","selector","reference","expression"],svoPosition:1,sovPosition:1}]},break:{action:"break",description:"Exit from the current loop",category:"control-flow",primaryRole:"patient",roles:[]},copy:{action:"copy",description:"Copy text or element content to the clipboard",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The text or element to copy",required:!0,expectedTypes:["literal","selector","reference","expression"],svoPosition:1,sovPosition:1}]},exit:{action:"exit",description:"Exit from the current event handler",category:"control-flow",primaryRole:"patient",roles:[]},pick:{action:"pick",description:"Select a random element from a collection",category:"variable",primaryRole:"patient",roles:[{role:"patient",description:"The items to pick from",required:!0,expectedTypes:["literal","expression","reference"],svoPosition:1,sovPosition:1},{role:"source",description:'The array to pick from (with "from" keyword)',required:!1,expectedTypes:["reference","expression"],svoPosition:2,sovPosition:2}]},render:{action:"render",description:"Render a template with optional variables",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The template to render",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:1,sovPosition:2},{role:"style",description:"Variables to pass to the template (with keyword)",required:!1,expectedTypes:["expression","reference"],svoPosition:2,sovPosition:1}]},compound:{action:"compound",description:"A compound node representing chained statements",primaryRole:"patient",category:"control-flow",hasBody:!0,roles:[]}},"undefined"!=typeof process&&"production"!==process.env.NODE_ENV&&Promise.resolve().then(()=>(Iu(),pu)).then(({validateAllSchemas:e,formatValidationResults:t})=>{const n=e(Pu);n.size>0&&(console.warn("[SCHEMA VALIDATION] Found issues in command schemas:"),console.warn(t(n)),console.warn("\nThese warnings help identify potential schema design issues."),console.warn("Fix them to improve type inference and avoid runtime bugs."))}).catch(e=>{console.debug("Schema validation skipped:",e)})}});function Ru(e,t){const n="SOV"===t?"sovPosition":"svoPosition";return[...e].sort((e,t)=>(e[n]??99)-(t[n]??99))}var Mu=fl({"src/parser/utils/role-positioning.ts"(){}});var Wu=fl({"src/parser/utils/marker-resolution.ts"(){}});var $u=fl({"src/generators/event-handlers-sov.ts"(){}});function Hu(e,t,n,r,i){const a=[];if("before"===r.position){const e=r.alternatives?{type:"literal",value:r.primary,alternatives:r.alternatives}:{type:"literal",value:r.primary};a.push(e)}a.push({type:"role",role:"event",optional:!1});const o=n.alternatives?{type:"literal",value:n.primary,alternatives:n.alternatives}:{type:"literal",value:n.primary};a.push(o),a.push({type:"role",role:"patient",optional:!1});const s=t.roleMarkers.destination;return s&&a.push({type:"group",optional:!0,tokens:[s.alternatives?{type:"literal",value:s.primary,alternatives:s.alternatives}:{type:"literal",value:s.primary},{type:"role",role:"destination",optional:!0}]}),{id:`${e.action}-event-${t.code}-vso`,language:t.code,command:"on",priority:(i.basePriority??100)+50,template:{format:`${r.primary} {event} ${n.primary} {patient} ${s?.primary||""} {destination?}`,tokens:a},extraction:{action:{value:e.action},event:{fromRole:"event"},patient:{fromRole:"patient"},destination:{fromRole:"destination",default:{type:"reference",value:"me"}}}}}function qu(e,t,n,r,i){const a=[];if("before"===r.position){const e=r.alternatives?{type:"literal",value:r.primary,alternatives:r.alternatives}:{type:"literal",value:r.primary};a.push(e)}a.push({type:"role",role:"event",optional:!1});const o=n.alternatives?{type:"literal",value:n.primary,alternatives:n.alternatives}:{type:"literal",value:n.primary};a.push(o);const s=[...e.roles.filter(e=>e.required)].sort((e,t)=>(e.svoPosition??999)-(t.svoPosition??999));for(const e of s){let n,r;if(e.markerOverride&&void 0!==e.markerOverride[t.code])n=e.markerOverride[t.code];else{const i=t.roleMarkers[e.role];i&&(n=i.primary,r=i.alternatives)}if(n){const e=r?{type:"literal",value:n,alternatives:r}:{type:"literal",value:n};a.push(e)}a.push({type:"role",role:e.role,optional:!1})}const l=s.map(e=>`{${e.role}}`).join(" ");return{id:`${e.action}-event-${t.code}-vso-2role`,language:t.code,command:"on",priority:(i.basePriority??100)+55,template:{format:`${r.primary} {event} ${n.primary} ${l}`,tokens:a},extraction:{action:{value:e.action},event:{fromRole:"event"},...Object.fromEntries(s.map(e=>[e.role,{fromRole:e.role}]))}}}var Du,_u=fl({"src/generators/event-handlers-vso.ts"(){}});function Vu(){return Tl().map(e=>Sl(e)).filter(e=>void 0!==e)}function Bu(e,t,n=Du){const r=`${e.action}-${t.code}-generated`,i=n.basePriority??100,a=t.keywords[e.action];if(!a)throw new Error(`No keyword translation for '${e.action}' in ${t.code}`);const o=function(e,t,n){const r=[],i=n.alternatives?{type:"literal",value:n.primary,alternatives:n.alternatives}:{type:"literal",value:n.primary},a=function(e,t){const n=[],r=Ru(e.roles,t.wordOrder);for(const e of r){const r=Qu(e,t);e.required?n.push(...r):n.push({type:"group",optional:!0,tokens:r})}return n}(e,t);switch(t.wordOrder){case"SVO":case"VSO":default:r.push(i),r.push(...a);break;case"SOV":r.push(...a),r.push(i)}return r}(e,t,a),s=Ju(e,t),l=function(e,t,n){const r=[],i=Ru(e.roles,t.wordOrder),a=i.map(e=>{const n=function(e,t){const n=e.markerOverride?.[t.code],r=t.roleMarkers[e.role];if(void 0!==n)return{primary:n,position:r?.position??"before",isOverride:!0};if(r&&r.primary){const e={primary:r.primary,position:r.position,isOverride:!1};return r.alternatives&&(e.alternatives=r.alternatives),e}return null}(e,t);let r="";return r=n&&n.primary?"before"===n.position?`${n.primary} {${e.role}}`:`{${e.role}} ${n.primary}`:`{${e.role}}`,e.required?r:`[${r}]`});switch(t.wordOrder){case"SVO":case"VSO":default:r.push(n.primary,...a);break;case"SOV":r.push(...a,n.primary)}return r.join(" ")}(e,t,a);return{id:r,language:t.code,command:e.action,priority:i,template:{format:l,tokens:o},extraction:s}}function Fu(e,t,n=Du){if(0===e.roles.filter(e=>!e.required).length)return null;const r=e.roles.filter(e=>e.required);return{...Bu({...e,roles:r},t,n),id:`${e.action}-${t.code}-simple`,priority:(n.basePriority??100)-5,extraction:Ju(e,t)}}function Uu(e,t,n=Du){const r=[];if(r.push(Bu(e,t,n)),n.generateSimpleVariants){const i=Fu(e,t,n);i&&r.push(i)}return r}function Ku(e,t=Du){const n=[],r=Nu();for(const i of r){if(!e.keywords[i.action])continue;const r=Uu(i,e,t);if(n.push(...r),e.eventHandler?.eventMarker){const r=Gu(i,e,t);n.push(...r)}}return n}function Gu(e,t,n=Du){if(!t.eventHandler||!t.eventHandler.eventMarker)return[];const r=[],i=t.eventHandler.eventMarker,a=t.keywords[e.action];if(!a)return[];const o=2===e.roles.filter(e=>e.required).length;if("SOV"===t.wordOrder)if(o)r.push(function(e,t,n,r,i){const a=[];if(a.push({type:"role",role:"event",optional:!1}),"after"===r.position){const e=r.primary.split(/\s+/);if(e.length>1)for(const t of e)a.push({type:"literal",value:t});else{const e=r.alternatives?{type:"literal",value:r.primary,alternatives:r.alternatives}:{type:"literal",value:r.primary};a.push(e)}}const o=[...e.roles.filter(e=>e.required)].sort((e,t)=>(e.sovPosition??999)-(t.sovPosition??999));for(const e of o){let n,r;if(a.push({type:"role",role:e.role,optional:!1}),e.markerOverride&&void 0!==e.markerOverride[t.code])n=e.markerOverride[t.code];else{const i=t.roleMarkers[e.role];i&&(n=i.primary,r=i.alternatives)}if(n){const e=r?{type:"literal",value:n,alternatives:r}:{type:"literal",value:n};a.push(e)}}const s=n.alternatives?{type:"literal",value:n.primary,alternatives:n.alternatives}:{type:"literal",value:n.primary};a.push(s);const l=o.map(e=>`{${e.role}}`).join(" ");return{id:`${e.action}-event-${t.code}-sov-2role`,language:t.code,command:"on",priority:(i.basePriority??100)+55,template:{format:`{event} ${r.primary} ${l} ${n.primary}`,tokens:a},extraction:{action:{value:e.action},event:{fromRole:"event"},...Object.fromEntries(o.map(e=>[e.role,{fromRole:e.role}]))}}}(e,t,a,i,n)),r.push(function(e,t,n,r,i){const a=[],o=[...e.roles.filter(e=>e.required)].sort((e,t)=>(e.sovPosition??999)-(t.sovPosition??999)),s=o[0];let l;if(a.push({type:"role",role:s.role,optional:!1}),s.markerOverride&&void 0!==s.markerOverride[t.code])l=s.markerOverride[t.code];else{const e=t.roleMarkers[s.role];e&&(l=e.primary)}if(l&&a.push({type:"literal",value:l}),a.push({type:"role",role:"event",optional:!1}),"after"===r.position){const e=r.primary.split(/\s+/);if(e.length>1)for(const t of e)a.push({type:"literal",value:t});else{const e=r.alternatives?{type:"literal",value:r.primary,alternatives:r.alternatives}:{type:"literal",value:r.primary};a.push(e)}}const c=n.alternatives?{type:"literal",value:n.primary,alternatives:n.alternatives}:{type:"literal",value:n.primary};a.push(c);const u=o[1];let p,m;if(a.push({type:"role",role:u.role,optional:!1}),u.markerOverride&&void 0!==u.markerOverride[t.code])p=u.markerOverride[t.code];else{const e=t.roleMarkers[u.role];e&&(p=e.primary,m=e.alternatives)}if(p){const e=m?{type:"literal",value:p,alternatives:m}:{type:"literal",value:p};a.push(e)}return{id:`${e.action}-event-${t.code}-sov-2role-dest-first`,language:t.code,command:"on",priority:(i.basePriority??100)+48,template:{format:`{${s.role}} {event} ${r.primary} ${n.primary} {${u.role}}`,tokens:a},extraction:{action:{value:e.action},event:{fromRole:"event"},[s.role]:{fromRole:s.role},[u.role]:{fromRole:u.role}}}}(e,t,a,i,n));else{r.push(function(e,t,n,r,i){const a=[];if(a.push({type:"role",role:"event",optional:!1}),"after"===r.position){const e=r.primary.split(/\s+/);if(e.length>1)for(const t of e)a.push({type:"literal",value:t});else{const e=r.alternatives?{type:"literal",value:r.primary,alternatives:r.alternatives}:{type:"literal",value:r.primary};a.push(e)}}const o=t.roleMarkers.destination;o&&a.push({type:"group",optional:!0,tokens:[{type:"role",role:"destination",optional:!0},o.alternatives?{type:"literal",value:o.primary,alternatives:o.alternatives}:{type:"literal",value:o.primary}]}),a.push({type:"role",role:"patient",optional:!1});const s=t.roleMarkers.patient;if(s){const e=s.alternatives?{type:"literal",value:s.primary,alternatives:s.alternatives}:{type:"literal",value:s.primary};a.push(e)}const l=n.alternatives?{type:"literal",value:n.primary,alternatives:n.alternatives}:{type:"literal",value:n.primary};return a.push(l),{id:`${e.action}-event-${t.code}-sov`,language:t.code,command:"on",priority:(i.basePriority??100)+50,template:{format:`{event} ${r.primary} {destination?} {patient} ${s?.primary||""} ${n.primary}`,tokens:a},extraction:{action:{value:e.action},event:{fromRole:"event"},patient:{fromRole:"patient"},destination:{fromRole:"destination",default:{type:"reference",value:"me"}}}}}(e,t,a,i,n)),r.push(function(e,t,n,r,i){const a=[];a.push({type:"role",role:"patient",optional:!1});const o=t.roleMarkers.patient;if(o){const e=o.alternatives?{type:"literal",value:o.primary,alternatives:o.alternatives}:{type:"literal",value:o.primary};a.push(e)}if(a.push({type:"role",role:"event",optional:!1}),"after"===r.position){const e=r.primary.split(/\s+/);if(e.length>1)for(const t of e)a.push({type:"literal",value:t});else{const e=r.alternatives?{type:"literal",value:r.primary,alternatives:r.alternatives}:{type:"literal",value:r.primary};a.push(e)}}const s=n.alternatives?{type:"literal",value:n.primary,alternatives:n.alternatives}:{type:"literal",value:n.primary};return a.push(s),{id:`${e.action}-event-${t.code}-sov-patient-first`,language:t.code,command:"on",priority:(i.basePriority??100)+45,template:{format:`{patient} ${o?.primary||""} {event} ${r.primary} ${n.primary}`,tokens:a},extraction:{action:{value:e.action},event:{fromRole:"event"},patient:{fromRole:"patient"},destination:{fromRole:"destination",default:{type:"reference",value:"me"}}}}}(e,t,a,i,n));const o=t.roleMarkers.destination;o&&o.primary!==i.primary&&r.push(function(e,t,n,r,i){const a=[];a.push({type:"role",role:"patient",optional:!1});const o=t.roleMarkers.patient;if(o){const e=o.alternatives?{type:"literal",value:o.primary,alternatives:o.alternatives}:{type:"literal",value:o.primary};a.push(e)}const s=t.roleMarkers.destination;if(s&&(a.push({type:"role",role:"destination",optional:!1}),a.push(s.alternatives?{type:"literal",value:s.primary,alternatives:s.alternatives}:{type:"literal",value:s.primary})),a.push({type:"role",role:"event",optional:!1}),"after"===r.position){const e=r.primary.split(/\s+/);if(e.length>1)for(const t of e)a.push({type:"literal",value:t});else{const e=r.alternatives?{type:"literal",value:r.primary,alternatives:r.alternatives}:{type:"literal",value:r.primary};a.push(e)}}const l=n.alternatives?{type:"literal",value:n.primary,alternatives:n.alternatives}:{type:"literal",value:n.primary};return a.push(l),{id:`${e.action}-event-${t.code}-sov-patient-first-dest`,language:t.code,command:"on",priority:(i.basePriority??100)+40,template:{format:`{patient} ${o?.primary||""} {destination} ${s?.primary||""} {event} ${r.primary} ${n.primary}`,tokens:a},extraction:{action:{value:e.action},event:{fromRole:"event"},patient:{fromRole:"patient"},destination:{fromRole:"destination"}}}}(e,t,a,i,n));const s=i.primary.split(/\s+/),l=i.alternatives?.some(e=>!e.includes(" ")&&e.length>1);s.length>1&&l&&r.push(function(e,t,n,r,i){const a=[];a.push({type:"role",role:"event",optional:!1});const o=r.alternatives?.filter(e=>!e.includes(" ")&&e.length>1)||[];o.length>0&&a.push({type:"literal",value:o[0],alternatives:o.slice(1)});const s=t.roleMarkers.destination;s&&a.push({type:"group",optional:!0,tokens:[{type:"role",role:"destination",optional:!0},s.alternatives?{type:"literal",value:s.primary,alternatives:s.alternatives}:{type:"literal",value:s.primary}]}),a.push({type:"role",role:"patient",optional:!1});const l=t.roleMarkers.patient;if(l){const e=l.alternatives?{type:"literal",value:l.primary,alternatives:l.alternatives}:{type:"literal",value:l.primary};a.push(e)}const c=n.alternatives?{type:"literal",value:n.primary,alternatives:n.alternatives}:{type:"literal",value:n.primary};return a.push(c),{id:`${e.action}-event-${t.code}-sov-compact`,language:t.code,command:"on",priority:(i.basePriority??100)+52,template:{format:`{event}${o[0]||""} {patient} ${n.primary}`,tokens:a},extraction:{action:{value:e.action},event:{fromRole:"event"},patient:{fromRole:"patient"},destination:{fromRole:"destination",default:{type:"reference",value:"me"}}}}}(e,t,a,i,n)),r.push(function(e,t,n,r,i){const a=[];if(a.push({type:"role",role:"event",optional:!1}),"after"===r.position){const e=r.primary.split(/\s+/);if(e.length>1)for(const t of e)a.push({type:"literal",value:t});else{const e=r.alternatives?{type:"literal",value:r.primary,alternatives:r.alternatives}:{type:"literal",value:r.primary};a.push(e)}}const o=n.alternatives?{type:"literal",value:n.primary,alternatives:n.alternatives}:{type:"literal",value:n.primary};return a.push(o),{id:`${e.action}-event-${t.code}-sov-simple`,language:t.code,command:"on",priority:(i.basePriority??100)+48,template:{format:`{event} ${r.primary} ${n.primary}`,tokens:a},extraction:{action:{value:e.action},event:{fromRole:"event"},patient:{default:{type:"reference",value:"me"}}}}}(e,t,a,i,n));const c=function(e,t,n,r){const i=t.eventHandler?.temporalMarkers;if(!i||0===i.length)return null;const a=[];a.push({type:"role",role:"event",optional:!1}),t.possessive?.marker&&a.push({type:"group",optional:!0,tokens:[{type:"literal",value:t.possessive.marker}]}),a.push({type:"literal",value:i[0],alternatives:i.slice(1)}),a.push({type:"role",role:"patient",optional:!1});const o=t.roleMarkers.patient;if(o?.primary){const e=o.alternatives?{type:"literal",value:o.primary,alternatives:o.alternatives}:{type:"literal",value:o.primary};a.push(e)}const s=n.alternatives?{type:"literal",value:n.primary,alternatives:n.alternatives}:{type:"literal",value:n.primary};return a.push(s),{id:`${e.action}-event-${t.code}-sov-temporal`,language:t.code,command:"on",priority:(r.basePriority??100)+49,template:{format:`{event} ${i[0]} {patient} ${n.primary}`,tokens:a},extraction:{action:{value:e.action},event:{fromRole:"event"},patient:{fromRole:"patient"}}}}(e,t,a,n);c&&r.push(c)}else"VSO"===t.wordOrder?o?(r.push(qu(e,t,a,i,n)),r.push(function(e,t,n,r,i){const a=[],o=n.alternatives?{type:"literal",value:n.primary,alternatives:n.alternatives}:{type:"literal",value:n.primary};a.push(o);const s=[...e.roles.filter(e=>e.required)].sort((e,t)=>(e.svoPosition??999)-(t.svoPosition??999));for(const e of s){let n,r;if(e.markerOverride&&void 0!==e.markerOverride[t.code])n=e.markerOverride[t.code];else{const i=t.roleMarkers[e.role];i&&(n=i.primary,r=i.alternatives)}if(n){const e=r?{type:"literal",value:n,alternatives:r}:{type:"literal",value:n};a.push(e)}a.push({type:"role",role:e.role,optional:!1})}if("before"===r.position){const e=r.alternatives?{type:"literal",value:r.primary,alternatives:r.alternatives}:{type:"literal",value:r.primary};a.push(e)}a.push({type:"role",role:"event",optional:!1});const l=s.map(e=>`{${e.role}}`).join(" ");return{id:`${e.action}-event-${t.code}-vso-verb-first-2role`,language:t.code,command:"on",priority:(i.basePriority??100)+48,template:{format:`${n.primary} ${l} ${r.primary} {event}`,tokens:a},extraction:{action:{value:e.action},event:{fromRole:"event"},...Object.fromEntries(s.map(e=>[e.role,{fromRole:e.role}]))}}}(e,t,a,i,n))):(r.push(Hu(e,t,a,i,n)),r.push(function(e,t,n,r,i){const a=[],o=n.alternatives?{type:"literal",value:n.primary,alternatives:n.alternatives}:{type:"literal",value:n.primary};a.push(o),a.push({type:"role",role:"patient",optional:!1});const s=t.roleMarkers.destination;if(s&&a.push({type:"group",optional:!0,tokens:[s.alternatives?{type:"literal",value:s.primary,alternatives:s.alternatives}:{type:"literal",value:s.primary},{type:"role",role:"destination",optional:!0}]}),"before"===r.position){const e=r.alternatives?{type:"literal",value:r.primary,alternatives:r.alternatives}:{type:"literal",value:r.primary};a.push(e)}return a.push({type:"role",role:"event",optional:!1}),{id:`${e.action}-event-${t.code}-vso-verb-first`,language:t.code,command:"on",priority:(i.basePriority??100)+45,template:{format:`${n.primary} {patient} ${s?.primary||""} {destination?} ${r.primary} {event}`,tokens:a},extraction:{action:{value:e.action},event:{fromRole:"event"},patient:{fromRole:"patient"},destination:{fromRole:"destination",default:{type:"reference",value:"me"}}}}}(e,t,a,i,n)),t.eventHandler?.negationMarker&&r.push(function(e,t,n,r,i){const a=[],o=t.eventHandler?.negationMarker;if("before"===r.position){const e=r.alternatives?{type:"literal",value:r.primary,alternatives:r.alternatives}:{type:"literal",value:r.primary};a.push(e)}if(o){const e=o.alternatives?{type:"literal",value:o.primary,alternatives:o.alternatives}:{type:"literal",value:o.primary};a.push(e)}a.push({type:"role",role:"event",optional:!1});const s=n.alternatives?{type:"literal",value:n.primary,alternatives:n.alternatives}:{type:"literal",value:n.primary};a.push(s),a.push({type:"role",role:"patient",optional:!1});const l=t.roleMarkers.destination;return l&&a.push({type:"group",optional:!0,tokens:[l.alternatives?{type:"literal",value:l.primary,alternatives:l.alternatives}:{type:"literal",value:l.primary},{type:"role",role:"destination",optional:!0}]}),{id:`${e.action}-event-${t.code}-vso-negated`,language:t.code,command:"on",priority:(i.basePriority??100)+48,template:{format:`${r.primary} ${o?.primary||""} {event} ${n.primary} {patient} ${l?.primary||""} {destination?}`,tokens:a},extraction:{action:{value:e.action},event:{fromRole:"event"},patient:{fromRole:"patient"},destination:{fromRole:"destination",default:{type:"reference",value:"me"}}}}}(e,t,a,i,n)),t.tokenization?.prefixes&&r.push(function(e,t,n,r){const i=[];i.push({type:"literal",value:"and",alternatives:["then"]}),i.push({type:"role",role:"event",optional:!1});const a=n.alternatives?{type:"literal",value:n.primary,alternatives:n.alternatives}:{type:"literal",value:n.primary};i.push(a),i.push({type:"role",role:"patient",optional:!1});const o=t.roleMarkers.destination;return o&&i.push({type:"group",optional:!0,tokens:[o.alternatives?{type:"literal",value:o.primary,alternatives:o.alternatives}:{type:"literal",value:o.primary},{type:"role",role:"destination",optional:!0}]}),{id:`${e.action}-event-${t.code}-vso-proclitic`,language:t.code,command:"on",priority:(r.basePriority??100)+45,template:{format:`[proclitic?] {event} ${n.primary} {patient} ${o?.primary||""} {destination?}`,tokens:i},extraction:{action:{value:e.action},event:{fromRole:"event"},patient:{fromRole:"patient"},destination:{fromRole:"destination",default:{type:"reference",value:"me"}}}}}(e,t,a,n))):o?r.push(qu(e,t,a,i,n)):r.push(Hu(e,t,a,i,n));return r}function Qu(e,t){const n=[],r=e.markerOverride?.[t.code],i=t.roleMarkers[e.role],a={type:"role",role:e.role,optional:!e.required,expectedTypes:e.expectedTypes};if(void 0!==r){"before"===(i?.position??"before")?(r&&n.push({type:"literal",value:r}),n.push(a)):(n.push(a),r&&n.push({type:"literal",value:r}))}else if(i)if("before"===i.position){if(i.primary){const e=i.alternatives?{type:"literal",value:i.primary,alternatives:i.alternatives}:{type:"literal",value:i.primary};n.push(e)}n.push(a)}else{n.push(a);const e=i.alternatives?{type:"literal",value:i.primary,alternatives:i.alternatives}:{type:"literal",value:i.primary};n.push(e)}else n.push(a);return n}function Ju(e,t){const n=function(e,t){const n={};for(const r of e.roles){const e=r.markerOverride?.[t.code],i=t.roleMarkers[r.role];void 0!==e?n[r.role]=e?{marker:e}:{}:i&&i.primary?n[r.role]=i.alternatives?{marker:i.primary,markerAlternatives:i.alternatives}:{marker:i.primary}:n[r.role]={}}return n}(e,t),r={};for(const t of e.roles){const e=n[t.role]||{};!t.required&&t.default?r[t.role]={...e,default:t.default}:r[t.role]=e}return r}var Yu=fl({"src/generators/pattern-generator.ts"(){Ou(),Mu(),Wu(),$u(),_u(),Pl(),Du={basePriority:100,generateSimpleVariants:!0,generateAlternatives:!0}}});var Zu=fl({"src/patterns/toggle/en.ts"(){}});var Xu=fl({"src/patterns/put/en.ts"(){}});var ep,tp,np,rp,ip,ap,op,sp,lp,cp,up,pp=fl({"src/patterns/event-handler/en.ts"(){}}),mp={};function dp(){const e=[];e.push({id:"toggle-en-full",language:"en",command:"toggle",priority:100,template:{format:"toggle {patient} on {target}",tokens:[{type:"literal",value:"toggle"},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"on",alternatives:["from"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"on",markerAlternatives:["from"],default:{type:"reference",value:"me"}}}},{id:"toggle-en-simple",language:"en",command:"toggle",priority:90,template:{format:"toggle {patient}",tokens:[{type:"literal",value:"toggle"},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}}),e.push({id:"put-en-into",language:"en",command:"put",priority:100,template:{format:"put {patient} into {destination}",tokens:[{type:"literal",value:"put"},{type:"role",role:"patient"},{type:"literal",value:"into",alternatives:["in","to"]},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"into",markerAlternatives:["in","to"]}}},{id:"put-en-before",language:"en",command:"put",priority:95,template:{format:"put {patient} before {destination}",tokens:[{type:"literal",value:"put"},{type:"role",role:"patient"},{type:"literal",value:"before"},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"before"},manner:{default:{type:"literal",value:"before"}}}},{id:"put-en-after",language:"en",command:"put",priority:95,template:{format:"put {patient} after {destination}",tokens:[{type:"literal",value:"put"},{type:"role",role:"patient"},{type:"literal",value:"after"},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"after"},manner:{default:{type:"literal",value:"after"}}}}),e.push({id:"event-en-when-source",language:"en",command:"on",priority:115,template:{format:"when {event} from {source} {body}",tokens:[{type:"literal",value:"when"},{type:"role",role:"event"},{type:"literal",value:"from"},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"from"}}},{id:"event-en-when",language:"en",command:"on",priority:105,template:{format:"when {event} {body}",tokens:[{type:"literal",value:"when"},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-en-source",language:"en",command:"on",priority:110,template:{format:"on {event} from {source} {body}",tokens:[{type:"literal",value:"on"},{type:"role",role:"event"},{type:"literal",value:"from"},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"from"}}},{id:"event-en-standard",language:"en",command:"on",priority:100,template:{format:"on {event} {body}",tokens:[{type:"literal",value:"on"},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-en-upon",language:"en",command:"on",priority:98,template:{format:"upon {event} {body}",tokens:[{type:"literal",value:"upon"},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-en-if",language:"en",command:"on",priority:95,template:{format:"if {event} {body}",tokens:[{type:"literal",value:"if"},{type:"role",role:"event"}]},extraction:{event:{position:1}}}),e.push(ep,tp,np,rp,ip,ap,op,sp,lp,cp,up);const t=Ku(Gc);return e.push(...t),e}yl(mp,{buildEnglishPatterns:()=>dp});var hp,fp,yp,vp,gp,bp,kp=fl({"src/patterns/en.ts"(){eu(),Yu(),Zu(),Xu(),pp(),ep={id:"fetch-en-with-response-type",language:"en",command:"fetch",priority:90,template:{format:"fetch {source} as {responseType}",tokens:[{type:"literal",value:"fetch"},{type:"role",role:"source",expectedTypes:["literal","expression"]},{type:"literal",value:"as"},{type:"role",role:"responseType",expectedTypes:["literal","expression"]}]},extraction:{source:{position:1},responseType:{marker:"as"}}},tp={id:"fetch-en-simple",language:"en",command:"fetch",priority:80,template:{format:"fetch {source}",tokens:[{type:"literal",value:"fetch"},{type:"role",role:"source"}]},extraction:{source:{position:1}}},np={id:"swap-en-handcrafted",language:"en",command:"swap",priority:110,template:{format:"swap {method} {destination}",tokens:[{type:"literal",value:"swap"},{type:"role",role:"method"},{type:"role",role:"destination"}]},extraction:{method:{position:1},destination:{position:2}}},rp={id:"repeat-en-until-event-from",language:"en",command:"repeat",priority:120,template:{format:"repeat until event {event} from {source}",tokens:[{type:"literal",value:"repeat"},{type:"literal",value:"until"},{type:"literal",value:"event"},{type:"role",role:"event",expectedTypes:["literal","expression"]},{type:"literal",value:"from"},{type:"role",role:"source",expectedTypes:["selector","reference","expression"]}]},extraction:{event:{marker:"event"},source:{marker:"from"},loopType:{default:{type:"literal",value:"until-event"}}}},ip={id:"repeat-en-until-event",language:"en",command:"repeat",priority:110,template:{format:"repeat until event {event}",tokens:[{type:"literal",value:"repeat"},{type:"literal",value:"until"},{type:"literal",value:"event"},{type:"role",role:"event",expectedTypes:["literal","expression"]}]},extraction:{event:{marker:"event"},loopType:{default:{type:"literal",value:"until-event"}}}},ap={id:"set-en-possessive",language:"en",command:"set",priority:100,template:{format:"set {destination} to {patient}",tokens:[{type:"literal",value:"set"},{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"literal",value:"to"},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:1},patient:{marker:"to"}}},op={id:"for-en-basic",language:"en",command:"for",priority:100,template:{format:"for {patient} in {source}",tokens:[{type:"literal",value:"for"},{type:"role",role:"patient",expectedTypes:["expression","reference"]},{type:"literal",value:"in"},{type:"role",role:"source",expectedTypes:["selector","expression","reference"]}]},extraction:{patient:{position:1},source:{marker:"in"},loopType:{default:{type:"literal",value:"for"}}}},sp={id:"if-en-basic",language:"en",command:"if",priority:100,template:{format:"if {condition}",tokens:[{type:"literal",value:"if"},{type:"role",role:"condition",expectedTypes:["expression","reference","selector"]}]},extraction:{condition:{position:1}}},lp={id:"unless-en-basic",language:"en",command:"unless",priority:100,template:{format:"unless {condition}",tokens:[{type:"literal",value:"unless"},{type:"role",role:"condition",expectedTypes:["expression","reference","selector"]}]},extraction:{condition:{position:1}}},cp={id:"temporal-en-in",language:"en",command:"wait",priority:95,template:{format:"in {duration}",tokens:[{type:"literal",value:"in"},{type:"role",role:"duration",expectedTypes:["literal","expression"]}]},extraction:{duration:{position:1}}},up={id:"temporal-en-after",language:"en",command:"wait",priority:95,template:{format:"after {duration}",tokens:[{type:"literal",value:"after"},{type:"role",role:"duration",expectedTypes:["literal","expression"]}]},extraction:{duration:{position:1}}}}});function wp(e){return/[áéíóúüñÁÉÍÓÚÜÑ]/.test(e)}var zp,xp=fl({"src/tokenizers/morphology/spanish-normalizer.ts"(){ic(),hp=["se","me","te","nos","os"],fp=[{ending:"ando",stem:"ar",confidence:.88,type:"gerund"},{ending:"ado",stem:"ar",confidence:.88,type:"participle"},{ending:"ada",stem:"ar",confidence:.88,type:"participle"},{ending:"ados",stem:"ar",confidence:.88,type:"participle"},{ending:"adas",stem:"ar",confidence:.88,type:"participle"},{ending:"o",stem:"ar",confidence:.75,type:"present"},{ending:"as",stem:"ar",confidence:.82,type:"present"},{ending:"a",stem:"ar",confidence:.75,type:"present"},{ending:"amos",stem:"ar",confidence:.85,type:"present"},{ending:"áis",stem:"ar",confidence:.85,type:"present"},{ending:"ais",stem:"ar",confidence:.82,type:"present"},{ending:"an",stem:"ar",confidence:.8,type:"present"},{ending:"é",stem:"ar",confidence:.85,type:"past"},{ending:"aste",stem:"ar",confidence:.88,type:"past"},{ending:"ó",stem:"ar",confidence:.82,type:"past"},{ending:"amos",stem:"ar",confidence:.85,type:"past"},{ending:"asteis",stem:"ar",confidence:.88,type:"past"},{ending:"aron",stem:"ar",confidence:.88,type:"past"},{ending:"aba",stem:"ar",confidence:.88,type:"past"},{ending:"abas",stem:"ar",confidence:.88,type:"past"},{ending:"ábamos",stem:"ar",confidence:.88,type:"past"},{ending:"abamos",stem:"ar",confidence:.85,type:"past"},{ending:"abais",stem:"ar",confidence:.88,type:"past"},{ending:"aban",stem:"ar",confidence:.88,type:"past"},{ending:"e",stem:"ar",confidence:.72,type:"subjunctive"},{ending:"es",stem:"ar",confidence:.78,type:"subjunctive"},{ending:"emos",stem:"ar",confidence:.82,type:"subjunctive"},{ending:"éis",stem:"ar",confidence:.85,type:"subjunctive"},{ending:"eis",stem:"ar",confidence:.82,type:"subjunctive"},{ending:"en",stem:"ar",confidence:.78,type:"subjunctive"},{ending:"a",stem:"ar",confidence:.75,type:"imperative"},{ending:"ad",stem:"ar",confidence:.85,type:"imperative"},{ending:"ar",stem:"ar",confidence:.92,type:"dictionary"}],yp=[{ending:"iendo",stem:"er",confidence:.88,type:"gerund"},{ending:"ido",stem:"er",confidence:.85,type:"participle"},{ending:"ida",stem:"er",confidence:.85,type:"participle"},{ending:"idos",stem:"er",confidence:.85,type:"participle"},{ending:"idas",stem:"er",confidence:.85,type:"participle"},{ending:"o",stem:"er",confidence:.72,type:"present"},{ending:"es",stem:"er",confidence:.78,type:"present"},{ending:"e",stem:"er",confidence:.72,type:"present"},{ending:"emos",stem:"er",confidence:.85,type:"present"},{ending:"éis",stem:"er",confidence:.85,type:"present"},{ending:"eis",stem:"er",confidence:.82,type:"present"},{ending:"en",stem:"er",confidence:.78,type:"present"},{ending:"í",stem:"er",confidence:.85,type:"past"},{ending:"iste",stem:"er",confidence:.88,type:"past"},{ending:"ió",stem:"er",confidence:.85,type:"past"},{ending:"io",stem:"er",confidence:.82,type:"past"},{ending:"imos",stem:"er",confidence:.85,type:"past"},{ending:"isteis",stem:"er",confidence:.88,type:"past"},{ending:"ieron",stem:"er",confidence:.88,type:"past"},{ending:"ía",stem:"er",confidence:.88,type:"past"},{ending:"ia",stem:"er",confidence:.85,type:"past"},{ending:"ías",stem:"er",confidence:.88,type:"past"},{ending:"ias",stem:"er",confidence:.85,type:"past"},{ending:"íamos",stem:"er",confidence:.88,type:"past"},{ending:"iamos",stem:"er",confidence:.85,type:"past"},{ending:"íais",stem:"er",confidence:.88,type:"past"},{ending:"iais",stem:"er",confidence:.85,type:"past"},{ending:"ían",stem:"er",confidence:.88,type:"past"},{ending:"ian",stem:"er",confidence:.85,type:"past"},{ending:"er",stem:"er",confidence:.92,type:"dictionary"}],vp=[{ending:"iendo",stem:"ir",confidence:.88,type:"gerund"},{ending:"ido",stem:"ir",confidence:.85,type:"participle"},{ending:"ida",stem:"ir",confidence:.85,type:"participle"},{ending:"idos",stem:"ir",confidence:.85,type:"participle"},{ending:"idas",stem:"ir",confidence:.85,type:"participle"},{ending:"o",stem:"ir",confidence:.72,type:"present"},{ending:"es",stem:"ir",confidence:.78,type:"present"},{ending:"e",stem:"ir",confidence:.72,type:"present"},{ending:"imos",stem:"ir",confidence:.85,type:"present"},{ending:"ís",stem:"ir",confidence:.85,type:"present"},{ending:"is",stem:"ir",confidence:.82,type:"present"},{ending:"en",stem:"ir",confidence:.78,type:"present"},{ending:"í",stem:"ir",confidence:.85,type:"past"},{ending:"iste",stem:"ir",confidence:.88,type:"past"},{ending:"ió",stem:"ir",confidence:.85,type:"past"},{ending:"io",stem:"ir",confidence:.82,type:"past"},{ending:"imos",stem:"ir",confidence:.85,type:"past"},{ending:"isteis",stem:"ir",confidence:.88,type:"past"},{ending:"ieron",stem:"ir",confidence:.88,type:"past"},{ending:"ía",stem:"ir",confidence:.88,type:"past"},{ending:"ia",stem:"ir",confidence:.85,type:"past"},{ending:"ías",stem:"ir",confidence:.88,type:"past"},{ending:"ias",stem:"ir",confidence:.85,type:"past"},{ending:"íamos",stem:"ir",confidence:.88,type:"past"},{ending:"iamos",stem:"ir",confidence:.85,type:"past"},{ending:"íais",stem:"ir",confidence:.88,type:"past"},{ending:"iais",stem:"ir",confidence:.85,type:"past"},{ending:"ían",stem:"ir",confidence:.88,type:"past"},{ending:"ian",stem:"ir",confidence:.85,type:"past"},{ending:"ir",stem:"ir",confidence:.92,type:"dictionary"}],gp=[...fp,...yp,...vp].sort((e,t)=>t.ending.length-e.ending.length),new(bp=class{constructor(){this.language="es"}isNormalizable(e){return!(e.length<3)&&function(e){const t=e.toLowerCase();if(t.endsWith("ar")||t.endsWith("er")||t.endsWith("ir"))return!0;if(t.endsWith("ando")||t.endsWith("iendo"))return!0;if(t.endsWith("ado")||t.endsWith("ido"))return!0;if(t.endsWith("arse")||t.endsWith("erse")||t.endsWith("irse"))return!0;for(const t of e)if(wp(t))return!0;return!1}(e)}normalize(e){const t=e.toLowerCase();if((t.endsWith("ar")||t.endsWith("er")||t.endsWith("ir"))&&!hp.some(e=>t.endsWith(e+"ar")||t.endsWith(e+"er")||t.endsWith(e+"ir")))return Yl(e);const n=this.tryReflexiveNormalization(t);if(n)return n;const r=this.tryConjugationNormalization(t);return r||Yl(e)}tryReflexiveNormalization(e){for(const t of hp)if(e.endsWith(t)){const n=e.slice(0,-t.length);if(n.endsWith("ar")||n.endsWith("er")||n.endsWith("ir"))return Zl(n,.88,{removedSuffixes:[t],conjugationType:"reflexive"});const r=this.tryConjugationNormalization(n);if(r&&r.stem!==n)return Zl(r.stem,.95*r.confidence,{removedSuffixes:[t,...r.metadata?.removedSuffixes||[]],conjugationType:"reflexive"})}return null}tryConjugationNormalization(e){for(const t of gp)if(e.endsWith(t.ending)){const n=e.slice(0,-t.ending.length);if(n.length<2)continue;return Zl(n+t.stem,t.confidence,{removedSuffixes:[t.ending],conjugationType:t.type})}return null}})}}),Ep={};yl(Ep,{spanishProfile:()=>zp});var Sp,Tp,Cp,Ap,jp,Lp,Pp,Ip=fl({"src/generators/profiles/spanish.ts"(){zp={code:"es",name:"Spanish",nativeName:"Español",direction:"ltr",wordOrder:"SVO",markingStrategy:"preposition",usesSpaces:!0,defaultVerbForm:"infinitive",verb:{position:"start",subjectDrop:!0},references:{me:"yo",it:"ello",you:"tú",result:"resultado",event:"evento",target:"objetivo",body:"cuerpo"},possessive:{marker:"de",markerPosition:"before-property",usePossessiveAdjectives:!0,specialForms:{me:"mi",it:"su",you:"tu"},keywords:{mi:"me",tu:"you",su:"it"}},roleMarkers:{destination:{primary:"en",alternatives:["sobre","a"],position:"before"},source:{primary:"de",alternatives:["desde"],position:"before"},patient:{primary:"",position:"before"},style:{primary:"con",position:"before"}},keywords:{toggle:{primary:"alternar",alternatives:["cambiar","conmutar"],normalized:"toggle"},add:{primary:"agregar",alternatives:["añadir"],normalized:"add"},remove:{primary:"quitar",alternatives:["eliminar","remover","sacar"],normalized:"remove"},put:{primary:"poner",alternatives:["colocar"],normalized:"put"},append:{primary:"añadir",normalized:"append"},prepend:{primary:"anteponer",normalized:"prepend"},take:{primary:"tomar",normalized:"take"},make:{primary:"hacer",alternatives:["crear"],normalized:"make"},clone:{primary:"clonar",alternatives:["copiar"],normalized:"clone"},swap:{primary:"intercambiar",alternatives:["cambiar"],normalized:"swap"},morph:{primary:"transformar",alternatives:["convertir"],normalized:"morph"},set:{primary:"establecer",alternatives:["fijar","definir"],normalized:"set"},get:{primary:"obtener",alternatives:["conseguir"],normalized:"get"},increment:{primary:"incrementar",alternatives:["aumentar"],normalized:"increment"},decrement:{primary:"decrementar",alternatives:["disminuir"],normalized:"decrement"},log:{primary:"registrar",alternatives:["imprimir"],normalized:"log"},show:{primary:"mostrar",alternatives:["enseñar"],normalized:"show"},hide:{primary:"ocultar",alternatives:["esconder"],normalized:"hide"},transition:{primary:"transición",alternatives:["animar"],normalized:"transition"},on:{primary:"en",alternatives:["cuando","al"],normalized:"on"},trigger:{primary:"disparar",alternatives:["activar"],normalized:"trigger"},send:{primary:"enviar",normalized:"send"},focus:{primary:"enfocar",normalized:"focus"},blur:{primary:"desenfocar",normalized:"blur"},click:{primary:"clic",alternatives:["hacer clic"],normalized:"click"},hover:{primary:"sobrevolar",alternatives:["pasar por encima"],normalized:"hover"},submit:{primary:"envío",alternatives:["enviar"],normalized:"submit"},input:{primary:"entrada",alternatives:["introducir"],normalized:"input"},change:{primary:"cambio",alternatives:["cambiar"],normalized:"change"},go:{primary:"ir",alternatives:["navegar"],normalized:"go"},wait:{primary:"esperar",normalized:"wait"},fetch:{primary:"buscar",alternatives:["obtener"],normalized:"fetch"},settle:{primary:"estabilizar",normalized:"settle"},if:{primary:"si",normalized:"if"},when:{primary:"cuando",normalized:"when"},where:{primary:"donde",normalized:"where"},else:{primary:"sino",alternatives:["de lo contrario"],normalized:"else"},repeat:{primary:"repetir",normalized:"repeat"},for:{primary:"para",normalized:"for"},while:{primary:"mientras",normalized:"while"},continue:{primary:"continuar",normalized:"continue"},halt:{primary:"detener",alternatives:["parar"],normalized:"halt"},throw:{primary:"lanzar",alternatives:["arrojar"],normalized:"throw"},call:{primary:"llamar",normalized:"call"},return:{primary:"retornar",alternatives:["devolver"],normalized:"return"},then:{primary:"entonces",alternatives:["luego","después"],normalized:"then"},and:{primary:"y",alternatives:["además","también"],normalized:"and"},end:{primary:"fin",alternatives:["final","terminar"],normalized:"end"},js:{primary:"js",normalized:"js"},async:{primary:"asíncrono",normalized:"async"},tell:{primary:"decir",normalized:"tell"},default:{primary:"predeterminar",alternatives:["por defecto"],normalized:"default"},init:{primary:"iniciar",alternatives:["inicializar"],normalized:"init"},behavior:{primary:"comportamiento",normalized:"behavior"},install:{primary:"instalar",normalized:"install"},measure:{primary:"medir",normalized:"measure"},beep:{primary:"pitido",normalized:"beep"},break:{primary:"romper",normalized:"break"},copy:{primary:"copiar",normalized:"copy"},exit:{primary:"salir",normalized:"exit"},pick:{primary:"escoger",normalized:"pick"},render:{primary:"renderizar",normalized:"render"},into:{primary:"en",alternatives:["dentro de"],normalized:"into"},before:{primary:"antes",normalized:"before"},after:{primary:"después",normalized:"after"},until:{primary:"hasta",normalized:"until"},event:{primary:"evento",normalized:"event"},from:{primary:"de",alternatives:["desde"],normalized:"from"}},eventHandler:{keyword:{primary:"al",alternatives:["cuando","en"],normalized:"on"},sourceMarker:{primary:"de",alternatives:["desde"],position:"before"},eventMarker:{primary:"al",alternatives:["cuando"],position:"before"},temporalMarkers:["cuando","al"]}}}}),Np={};yl(Np,{SpanishTokenizer:()=>Lp,spanishTokenizer:()=>Pp});var Op,Rp=fl({"src/tokenizers/spanish.ts"(){Jl(),xp(),Ip(),({isLetter:Sp,isIdentifierChar:Tp}=_l(/[a-zA-ZáéíóúüñÁÉÍÓÚÜÑ]/)),Cp=[{pattern:"milisegundos",suffix:"ms",length:12,caseInsensitive:!0},{pattern:"milisegundo",suffix:"ms",length:11,caseInsensitive:!0},{pattern:"segundos",suffix:"s",length:8,caseInsensitive:!0},{pattern:"segundo",suffix:"s",length:7,caseInsensitive:!0},{pattern:"minutos",suffix:"m",length:7,caseInsensitive:!0},{pattern:"minuto",suffix:"m",length:6,caseInsensitive:!0},{pattern:"horas",suffix:"h",length:5,caseInsensitive:!0},{pattern:"hora",suffix:"h",length:4,caseInsensitive:!0}],Ap=new Set(["en","a","de","desde","hasta","con","sin","por","para","sobre","entre","antes","después","despues","dentro","fuera","al","del"]),jp=[{native:"verdadero",normalized:"true"},{native:"falso",normalized:"false"},{native:"nulo",normalized:"null"},{native:"indefinido",normalized:"undefined"},{native:"primero",normalized:"first"},{native:"primera",normalized:"first"},{native:"último",normalized:"last"},{native:"ultima",normalized:"last"},{native:"siguiente",normalized:"next"},{native:"anterior",normalized:"previous"},{native:"cercano",normalized:"closest"},{native:"padre",normalized:"parent"},{native:"clic",normalized:"click"},{native:"click",normalized:"click"},{native:"hacer clic",normalized:"click"},{native:"entrada",normalized:"input"},{native:"cambio",normalized:"change"},{native:"envío",normalized:"submit"},{native:"envio",normalized:"submit"},{native:"tecla abajo",normalized:"keydown"},{native:"tecla arriba",normalized:"keyup"},{native:"ratón encima",normalized:"mouseover"},{native:"raton encima",normalized:"mouseover"},{native:"ratón fuera",normalized:"mouseout"},{native:"raton fuera",normalized:"mouseout"},{native:"enfoque",normalized:"focus"},{native:"desenfoque",normalized:"blur"},{native:"carga",normalized:"load"},{native:"desplazamiento",normalized:"scroll"},{native:"yo",normalized:"me"},{native:"mí",normalized:"me"},{native:"mi",normalized:"me"},{native:"ello",normalized:"it"},{native:"resultado",normalized:"result"},{native:"objetivo",normalized:"target"},{native:"destino",normalized:"target"},{native:"segundo",normalized:"s"},{native:"segundos",normalized:"s"},{native:"milisegundo",normalized:"ms"},{native:"milisegundos",normalized:"ms"},{native:"minuto",normalized:"m"},{native:"minutos",normalized:"m"},{native:"hora",normalized:"h"},{native:"horas",normalized:"h"},{native:"de lo contrario",normalized:"else"},{native:"hasta que",normalized:"until"},{native:"antes de",normalized:"before"},{native:"después de",normalized:"after"},{native:"despues de",normalized:"after"},{native:"dentro de",normalized:"into"},{native:"fuera de",normalized:"out"},{native:"asincrono",normalized:"async"},{native:"despues",normalized:"after"},{native:"añadir",normalized:"add"},{native:"toggle",normalized:"toggle"},{native:"borrar",normalized:"remove"},{native:"pon",normalized:"put"},{native:"crear",normalized:"make"},{native:"y",normalized:"and"},{native:"o",normalized:"or"},{native:"no",normalized:"not"},{native:"es",normalized:"is"},{native:"existe",normalized:"exists"},{native:"vacío",normalized:"empty"},{native:"vacio",normalized:"empty"}],Pp=new(Lp=class extends Kl{constructor(){super(),this.language="es",this.direction="ltr",this.initializeKeywordsFromProfile(zp,jp),this.normalizer=new bp}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])||"-"===e[n]&&n+1<e.length&&Wl(e[n+1])){const r=this.extractSpanishNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}const i=this.tryMultiWordPhrase(e,n);if(i){t.push(i),n=i.position.end;continue}if(Sp(e[n])){const r=this.extractSpanishWord(e,n);if(r){t.push(r),n=r.position.end;continue}}const a=this.tryOperator(e,n);a?(t.push(a),n=a.position.end):n++}return new Ll(t,"es")}classifyToken(e){const t=e.toLowerCase();return Ap.has(t)?"particle":this.isKeyword(t)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||/^\d/.test(e)?"literal":["==","!=","<=",">=","<",">","&&","||","!"].includes(e)?"operator":"identifier"}tryMultiWordPhrase(e,t){for(const n of this.profileKeywords){if(!n.native.includes(" "))continue;const r=n.native;if(e.slice(t,t+r.length).toLowerCase()===r.toLowerCase()){const i=t+r.length;if(i>=e.length||Ol(e[i])||!Sp(e[i]))return Nl(e.slice(t,t+r.length),"keyword",Il(t,i),n.normalized)}}return null}extractSpanishWord(e,t){let n=t,r="";for(;n<e.length&&Tp(e[n]);)r+=e[n++];if(!r)return null;const i=r.toLowerCase();if(Ap.has(i))return Nl(r,"particle",Il(t,n));const a=this.lookupKeyword(i);if(a)return Nl(r,"keyword",Il(t,n),a.normalized);const o=this.tryMorphKeywordMatch(i,t,n);return o||Nl(r,"identifier",Il(t,n))}extractSpanishNumber(e,t){return this.tryNumberWithTimeUnits(e,t,Cp,{allowSign:!0,skipWhitespace:!0})}})}}),Mp={};yl(Mp,{frenchProfile:()=>Op});var Wp,$p,Hp,qp,Dp,_p,Vp=fl({"src/generators/profiles/french.ts"(){Op={code:"fr",name:"French",nativeName:"Français",direction:"ltr",wordOrder:"SVO",markingStrategy:"preposition",usesSpaces:!0,defaultVerbForm:"infinitive",verb:{position:"start",subjectDrop:!1},references:{me:"moi",it:"il",you:"toi",result:"résultat",event:"événement",target:"cible",body:"corps"},possessive:{marker:"de",markerPosition:"before-property",usePossessiveAdjectives:!0,specialForms:{me:"ma",it:"sa",you:"ta"},keywords:{mon:"me",ma:"me",mes:"me",ton:"you",ta:"you",tes:"you",son:"it",sa:"it",ses:"it"}},roleMarkers:{destination:{primary:"sur",alternatives:["à","dans"],position:"before"},source:{primary:"de",alternatives:["depuis"],position:"before"},patient:{primary:"",position:"before"},style:{primary:"avec",position:"before"}},keywords:{toggle:{primary:"basculer",alternatives:["permuter","alterner"],normalized:"toggle"},add:{primary:"ajouter",normalized:"add"},remove:{primary:"supprimer",alternatives:["enlever","retirer"],normalized:"remove"},put:{primary:"mettre",alternatives:["placer"],normalized:"put"},append:{primary:"annexer",normalized:"append"},prepend:{primary:"préfixer",normalized:"prepend"},take:{primary:"prendre",normalized:"take"},make:{primary:"faire",alternatives:["créer"],normalized:"make"},clone:{primary:"cloner",alternatives:["copier"],normalized:"clone"},swap:{primary:"échanger",alternatives:["permuter"],normalized:"swap"},morph:{primary:"transformer",alternatives:["métamorphoser"],normalized:"morph"},set:{primary:"définir",alternatives:["établir"],normalized:"set"},get:{primary:"obtenir",normalized:"get"},increment:{primary:"incrémenter",alternatives:["augmenter"],normalized:"increment"},decrement:{primary:"décrémenter",alternatives:["diminuer"],normalized:"decrement"},log:{primary:"enregistrer",alternatives:["afficher"],normalized:"log"},show:{primary:"montrer",alternatives:["afficher"],normalized:"show"},hide:{primary:"cacher",alternatives:["masquer"],normalized:"hide"},transition:{primary:"transition",alternatives:["animer"],normalized:"transition"},on:{primary:"sur",alternatives:["quand","lors"],normalized:"on"},trigger:{primary:"déclencher",normalized:"trigger"},send:{primary:"envoyer",normalized:"send"},focus:{primary:"focaliser",alternatives:["concentrer"],normalized:"focus"},blur:{primary:"défocaliser",normalized:"blur"},go:{primary:"aller",alternatives:["naviguer"],normalized:"go"},wait:{primary:"attendre",normalized:"wait"},fetch:{primary:"chercher",alternatives:["récupérer"],normalized:"fetch"},settle:{primary:"stabiliser",normalized:"settle"},if:{primary:"si",normalized:"if"},when:{primary:"quand",normalized:"when"},where:{primary:"où",normalized:"where"},else:{primary:"sinon",normalized:"else"},repeat:{primary:"répéter",normalized:"repeat"},for:{primary:"pour",normalized:"for"},while:{primary:"pendant",normalized:"while"},continue:{primary:"continuer",normalized:"continue"},halt:{primary:"arrêter",alternatives:["stopper"],normalized:"halt"},throw:{primary:"lancer",normalized:"throw"},call:{primary:"appeler",normalized:"call"},return:{primary:"retourner",alternatives:["renvoyer"],normalized:"return"},then:{primary:"puis",alternatives:["ensuite","alors"],normalized:"then"},and:{primary:"et",alternatives:["aussi","également"],normalized:"and"},end:{primary:"fin",alternatives:["terminer","finir"],normalized:"end"},js:{primary:"js",normalized:"js"},async:{primary:"asynchrone",normalized:"async"},tell:{primary:"dire",normalized:"tell"},default:{primary:"défaut",normalized:"default"},init:{primary:"initialiser",normalized:"init"},behavior:{primary:"comportement",normalized:"behavior"},install:{primary:"installer",normalized:"install"},measure:{primary:"mesurer",normalized:"measure"},beep:{primary:"bip",normalized:"beep"},break:{primary:"arrêter",normalized:"break"},copy:{primary:"copier",normalized:"copy"},exit:{primary:"sortir",normalized:"exit"},pick:{primary:"choisir",normalized:"pick"},render:{primary:"rendu",normalized:"render"},into:{primary:"dans",normalized:"into"},before:{primary:"avant",normalized:"before"},after:{primary:"après",normalized:"after"},click:{primary:"clic",alternatives:["clique"],normalized:"click"},hover:{primary:"survol",alternatives:["survoler"],normalized:"hover"},submit:{primary:"soumission",alternatives:["soumettre"],normalized:"submit"},input:{primary:"saisie",alternatives:["entrée"],normalized:"input"},change:{primary:"changement",alternatives:["modifier"],normalized:"change"},until:{primary:"jusqu'à",alternatives:["jusque"],normalized:"until"},event:{primary:"événement",normalized:"event"},from:{primary:"de",alternatives:["depuis"],normalized:"from"}},eventHandler:{keyword:{primary:"sur",alternatives:["lors"],normalized:"on"},sourceMarker:{primary:"de",alternatives:["depuis"],position:"before"},conditionalKeyword:{primary:"quand",alternatives:["lorsque"]},eventMarker:{primary:"au",alternatives:["lors du","lors de"],position:"before"},temporalMarkers:["quand","lorsque"]}}}});var Bp,Fp,Up,Kp,Gp,Qp,Jp,Yp=fl({"src/tokenizers/morphology/french-normalizer.ts"(){ic(),Wp=["toi","vous","nous"],$p=[{ending:"ant",stem:"er",confidence:.88,type:"gerund"},{ending:"é",stem:"er",confidence:.88,type:"participle"},{ending:"ée",stem:"er",confidence:.88,type:"participle"},{ending:"és",stem:"er",confidence:.88,type:"participle"},{ending:"ées",stem:"er",confidence:.88,type:"participle"},{ending:"e",stem:"er",confidence:.75,type:"present"},{ending:"es",stem:"er",confidence:.78,type:"present"},{ending:"ons",stem:"er",confidence:.85,type:"present"},{ending:"ez",stem:"er",confidence:.85,type:"present"},{ending:"ent",stem:"er",confidence:.82,type:"present"},{ending:"ais",stem:"er",confidence:.82,type:"past"},{ending:"ait",stem:"er",confidence:.82,type:"past"},{ending:"ions",stem:"er",confidence:.85,type:"past"},{ending:"iez",stem:"er",confidence:.85,type:"past"},{ending:"aient",stem:"er",confidence:.85,type:"past"},{ending:"ai",stem:"er",confidence:.8,type:"past"},{ending:"as",stem:"er",confidence:.78,type:"past"},{ending:"a",stem:"er",confidence:.75,type:"past"},{ending:"âmes",stem:"er",confidence:.88,type:"past"},{ending:"âtes",stem:"er",confidence:.88,type:"past"},{ending:"èrent",stem:"er",confidence:.88,type:"past"},{ending:"erai",stem:"er",confidence:.85,type:"future"},{ending:"eras",stem:"er",confidence:.85,type:"future"},{ending:"era",stem:"er",confidence:.82,type:"future"},{ending:"erons",stem:"er",confidence:.88,type:"future"},{ending:"erez",stem:"er",confidence:.88,type:"future"},{ending:"eront",stem:"er",confidence:.88,type:"future"},{ending:"erais",stem:"er",confidence:.85,type:"conditional"},{ending:"erait",stem:"er",confidence:.85,type:"conditional"},{ending:"erions",stem:"er",confidence:.88,type:"conditional"},{ending:"eriez",stem:"er",confidence:.88,type:"conditional"},{ending:"eraient",stem:"er",confidence:.88,type:"conditional"},{ending:"ions",stem:"er",confidence:.8,type:"subjunctive"},{ending:"iez",stem:"er",confidence:.8,type:"subjunctive"},{ending:"ons",stem:"er",confidence:.82,type:"imperative"},{ending:"ez",stem:"er",confidence:.82,type:"imperative"},{ending:"er",stem:"er",confidence:.92,type:"dictionary"}],Hp=[{ending:"issant",stem:"ir",confidence:.88,type:"gerund"},{ending:"i",stem:"ir",confidence:.8,type:"participle"},{ending:"ie",stem:"ir",confidence:.82,type:"participle"},{ending:"is",stem:"ir",confidence:.78,type:"participle"},{ending:"ies",stem:"ir",confidence:.82,type:"participle"},{ending:"is",stem:"ir",confidence:.78,type:"present"},{ending:"it",stem:"ir",confidence:.78,type:"present"},{ending:"issons",stem:"ir",confidence:.88,type:"present"},{ending:"issez",stem:"ir",confidence:.88,type:"present"},{ending:"issent",stem:"ir",confidence:.88,type:"present"},{ending:"issais",stem:"ir",confidence:.85,type:"past"},{ending:"issait",stem:"ir",confidence:.85,type:"past"},{ending:"issions",stem:"ir",confidence:.88,type:"past"},{ending:"issiez",stem:"ir",confidence:.88,type:"past"},{ending:"issaient",stem:"ir",confidence:.88,type:"past"},{ending:"irai",stem:"ir",confidence:.85,type:"future"},{ending:"iras",stem:"ir",confidence:.85,type:"future"},{ending:"ira",stem:"ir",confidence:.82,type:"future"},{ending:"irons",stem:"ir",confidence:.88,type:"future"},{ending:"irez",stem:"ir",confidence:.88,type:"future"},{ending:"iront",stem:"ir",confidence:.88,type:"future"},{ending:"ir",stem:"ir",confidence:.9,type:"dictionary"}],qp=[{ending:"ant",stem:"re",confidence:.82,type:"gerund"},{ending:"u",stem:"re",confidence:.8,type:"participle"},{ending:"ue",stem:"re",confidence:.82,type:"participle"},{ending:"us",stem:"re",confidence:.82,type:"participle"},{ending:"ues",stem:"re",confidence:.82,type:"participle"},{ending:"s",stem:"re",confidence:.72,type:"present"},{ending:"d",stem:"re",confidence:.75,type:"present"},{ending:"ons",stem:"re",confidence:.82,type:"present"},{ending:"ez",stem:"re",confidence:.82,type:"present"},{ending:"ent",stem:"re",confidence:.8,type:"present"},{ending:"re",stem:"re",confidence:.9,type:"dictionary"}],Dp=[...$p,...Hp,...qp].sort((e,t)=>t.ending.length-e.ending.length),new(_p=class{constructor(){this.language="fr"}isNormalizable(e){return!(e.length<3)&&function(e){const t=e.toLowerCase();return!!(t.endsWith("er")||t.endsWith("ir")||t.endsWith("re")||t.endsWith("ant")||t.endsWith("é")||t.endsWith("i")||t.endsWith("u")||/[àâäéèêëïîôùûüÿçœæ]/i.test(e))}(e)}normalize(e){const t=e.toLowerCase();if((t.endsWith("er")||t.endsWith("ir")||t.endsWith("re"))&&t.length>=4)return Yl(e);const n=this.tryReflexiveNormalization(t);if(n)return n;const r=this.tryConjugationNormalization(t);return r||Yl(e)}tryReflexiveNormalization(e){for(const t of Wp){const n="-"+t;if(e.endsWith(n)){const t=e.slice(0,-n.length),r=this.tryConjugationNormalization(t);if(r&&r.stem!==t)return Zl(r.stem,.95*r.confidence,{removedSuffixes:[n,...r.metadata?.removedSuffixes||[]],conjugationType:"reflexive"})}}return null}tryConjugationNormalization(e){for(const t of Dp)if(e.endsWith(t.ending)){const n=e.slice(0,-t.ending.length);if(n.length<2)continue;return Zl(n+t.stem,t.confidence,{removedSuffixes:[t.ending],conjugationType:t.type})}return null}})}}),Zp={};yl(Zp,{FrenchTokenizer:()=>Qp,frenchTokenizer:()=>Jp});var Xp,em,tm,nm,rm,im,am,om,sm,lm,cm=fl({"src/tokenizers/french.ts"(){Jl(),Vp(),Yp(),({isLetter:Bp,isIdentifierChar:Fp}=_l(/[a-zA-ZàâäéèêëîïôùûüçœæÀÂÄÉÈÊËÎÏÔÙÛÜÇŒÆ]/)),Up=new Set(["à","a","de","du","des","dans","sur","sous","avec","sans","par","pour","entre","avant","après","apres","depuis","vers","chez","contre","au","aux"]),Kp=[{native:"vrai",normalized:"true"},{native:"faux",normalized:"false"},{native:"nul",normalized:"null"},{native:"indéfini",normalized:"undefined"},{native:"indefini",normalized:"undefined"},{native:"premier",normalized:"first"},{native:"première",normalized:"first"},{native:"premiere",normalized:"first"},{native:"dernier",normalized:"last"},{native:"dernière",normalized:"last"},{native:"derniere",normalized:"last"},{native:"suivant",normalized:"next"},{native:"précédent",normalized:"previous"},{native:"precedent",normalized:"previous"},{native:"plus proche",normalized:"closest"},{native:"parent",normalized:"parent"},{native:"clic",normalized:"click"},{native:"click",normalized:"click"},{native:"entrée",normalized:"input"},{native:"entree",normalized:"input"},{native:"changement",normalized:"change"},{native:"soumission",normalized:"submit"},{native:"touche bas",normalized:"keydown"},{native:"touche haut",normalized:"keyup"},{native:"souris dessus",normalized:"mouseover"},{native:"souris dehors",normalized:"mouseout"},{native:"focus",normalized:"focus"},{native:"flou",normalized:"blur"},{native:"chargement",normalized:"load"},{native:"défilement",normalized:"scroll"},{native:"defilement",normalized:"scroll"},{native:"je",normalized:"me"},{native:"mon",normalized:"my"},{native:"ma",normalized:"my"},{native:"mes",normalized:"my"},{native:"ça",normalized:"it"},{native:"ca",normalized:"it"},{native:"resultat",normalized:"result"},{native:"evenement",normalized:"event"},{native:"seconde",normalized:"s"},{native:"secondes",normalized:"s"},{native:"milliseconde",normalized:"ms"},{native:"millisecondes",normalized:"ms"},{native:"minute",normalized:"m"},{native:"minutes",normalized:"m"},{native:"heure",normalized:"h"},{native:"heures",normalized:"h"},{native:"prefixer",normalized:"prepend"},{native:"creer",normalized:"make"},{native:"definir",normalized:"set"},{native:"etablir",normalized:"set"},{native:"incrementer",normalized:"increment"},{native:"decrementer",normalized:"decrement"},{native:"declencher",normalized:"trigger"},{native:"defocaliser",normalized:"blur"},{native:"recuperer",normalized:"fetch"},{native:"repeter",normalized:"repeat"},{native:"arreter",normalized:"halt"},{native:"defaut",normalized:"default"},{native:"jusqua",normalized:"until"},{native:"apres",normalized:"after"},{native:"journaliser",normalized:"log"},{native:"transmuter",normalized:"morph"},{native:"tant que",normalized:"while"}],Gp=[{pattern:"millisecondes",suffix:"ms",length:13,caseInsensitive:!0},{pattern:"milliseconde",suffix:"ms",length:12,caseInsensitive:!0},{pattern:"secondes",suffix:"s",length:8,caseInsensitive:!0},{pattern:"seconde",suffix:"s",length:7,caseInsensitive:!0},{pattern:"minutes",suffix:"m",length:7,caseInsensitive:!0},{pattern:"minute",suffix:"m",length:6,caseInsensitive:!0},{pattern:"heures",suffix:"h",length:6,caseInsensitive:!0},{pattern:"heure",suffix:"h",length:5,caseInsensitive:!0}],Jp=new(Qp=class extends Kl{constructor(){super(),this.language="fr",this.direction="ltr",this.initializeKeywordsFromProfile(Op,Kp),this.normalizer=new _p}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])||"-"===e[n]&&n+1<e.length&&Wl(e[n+1])){const r=this.extractNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}if(Bp(e[n])){const r=this.extractWord(e,n);if(r){t.push(r),n=r.position.end;continue}}const i=this.tryOperator(e,n);i?(t.push(i),n=i.position.end):n++}return new Ll(t,"fr")}classifyToken(e){const t=e.toLowerCase();return Up.has(t)?"particle":this.isKeyword(t)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||/^\d/.test(e)?"literal":"identifier"}extractWord(e,t){let n=t,r="";for(;n<e.length&&Fp(e[n]);)r+=e[n++];if(!r)return null;const i=r.toLowerCase(),a=this.lookupKeyword(i);return a?Nl(r,"keyword",Il(t,n),a.normalized):Up.has(i)?Nl(r,"particle",Il(t,n)):Nl(r,"identifier",Il(t,n))}extractNumber(e,t){return this.tryNumberWithTimeUnits(e,t,Gp,{allowSign:!0,skipWhitespace:!0})}})}}),um=fl({"src/generators/profiles/hebrew.ts"(){Xp={code:"he",name:"Hebrew",nativeName:"עברית",direction:"rtl",wordOrder:"SVO",markingStrategy:"preposition",usesSpaces:!0,verb:{position:"second",subjectDrop:!0},references:{me:"אני",it:"זה",you:"אתה",result:"תוצאה",event:"אירוע",target:"יעד",body:"גוף"},possessive:{marker:"של",markerPosition:"before-property",usePossessiveAdjectives:!0,specialForms:{me:"שלי",it:"שלו",you:"שלך"},keywords:{"שלי":"me","שלך":"you","שלו":"it","שלה":"it"}},roleMarkers:{destination:{primary:"על",alternatives:["ב","אל","ל"],position:"before"},source:{primary:"מ",alternatives:["מן","מאת"],position:"before"},patient:{primary:"את",position:"before"},style:{primary:"עם",alternatives:["ב"],position:"before"}},keywords:{toggle:{primary:"החלף",alternatives:["שנה","הפוך"],normalized:"toggle"},add:{primary:"הוסף",alternatives:["הכנס"],normalized:"add"},remove:{primary:"הסר",alternatives:["מחק","הורד"],normalized:"remove"},put:{primary:"שים",alternatives:["הנח","הכנס"],normalized:"put"},append:{primary:"צרף",alternatives:["הוסף בסוף"],normalized:"append"},prepend:{primary:"הקדם",alternatives:["הוסף בהתחלה"],normalized:"prepend"},take:{primary:"קח",normalized:"take"},make:{primary:"צור",alternatives:["הכן"],normalized:"make"},clone:{primary:"שכפל",alternatives:["העתק"],normalized:"clone"},swap:{primary:"החלף",alternatives:["המר"],normalized:"swap"},morph:{primary:"הפוך",alternatives:["שנה"],normalized:"morph"},set:{primary:"קבע",alternatives:["הגדר"],normalized:"set"},get:{primary:"קבל",alternatives:["השג"],normalized:"get"},increment:{primary:"הגדל",alternatives:["הוסף אחד"],normalized:"increment"},decrement:{primary:"הקטן",alternatives:["הפחת"],normalized:"decrement"},log:{primary:"רשום",normalized:"log"},show:{primary:"הראה",alternatives:["הצג"],normalized:"show"},hide:{primary:"הסתר",alternatives:["החבא"],normalized:"hide"},transition:{primary:"מעבר",alternatives:["הנפש"],normalized:"transition"},on:{primary:"ב",alternatives:["כש","כאשר","עם"],normalized:"on"},trigger:{primary:"הפעל",alternatives:["שגר"],normalized:"trigger"},send:{primary:"שלח",normalized:"send"},focus:{primary:"מקד",alternatives:["התמקד"],normalized:"focus"},blur:{primary:"טשטש",alternatives:["הסר מיקוד"],normalized:"blur"},go:{primary:"לך",alternatives:["נווט","עבור"],normalized:"go"},wait:{primary:"חכה",alternatives:["המתן"],normalized:"wait"},fetch:{primary:"הבא",alternatives:["טען"],normalized:"fetch"},settle:{primary:"התייצב",normalized:"settle"},if:{primary:"אם",normalized:"if"},when:{primary:"כאשר",alternatives:["כש"],normalized:"when"},where:{primary:"איפה",alternatives:["היכן"],normalized:"where"},else:{primary:"אחרת",alternatives:["אם לא"],normalized:"else"},repeat:{primary:"חזור",normalized:"repeat"},for:{primary:"עבור",alternatives:["לכל"],normalized:"for"},while:{primary:"כל עוד",alternatives:["בזמן"],normalized:"while"},continue:{primary:"המשך",normalized:"continue"},halt:{primary:"עצור",alternatives:["הפסק"],normalized:"halt"},throw:{primary:"זרוק",normalized:"throw"},call:{primary:"קרא",alternatives:["הפעל"],normalized:"call"},return:{primary:"החזר",alternatives:["חזור"],normalized:"return"},then:{primary:"אז",alternatives:["אחרי","ואז"],normalized:"then"},and:{primary:"וגם",alternatives:["גם"],normalized:"and"},end:{primary:"סוף",alternatives:["סיום"],normalized:"end"},js:{primary:"js",alternatives:["ג׳אווהסקריפט"],normalized:"js"},async:{primary:"אסינכרוני",normalized:"async"},tell:{primary:"אמור",normalized:"tell"},default:{primary:"ברירת מחדל",normalized:"default"},init:{primary:"אתחל",alternatives:["התחל"],normalized:"init"},behavior:{primary:"התנהגות",normalized:"behavior"},install:{primary:"התקן",normalized:"install"},measure:{primary:"מדוד",normalized:"measure"},beep:{primary:"ביפ",normalized:"beep"},break:{primary:"שבור",normalized:"break"},copy:{primary:"העתק",normalized:"copy"},exit:{primary:"צא",normalized:"exit"},pick:{primary:"בחר",normalized:"pick"},render:{primary:"רנדר",normalized:"render"},into:{primary:"לתוך",alternatives:["אל"],normalized:"into"},before:{primary:"לפני",normalized:"before"},after:{primary:"אחרי",normalized:"after"},click:{primary:"לחיצה",alternatives:["קליק"],normalized:"click"},hover:{primary:"ריחוף",alternatives:["מעבר"],normalized:"hover"},submit:{primary:"שליחה",alternatives:["הגשה"],normalized:"submit"},input:{primary:"קלט",alternatives:["הזנה"],normalized:"input"},change:{primary:"שינוי",alternatives:["עדכון"],normalized:"change"},until:{primary:"עד",normalized:"until"},event:{primary:"אירוע",normalized:"event"},from:{primary:"מ",alternatives:["מאת"],normalized:"from"}},tokenization:{prefixes:["ה","ו","ב","כ","ל","מ","ש"]},eventHandler:{keyword:{primary:"ב",alternatives:["כש","כאשר","עם"],normalized:"on"},sourceMarker:{primary:"מ",alternatives:["מאת"],position:"before"},conditionalKeyword:{primary:"כאשר",alternatives:["כש","אם"]},eventMarker:{primary:"ב",alternatives:["כש","עם"],position:"before"},temporalMarkers:["כאשר","כש","עם"]}}}}),pm=fl({"src/tokenizers/he.ts"(){Jl(),um(),em=ql([[1424,1535],[64285,64335]]),tm=new Map([["ו","and"]]),nm=new Map([["ב","on"],["כ","when"]]),rm=new Set(["לחיצה","קליק","שליחה","הגשה","ריחוף","מעבר","שינוי","עדכון","קלט","הזנה","מיקוד","טשטוש","טעינה","גלילה"]),im=new Set(["על","את","אל","מן","עם","בתוך","מתוך","ליד","אחרי","לפני","בין","עד","של"]),am=[{native:"אמת",normalized:"true"},{native:"שקר",normalized:"false"},{native:"null",normalized:"null"},{native:"ריק",normalized:"null"},{native:"לא מוגדר",normalized:"undefined"},{native:"ראשון",normalized:"first"},{native:"אחרון",normalized:"last"},{native:"הבא",normalized:"next"},{native:"הקודם",normalized:"previous"},{native:"הקרוב",normalized:"closest"},{native:"הורה",normalized:"parent"},{native:"לחיצה",normalized:"click"},{native:"קליק",normalized:"click"},{native:"קלט",normalized:"input"},{native:"שינוי",normalized:"change"},{native:"שליחה",normalized:"submit"},{native:"מיקוד",normalized:"focus"},{native:"טשטוש",normalized:"blur"},{native:"לחיצת מקש",normalized:"keydown"},{native:"שחרור מקש",normalized:"keyup"},{native:"מעבר עכבר",normalized:"mouseover"},{native:"יציאת עכבר",normalized:"mouseout"},{native:"טעינה",normalized:"load"},{native:"גלילה",normalized:"scroll"},{native:"היא",normalized:"it"},{native:"הוא",normalized:"it"},{native:"את",normalized:"you"},{native:"שנייה",normalized:"s"},{native:"שניות",normalized:"s"},{native:"מילישנייה",normalized:"ms"},{native:"דקה",normalized:"m"},{native:"דקות",normalized:"m"},{native:"שעה",normalized:"h"},{native:"שעות",normalized:"h"}],om=[{pattern:"מילישנייה",suffix:"ms",length:8,caseInsensitive:!1},{pattern:"מילישניות",suffix:"ms",length:9,caseInsensitive:!1},{pattern:"שניות",suffix:"s",length:5,caseInsensitive:!1},{pattern:"שנייה",suffix:"s",length:5,caseInsensitive:!1},{pattern:"דקות",suffix:"m",length:4,caseInsensitive:!1},{pattern:"דקה",suffix:"m",length:3,caseInsensitive:!1},{pattern:"שעות",suffix:"h",length:4,caseInsensitive:!1},{pattern:"שעה",suffix:"h",length:3,caseInsensitive:!1}],sm=new class extends Kl{constructor(){super(),this.language="he",this.direction="rtl",this.initializeKeywordsFromProfile(Xp,am)}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])){const r=this.extractHebrewNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}const i=this.tryPreposition(e,n);if(i)t.push(i),n=i.position.end;else{if(em(e[n])){const r=this.tryEventMarkerPrefix(e,n);if(r){t.push(r.marker),t.push(r.event),n=r.event.position.end;continue}const i=this.tryPrefixConjunction(e,n);if(i){t.push(i.conjunction),n=i.conjunction.position.end;continue}const a=this.extractHebrewWord(e,n);if(a){t.push(a),n=a.position.end;continue}}if($l(e[n])){const r=this.extractAsciiWord(e,n);if(r){t.push(r),n=r.position.end;continue}}n++}}return new Ll(t,"he")}classifyToken(e){return im.has(e)?"particle":this.isKeyword(e)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||/^\d/.test(e)?"literal":"identifier"}tryPreposition(e,t){const n=Array.from(im).sort((e,t)=>t.length-e.length);for(const r of n)if(e.slice(t,t+r.length)===r){const n=t+r.length;if(n>=e.length||Ol(e[n])||!em(e[n])){return{...Nl(r,"particle",Il(t,n)),metadata:{prepositionValue:r}}}}return null}tryPrefixConjunction(e,t){let n=t;for(;n<e.length&&em(e[n]);)n++;const r=e.slice(t,n);if(this.lookupKeyword(r))return null;if(im.has(r))return null;const i=e[t],a=tm.get(i);if(!a)return null;const o=t+1;if(o>=e.length||!em(e[o]))return null;let s=0,l=o;for(;l<e.length&&em(e[l]);)s++,l++;if(s<2)return null;const c=e.slice(o,n);return this.lookupKeyword(c)?{conjunction:Nl(i,"conjunction",Il(t,o),a)}:null}tryEventMarkerPrefix(e,t){const n=e[t],r=nm.get(n);if(!r)return null;const i=t+1;if(i>=e.length||!em(e[i]))return null;let a=i;for(;a<e.length&&em(e[a]);)a++;const o=e.slice(i,a);if(rm.has(o)){const e=Nl(n,"keyword",Il(t,i),r),s=this.lookupKeyword(o);return{marker:e,event:s?Nl(o,"keyword",Il(i,a),s.normalized):Nl(o,"keyword",Il(i,a))}}return null}extractHebrewWord(e,t){let n=t,r="";for(;n<e.length&&em(e[n]);)r+=e[n++];if(!r)return null;const i=this.lookupKeyword(r);if(i)return Nl(r,"keyword",Il(t,n),i.normalized);if(im.has(r)){return{...Nl(r,"particle",Il(t,n)),metadata:{prepositionValue:r}}}const a=this.tryMorphKeywordMatch(r,t,n);return a||Nl(r,"identifier",Il(t,n))}extractAsciiWord(e,t){let n=t,r="";for(;n<e.length&&$l(e[n]);)r+=e[n++];return r?Nl(r,"identifier",Il(t,n)):null}extractHebrewNumber(e,t){return this.tryNumberWithTimeUnits(e,t,om,{allowSign:!1,skipWhitespace:!0})}}}}),mm={};yl(mm,{hindiProfile:()=>lm});var dm,hm,fm,ym,vm,gm,bm=fl({"src/generators/profiles/hindi.ts"(){lm={code:"hi",name:"Hindi",nativeName:"हिन्दी",direction:"ltr",wordOrder:"SOV",markingStrategy:"postposition",usesSpaces:!0,defaultVerbForm:"imperative",verb:{position:"end",suffixes:["ें","ा","ी","े","ो"],subjectDrop:!0},references:{me:"मैं",it:"यह",you:"आप",result:"परिणाम",event:"घटना",target:"लक्ष्य",body:"बॉडी"},possessive:{marker:"का",markerPosition:"between",keywords:{"मेरा":"me","मेरी":"me","मेरे":"me","तेरा":"you","तेरी":"you","तेरे":"you","आपका":"you","आपकी":"you","आपके":"you","उसका":"it","उसकी":"it","उसके":"it","इसका":"it","इसकी":"it","इसके":"it"}},roleMarkers:{patient:{primary:"को",position:"after"},destination:{primary:"में",alternatives:["को","पर"],position:"after"},source:{primary:"से",position:"after"},style:{primary:"से",position:"after"},event:{primary:"पर",position:"after"}},keywords:{toggle:{primary:"टॉगल",alternatives:["बदलें","बदल"],normalized:"toggle"},add:{primary:"जोड़ें",alternatives:["जोड़"],normalized:"add"},remove:{primary:"हटाएं",alternatives:["हटा","मिटाएं"],normalized:"remove"},put:{primary:"रखें",alternatives:["रख","डालें","डाल"],normalized:"put"},append:{primary:"जोड़ें_अंत",alternatives:[],normalized:"append"},prepend:{primary:"जोड़ें_शुरू",alternatives:[],normalized:"prepend"},take:{primary:"लें",alternatives:["ले"],normalized:"take"},make:{primary:"बनाएं",alternatives:["बना"],normalized:"make"},clone:{primary:"कॉपी",alternatives:["प्रतिलिपि"],normalized:"clone"},swap:{primary:"बदलें_स्थान",alternatives:[],normalized:"swap"},morph:{primary:"रूपांतर",alternatives:[],normalized:"morph"},set:{primary:"सेट",alternatives:["निर्धारित"],normalized:"set"},get:{primary:"प्राप्त",alternatives:["पाएं"],normalized:"get"},increment:{primary:"बढ़ाएं",alternatives:["बढ़ा"],normalized:"increment"},decrement:{primary:"घटाएं",alternatives:["घटा"],normalized:"decrement"},log:{primary:"लॉग",alternatives:["दर्ज"],normalized:"log"},show:{primary:"दिखाएं",alternatives:["दिखा"],normalized:"show"},hide:{primary:"छिपाएं",alternatives:["छिपा"],normalized:"hide"},transition:{primary:"संक्रमण",alternatives:[],normalized:"transition"},on:{primary:"पर",alternatives:["में","जब"],normalized:"on"},trigger:{primary:"ट्रिगर",alternatives:[],normalized:"trigger"},send:{primary:"भेजें",alternatives:["भेज"],normalized:"send"},focus:{primary:"फोकस",alternatives:["केंद्रित"],normalized:"focus"},blur:{primary:"धुंधला",alternatives:["फोकस_हटाएं"],normalized:"blur"},click:{primary:"क्लिक",normalized:"click"},hover:{primary:"होवर",alternatives:["ऊपर_रखें"],normalized:"hover"},submit:{primary:"सबमिट",alternatives:["जमा"],normalized:"submit"},input:{primary:"इनपुट",alternatives:["दर्ज"],normalized:"input"},change:{primary:"बदलाव",alternatives:["परिवर्तन"],normalized:"change"},go:{primary:"जाएं",alternatives:["जा"],normalized:"go"},wait:{primary:"प्रतीक्षा",alternatives:["रुकें"],normalized:"wait"},fetch:{primary:"लाएं",alternatives:[],normalized:"fetch"},settle:{primary:"स्थिर",alternatives:[],normalized:"settle"},if:{primary:"अगर",alternatives:["यदि"],normalized:"if"},when:{primary:"जब",normalized:"when"},where:{primary:"कहाँ",normalized:"where"},else:{primary:"वरना",alternatives:["नहीं तो"],normalized:"else"},repeat:{primary:"दोहराएं",alternatives:["दोहरा"],normalized:"repeat"},for:{primary:"के लिए",alternatives:[],normalized:"for"},while:{primary:"जब तक",alternatives:[],normalized:"while"},continue:{primary:"जारी",alternatives:[],normalized:"continue"},halt:{primary:"रोकें",alternatives:["रोक"],normalized:"halt"},throw:{primary:"फेंकें",alternatives:["फेंक"],normalized:"throw"},call:{primary:"कॉल",alternatives:["बुलाएं"],normalized:"call"},return:{primary:"लौटाएं",alternatives:["लौटा"],normalized:"return"},then:{primary:"फिर",alternatives:["तब"],normalized:"then"},and:{primary:"और",alternatives:[],normalized:"and"},end:{primary:"समाप्त",alternatives:["अंत"],normalized:"end"},js:{primary:"जेएस",alternatives:["js"],normalized:"js"},async:{primary:"असिंक",alternatives:[],normalized:"async"},tell:{primary:"बताएं",alternatives:["बता"],normalized:"tell"},default:{primary:"डिफ़ॉल्ट",alternatives:[],normalized:"default"},init:{primary:"प्रारंभ",alternatives:[],normalized:"init"},behavior:{primary:"व्यवहार",alternatives:[],normalized:"behavior"},install:{primary:"इंस्टॉल",alternatives:[],normalized:"install"},measure:{primary:"मापें",alternatives:[],normalized:"measure"},beep:{primary:"बीप",alternatives:[],normalized:"beep"},break:{primary:"रोकें",alternatives:[],normalized:"break"},copy:{primary:"कॉपी",alternatives:[],normalized:"copy"},exit:{primary:"बाहर",alternatives:[],normalized:"exit"},pick:{primary:"चुनें",alternatives:[],normalized:"pick"},render:{primary:"रेंडर",alternatives:[],normalized:"render"},into:{primary:"में",alternatives:["को"],normalized:"into"},before:{primary:"से पहले",alternatives:["पहले"],normalized:"before"},after:{primary:"के बाद",alternatives:["बाद"],normalized:"after"},until:{primary:"तक",alternatives:[],normalized:"until"},event:{primary:"घटना",alternatives:[],normalized:"event"},from:{primary:"से",normalized:"from"}},tokenization:{particles:["को","में","पर","से","का","की","के","तक","ने"],boundaryStrategy:"space"},eventHandler:{keyword:{primary:"पर",alternatives:["में","जब"],normalized:"on"},sourceMarker:{primary:"से",position:"after"},eventMarker:{primary:"पर",alternatives:["में"],position:"after"},temporalMarkers:["जब","जब भी"]}}}}),km={};yl(km,{HindiTokenizer:()=>vm,hindiTokenizer:()=>gm});var wm,zm=fl({"src/tokenizers/hindi.ts"(){Jl(),bm(),dm=ql([[2304,2431],[43232,43263]]),hm=dm,fm=new Set(["को","में","पर","से","का","की","के","तक","ने"]),ym=[{native:"सच",normalized:"true"},{native:"सत्य",normalized:"true"},{native:"झूठ",normalized:"false"},{native:"असत्य",normalized:"false"},{native:"खाली",normalized:"null"},{native:"अपरिभाषित",normalized:"undefined"},{native:"पहला",normalized:"first"},{native:"अंतिम",normalized:"last"},{native:"अगला",normalized:"next"},{native:"पिछला",normalized:"previous"},{native:"निकटतम",normalized:"closest"},{native:"मूल",normalized:"parent"},{native:"क्लिक",normalized:"click"},{native:"परिवर्तन",normalized:"change"},{native:"जमा",normalized:"submit"},{native:"इनपुट",normalized:"input"},{native:"लोड",normalized:"load"},{native:"स्क्रॉल",normalized:"scroll"},{native:"को",normalized:"to"},{native:"के साथ",normalized:"with"}],gm=new(vm=class extends Kl{constructor(){super(),this.language="hi",this.direction="ltr",this.initializeKeywordsFromProfile(lm,ym)}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])||"-"===e[n]&&n+1<e.length&&Wl(e[n+1])){const r=this.extractNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}if(":"===e[n]){const r=n;n++;let i="";for(;n<e.length&&($l(e[n])||hm(e[n]));)i+=e[n],n++;if(i){t.push(Nl(":"+i,"identifier",Il(r,n),":"+i));continue}n=r}if(hm(e[n])){const r=n;let i="";for(;n<e.length&&(hm(e[n])||" "===e[n]);){if(" "===e[n]){if(n+1<e.length&&hm(e[n+1])){const t=e.slice(n),r=[" के लिए"," के साथ"," के बाद"," से पहले"," नहीं तो"," जब तक"," के बारे में"].find(e=>t.startsWith(e));if(r){i+=r,n+=r.length;continue}}break}i+=e[n],n++}const a=this.lookupKeyword(i);a?t.push(Nl(i,"keyword",Il(r,n),a.normalized)):fm.has(i)?t.push(Nl(i,"particle",Il(r,n))):t.push(Nl(i,"identifier",Il(r,n)));continue}if($l(e[n])){const r=n;let i="";for(;n<e.length&&$l(e[n]);)i+=e[n],n++;const a=this.lookupKeyword(i),o=a?"keyword":"identifier";t.push(Nl(i,o,Il(r,n),a?.normalized||i.toLowerCase()));continue}const r=n;t.push(Nl(e[n],"operator",Il(r,n+1))),n++}return new Ll(t,this.language)}classifyToken(e){return this.isKeyword(e)?"keyword":fm.has(e)?"particle":e.startsWith(".")||e.startsWith("#")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith(":")?"identifier":e.startsWith('"')||e.startsWith("'")||/^-?\d/.test(e)?"literal":"identifier"}extractNumber(e,t){let n=t,r="";for("-"===e[n]&&(r+="-",n++);n<e.length&&Wl(e[n]);)r+=e[n],n++;if(n<e.length&&"."===e[n])for(r+=".",n++;n<e.length&&Wl(e[n]);)r+=e[n],n++;return"-"===r?null:Nl(r,"literal",Il(t,n))}})}}),xm={};yl(xm,{indonesianProfile:()=>wm});var Em,Sm,Tm,Cm,Am,jm,Lm=fl({"src/generators/profiles/indonesian.ts"(){wm={code:"id",name:"Indonesian",nativeName:"Bahasa Indonesia",direction:"ltr",wordOrder:"SVO",markingStrategy:"preposition",usesSpaces:!0,verb:{position:"start",subjectDrop:!0},references:{me:"saya",it:"itu",you:"anda",result:"hasil",event:"peristiwa",target:"target",body:"tubuh"},possessive:{marker:"",markerPosition:"after-object",usePossessiveAdjectives:!0,specialForms:{me:"saya",it:"nya",you:"anda"},keywords:{saya:"me",aku:"me",ku:"me",anda:"you",kamu:"you",mu:"you",nya:"it",dia:"it"}},roleMarkers:{destination:{primary:"pada",alternatives:["ke","di"],position:"before"},source:{primary:"dari",position:"before"},patient:{primary:"",position:"before"},style:{primary:"dengan",position:"before"}},keywords:{toggle:{primary:"alihkan",alternatives:["ganti","tukar"],normalized:"toggle"},add:{primary:"tambah",alternatives:["tambahkan"],normalized:"add"},remove:{primary:"hapus",alternatives:["buang","hilangkan"],normalized:"remove"},put:{primary:"taruh",alternatives:["letakkan","masukkan"],normalized:"put"},append:{primary:"sisipkan",normalized:"append"},prepend:{primary:"awali",normalized:"prepend"},take:{primary:"ambil",normalized:"take"},make:{primary:"buat",alternatives:["bikin","ciptakan"],normalized:"make"},clone:{primary:"klon",alternatives:["salin","tiru"],normalized:"clone"},swap:{primary:"tukar",alternatives:["ganti"],normalized:"swap"},morph:{primary:"ubah",alternatives:["transformasi"],normalized:"morph"},set:{primary:"atur",alternatives:["tetapkan"],normalized:"set"},get:{primary:"dapatkan",alternatives:["peroleh"],normalized:"get"},increment:{primary:"tingkatkan",alternatives:["naikkan"],normalized:"increment"},decrement:{primary:"turunkan",alternatives:["kurangi"],normalized:"decrement"},log:{primary:"catat",alternatives:["rekam","cetak"],normalized:"log"},show:{primary:"tampilkan",alternatives:["perlihatkan"],normalized:"show"},hide:{primary:"sembunyikan",alternatives:["tutup"],normalized:"hide"},transition:{primary:"transisi",alternatives:["animasikan"],normalized:"transition"},on:{primary:"pada",alternatives:["saat","ketika"],normalized:"on"},trigger:{primary:"picu",alternatives:["jalankan"],normalized:"trigger"},send:{primary:"kirim",alternatives:["kirimkan"],normalized:"send"},focus:{primary:"fokus",alternatives:["fokuskan"],normalized:"focus"},blur:{primary:"blur",normalized:"blur"},go:{primary:"pergi",alternatives:["pindah","navigasi"],normalized:"go"},wait:{primary:"tunggu",normalized:"wait"},fetch:{primary:"ambil",alternatives:["muat"],normalized:"fetch"},settle:{primary:"stabilkan",normalized:"settle"},if:{primary:"jika",alternatives:["kalau","bila"],normalized:"if"},when:{primary:"ketika",normalized:"when"},where:{primary:"di_mana",normalized:"where"},else:{primary:"selainnya",normalized:"else"},repeat:{primary:"ulangi",normalized:"repeat"},for:{primary:"untuk",normalized:"for"},while:{primary:"selama",normalized:"while"},continue:{primary:"lanjutkan",alternatives:["terus"],normalized:"continue"},halt:{primary:"hentikan",alternatives:["berhenti"],normalized:"halt"},throw:{primary:"lempar",normalized:"throw"},call:{primary:"panggil",normalized:"call"},return:{primary:"kembalikan",alternatives:["kembali"],normalized:"return"},then:{primary:"lalu",alternatives:["kemudian","setelah itu"],normalized:"then"},and:{primary:"dan",alternatives:["juga","serta"],normalized:"and"},end:{primary:"selesai",alternatives:["akhir","tamat"],normalized:"end"},js:{primary:"js",alternatives:["javascript"],normalized:"js"},async:{primary:"asinkron",normalized:"async"},tell:{primary:"katakan",alternatives:["beritahu"],normalized:"tell"},default:{primary:"bawaan",normalized:"default"},init:{primary:"inisialisasi",alternatives:["mulai"],normalized:"init"},behavior:{primary:"perilaku",normalized:"behavior"},install:{primary:"pasang",alternatives:["instal"],normalized:"install"},measure:{primary:"ukur",normalized:"measure"},beep:{primary:"bunyi",normalized:"beep"},break:{primary:"hentikan",normalized:"break"},copy:{primary:"salin",normalized:"copy"},exit:{primary:"keluar",normalized:"exit"},pick:{primary:"pilih",normalized:"pick"},render:{primary:"tampilkan",normalized:"render"},into:{primary:"ke dalam",normalized:"into"},before:{primary:"sebelum",normalized:"before"},after:{primary:"sesudah",alternatives:["setelah"],normalized:"after"},click:{primary:"klik",alternatives:["tekan"],normalized:"click"},hover:{primary:"hover",alternatives:["arahkan"],normalized:"hover"},submit:{primary:"kirim",alternatives:["submit"],normalized:"submit"},input:{primary:"masuk",alternatives:["input"],normalized:"input"},change:{primary:"ubah",alternatives:["berubah"],normalized:"change"},until:{primary:"sampai",normalized:"until"},event:{primary:"peristiwa",alternatives:["event"],normalized:"event"},from:{primary:"dari",normalized:"from"}},eventHandler:{keyword:{primary:"pada",alternatives:["ketika","saat"],normalized:"on"},sourceMarker:{primary:"dari",position:"before"},conditionalKeyword:{primary:"ketika",alternatives:["saat","waktu"]},eventMarker:{primary:"saat",alternatives:["ketika"],position:"before"},temporalMarkers:["ketika","saat"]}}}}),Pm={};yl(Pm,{IndonesianTokenizer:()=>Am,indonesianTokenizer:()=>jm});var Im,Nm,Om,Rm,Mm,Wm,$m=fl({"src/tokenizers/indonesian.ts"(){Jl(),Lm(),({isLetter:Em,isIdentifierChar:Sm}=_l(/[a-zA-Z]/)),Tm=new Set(["di","ke","dari","pada","dengan","tanpa","untuk","oleh","antara","sebelum","sesudah","setelah","selama","sampai","hingga","sejak","menuju","tentang","terhadap","melalui","dalam","luar"]),Cm=[{native:"benar",normalized:"true"},{native:"salah",normalized:"false"},{native:"null",normalized:"null"},{native:"kosong",normalized:"null"},{native:"tidak terdefinisi",normalized:"undefined"},{native:"pertama",normalized:"first"},{native:"terakhir",normalized:"last"},{native:"selanjutnya",normalized:"next"},{native:"berikutnya",normalized:"next"},{native:"sebelumnya",normalized:"previous"},{native:"terdekat",normalized:"closest"},{native:"induk",normalized:"parent"},{native:"klik",normalized:"click"},{native:"click",normalized:"click"},{native:"masukan",normalized:"input"},{native:"input",normalized:"input"},{native:"perubahan",normalized:"change"},{native:"tombol turun",normalized:"keydown"},{native:"tombol naik",normalized:"keyup"},{native:"mouse masuk",normalized:"mouseover"},{native:"mouse keluar",normalized:"mouseout"},{native:"gulir",normalized:"scroll"},{native:"aku",normalized:"me"},{native:"ini",normalized:"me"},{native:"milikku",normalized:"my"},{native:"dia",normalized:"it"},{native:"kejadian",normalized:"event"},{native:"sasaran",normalized:"target"},{native:"detik",normalized:"s"},{native:"milidetik",normalized:"ms"},{native:"menit",normalized:"m"},{native:"jam",normalized:"h"},{native:"jika tidak",normalized:"else"},{native:"hilangkan fokus",normalized:"blur"},{native:"maka",normalized:"then"}],jm=new(Am=class extends Kl{constructor(){super(),this.language="id",this.direction="ltr",this.initializeKeywordsFromProfile(wm,Cm)}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])||"-"===e[n]&&n+1<e.length&&Wl(e[n+1])){const r=this.extractNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}if(Em(e[n])){const r=this.extractWord(e,n);if(r){t.push(r),n=r.position.end;continue}}const i=this.tryOperator(e,n);i?(t.push(i),n=i.position.end):n++}return new Ll(t,"id")}classifyToken(e){const t=e.toLowerCase();return Tm.has(t)?"particle":this.isKeyword(t)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||/^\d/.test(e)?"literal":"identifier"}extractWord(e,t){let n=t,r="";for(;n<e.length&&Sm(e[n]);)r+=e[n++];if(!r)return null;const i=r.toLowerCase(),a=this.lookupKeyword(i);return a?Nl(r,"keyword",Il(t,n),a.normalized):Tm.has(i)?Nl(r,"particle",Il(t,n)):Nl(r,"identifier",Il(t,n))}extractNumber(e,t){let n=t,r="";for("-"!==e[n]&&"+"!==e[n]||(r+=e[n++]);n<e.length&&Wl(e[n]);)r+=e[n++];if(n<e.length&&"."===e[n])for(r+=e[n++];n<e.length&&Wl(e[n]);)r+=e[n++];let i=n;for(;i<e.length&&Ol(e[i]);)i++;const a=e.slice(i).toLowerCase();return a.startsWith("milidetik")?(r+="ms",n=i+9):a.startsWith("detik")?(r+="s",n=i+5):a.startsWith("menit")?(r+="m",n=i+5):a.startsWith("jam")&&(r+="h",n=i+3),r&&"-"!==r&&"+"!==r?Nl(r,"literal",Il(t,n)):null}})}});function Hm(e){return/[àèéìíîòóùúÀÈÉÌÍÎÒÓÙÚ]/.test(e)}var qm,Dm=fl({"src/tokenizers/morphology/italian-normalizer.ts"(){ic(),Im=["si","mi","ti","ci","vi"],Nm=[{ending:"ando",stem:"are",confidence:.88,type:"gerund"},{ending:"ato",stem:"are",confidence:.88,type:"participle"},{ending:"ata",stem:"are",confidence:.88,type:"participle"},{ending:"ati",stem:"are",confidence:.88,type:"participle"},{ending:"ate",stem:"are",confidence:.88,type:"participle"},{ending:"o",stem:"are",confidence:.75,type:"present"},{ending:"i",stem:"are",confidence:.72,type:"present"},{ending:"a",stem:"are",confidence:.75,type:"present"},{ending:"iamo",stem:"are",confidence:.85,type:"present"},{ending:"ate",stem:"are",confidence:.85,type:"present"},{ending:"ano",stem:"are",confidence:.85,type:"present"},{ending:"avo",stem:"are",confidence:.88,type:"past"},{ending:"avi",stem:"are",confidence:.88,type:"past"},{ending:"ava",stem:"are",confidence:.88,type:"past"},{ending:"avamo",stem:"are",confidence:.88,type:"past"},{ending:"avate",stem:"are",confidence:.88,type:"past"},{ending:"avano",stem:"are",confidence:.88,type:"past"},{ending:"ai",stem:"are",confidence:.85,type:"past"},{ending:"asti",stem:"are",confidence:.88,type:"past"},{ending:"ò",stem:"are",confidence:.85,type:"past"},{ending:"ammo",stem:"are",confidence:.88,type:"past"},{ending:"aste",stem:"are",confidence:.88,type:"past"},{ending:"arono",stem:"are",confidence:.88,type:"past"},{ending:"i",stem:"are",confidence:.72,type:"subjunctive"},{ending:"ino",stem:"are",confidence:.82,type:"subjunctive"},{ending:"a",stem:"are",confidence:.75,type:"imperative"},{ending:"are",stem:"are",confidence:.92,type:"dictionary"}],Om=[{ending:"endo",stem:"ere",confidence:.88,type:"gerund"},{ending:"uto",stem:"ere",confidence:.85,type:"participle"},{ending:"uta",stem:"ere",confidence:.85,type:"participle"},{ending:"uti",stem:"ere",confidence:.85,type:"participle"},{ending:"ute",stem:"ere",confidence:.85,type:"participle"},{ending:"o",stem:"ere",confidence:.72,type:"present"},{ending:"i",stem:"ere",confidence:.72,type:"present"},{ending:"e",stem:"ere",confidence:.72,type:"present"},{ending:"iamo",stem:"ere",confidence:.85,type:"present"},{ending:"ete",stem:"ere",confidence:.85,type:"present"},{ending:"ono",stem:"ere",confidence:.82,type:"present"},{ending:"evo",stem:"ere",confidence:.88,type:"past"},{ending:"evi",stem:"ere",confidence:.88,type:"past"},{ending:"eva",stem:"ere",confidence:.88,type:"past"},{ending:"evamo",stem:"ere",confidence:.88,type:"past"},{ending:"evate",stem:"ere",confidence:.88,type:"past"},{ending:"evano",stem:"ere",confidence:.88,type:"past"},{ending:"ei",stem:"ere",confidence:.85,type:"past"},{ending:"etti",stem:"ere",confidence:.85,type:"past"},{ending:"esti",stem:"ere",confidence:.88,type:"past"},{ending:"é",stem:"ere",confidence:.85,type:"past"},{ending:"ette",stem:"ere",confidence:.85,type:"past"},{ending:"emmo",stem:"ere",confidence:.88,type:"past"},{ending:"este",stem:"ere",confidence:.88,type:"past"},{ending:"erono",stem:"ere",confidence:.88,type:"past"},{ending:"ettero",stem:"ere",confidence:.88,type:"past"},{ending:"ere",stem:"ere",confidence:.92,type:"dictionary"}],Rm=[{ending:"endo",stem:"ire",confidence:.85,type:"gerund"},{ending:"ito",stem:"ire",confidence:.85,type:"participle"},{ending:"ita",stem:"ire",confidence:.85,type:"participle"},{ending:"iti",stem:"ire",confidence:.85,type:"participle"},{ending:"ite",stem:"ire",confidence:.85,type:"participle"},{ending:"o",stem:"ire",confidence:.7,type:"present"},{ending:"i",stem:"ire",confidence:.7,type:"present"},{ending:"e",stem:"ire",confidence:.7,type:"present"},{ending:"iamo",stem:"ire",confidence:.85,type:"present"},{ending:"ite",stem:"ire",confidence:.85,type:"present"},{ending:"ono",stem:"ire",confidence:.78,type:"present"},{ending:"isco",stem:"ire",confidence:.85,type:"present"},{ending:"isci",stem:"ire",confidence:.85,type:"present"},{ending:"isce",stem:"ire",confidence:.85,type:"present"},{ending:"iscono",stem:"ire",confidence:.88,type:"present"},{ending:"ivo",stem:"ire",confidence:.88,type:"past"},{ending:"ivi",stem:"ire",confidence:.88,type:"past"},{ending:"iva",stem:"ire",confidence:.88,type:"past"},{ending:"ivamo",stem:"ire",confidence:.88,type:"past"},{ending:"ivate",stem:"ire",confidence:.88,type:"past"},{ending:"ivano",stem:"ire",confidence:.88,type:"past"},{ending:"ii",stem:"ire",confidence:.85,type:"past"},{ending:"isti",stem:"ire",confidence:.88,type:"past"},{ending:"ì",stem:"ire",confidence:.85,type:"past"},{ending:"immo",stem:"ire",confidence:.88,type:"past"},{ending:"iste",stem:"ire",confidence:.88,type:"past"},{ending:"irono",stem:"ire",confidence:.88,type:"past"},{ending:"ire",stem:"ire",confidence:.92,type:"dictionary"}],Mm=[...Nm,...Om,...Rm].sort((e,t)=>t.ending.length-e.ending.length),new(Wm=class{constructor(){this.language="it"}isNormalizable(e){return!(e.length<3)&&function(e){const t=e.toLowerCase();if(t.endsWith("are")||t.endsWith("ere")||t.endsWith("ire"))return!0;if(t.endsWith("ando")||t.endsWith("endo"))return!0;if(t.endsWith("ato")||t.endsWith("uto")||t.endsWith("ito"))return!0;if(t.endsWith("arsi")||t.endsWith("ersi")||t.endsWith("irsi"))return!0;for(const t of e)if(Hm(t))return!0;return!1}(e)}normalize(e){const t=e.toLowerCase();if((t.endsWith("are")||t.endsWith("ere")||t.endsWith("ire"))&&!Im.some(e=>t.endsWith(e+"are")||t.endsWith(e+"ere")||t.endsWith(e+"ire")))return Yl(e);const n=this.tryReflexiveNormalization(t);if(n)return n;const r=this.tryConjugationNormalization(t);return r||Yl(e)}tryReflexiveNormalization(e){for(const t of Im)if(e.endsWith(t)){const n=e.slice(0,-t.length);if(n.endsWith("ar")||n.endsWith("er")||n.endsWith("ir")){return Zl(n+"e",.88,{removedSuffixes:[t],conjugationType:"reflexive"})}if(n.endsWith("are")||n.endsWith("ere")||n.endsWith("ire"))return Zl(n,.88,{removedSuffixes:[t],conjugationType:"reflexive"});const r=this.tryConjugationNormalization(n);if(r&&r.stem!==n)return Zl(r.stem,.95*r.confidence,{removedSuffixes:[t,...r.metadata?.removedSuffixes||[]],conjugationType:"reflexive"})}return null}tryConjugationNormalization(e){for(const t of Mm)if(e.endsWith(t.ending)){const n=e.slice(0,-t.ending.length);if(n.length<2)continue;return Zl(n+t.stem,t.confidence,{removedSuffixes:[t.ending],conjugationType:t.type})}return null}})}}),_m={};yl(_m,{italianProfile:()=>qm});var Vm,Bm,Fm,Um,Km,Gm,Qm,Jm=fl({"src/generators/profiles/italian.ts"(){qm={code:"it",name:"Italian",nativeName:"Italiano",direction:"ltr",wordOrder:"SVO",markingStrategy:"preposition",usesSpaces:!0,defaultVerbForm:"infinitive",verb:{position:"start",subjectDrop:!0},references:{me:"io",it:"esso",you:"tu",result:"risultato",event:"evento",target:"obiettivo",body:"corpo"},possessive:{marker:"di",markerPosition:"before-property",usePossessiveAdjectives:!0,specialForms:{me:"mio",it:"suo",you:"tuo"},keywords:{mio:"me",mia:"me",miei:"me",mie:"me",tuo:"you",tua:"you",tuoi:"you",tue:"you",suo:"it",sua:"it",suoi:"it",sue:"it"}},roleMarkers:{destination:{primary:"in",alternatives:["su","a"],position:"before"},source:{primary:"da",alternatives:["di"],position:"before"},patient:{primary:"",position:"before"},style:{primary:"con",position:"before"}},keywords:{toggle:{primary:"commutare",alternatives:["alternare","cambiare"],normalized:"toggle"},add:{primary:"aggiungere",alternatives:["aggiungi"],normalized:"add"},remove:{primary:"rimuovere",alternatives:["eliminare","togliere"],normalized:"remove"},put:{primary:"mettere",alternatives:["inserire"],normalized:"put"},append:{primary:"aggiungere",normalized:"append"},prepend:{primary:"anteporre",normalized:"prepend"},take:{primary:"prendere",normalized:"take"},make:{primary:"fare",alternatives:["creare"],normalized:"make"},clone:{primary:"clonare",alternatives:["copiare"],normalized:"clone"},swap:{primary:"scambiare",alternatives:["cambiare"],normalized:"swap"},morph:{primary:"trasformare",alternatives:["convertire"],normalized:"morph"},set:{primary:"impostare",alternatives:["definire"],normalized:"set"},get:{primary:"ottenere",alternatives:["prendere"],normalized:"get"},increment:{primary:"incrementare",alternatives:["aumentare"],normalized:"increment"},decrement:{primary:"decrementare",alternatives:["diminuire"],normalized:"decrement"},log:{primary:"registrare",normalized:"log"},show:{primary:"mostrare",alternatives:["visualizzare"],normalized:"show"},hide:{primary:"nascondere",normalized:"hide"},transition:{primary:"transizione",alternatives:["animare"],normalized:"transition"},on:{primary:"su",alternatives:["quando","al"],normalized:"on"},trigger:{primary:"scatenare",alternatives:["attivare"],normalized:"trigger"},send:{primary:"inviare",normalized:"send"},focus:{primary:"focalizzare",normalized:"focus"},blur:{primary:"sfuocare",normalized:"blur"},go:{primary:"andare",alternatives:["navigare","vai"],normalized:"go"},wait:{primary:"aspettare",alternatives:["attendere"],normalized:"wait"},fetch:{primary:"recuperare",normalized:"fetch"},settle:{primary:"stabilizzare",normalized:"settle"},if:{primary:"se",normalized:"if"},when:{primary:"quando",normalized:"when"},where:{primary:"dove",normalized:"where"},else:{primary:"altrimenti",normalized:"else"},repeat:{primary:"ripetere",normalized:"repeat"},for:{primary:"per",normalized:"for"},while:{primary:"mentre",normalized:"while"},continue:{primary:"continuare",normalized:"continue"},halt:{primary:"fermare",normalized:"halt"},throw:{primary:"lanciare",normalized:"throw"},call:{primary:"chiamare",normalized:"call"},return:{primary:"ritornare",normalized:"return"},then:{primary:"allora",alternatives:["poi","quindi"],normalized:"then"},and:{primary:"e",alternatives:["anche"],normalized:"and"},end:{primary:"fine",normalized:"end"},js:{primary:"js",normalized:"js"},async:{primary:"asincrono",normalized:"async"},tell:{primary:"dire",normalized:"tell"},default:{primary:"predefinito",normalized:"default"},init:{primary:"inizializzare",alternatives:["inizia"],normalized:"init"},behavior:{primary:"comportamento",normalized:"behavior"},install:{primary:"installare",normalized:"install"},measure:{primary:"misurare",normalized:"measure"},beep:{primary:"beep",normalized:"beep"},break:{primary:"interrompere",normalized:"break"},copy:{primary:"copiare",normalized:"copy"},exit:{primary:"uscire",normalized:"exit"},pick:{primary:"scegliere",normalized:"pick"},render:{primary:"renderizzare",normalized:"render"},into:{primary:"in",alternatives:["dentro"],normalized:"into"},before:{primary:"prima",normalized:"before"},after:{primary:"dopo",normalized:"after"},click:{primary:"clic",alternatives:["clicca"],normalized:"click"},hover:{primary:"passaggio",alternatives:["sorvolo"],normalized:"hover"},submit:{primary:"invio",alternatives:["inviare"],normalized:"submit"},input:{primary:"inserimento",alternatives:["input"],normalized:"input"},change:{primary:"cambio",alternatives:["cambiamento"],normalized:"change"},until:{primary:"fino",normalized:"until"},event:{primary:"evento",normalized:"event"},from:{primary:"da",alternatives:["di"],normalized:"from"}},eventHandler:{keyword:{primary:"su",alternatives:["al","quando"],normalized:"on"},sourceMarker:{primary:"da",alternatives:["di"],position:"before"},conditionalKeyword:{primary:"quando",alternatives:["se"]},eventMarker:{primary:"al",alternatives:["allo","alla"],position:"before"},temporalMarkers:["quando","al"]}}}}),Ym={};yl(Ym,{ItalianTokenizer:()=>Gm,italianTokenizer:()=>Qm});var Zm,Xm,ed,td=fl({"src/tokenizers/italian.ts"(){Jl(),Dm(),Jm(),({isLetter:Vm,isIdentifierChar:Bm}=_l(/[a-zA-ZàèéìíîòóùúÀÈÉÌÍÎÒÓÙÚ]/)),Fm=[{pattern:"millisecondi",suffix:"ms",length:12,caseInsensitive:!0},{pattern:"millisecondo",suffix:"ms",length:12,caseInsensitive:!0},{pattern:"secondi",suffix:"s",length:7,caseInsensitive:!0},{pattern:"secondo",suffix:"s",length:7,caseInsensitive:!0},{pattern:"minuti",suffix:"m",length:6,caseInsensitive:!0},{pattern:"minuto",suffix:"m",length:6,caseInsensitive:!0},{pattern:"ore",suffix:"h",length:3,caseInsensitive:!0},{pattern:"ora",suffix:"h",length:3,caseInsensitive:!0}],Um=new Set(["in","a","di","da","con","su","per","tra","fra","dopo","prima","dentro","fuori","sopra","sotto","al","allo","alla","ai","agli","alle","del","dello","della","dei","degli","delle","dal","dallo","dalla","dai","dagli","dalle","nel","nello","nella","nei","negli","nelle","sul","sullo","sulla","sui","sugli","sulle"]),Km=[{native:"vero",normalized:"true"},{native:"falso",normalized:"false"},{native:"nullo",normalized:"null"},{native:"indefinito",normalized:"undefined"},{native:"primo",normalized:"first"},{native:"prima",normalized:"first"},{native:"ultimo",normalized:"last"},{native:"ultima",normalized:"last"},{native:"prossimo",normalized:"next"},{native:"successivo",normalized:"next"},{native:"precedente",normalized:"previous"},{native:"vicino",normalized:"closest"},{native:"padre",normalized:"parent"},{native:"clic",normalized:"click"},{native:"click",normalized:"click"},{native:"fare clic",normalized:"click"},{native:"input",normalized:"input"},{native:"cambio",normalized:"change"},{native:"invio",normalized:"submit"},{native:"tasto giù",normalized:"keydown"},{native:"tasto su",normalized:"keyup"},{native:"mouse sopra",normalized:"mouseover"},{native:"mouse fuori",normalized:"mouseout"},{native:"fuoco",normalized:"focus"},{native:"sfuocatura",normalized:"blur"},{native:"caricamento",normalized:"load"},{native:"scorrimento",normalized:"scroll"},{native:"io",normalized:"me"},{native:"me",normalized:"me"},{native:"destinazione",normalized:"target"},{native:"secondo",normalized:"s"},{native:"secondi",normalized:"s"},{native:"millisecondo",normalized:"ms"},{native:"millisecondi",normalized:"ms"},{native:"minuto",normalized:"m"},{native:"minuti",normalized:"m"},{native:"ora",normalized:"h"},{native:"ore",normalized:"h"},{native:"fino a",normalized:"until"},{native:"prima di",normalized:"before"},{native:"dopo di",normalized:"after"},{native:"dentro di",normalized:"into"},{native:"fuori di",normalized:"out"},{native:"aggiungere",normalized:"add"},{native:"aggiungi",normalized:"add"},{native:"rimuovi",normalized:"remove"},{native:"elimina",normalized:"remove"},{native:"togli",normalized:"remove"},{native:"metti",normalized:"put"},{native:"inserisci",normalized:"put"},{native:"prendi",normalized:"take"},{native:"fai",normalized:"make"},{native:"crea",normalized:"make"},{native:"clona",normalized:"clone"},{native:"copia",normalized:"clone"},{native:"imposta",normalized:"set"},{native:"ottieni",normalized:"get"},{native:"incrementa",normalized:"increment"},{native:"aumenta",normalized:"increment"},{native:"decrementa",normalized:"decrement"},{native:"diminuisci",normalized:"decrement"},{native:"registra",normalized:"log"},{native:"mostra",normalized:"show"},{native:"visualizza",normalized:"show"},{native:"nascondi",normalized:"hide"},{native:"anima",normalized:"transition"},{native:"scatena",normalized:"trigger"},{native:"attiva",normalized:"trigger"},{native:"invia",normalized:"send"},{native:"focalizza",normalized:"focus"},{native:"sfuoca",normalized:"blur"},{native:"vai",normalized:"go"},{native:"naviga",normalized:"go"},{native:"aspetta",normalized:"wait"},{native:"attendi",normalized:"wait"},{native:"recupera",normalized:"fetch"},{native:"stabilizza",normalized:"settle"},{native:"ripeti",normalized:"repeat"},{native:"continua",normalized:"continue"},{native:"ferma",normalized:"halt"},{native:"lancia",normalized:"throw"},{native:"chiama",normalized:"call"},{native:"ritorna",normalized:"return"},{native:"inizializza",normalized:"init"},{native:"installa",normalized:"install"},{native:"misura",normalized:"measure"},{native:"e",normalized:"and"},{native:"o",normalized:"or"},{native:"non",normalized:"not"},{native:"è",normalized:"is"},{native:"esiste",normalized:"exists"},{native:"vuoto",normalized:"empty"},{native:"toggle",normalized:"toggle"},{native:"di",normalized:"tell"}],Qm=new(Gm=class extends Kl{constructor(){super(),this.language="it",this.direction="ltr",this.initializeKeywordsFromProfile(qm,Km),this.normalizer=new Wm}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])||"-"===e[n]&&n+1<e.length&&Wl(e[n+1])){const r=this.extractItalianNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}const i=this.tryMultiWordPhrase(e,n);if(i){t.push(i),n=i.position.end;continue}if(Vm(e[n])){const r=this.extractItalianWord(e,n);if(r){t.push(r),n=r.position.end;continue}}const a=this.tryOperator(e,n);a?(t.push(a),n=a.position.end):n++}return new Ll(t,"it")}classifyToken(e){const t=e.toLowerCase();return Um.has(t)?"particle":this.isKeyword(t)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||/^\d/.test(e)?"literal":["==","!=","<=",">=","<",">","&&","||","!"].includes(e)?"operator":"identifier"}tryMultiWordPhrase(e,t){for(const n of this.profileKeywords){if(!n.native.includes(" "))continue;const r=n.native;if(e.slice(t,t+r.length).toLowerCase()===r.toLowerCase()){const i=t+r.length;if(i>=e.length||Ol(e[i])||!Vm(e[i]))return Nl(e.slice(t,t+r.length),"keyword",Il(t,i),n.normalized)}}return null}extractItalianWord(e,t){let n=t,r="";for(;n<e.length&&Bm(e[n]);)r+=e[n++];if(!r)return null;const i=r.toLowerCase();if(Um.has(i))return Nl(r,"particle",Il(t,n));const a=this.lookupKeyword(i);if(a)return Nl(r,"keyword",Il(t,n),a.normalized);const o=this.tryMorphKeywordMatch(i,t,n);return o||Nl(r,"identifier",Il(t,n))}extractItalianNumber(e,t){return this.tryNumberWithTimeUnits(e,t,Fm,{allowSign:!0,skipWhitespace:!0})}})}});function nd(e){const t=e.charCodeAt(0);return t>=12352&&t<=12447}function rd(e){const t=e.charCodeAt(0);return t>=12448&&t<=12543}function id(e){const t=e.charCodeAt(0);return t>=19968&&t<=40959||t>=13312&&t<=19903}var ad,od=fl({"src/tokenizers/morphology/japanese-normalizer.ts"(){ic(),Zm=[{pattern:"したら",confidence:.88,conjugationType:"conditional-tara",minStemLength:2},{pattern:"すると",confidence:.88,conjugationType:"conditional-to",minStemLength:2},{pattern:"すれば",confidence:.85,conjugationType:"conditional-ba",minStemLength:2},{pattern:"たら",confidence:.85,conjugationType:"conditional-tara",minStemLength:2},{pattern:"れば",confidence:.82,conjugationType:"conditional-ba",minStemLength:2},{pattern:"ていました",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"ています",confidence:.85,conjugationType:"progressive",minStemLength:2},{pattern:"てください",confidence:.85,conjugationType:"request",minStemLength:2},{pattern:"でください",confidence:.85,conjugationType:"request",minStemLength:2},{pattern:"ている",confidence:.85,conjugationType:"progressive",minStemLength:2},{pattern:"ておく",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"てみる",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"てある",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"てくれ",confidence:.8,conjugationType:"casual-request",minStemLength:2},{pattern:"でくれ",confidence:.8,conjugationType:"casual-request",minStemLength:2},{pattern:"ちゃった",confidence:.82,conjugationType:"contracted-past",minStemLength:2},{pattern:"じゃった",confidence:.82,conjugationType:"contracted-past",minStemLength:2},{pattern:"ちゃう",confidence:.82,conjugationType:"contracted",minStemLength:2},{pattern:"じゃう",confidence:.82,conjugationType:"contracted",minStemLength:2},{pattern:"ました",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"ません",confidence:.85,conjugationType:"negative",minStemLength:2},{pattern:"ます",confidence:.85,conjugationType:"polite",minStemLength:2},{pattern:"て",confidence:.85,conjugationType:"te-form",minStemLength:2},{pattern:"た",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"ない",confidence:.82,conjugationType:"negative",minStemLength:2},{pattern:"なかった",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"られる",confidence:.8,conjugationType:"potential",minStemLength:2},{pattern:"れる",confidence:.78,conjugationType:"potential",minStemLength:2},{pattern:"られた",confidence:.8,conjugationType:"passive",minStemLength:2},{pattern:"させる",confidence:.8,conjugationType:"causative",minStemLength:2},{pattern:"せる",confidence:.78,conjugationType:"causative",minStemLength:2},{pattern:"よう",confidence:.8,conjugationType:"volitional",minStemLength:2},{pattern:"る",confidence:.75,conjugationType:"dictionary",minStemLength:3}],Xm=[{pattern:"したら",confidence:.88,conjugationType:"conditional-tara"},{pattern:"すると",confidence:.88,conjugationType:"conditional-to"},{pattern:"すれば",confidence:.85,conjugationType:"conditional-ba"},{pattern:"しています",confidence:.85,conjugationType:"progressive"},{pattern:"している",confidence:.85,conjugationType:"progressive"},{pattern:"しました",confidence:.85,conjugationType:"past"},{pattern:"します",confidence:.85,conjugationType:"polite"},{pattern:"しない",confidence:.82,conjugationType:"negative"},{pattern:"して",confidence:.85,conjugationType:"te-form"},{pattern:"した",confidence:.85,conjugationType:"past"},{pattern:"する",confidence:.88,conjugationType:"dictionary"}],new(ed=class{constructor(){this.language="ja"}isNormalizable(e){if(!function(e){for(const t of e)if(nd(t)||rd(t)||id(t))return!0;return!1}(e))return!1;if(e.length<2)return!1;return nd(e[e.length-1])}normalize(e){const t=this.normalizeCompound(e);if(t)return t;const n=this.trySuruNormalization(e);if(n)return n;for(const t of Zm)if(e.endsWith(t.pattern)){const n=e.slice(0,-t.pattern.length),r=t.minStemLength??2;if(n.length<r)continue;const i={removedSuffixes:[t.pattern]};return t.conjugationType&&(i.conjugationType=t.conjugationType),Zl(n,t.confidence,i)}return Yl(e)}trySuruNormalization(e){for(const t of Xm)if(e.endsWith(t.pattern)){const n=e.slice(0,-t.pattern.length);if(n.length<1)continue;return Zl(n,t.confidence,{removedSuffixes:[t.pattern],conjugationType:t.conjugationType,originalForm:"suru-verb"})}return null}normalizeCompound(e){const t=[{pattern:"ていなかった",suffixes:["て","い","なかった"],confidence:.8,minStemLength:2},{pattern:"でいなかった",suffixes:["で","い","なかった"],confidence:.8,minStemLength:2},{pattern:"ていない",suffixes:["て","い","ない"],confidence:.82,minStemLength:2},{pattern:"でいない",suffixes:["で","い","ない"],confidence:.82,minStemLength:2},{pattern:"ていた",suffixes:["て","い","た"],confidence:.85,minStemLength:2},{pattern:"でいた",suffixes:["で","い","た"],confidence:.85,minStemLength:2}];for(const{pattern:n,suffixes:r,confidence:i,minStemLength:a}of t)if(e.endsWith(n)){const t=e.slice(0,-n.length);if(t.length<a)continue;return Zl(t,i,{removedSuffixes:r,conjugationType:"compound"})}return null}})}}),sd={};yl(sd,{japaneseProfile:()=>ad});var ld,cd,ud,pd,md,dd,hd,fd,yd,vd,gd,bd,kd=fl({"src/generators/profiles/japanese.ts"(){ad={code:"ja",name:"Japanese",nativeName:"日本語",direction:"ltr",wordOrder:"SOV",markingStrategy:"particle",usesSpaces:!1,defaultVerbForm:"base",verb:{position:"end",suffixes:["る","て","た","ます","ない"],subjectDrop:!0},references:{me:"自分",it:"それ",you:"あなた",result:"結果",event:"イベント",target:"ターゲット",body:"ボディ"},possessive:{marker:"の",markerPosition:"between",keywords:{"私の":"me","あなたの":"you","その":"it"}},roleMarkers:{patient:{primary:"を",position:"after"},destination:{primary:"に",alternatives:["へ","で","の"],position:"after"},source:{primary:"から",position:"after"},style:{primary:"で",position:"after"},event:{primary:"を",position:"after"}},keywords:{toggle:{primary:"切り替え",alternatives:["切り替える","トグル","トグルする"],normalized:"toggle"},add:{primary:"追加",alternatives:["追加する","加える"],normalized:"add"},remove:{primary:"削除",alternatives:["削除する","取り除く"],normalized:"remove"},put:{primary:"置く",alternatives:["入れる","セット"],normalized:"put"},append:{primary:"末尾追加",alternatives:["末尾に追加","アペンド"],normalized:"append"},prepend:{primary:"先頭追加",alternatives:["先頭に追加","プリペンド"],normalized:"prepend"},take:{primary:"取る",normalized:"take"},make:{primary:"作る",alternatives:["作成"],normalized:"make"},clone:{primary:"複製",alternatives:["クローン"],normalized:"clone"},swap:{primary:"交換",alternatives:["スワップ","入れ替え"],normalized:"swap"},morph:{primary:"変形",alternatives:["モーフ","変換"],normalized:"morph"},set:{primary:"設定",alternatives:["設定する","セット"],normalized:"set"},get:{primary:"取得",alternatives:["取得する","ゲット"],normalized:"get"},increment:{primary:"増加",alternatives:["増やす","インクリメント"],normalized:"increment"},decrement:{primary:"減少",alternatives:["減らす","デクリメント"],normalized:"decrement"},log:{primary:"記録",alternatives:["ログ","出力"],normalized:"log"},show:{primary:"表示",alternatives:["表示する","見せる"],normalized:"show"},hide:{primary:"隠す",alternatives:["非表示","非表示にする"],normalized:"hide"},transition:{primary:"遷移",alternatives:["トランジション","アニメーション"],normalized:"transition"},on:{primary:"で",alternatives:["時","とき"],normalized:"on"},trigger:{primary:"引き金",alternatives:["発火","トリガー"],normalized:"trigger"},send:{primary:"送る",alternatives:["送信"],normalized:"send"},focus:{primary:"フォーカス",alternatives:["集中"],normalized:"focus"},blur:{primary:"ぼかし",alternatives:["フォーカス解除"],normalized:"blur"},go:{primary:"移動",alternatives:["行く","ナビゲート"],normalized:"go"},wait:{primary:"待つ",alternatives:["待機"],normalized:"wait"},fetch:{primary:"取得",alternatives:["フェッチ"],normalized:"fetch"},settle:{primary:"安定",alternatives:["落ち着く"],normalized:"settle"},if:{primary:"もし",alternatives:["条件"],normalized:"if"},when:{primary:"とき",normalized:"when"},where:{primary:"どこ",normalized:"where"},else:{primary:"そうでなければ",alternatives:["それ以外"],normalized:"else"},repeat:{primary:"繰り返し",alternatives:["繰り返す","リピート"],normalized:"repeat"},for:{primary:"ために",alternatives:["各"],normalized:"for"},while:{primary:"の間",alternatives:["間"],normalized:"while"},continue:{primary:"続ける",alternatives:["継続"],normalized:"continue"},halt:{primary:"停止",alternatives:["止める","ハルト"],normalized:"halt"},throw:{primary:"投げる",alternatives:["スロー"],normalized:"throw"},call:{primary:"呼び出し",alternatives:["コール","呼ぶ"],normalized:"call"},return:{primary:"戻る",alternatives:["返す","リターン"],normalized:"return"},then:{primary:"それから",alternatives:["次に","そして"],normalized:"then"},and:{primary:"そして",alternatives:["と","また"],normalized:"and"},end:{primary:"終わり",alternatives:["終了","おわり"],normalized:"end"},js:{primary:"JS実行",alternatives:["js"],normalized:"js"},async:{primary:"非同期",alternatives:["アシンク"],normalized:"async"},tell:{primary:"伝える",alternatives:["テル"],normalized:"tell"},default:{primary:"既定",alternatives:["デフォルト"],normalized:"default"},init:{primary:"初期化",alternatives:["イニット"],normalized:"init"},behavior:{primary:"振る舞い",alternatives:["ビヘイビア"],normalized:"behavior"},install:{primary:"インストール",alternatives:["導入"],normalized:"install"},measure:{primary:"測定",alternatives:["計測","メジャー"],normalized:"measure"},beep:{primary:"ビープ",normalized:"beep"},break:{primary:"中断",normalized:"break"},copy:{primary:"コピー",normalized:"copy"},exit:{primary:"終了",normalized:"exit"},pick:{primary:"選択",normalized:"pick"},render:{primary:"描画",normalized:"render"},into:{primary:"へ",alternatives:["に"],normalized:"into"},before:{primary:"前に",alternatives:["前"],normalized:"before"},after:{primary:"後に",alternatives:["後"],normalized:"after"},until:{primary:"まで",alternatives:["迄"],normalized:"until"},event:{primary:"イベント",alternatives:["事象"],normalized:"event"},from:{primary:"から",normalized:"from"}},tokenization:{particles:["を","に","で","から","の","が","は","も","へ","と"],boundaryStrategy:"particle"},eventHandler:{eventMarker:{primary:"で",position:"after"},temporalMarkers:["時","とき"]}}}}),wd={};yl(wd,{JapaneseTokenizer:()=>gd,japaneseTokenizer:()=>bd});var zd,xd,Ed,Sd=fl({"src/tokenizers/japanese.ts"(){Jl(),od(),kd(),ld=ql([[12352,12447]]),cd=ql([[12448,12543]]),ud=ql([[19968,40959],[13312,19903]]),pd=Dl(ld,cd,ud),md=new Set(["を","に","で","から","まで","へ","と","の","が","は","も","より"]),dd=new Set(["を","に","で","へ","と","の","が","は","も"]),hd=["から","まで","より"],fd=new Map([["を",{role:"patient",confidence:.95,description:"object marker"}],["に",{role:"destination",confidence:.85,description:"destination/time marker"}],["で",{role:"manner",confidence:.88,description:"means/location marker"}],["から",{role:"source",confidence:.9,description:"from/source marker"}],["まで",{role:"destination",confidence:.75,description:"until/boundary marker"}],["へ",{role:"destination",confidence:.9,description:"direction marker"}],["と",{role:"style",confidence:.7,description:"with/and marker"}],["の",{role:"destination",confidence:.75,description:"possessive/destination marker"}],["が",{role:"agent",confidence:.85,description:"subject marker"}],["は",{role:"agent",confidence:.75,description:"topic marker"}],["も",{role:"patient",confidence:.65,description:"also/too marker"}],["より",{role:"source",confidence:.85,description:"from/than marker"}]]),yd=[{native:"真",normalized:"true"},{native:"偽",normalized:"false"},{native:"ヌル",normalized:"null"},{native:"未定義",normalized:"undefined"},{native:"最初",normalized:"first"},{native:"最後",normalized:"last"},{native:"次",normalized:"next"},{native:"前",normalized:"previous"},{native:"最も近い",normalized:"closest"},{native:"親",normalized:"parent"},{native:"クリック",normalized:"click"},{native:"変更",normalized:"change"},{native:"送信",normalized:"submit"},{native:"入力",normalized:"input"},{native:"ロード",normalized:"load"},{native:"スクロール",normalized:"scroll"},{native:"キーダウン",normalized:"keydown"},{native:"キーアップ",normalized:"keyup"},{native:"マウスオーバー",normalized:"mouseover"},{native:"マウスアウト",normalized:"mouseout"},{native:"ブラー",normalized:"blur"},{native:"私",normalized:"me"},{native:"私の",normalized:"my"},{native:"その",normalized:"its"},{native:"したら",normalized:"on"},{native:"すると",normalized:"on"},{native:"時に",normalized:"on"},{native:"もし",normalized:"if"},{native:"ならば",normalized:"then"},{native:"なら",normalized:"then"},{native:"それから",normalized:"then"},{native:"そして",normalized:"and"},{native:"秒",normalized:"s"},{native:"ミリ秒",normalized:"ms"},{native:"分",normalized:"m"},{native:"時間",normalized:"h"}],vd=[{pattern:"ミリ秒",suffix:"ms",length:3},{pattern:"時間",suffix:"h",length:2},{pattern:"秒",suffix:"s",length:1},{pattern:"分",suffix:"m",length:1}],bd=new(gd=class extends Kl{constructor(){super(),this.language="ja",this.direction="ltr",this.initializeKeywordsFromProfile(ad,yd),this.normalizer=new ed}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])){const r=this.extractJapaneseNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}const i=this.tryMultiCharParticle(e,n,hd);if(i){const e=fd.get(i.value);e?t.push({...i,metadata:{particleRole:e.role,particleConfidence:e.confidence}}):t.push(i),n=i.position.end;continue}if(dd.has(e[n])){const r=this.tryProfileKeyword(e,n);if(r&&r.value.length>1){t.push(r),n=r.position.end;continue}const i=e[n],a=fd.get(i);a?t.push({...Nl(i,"particle",Il(n,n+1)),metadata:{particleRole:a.role,particleConfidence:a.confidence}}):t.push(Nl(i,"particle",Il(n,n+1))),n++;continue}if(pd(e[n])){const r=this.extractJapaneseWord(e,n);if(r){t.push(r),n=r.position.end;continue}}if($l(e[n])){const r=this.extractAsciiWord(e,n);if(r){t.push(r),n=r.position.end;continue}}n++}return new Ll(t,"ja")}classifyToken(e){return md.has(e)?"particle":this.isKeyword(e)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||e.startsWith("「")||/^\d/.test(e)?"literal":"identifier"}extractJapaneseWord(e,t){let n=t,r="";for(;n<e.length;){const t=e[n];if(dd.has(t)&&r.length>0)break;let i=!1;for(const t of hd)if(e.slice(n,n+t.length)===t&&r.length>0){i=!0;break}if(i)break;if(!pd(t))break;r+=t,n++}if(!r)return null;const i=this.lookupKeyword(r);if(i)return Nl(r,"keyword",Il(t,n),i.normalized);const a=this.tryMorphKeywordMatch(r,t,n);return a||Nl(r,"identifier",Il(t,n))}extractAsciiWord(e,t){let n=t,r="";for(;n<e.length&&$l(e[n]);)r+=e[n++];return r?Nl(r,"identifier",Il(t,n)):null}extractJapaneseNumber(e,t){return this.tryNumberWithTimeUnits(e,t,vd,{allowSign:!1,skipWhitespace:!1})}})}});function Td(e){const t=e.charCodeAt(0);return t>=44032&&t<=55203}var Cd,Ad=fl({"src/tokenizers/morphology/korean-normalizer.ts"(){ic(),zd=[{pattern:"하시니까",confidence:.85,conjugationType:"honorific-causal",minStemLength:1},{pattern:"하실때",confidence:.88,conjugationType:"honorific-temporal",minStemLength:1},{pattern:"하실 때",confidence:.88,conjugationType:"honorific-temporal",minStemLength:1},{pattern:"하시면",confidence:.88,conjugationType:"honorific-conditional",minStemLength:1},{pattern:"으시면",confidence:.85,conjugationType:"honorific-conditional",minStemLength:2},{pattern:"시면",confidence:.82,conjugationType:"honorific-conditional",minStemLength:2},{pattern:"하고나서",confidence:.85,conjugationType:"sequential-after",minStemLength:1},{pattern:"하고 나서",confidence:.85,conjugationType:"sequential-after",minStemLength:1},{pattern:"하고서",confidence:.85,conjugationType:"sequential-after",minStemLength:1},{pattern:"고나서",confidence:.82,conjugationType:"sequential-after",minStemLength:2},{pattern:"고 나서",confidence:.82,conjugationType:"sequential-after",minStemLength:2},{pattern:"고서",confidence:.82,conjugationType:"sequential-after",minStemLength:2},{pattern:"하기전에",confidence:.85,conjugationType:"sequential-before",minStemLength:1},{pattern:"하기 전에",confidence:.85,conjugationType:"sequential-before",minStemLength:1},{pattern:"기전에",confidence:.82,conjugationType:"sequential-before",minStemLength:2},{pattern:"기 전에",confidence:.82,conjugationType:"sequential-before",minStemLength:2},{pattern:"하자마자",confidence:.88,conjugationType:"immediate",minStemLength:1},{pattern:"자마자",confidence:.85,conjugationType:"immediate",minStemLength:2},{pattern:"해야해요",confidence:.85,conjugationType:"obligation",minStemLength:1},{pattern:"해야해",confidence:.85,conjugationType:"obligation",minStemLength:1},{pattern:"해야하다",confidence:.85,conjugationType:"obligation",minStemLength:1},{pattern:"어야해요",confidence:.82,conjugationType:"obligation",minStemLength:2},{pattern:"어야해",confidence:.82,conjugationType:"obligation",minStemLength:2},{pattern:"아야해요",confidence:.82,conjugationType:"obligation",minStemLength:2},{pattern:"아야해",confidence:.82,conjugationType:"obligation",minStemLength:2},{pattern:"하니까",confidence:.85,conjugationType:"causal-nikka",minStemLength:1},{pattern:"할때",confidence:.88,conjugationType:"temporal-ttae",minStemLength:1},{pattern:"할 때",confidence:.88,conjugationType:"temporal-ttae",minStemLength:1},{pattern:"을때",confidence:.85,conjugationType:"temporal-ttae",minStemLength:2},{pattern:"을 때",confidence:.85,conjugationType:"temporal-ttae",minStemLength:2},{pattern:"하면",confidence:.88,conjugationType:"conditional-myeon",minStemLength:1},{pattern:"으면",confidence:.85,conjugationType:"conditional-myeon",minStemLength:2},{pattern:"니까",confidence:.82,conjugationType:"causal-nikka",minStemLength:2},{pattern:"면",confidence:.8,conjugationType:"conditional-myeon",minStemLength:2},{pattern:"하였습니다",confidence:.85,conjugationType:"past",minStemLength:1},{pattern:"했습니다",confidence:.85,conjugationType:"past",minStemLength:1},{pattern:"합니다",confidence:.85,conjugationType:"polite",minStemLength:1},{pattern:"습니다",confidence:.82,conjugationType:"polite",minStemLength:2},{pattern:"됩니다",confidence:.82,conjugationType:"polite",minStemLength:1},{pattern:"ㅂ니다",confidence:.82,conjugationType:"polite",minStemLength:2},{pattern:"하세요",confidence:.85,conjugationType:"honorific",minStemLength:1},{pattern:"하십시오",confidence:.85,conjugationType:"honorific",minStemLength:1},{pattern:"세요",confidence:.82,conjugationType:"honorific",minStemLength:2},{pattern:"십시오",confidence:.82,conjugationType:"honorific",minStemLength:2},{pattern:"하고있어요",confidence:.82,conjugationType:"progressive",minStemLength:1},{pattern:"하고있어",confidence:.82,conjugationType:"progressive",minStemLength:1},{pattern:"했어요",confidence:.85,conjugationType:"past",minStemLength:1},{pattern:"해요",confidence:.85,conjugationType:"polite",minStemLength:1},{pattern:"어요",confidence:.82,conjugationType:"polite",minStemLength:2},{pattern:"아요",confidence:.82,conjugationType:"polite",minStemLength:2},{pattern:"했어",confidence:.85,conjugationType:"past",minStemLength:1},{pattern:"해",confidence:.8,conjugationType:"present",minStemLength:1},{pattern:"었어",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"았어",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"하고있다",confidence:.82,conjugationType:"progressive",minStemLength:1},{pattern:"고있다",confidence:.8,conjugationType:"progressive",minStemLength:2},{pattern:"고있어",confidence:.8,conjugationType:"progressive",minStemLength:2},{pattern:"하다",confidence:.88,conjugationType:"dictionary",minStemLength:1},{pattern:"하지않다",confidence:.82,conjugationType:"negative",minStemLength:1},{pattern:"안하다",confidence:.82,conjugationType:"negative",minStemLength:1},{pattern:"지않다",confidence:.8,conjugationType:"negative",minStemLength:2},{pattern:"해라",confidence:.82,conjugationType:"imperative",minStemLength:1},{pattern:"하라",confidence:.82,conjugationType:"imperative",minStemLength:1},{pattern:"다",confidence:.75,conjugationType:"dictionary",minStemLength:2}],xd=[{pattern:"하시니까",confidence:.88,conjugationType:"honorific-causal"},{pattern:"하실때",confidence:.88,conjugationType:"honorific-temporal"},{pattern:"하실 때",confidence:.88,conjugationType:"honorific-temporal"},{pattern:"하시면",confidence:.88,conjugationType:"honorific-conditional"},{pattern:"하셨어요",confidence:.85,conjugationType:"honorific-past"},{pattern:"하셨어",confidence:.85,conjugationType:"honorific-past"},{pattern:"하십니다",confidence:.85,conjugationType:"honorific-polite"},{pattern:"하고나서",confidence:.88,conjugationType:"sequential-after"},{pattern:"하고 나서",confidence:.88,conjugationType:"sequential-after"},{pattern:"하고서",confidence:.88,conjugationType:"sequential-after"},{pattern:"하기전에",confidence:.88,conjugationType:"sequential-before"},{pattern:"하기 전에",confidence:.88,conjugationType:"sequential-before"},{pattern:"하자마자",confidence:.88,conjugationType:"immediate"},{pattern:"해야해요",confidence:.88,conjugationType:"obligation"},{pattern:"해야해",confidence:.88,conjugationType:"obligation"},{pattern:"해야하다",confidence:.88,conjugationType:"obligation"},{pattern:"하니까",confidence:.88,conjugationType:"causal-nikka"},{pattern:"할때",confidence:.88,conjugationType:"temporal-ttae"},{pattern:"할 때",confidence:.88,conjugationType:"temporal-ttae"},{pattern:"하면",confidence:.88,conjugationType:"conditional-myeon"},{pattern:"하였습니다",confidence:.85,conjugationType:"past"},{pattern:"했습니다",confidence:.85,conjugationType:"past"},{pattern:"합니다",confidence:.85,conjugationType:"polite"},{pattern:"하십시오",confidence:.85,conjugationType:"honorific"},{pattern:"하세요",confidence:.85,conjugationType:"honorific"},{pattern:"했어요",confidence:.85,conjugationType:"past"},{pattern:"해요",confidence:.85,conjugationType:"polite"},{pattern:"했어",confidence:.85,conjugationType:"past"},{pattern:"해",confidence:.8,conjugationType:"present"},{pattern:"하고있어요",confidence:.82,conjugationType:"progressive"},{pattern:"하고있어",confidence:.82,conjugationType:"progressive"},{pattern:"하고있다",confidence:.82,conjugationType:"progressive"},{pattern:"해서",confidence:.82,conjugationType:"connective"},{pattern:"하고",confidence:.8,conjugationType:"connective"},{pattern:"하지않아요",confidence:.82,conjugationType:"negative"},{pattern:"하지않다",confidence:.82,conjugationType:"negative"},{pattern:"안해요",confidence:.82,conjugationType:"negative"},{pattern:"안해",confidence:.82,conjugationType:"negative"},{pattern:"해라",confidence:.82,conjugationType:"imperative"},{pattern:"하라",confidence:.82,conjugationType:"imperative"},{pattern:"하다",confidence:.88,conjugationType:"dictionary"}],new(Ed=class{constructor(){this.language="ko"}isNormalizable(e){return!!function(e){for(const t of e)if(Td(t))return!0;return!1}(e)&&!(e.length<2)}normalize(e){const t=this.normalizeCompound(e);if(t)return t;const n=this.tryHadaNormalization(e);if(n)return n;for(const t of zd)if(e.endsWith(t.pattern)){const n=e.slice(0,-t.pattern.length),r=t.minStemLength??2;if(n.length<r)continue;const i={removedSuffixes:[t.pattern]};return t.conjugationType&&(i.conjugationType=t.conjugationType),Zl(n,t.confidence,i)}return Yl(e)}tryHadaNormalization(e){for(const t of xd)if(e.endsWith(t.pattern)){const n=e.slice(0,-t.pattern.length);if(n.length<1)continue;return Zl(n,t.confidence,{removedSuffixes:[t.pattern],conjugationType:t.conjugationType,originalForm:"hada-verb"})}return null}normalizeCompound(e){const t=[{pattern:"하고나서였어",suffixes:["하고나서","였어"],confidence:.78,conjugationType:"sequential-after",minStemLength:2},{pattern:"하고나서였다",suffixes:["하고나서","였다"],confidence:.78,conjugationType:"sequential-after",minStemLength:2},{pattern:"하고나서",suffixes:["하고","나서"],confidence:.85,conjugationType:"sequential-after",minStemLength:2},{pattern:"해야했어",suffixes:["해야","했어"],confidence:.8,conjugationType:"obligation",minStemLength:2},{pattern:"해야했다",suffixes:["해야","했다"],confidence:.8,conjugationType:"obligation",minStemLength:2},{pattern:"해야했습니다",suffixes:["해야","했습니다"],confidence:.8,conjugationType:"obligation",minStemLength:2},{pattern:"하시면서",suffixes:["하시","면서"],confidence:.82,conjugationType:"connective",minStemLength:2},{pattern:"하시며",suffixes:["하시","며"],confidence:.82,conjugationType:"connective",minStemLength:2},{pattern:"하고있었어",suffixes:["하고","있었어"],confidence:.8,conjugationType:"progressive",minStemLength:2},{pattern:"하고있었다",suffixes:["하고","있었다"],confidence:.8,conjugationType:"progressive",minStemLength:2}];for(const{pattern:n,suffixes:r,confidence:i,conjugationType:a,minStemLength:o}of t)if(e.endsWith(n)){const t=e.slice(0,-n.length);if(t.length<o)continue;return Zl(t,i,{removedSuffixes:r,conjugationType:a})}return null}})}}),jd={};yl(jd,{koreanProfile:()=>Cd});var Ld,Pd,Id,Nd,Od,Rd,Md,Wd,$d,Hd,qd,Dd,_d=fl({"src/generators/profiles/korean.ts"(){Cd={code:"ko",name:"Korean",nativeName:"한국어",direction:"ltr",wordOrder:"SOV",markingStrategy:"particle",usesSpaces:!0,verb:{position:"end",suffixes:["다","요","니다","세요"],subjectDrop:!0},references:{me:"나",it:"그것",you:"너",result:"결과",event:"이벤트",target:"대상",body:"본문"},possessive:{marker:"의",markerPosition:"between",specialForms:{me:"내",it:"그것의",you:"네"},keywords:{"내":"me","네":"you","그의":"it"}},roleMarkers:{patient:{primary:"을",alternatives:["를"],position:"after"},destination:{primary:"에",alternatives:["으로","로","에서","의"],position:"after"},source:{primary:"에서",alternatives:["부터"],position:"after"},style:{primary:"로",alternatives:["으로"],position:"after"},event:{primary:"을",alternatives:["를"],position:"after"}},keywords:{toggle:{primary:"토글",alternatives:["전환"],normalized:"toggle"},add:{primary:"추가",normalized:"add"},remove:{primary:"제거",alternatives:["삭제"],normalized:"remove"},put:{primary:"넣다",alternatives:["넣기","놓기"],normalized:"put"},append:{primary:"추가",normalized:"append"},take:{primary:"가져오다",normalized:"take"},make:{primary:"만들다",normalized:"make"},clone:{primary:"복사",normalized:"clone"},swap:{primary:"교환",alternatives:["바꾸다"],normalized:"swap"},morph:{primary:"변형",alternatives:["변환"],normalized:"morph"},set:{primary:"설정",normalized:"set"},get:{primary:"얻다",alternatives:["가져오기"],normalized:"get"},increment:{primary:"증가",normalized:"increment"},decrement:{primary:"감소",normalized:"decrement"},log:{primary:"로그",normalized:"log"},show:{primary:"보이다",alternatives:["표시","보이기"],normalized:"show"},hide:{primary:"숨기다",alternatives:["숨기기"],normalized:"hide"},transition:{primary:"전환",normalized:"transition"},on:{primary:"에",alternatives:["시","때","할 때"],normalized:"on"},trigger:{primary:"트리거",normalized:"trigger"},send:{primary:"보내다",normalized:"send"},focus:{primary:"포커스",normalized:"focus"},blur:{primary:"블러",normalized:"blur"},click:{primary:"클릭",normalized:"click"},hover:{primary:"호버",normalized:"hover"},submit:{primary:"제출",normalized:"submit"},input:{primary:"입력",normalized:"input"},change:{primary:"변경",normalized:"change"},go:{primary:"이동",normalized:"go"},wait:{primary:"대기",normalized:"wait"},fetch:{primary:"가져오기",normalized:"fetch"},settle:{primary:"안정",normalized:"settle"},if:{primary:"만약",normalized:"if"},when:{primary:"때",normalized:"when"},where:{primary:"어디",normalized:"where"},else:{primary:"아니면",normalized:"else"},repeat:{primary:"반복",normalized:"repeat"},for:{primary:"동안",normalized:"for"},while:{primary:"동안",normalized:"while"},continue:{primary:"계속",normalized:"continue"},halt:{primary:"정지",normalized:"halt"},throw:{primary:"던지다",normalized:"throw"},call:{primary:"호출",normalized:"call"},return:{primary:"반환",normalized:"return"},then:{primary:"그다음",alternatives:["그리고","그런후"],normalized:"then"},and:{primary:"그리고",alternatives:["또한","및"],normalized:"and"},end:{primary:"끝",alternatives:["종료","마침"],normalized:"end"},js:{primary:"JS실행",alternatives:["js"],normalized:"js"},async:{primary:"비동기",normalized:"async"},tell:{primary:"말하다",normalized:"tell"},default:{primary:"기본값",normalized:"default"},init:{primary:"초기화",normalized:"init"},behavior:{primary:"동작",normalized:"behavior"},install:{primary:"설치",normalized:"install"},measure:{primary:"측정",normalized:"measure"},beep:{primary:"비프",normalized:"beep"},break:{primary:"중단",normalized:"break"},copy:{primary:"복사",normalized:"copy"},exit:{primary:"종료",normalized:"exit"},pick:{primary:"선택",normalized:"pick"},render:{primary:"렌더링",normalized:"render"},into:{primary:"으로",normalized:"into"},before:{primary:"전에",normalized:"before"},after:{primary:"후에",normalized:"after"},until:{primary:"까지",normalized:"until"},event:{primary:"이벤트",normalized:"event"},from:{primary:"에서",normalized:"from"}},tokenization:{particles:["을","를","이","가","은","는","에","에서","으로","로","와","과","도"],boundaryStrategy:"space"},eventHandler:{eventMarker:{primary:"할 때",alternatives:["할때","때","에"],position:"after"},temporalMarkers:["할 때","할때","때"]}}}}),Vd={};yl(Vd,{KoreanTokenizer:()=>qd,koreanTokenizer:()=>Dd});var Bd,Fd=fl({"src/tokenizers/korean.ts"(){Jl(),Ad(),_d(),Ld=ql([[44032,55203]]),Pd=ql([[4352,4607],[12592,12687]]),Id=Dl(Ld,Pd),Nd=new Set(["이","가","을","를","은","는","에","에서","로","으로","와","과","의","도","만","부터","까지","처럼","보다"]),Od=new Set(["이","가","을","를","은","는","에","로","와","과","의","도","만"]),Rd=["에서","으로","부터","까지","처럼","보다"],Md=["할때","하면","하니까","할 때"],Wd=new Map([["이",{role:"agent",confidence:.85,variant:"consonant",description:"subject marker (after consonant)"}],["가",{role:"agent",confidence:.85,variant:"vowel",description:"subject marker (after vowel)"}],["을",{role:"patient",confidence:.95,variant:"consonant",description:"object marker (after consonant)"}],["를",{role:"patient",confidence:.95,variant:"vowel",description:"object marker (after vowel)"}],["은",{role:"agent",confidence:.75,variant:"consonant",description:"topic marker (after consonant)"}],["는",{role:"agent",confidence:.75,variant:"vowel",description:"topic marker (after vowel)"}],["에",{role:"destination",confidence:.85,description:"at/to marker"}],["에서",{role:"source",confidence:.8,description:"at/from marker (action location)"}],["로",{role:"destination",confidence:.85,variant:"vowel",description:"to/by means (after vowel or ㄹ)"}],["으로",{role:"destination",confidence:.85,variant:"consonant",description:"to/by means (after consonant)"}],["와",{role:"style",confidence:.7,variant:"vowel",description:"and/with (after vowel)"}],["과",{role:"style",confidence:.7,variant:"consonant",description:"and/with (after consonant)"}],["의",{role:"patient",confidence:.6,description:"possessive marker"}],["도",{role:"patient",confidence:.65,description:"also/too marker"}],["만",{role:"patient",confidence:.65,description:"only marker"}],["부터",{role:"source",confidence:.9,description:"from/since marker"}],["까지",{role:"destination",confidence:.75,description:"until/to marker"}],["처럼",{role:"manner",confidence:.8,description:"like/as marker"}],["보다",{role:"source",confidence:.75,description:"than marker"}]]),$d=[{native:"참",normalized:"true"},{native:"거짓",normalized:"false"},{native:"널",normalized:"null"},{native:"미정의",normalized:"undefined"},{native:"첫번째",normalized:"first"},{native:"마지막",normalized:"last"},{native:"다음",normalized:"next"},{native:"이전",normalized:"previous"},{native:"가장가까운",normalized:"closest"},{native:"부모",normalized:"parent"},{native:"클릭",normalized:"click"},{native:"더블클릭",normalized:"dblclick"},{native:"변경",normalized:"change"},{native:"제출",normalized:"submit"},{native:"입력",normalized:"input"},{native:"로드",normalized:"load"},{native:"스크롤",normalized:"scroll"},{native:"키다운",normalized:"keydown"},{native:"키업",normalized:"keyup"},{native:"마우스오버",normalized:"mouseover"},{native:"마우스아웃",normalized:"mouseout"},{native:"내",normalized:"my"},{native:"그것의",normalized:"its"},{native:"그다음",normalized:"then"},{native:"그런후",normalized:"then"},{native:"그러면",normalized:"then"},{native:"그리고",normalized:"and"},{native:"또는",normalized:"or"},{native:"아니",normalized:"not"},{native:"이다",normalized:"is"},{native:"초",normalized:"s"},{native:"밀리초",normalized:"ms"},{native:"분",normalized:"m"},{native:"시간",normalized:"h"}],Hd=[{pattern:"밀리초",suffix:"ms",length:3},{pattern:"시간",suffix:"h",length:2},{pattern:"초",suffix:"s",length:1},{pattern:"분",suffix:"m",length:1}],Dd=new(qd=class extends Kl{constructor(){super(),this.language="ko",this.direction="ltr",this.initializeKeywordsFromProfile(Cd,$d),this.normalizer=new Ed}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])){const r=this.extractKoreanNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}if(Id(e[n])){const r=this.extractKoreanWord(e,n);if(r){const e=this.trySplitTemporalSuffix(r);e?(t.push(e.stemToken),t.push(e.suffixToken)):t.push(r),n=r.position.end;continue}}const i=this.tryMultiCharParticle(e,n,Rd);if(i){const e=Wd.get(i.value);e?t.push({...i,metadata:{particleRole:e.role,particleConfidence:e.confidence,particleVariant:e.variant}}):t.push(i),n=i.position.end;continue}if(Od.has(e[n])){const r=e[n],i=Wd.get(r);i?t.push({...Nl(r,"particle",Il(n,n+1)),metadata:{particleRole:i.role,particleConfidence:i.confidence,particleVariant:i.variant}}):t.push(Nl(r,"particle",Il(n,n+1))),n++;continue}if($l(e[n])){const r=this.extractAsciiWord(e,n);if(r){t.push(r),n=r.position.end;continue}}n++}return new Ll(t,"ko")}classifyToken(e){return Nd.has(e)?"particle":this.isKeyword(e)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||/^\d/.test(e)?"literal":"identifier"}extractKoreanWord(e,t){for(let n=Math.min(6,e.length-t);n>=2;n--){const r=e.slice(t,t+n);let i=!0;for(let e=0;e<r.length;e++)if(!Id(r[e])){i=!1;break}if(!i)continue;if(Nd.has(r)&&t==t){const r=t+n,i=r<e.length?e[r]:"";if(""===i||Ol(i)||!Id(i))return null}const a=this.lookupKeyword(r);if(a)return Nl(r,"keyword",Il(t,t+n),a.normalized);const o=this.tryMorphKeywordMatch(r,t,t+n);if(o)return o}let n=t,r="";for(;n<e.length;){const t=e[n],i=n+1<e.length?e[n+1]:"";if(0===r.length&&Od.has(t))return null;if(Od.has(t)&&r.length>0){if(""===i||Ol(i)||!Id(i)||Od.has(i))break}let a=!1;for(const t of Rd)if(e.slice(n,n+t.length)===t&&r.length>0){const r=n+t.length,i=r<e.length?e[r]:"";if(""===i||Ol(i)||!Id(i)){a=!0;break}}if(a)break;if(!Id(t))break;r+=t,n++}if(!r)return null;if(Nd.has(r))return null;const i=this.lookupKeyword(r);if(i)return Nl(r,"keyword",Il(t,n),i.normalized);const a=this.tryMorphKeywordMatch(r,t,n);return a||Nl(r,"identifier",Il(t,n))}extractAsciiWord(e,t){let n=t,r="";for(;n<e.length&&$l(e[n]);)r+=e[n++];return r?Nl(r,"identifier",Il(t,n)):null}extractKoreanNumber(e,t){return this.tryNumberWithTimeUnits(e,t,Hd,{allowSign:!1,skipWhitespace:!1})}trySplitTemporalSuffix(e){const t=e.value;for(const n of Md)if(t.endsWith(n)&&t.length>n.length){const r=t.slice(0,-n.length),i=r.toLowerCase(),a=this.lookupKeyword(i);if(!a)continue;const o=e.position.start+r.length;return{stemToken:Nl(r,"keyword",Il(e.position.start,o),a.normalized),suffixToken:Nl(n,"keyword",Il(o,e.position.end),"when")}}return null}})}}),Ud={};yl(Ud,{malayProfile:()=>Bd});var Kd,Gd,Qd,Jd=fl({"src/generators/profiles/ms.ts"(){Bd={code:"ms",name:"Malay",nativeName:"Melayu",direction:"ltr",wordOrder:"SVO",markingStrategy:"preposition",usesSpaces:!0,defaultVerbForm:"base",verb:{position:"start",subjectDrop:!0},references:{me:"saya",it:"ia",you:"kamu",result:"hasil",event:"peristiwa",target:"sasaran",body:"badan"},possessive:{marker:"",markerPosition:"after-object",keywords:{saya:"me",aku:"me",awak:"you",kamu:"you",anda:"you",dia:"it",ia:"it","-ku":"me","-mu":"you","-nya":"it"}},roleMarkers:{destination:{primary:"ke",alternatives:["pada"],position:"before"},source:{primary:"dari",position:"before"},patient:{primary:"",position:"before"},style:{primary:"dengan",position:"before"}},keywords:{toggle:{primary:"togol",alternatives:["tukar"],normalized:"toggle"},add:{primary:"tambah",normalized:"add"},remove:{primary:"buang",alternatives:["padam"],normalized:"remove"},put:{primary:"letak",alternatives:["letakkan"],normalized:"put"},append:{primary:"tambah_hujung",normalized:"append"},prepend:{primary:"tambah_mula",normalized:"prepend"},take:{primary:"ambil",normalized:"take"},make:{primary:"buat",alternatives:["cipta"],normalized:"make"},clone:{primary:"klon",alternatives:["salin"],normalized:"clone"},swap:{primary:"tukar_tempat",normalized:"swap"},morph:{primary:"ubah_bentuk",normalized:"morph"},set:{primary:"tetapkan",alternatives:["setkan"],normalized:"set"},get:{primary:"dapatkan",alternatives:["ambil"],normalized:"get"},increment:{primary:"tambah_satu",normalized:"increment"},decrement:{primary:"kurang_satu",normalized:"decrement"},log:{primary:"catat",alternatives:["log"],normalized:"log"},show:{primary:"tunjuk",alternatives:["papar"],normalized:"show"},hide:{primary:"sembunyi",alternatives:["sorok"],normalized:"hide"},transition:{primary:"peralihan",normalized:"transition"},on:{primary:"apabila",alternatives:["bila","ketika"],normalized:"on"},trigger:{primary:"cetuskan",normalized:"trigger"},send:{primary:"hantar",normalized:"send"},focus:{primary:"fokus",normalized:"focus"},blur:{primary:"kabur",normalized:"blur"},go:{primary:"pergi",alternatives:["pindah"],normalized:"go"},wait:{primary:"tunggu",normalized:"wait"},fetch:{primary:"ambil_dari",alternatives:["muat"],normalized:"fetch"},settle:{primary:"selesai",normalized:"settle"},if:{primary:"jika",alternatives:["kalau"],normalized:"if"},when:{primary:"apabila",normalized:"when"},where:{primary:"di_mana",normalized:"where"},else:{primary:"kalau_tidak",alternatives:["jika_tidak"],normalized:"else"},repeat:{primary:"ulang",normalized:"repeat"},for:{primary:"untuk",normalized:"for"},while:{primary:"selagi",alternatives:["semasa"],normalized:"while"},continue:{primary:"teruskan",normalized:"continue"},halt:{primary:"henti",alternatives:["berhenti"],normalized:"halt"},throw:{primary:"lempar",normalized:"throw"},call:{primary:"panggil",normalized:"call"},return:{primary:"pulang",alternatives:["kembali"],normalized:"return"},then:{primary:"kemudian",alternatives:["lepas_itu"],normalized:"then"},and:{primary:"dan",normalized:"and"},end:{primary:"tamat",alternatives:["habis"],normalized:"end"},js:{primary:"js",normalized:"js"},async:{primary:"tak_segerak",normalized:"async"},tell:{primary:"beritahu",normalized:"tell"},default:{primary:"lalai",normalized:"default"},init:{primary:"mula",alternatives:["mulakan"],normalized:"init"},behavior:{primary:"kelakuan",normalized:"behavior"},install:{primary:"pasang",normalized:"install"},measure:{primary:"ukur",normalized:"measure"},beep:{primary:"bunyi",normalized:"beep"},break:{primary:"henti",normalized:"break"},copy:{primary:"salin",normalized:"copy"},exit:{primary:"keluar",normalized:"exit"},pick:{primary:"pilih",normalized:"pick"},render:{primary:"papar",normalized:"render"},into:{primary:"ke_dalam",normalized:"into"},before:{primary:"sebelum",normalized:"before"},after:{primary:"selepas",alternatives:["lepas"],normalized:"after"},until:{primary:"sehingga",alternatives:["sampai"],normalized:"until"},event:{primary:"peristiwa",normalized:"event"},from:{primary:"dari",normalized:"from"}},eventHandler:{keyword:{primary:"apabila",alternatives:["bila","ketika"],normalized:"on"},sourceMarker:{primary:"dari",position:"before"}}}}}),Yd={};yl(Yd,{MalayTokenizer:()=>Gd,malayTokenizer:()=>Qd});var Zd,Xd=fl({"src/tokenizers/ms.ts"(){Jl(),Jd(),Kd=[{native:"benar",normalized:"true"},{native:"salah",normalized:"false"},{native:"kosong",normalized:"null"},{native:"tak_tentu",normalized:"undefined"},{native:"pertama",normalized:"first"},{native:"terakhir",normalized:"last"},{native:"seterusnya",normalized:"next"},{native:"sebelumnya",normalized:"previous"},{native:"terdekat",normalized:"closest"},{native:"induk",normalized:"parent"},{native:"klik",normalized:"click"},{native:"berubah",normalized:"change"},{native:"ubah",normalized:"change"},{native:"hantar",normalized:"submit"},{native:"input",normalized:"input"},{native:"masuk",normalized:"input"},{native:"muat",normalized:"load"},{native:"tatal",normalized:"scroll"},{native:"hover",normalized:"hover"}],Qd=new(Gd=class extends Kl{constructor(){super(),this.language="ms",this.direction="ltr",this.initializeKeywordsFromProfile(Bd,Kd)}tokenize(e){const t=[];let n=0;for(;n<e.length;)if(Ol(e[n]))n++;else{if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])||"-"===e[n]&&n+1<e.length&&Wl(e[n+1])){const r=this.tryNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(":"===e[n]){const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}}if("()[]{}:,;".includes(e[n]))t.push(Nl(e[n],"operator",Il(n,n+1))),n++;else{if($l(e[n])){const r=n,i=this.tryProfileKeyword(e,n);if(i){t.push(i),n=i.position.end;continue}let a="";for(;n<e.length&&$l(e[n]);)a+=e[n],n++;a&&t.push(Nl(a,"identifier",Il(r,n)));continue}n++}}return new Ll(t,"ms")}classifyToken(e){return this.isKeyword(e)?"keyword":e.startsWith(".")||e.startsWith("#")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith(":")?"identifier":e.startsWith('"')||e.startsWith("'")||/^-?\d/.test(e)?"literal":"identifier"}})}}),eh={};yl(eh,{polishProfile:()=>Zd});var th,nh,rh,ih,ah,oh,sh,lh,ch=fl({"src/generators/profiles/polish.ts"(){Zd={code:"pl",name:"Polish",nativeName:"Polski",direction:"ltr",wordOrder:"SVO",markingStrategy:"preposition",usesSpaces:!0,defaultVerbForm:"imperative",verb:{position:"start",subjectDrop:!0,suffixes:["ać","eć","ić","yć","ąć","ować"]},references:{me:"ja",it:"to",you:"ty",result:"wynik",event:"zdarzenie",target:"cel",body:"body"},possessive:{marker:"",markerPosition:"after-object",usePossessiveAdjectives:!0,specialForms:{me:"mój",it:"jego",you:"twój"},keywords:{"mój":"me",moja:"me",moje:"me","twój":"you",twoja:"you",twoje:"you",jego:"it",jej:"it"}},roleMarkers:{destination:{primary:"do",alternatives:["w","na"],position:"before"},source:{primary:"z",alternatives:["od","ze"],position:"before"},patient:{primary:"",position:"before"},style:{primary:"z",alternatives:["ze"],position:"before"}},keywords:{toggle:{primary:"przełącz",alternatives:["przelacz"],normalized:"toggle",form:"imperative"},add:{primary:"dodaj",normalized:"add",form:"imperative"},remove:{primary:"usuń",alternatives:["usun","wyczyść","wyczysc"],normalized:"remove",form:"imperative"},put:{primary:"umieść",alternatives:["umiesc","wstaw"],normalized:"put",form:"imperative"},append:{primary:"dołącz",alternatives:["dolacz"],normalized:"append",form:"imperative"},prepend:{primary:"poprzedź",alternatives:["poprzedz"],normalized:"prepend",form:"imperative"},take:{primary:"weź",alternatives:["wez"],normalized:"take",form:"imperative"},make:{primary:"utwórz",alternatives:["utworz","stwórz","stworz"],normalized:"make",form:"imperative"},clone:{primary:"sklonuj",alternatives:["kopiuj"],normalized:"clone",form:"imperative"},swap:{primary:"zamień",alternatives:["zamien"],normalized:"swap",form:"imperative"},morph:{primary:"przekształć",alternatives:["przeksztalc"],normalized:"morph",form:"imperative"},set:{primary:"ustaw",alternatives:["określ","okresl"],normalized:"set",form:"imperative"},get:{primary:"pobierz",alternatives:["weź","wez"],normalized:"get",form:"imperative"},increment:{primary:"zwiększ",alternatives:["zwieksz"],normalized:"increment",form:"imperative"},decrement:{primary:"zmniejsz",normalized:"decrement",form:"imperative"},log:{primary:"loguj",alternatives:["wypisz"],normalized:"log",form:"imperative"},show:{primary:"pokaż",alternatives:["pokaz","wyświetl","wyswietl"],normalized:"show",form:"imperative"},hide:{primary:"ukryj",alternatives:["schowaj"],normalized:"hide",form:"imperative"},transition:{primary:"animuj",alternatives:["przejście","przejscie"],normalized:"transition",form:"imperative"},on:{primary:"gdy",alternatives:["kiedy","przy","na"],normalized:"on"},trigger:{primary:"wywołaj",alternatives:["wywolaj","wyzwól","wyzwol"],normalized:"trigger",form:"imperative"},send:{primary:"wyślij",alternatives:["wyslij"],normalized:"send",form:"imperative"},focus:{primary:"skup",alternatives:["skupienie"],normalized:"focus",form:"imperative"},blur:{primary:"rozmyj",alternatives:["odskup"],normalized:"blur",form:"imperative"},go:{primary:"idź",alternatives:["idz","przejdź","przejdz","nawiguj"],normalized:"go",form:"imperative"},wait:{primary:"czekaj",alternatives:["poczekaj"],normalized:"wait",form:"imperative"},fetch:{primary:"pobierz",alternatives:["załaduj","zaladuj"],normalized:"fetch",form:"imperative"},settle:{primary:"ustabilizuj",normalized:"settle",form:"imperative"},if:{primary:"jeśli",alternatives:["jesli","jeżeli","jezeli"],normalized:"if"},when:{primary:"kiedy",normalized:"when"},where:{primary:"gdzie",normalized:"where"},else:{primary:"inaczej",alternatives:["wpp"],normalized:"else"},repeat:{primary:"powtórz",alternatives:["powtorz"],normalized:"repeat",form:"imperative"},for:{primary:"dla",alternatives:["każdy","kazdy"],normalized:"for"},while:{primary:"dopóki",alternatives:["dopoki","podczas"],normalized:"while"},continue:{primary:"kontynuuj",alternatives:["dalej"],normalized:"continue",form:"imperative"},halt:{primary:"zatrzymaj",alternatives:["przerwij","stop"],normalized:"halt",form:"imperative"},throw:{primary:"rzuć",alternatives:["rzuc"],normalized:"throw",form:"imperative"},call:{primary:"wywołaj",alternatives:["wywolaj"],normalized:"call",form:"imperative"},return:{primary:"zwróć",alternatives:["zwroc"],normalized:"return",form:"imperative"},then:{primary:"wtedy",alternatives:["potem","następnie","nastepnie"],normalized:"then"},and:{primary:"i",alternatives:["oraz"],normalized:"and"},end:{primary:"koniec",normalized:"end"},js:{primary:"js",normalized:"js"},async:{primary:"async",alternatives:["asynchronicznie"],normalized:"async"},tell:{primary:"powiedz",normalized:"tell",form:"imperative"},default:{primary:"domyślnie",alternatives:["domyslnie"],normalized:"default"},init:{primary:"inicjuj",normalized:"init",form:"imperative"},behavior:{primary:"zachowanie",normalized:"behavior"},install:{primary:"zainstaluj",normalized:"install",form:"imperative"},measure:{primary:"zmierz",normalized:"measure",form:"imperative"},beep:{primary:"sygnał",normalized:"beep"},break:{primary:"przerwij",normalized:"break"},copy:{primary:"kopiuj",normalized:"copy"},exit:{primary:"wyjdź",normalized:"exit"},pick:{primary:"wybierz",normalized:"pick"},render:{primary:"renderuj",normalized:"render"},into:{primary:"do",alternatives:["w"],normalized:"into"},before:{primary:"przed",normalized:"before"},after:{primary:"po",normalized:"after"},click:{primary:"kliknięciu",alternatives:["klikniecie","klik"],normalized:"click"},hover:{primary:"najechaniu",alternatives:["hover"],normalized:"hover"},submit:{primary:"wysłaniu",alternatives:["wyslaniu","submit"],normalized:"submit"},input:{primary:"wprowadzeniu",alternatives:["input"],normalized:"input"},change:{primary:"zmianie",alternatives:["zmiana"],normalized:"change"},until:{primary:"aż",alternatives:["az","do"],normalized:"until"},event:{primary:"zdarzenie",normalized:"event"},from:{primary:"z",alternatives:["od","ze"],normalized:"from"}},eventHandler:{keyword:{primary:"gdy",alternatives:["kiedy","przy","na"],normalized:"on"},sourceMarker:{primary:"na",alternatives:["w","przy"],position:"before"},conditionalKeyword:{primary:"kiedy",alternatives:["gdy","jeśli"]},eventMarker:{primary:"przy",alternatives:["na"],position:"before"},temporalMarkers:["kiedy","gdy","przy"]}}}}),uh=fl({"src/tokenizers/morphology/polish-normalizer.ts"(){ic(),th=new Map([["przełącz","przełączać"],["przelacz","przelaczac"],["dodaj","dodawać"],["usuń","usuwać"],["usun","usuwac"],["umieść","umieszczać"],["umiesc","umieszczac"],["wstaw","wstawiać"],["ustaw","ustawiać"],["pobierz","pobierać"],["weź","brać"],["wez","brac"],["zwiększ","zwiększać"],["zwieksz","zwiekszac"],["zmniejsz","zmniejszać"],["pokaż","pokazywać"],["pokaz","pokazywac"],["ukryj","ukrywać"],["schowaj","schowywać"],["czekaj","czekać"],["poczekaj","poczekać"],["idź","iść"],["idz","isc"],["przejdź","przejść"],["przejdz","przejsc"],["wywołaj","wywoływać"],["wywolaj","wywolywac"],["wyślij","wysyłać"],["wyslij","wysylac"],["loguj","logować"],["wypisz","wypisywać"],["sklonuj","sklonować"],["kopiuj","kopiować"],["zamień","zamieniać"],["zamien","zamieniac"],["utwórz","tworzyć"],["utworz","tworzyc"],["stwórz","stwarzać"],["stworz","stwarzac"],["skup","skupiać"],["rozmyj","rozmywać"],["nawiguj","nawigować"],["załaduj","ładować"],["zaladuj","ladowac"],["powtórz","powtarzać"],["powtorz","powtarzac"],["kontynuuj","kontynuować"],["zatrzymaj","zatrzymywać"],["przerwij","przerywać"],["rzuć","rzucać"],["rzuc","rzucac"],["zwróć","zwracać"],["zwroc","zwracac"],["inicjuj","inicjować"],["zainstaluj","instalować"],["zmierz","mierzyć"]]),new(nh=class{constructor(){this.language="pl"}isNormalizable(e){return!(e.length<3)&&/[a-zA-ZąęćńóśźżłĄĘĆŃÓŚŹŻŁ]/.test(e)}normalize(e){const t=e.toLowerCase();if(this.isInfinitive(t))return Yl(t);const n=this.tryImperativeNormalization(t);if(n)return n;const r=this.tryPastTenseNormalization(t);if(r)return r;const i=this.tryPresentTenseNormalization(t);return i||Yl(t)}isInfinitive(e){return["ać","eć","ić","yć","ąć","ować","iwać","ywać"].some(t=>e.endsWith(t))}tryImperativeNormalization(e){return th.has(e)?Zl(th.get(e),.95,{removedSuffixes:["imperative"],conjugationType:"imperative"}):e.endsWith("aj")?Zl(e.slice(0,-2)+"ać",.8,{removedSuffixes:["aj"],conjugationType:"imperative"}):e.endsWith("uj")?Zl(e.slice(0,-2)+"ować",.8,{removedSuffixes:["uj"],conjugationType:"imperative"}):e.endsWith("ij")?Zl(e.slice(0,-2)+"ić",.75,{removedSuffixes:["ij"],conjugationType:"imperative"}):null}tryPresentTenseNormalization(e){return e.endsWith("uję")||e.endsWith("uje")?Zl(e.slice(0,-3)+"ować",.85,{removedSuffixes:["uję"],conjugationType:"present"}):e.endsWith("am")&&e.length>3?Zl(e.slice(0,-2)+"ać",.8,{removedSuffixes:["am"],conjugationType:"present"}):e.endsWith("em")&&e.length>3?Zl(e.slice(0,-2)+"eć",.75,{removedSuffixes:["em"],conjugationType:"present"}):e.endsWith("ę")&&e.length>2?Zl(e.slice(0,-1)+"ać",.7,{removedSuffixes:["ę"],conjugationType:"present"}):null}tryPastTenseNormalization(e){if(e.endsWith("ałem")||e.endsWith("ałam"))return Zl(e.slice(0,-4)+"ać",.85,{removedSuffixes:[e.slice(-4)],conjugationType:"past"});if(e.endsWith("ał")||e.endsWith("ała")){const t=e.endsWith("ała")?3:2;return Zl(e.slice(0,-t)+"ać",.8,{removedSuffixes:[e.slice(-t)],conjugationType:"past"})}if(e.endsWith("iłem")||e.endsWith("iłam")||e.endsWith("ilem")||e.endsWith("ilam"))return Zl(e.slice(0,-4)+"ić",.85,{removedSuffixes:[e.slice(-4)],conjugationType:"past"});if(e.endsWith("ił")||e.endsWith("iła")||e.endsWith("il")||e.endsWith("ila")){const t=e.endsWith("iła")||e.endsWith("ila")?3:2;return Zl(e.slice(0,-t)+"ić",.8,{removedSuffixes:[e.slice(-t)],conjugationType:"past"})}return null}})}}),ph={};yl(ph,{PolishTokenizer:()=>sh,polishTokenizer:()=>lh});var mh,dh=fl({"src/tokenizers/polish.ts"(){Jl(),ch(),uh(),({isLetter:rh,isIdentifierChar:ih}=_l(/[a-zA-ZąęćńóśźżłĄĘĆŃÓŚŹŻŁ]/)),ah=new Set(["do","od","z","ze","w","we","na","po","pod","przed","za","nad","między","miedzy","przez","dla","bez","o","przy","u","według","wedlug","mimo","wśród","wsrod","obok","poza","wokół","wokol","przeciw","ku"]),oh=[{native:"prawda",normalized:"true"},{native:"fałsz",normalized:"false"},{native:"falsz",normalized:"false"},{native:"null",normalized:"null"},{native:"nieokreślony",normalized:"undefined"},{native:"nieokreslony",normalized:"undefined"},{native:"pierwszy",normalized:"first"},{native:"pierwsza",normalized:"first"},{native:"pierwsze",normalized:"first"},{native:"ostatni",normalized:"last"},{native:"ostatnia",normalized:"last"},{native:"ostatnie",normalized:"last"},{native:"następny",normalized:"next"},{native:"nastepny",normalized:"next"},{native:"poprzedni",normalized:"previous"},{native:"najbliższy",normalized:"closest"},{native:"najblizszy",normalized:"closest"},{native:"rodzic",normalized:"parent"},{native:"kliknięcie",normalized:"click"},{native:"klikniecie",normalized:"click"},{native:"klik",normalized:"click"},{native:"click",normalized:"click"},{native:"zmiana",normalized:"change"},{native:"wysłanie",normalized:"submit"},{native:"wyslanie",normalized:"submit"},{native:"naciśnięcie",normalized:"keydown"},{native:"nacisniecie",normalized:"keydown"},{native:"klawisz",normalized:"keydown"},{native:"najechanie",normalized:"mouseover"},{native:"zjechanie",normalized:"mouseout"},{native:"rozmycie",normalized:"blur"},{native:"załadowanie",normalized:"load"},{native:"zaladowanie",normalized:"load"},{native:"przewinięcie",normalized:"scroll"},{native:"przewiniecie",normalized:"scroll"},{native:"input",normalized:"input"},{native:"mój",normalized:"my"},{native:"moj",normalized:"my"},{native:"sekunda",normalized:"s"},{native:"sekundy",normalized:"s"},{native:"sekund",normalized:"s"},{native:"milisekunda",normalized:"ms"},{native:"milisekundy",normalized:"ms"},{native:"milisekund",normalized:"ms"},{native:"minuta",normalized:"m"},{native:"minuty",normalized:"m"},{native:"minut",normalized:"m"},{native:"godzina",normalized:"h"},{native:"godziny",normalized:"h"},{native:"godzin",normalized:"h"},{native:"połóż",normalized:"put"},{native:"poloz",normalized:"put"},{native:"lub",normalized:"or"},{native:"nie",normalized:"not"},{native:"jest",normalized:"is"},{native:"istnieje",normalized:"exists"},{native:"pusty",normalized:"empty"},{native:"puste",normalized:"empty"}],lh=new(sh=class extends Kl{constructor(){super(),this.language="pl",this.direction="ltr",this.initializeKeywordsFromProfile(Zd,oh),this.normalizer=new nh}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])||"-"===e[n]&&n+1<e.length&&Wl(e[n+1])){const r=this.extractNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}if(rh(e[n])){const r=this.extractWord(e,n);if(r){t.push(r),n=r.position.end;continue}}const i=this.tryOperator(e,n);i?(t.push(i),n=i.position.end):n++}return new Ll(t,"pl")}classifyToken(e){const t=e.toLowerCase();return ah.has(t)?"particle":this.isKeyword(t)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||/^\d/.test(e)?"literal":"identifier"}extractWord(e,t){let n=t,r="";for(;n<e.length&&ih(e[n]);)r+=e[n++];if(!r)return null;const i=r.toLowerCase();if(ah.has(i))return Nl(r,"particle",Il(t,n));const a=this.lookupKeyword(i);return a?Nl(r,"keyword",Il(t,n),a.normalized):Nl(r,"identifier",Il(t,n))}extractNumber(e,t){let n=t,r="";for("-"!==e[n]&&"+"!==e[n]||(r+=e[n++]);n<e.length&&Wl(e[n]);)r+=e[n++];if(n<e.length&&"."===e[n])for(r+=e[n++];n<e.length&&Wl(e[n]);)r+=e[n++];let i=n;for(;i<e.length&&Ol(e[i]);)i++;const a=e.slice(i).toLowerCase();return a.startsWith("milisekund")||a.startsWith("milisekunda")?(r+="ms",n=i+(a.startsWith("milisekundy")||a.startsWith("milisekunda")?11:10)):a.startsWith("sekund")||a.startsWith("sekunda")?(r+="s",n=i+(a.startsWith("sekundy")||a.startsWith("sekunda")?7:6)):a.startsWith("minut")||a.startsWith("minuta")?(r+="m",n=i+(a.startsWith("minuty")||a.startsWith("minuta")?6:5)):a.startsWith("godzin")||a.startsWith("godzina")?(r+="h",n=i+(a.startsWith("godziny")||a.startsWith("godzina")?7:6)):a.startsWith("ms")?(r+="ms",n=i+2):a.startsWith("s")&&!a.startsWith("se")&&(r+="s",n=i+1),r&&"-"!==r&&"+"!==r?Nl(r,"literal",Il(t,n)):null}})}}),hh={};yl(hh,{portugueseProfile:()=>mh});var fh,yh,vh,gh,bh,kh,wh=fl({"src/generators/profiles/portuguese.ts"(){mh={code:"pt",name:"Portuguese",nativeName:"Português",direction:"ltr",wordOrder:"SVO",markingStrategy:"preposition",usesSpaces:!0,verb:{position:"start",subjectDrop:!0},references:{me:"eu",it:"ele",you:"você",result:"resultado",event:"evento",target:"alvo",body:"corpo"},possessive:{marker:"de",markerPosition:"before-property",usePossessiveAdjectives:!0,specialForms:{me:"meu",it:"seu",you:"teu"},keywords:{meu:"me",minha:"me",teu:"you",tua:"you",seu:"it",sua:"it"}},roleMarkers:{destination:{primary:"em",alternatives:["para","a"],position:"before"},source:{primary:"de",alternatives:["desde"],position:"before"},patient:{primary:"",position:"before"},style:{primary:"com",position:"before"}},keywords:{toggle:{primary:"alternar",alternatives:["trocar"],normalized:"toggle"},add:{primary:"adicionar",alternatives:["acrescentar"],normalized:"add"},remove:{primary:"remover",alternatives:["eliminar","apagar"],normalized:"remove"},put:{primary:"colocar",alternatives:["pôr","por"],normalized:"put"},append:{primary:"anexar",normalized:"append"},prepend:{primary:"preceder",normalized:"prepend"},take:{primary:"pegar",normalized:"take"},make:{primary:"fazer",alternatives:["criar"],normalized:"make"},clone:{primary:"clonar",alternatives:["copiar"],normalized:"clone"},swap:{primary:"trocar",alternatives:["substituir"],normalized:"swap"},morph:{primary:"transformar",alternatives:["converter"],normalized:"morph"},set:{primary:"definir",alternatives:["configurar"],normalized:"set"},get:{primary:"obter",normalized:"get"},increment:{primary:"incrementar",alternatives:["aumentar"],normalized:"increment"},decrement:{primary:"decrementar",alternatives:["diminuir"],normalized:"decrement"},log:{primary:"registrar",alternatives:["imprimir"],normalized:"log"},show:{primary:"mostrar",alternatives:["exibir"],normalized:"show"},hide:{primary:"ocultar",alternatives:["esconder"],normalized:"hide"},transition:{primary:"transição",alternatives:["animar"],normalized:"transition"},on:{primary:"em",alternatives:["quando","ao"],normalized:"on"},trigger:{primary:"disparar",alternatives:["ativar"],normalized:"trigger"},send:{primary:"enviar",normalized:"send"},focus:{primary:"focar",normalized:"focus"},blur:{primary:"desfocar",normalized:"blur"},go:{primary:"ir",alternatives:["navegar"],normalized:"go"},wait:{primary:"esperar",alternatives:["aguardar"],normalized:"wait"},fetch:{primary:"buscar",normalized:"fetch"},settle:{primary:"estabilizar",normalized:"settle"},if:{primary:"se",normalized:"if"},when:{primary:"quando",normalized:"when"},where:{primary:"onde",normalized:"where"},else:{primary:"senão",normalized:"else"},repeat:{primary:"repetir",normalized:"repeat"},for:{primary:"para",normalized:"for"},while:{primary:"enquanto",normalized:"while"},continue:{primary:"continuar",normalized:"continue"},halt:{primary:"parar",normalized:"halt"},throw:{primary:"lançar",normalized:"throw"},call:{primary:"chamar",normalized:"call"},return:{primary:"retornar",alternatives:["devolver"],normalized:"return"},then:{primary:"então",alternatives:["depois","logo"],normalized:"then"},and:{primary:"e",alternatives:["também","além disso"],normalized:"and"},end:{primary:"fim",alternatives:["final","término"],normalized:"end"},js:{primary:"js",normalized:"js"},async:{primary:"assíncrono",normalized:"async"},tell:{primary:"dizer",normalized:"tell"},default:{primary:"padrão",normalized:"default"},init:{primary:"iniciar",alternatives:["inicializar"],normalized:"init"},behavior:{primary:"comportamento",normalized:"behavior"},install:{primary:"instalar",normalized:"install"},measure:{primary:"medir",normalized:"measure"},beep:{primary:"apitar",normalized:"beep"},break:{primary:"parar",normalized:"break"},copy:{primary:"copiar",normalized:"copy"},exit:{primary:"sair",normalized:"exit"},pick:{primary:"escolher",normalized:"pick"},render:{primary:"renderizar",normalized:"render"},into:{primary:"em",alternatives:["dentro de"],normalized:"into"},before:{primary:"antes",normalized:"before"},after:{primary:"depois",normalized:"after"},click:{primary:"clique",alternatives:["clicar"],normalized:"click"},hover:{primary:"sobrevoar",alternatives:["passar"],normalized:"hover"},submit:{primary:"envio",alternatives:["submeter"],normalized:"submit"},input:{primary:"entrada",alternatives:["inserção"],normalized:"input"},change:{primary:"alteração",alternatives:["mudança"],normalized:"change"},until:{primary:"até",normalized:"until"},event:{primary:"evento",normalized:"event"},from:{primary:"de",alternatives:["desde"],normalized:"from"}},eventHandler:{keyword:{primary:"em",alternatives:["ao","quando"],normalized:"on"},sourceMarker:{primary:"de",alternatives:["desde"],position:"before"},conditionalKeyword:{primary:"quando",alternatives:["se"]},eventMarker:{primary:"ao",alternatives:["no"],position:"before"},temporalMarkers:["quando","ao"]}}}});function zh(e){return/[áàâãéêíóôõúüçÁÀÂÃÉÊÍÓÔÕÚÜÇ]/.test(e)}var xh,Eh,Sh,Th,Ch,Ah,jh,Lh=fl({"src/tokenizers/morphology/portuguese-normalizer.ts"(){ic(),fh=["-se","-me","-te","-nos","-vos"],yh=[{ending:"ando",stem:"ar",confidence:.88,type:"gerund"},{ending:"ado",stem:"ar",confidence:.88,type:"participle"},{ending:"ada",stem:"ar",confidence:.88,type:"participle"},{ending:"ados",stem:"ar",confidence:.88,type:"participle"},{ending:"adas",stem:"ar",confidence:.88,type:"participle"},{ending:"o",stem:"ar",confidence:.75,type:"present"},{ending:"as",stem:"ar",confidence:.82,type:"present"},{ending:"a",stem:"ar",confidence:.75,type:"present"},{ending:"amos",stem:"ar",confidence:.85,type:"present"},{ending:"ais",stem:"ar",confidence:.85,type:"present"},{ending:"am",stem:"ar",confidence:.8,type:"present"},{ending:"ei",stem:"ar",confidence:.88,type:"past"},{ending:"aste",stem:"ar",confidence:.88,type:"past"},{ending:"ou",stem:"ar",confidence:.88,type:"past"},{ending:"ámos",stem:"ar",confidence:.88,type:"past"},{ending:"amos",stem:"ar",confidence:.85,type:"past"},{ending:"astes",stem:"ar",confidence:.88,type:"past"},{ending:"aram",stem:"ar",confidence:.88,type:"past"},{ending:"ava",stem:"ar",confidence:.88,type:"past"},{ending:"avas",stem:"ar",confidence:.88,type:"past"},{ending:"ávamos",stem:"ar",confidence:.88,type:"past"},{ending:"avamos",stem:"ar",confidence:.85,type:"past"},{ending:"áveis",stem:"ar",confidence:.88,type:"past"},{ending:"aveis",stem:"ar",confidence:.85,type:"past"},{ending:"avam",stem:"ar",confidence:.88,type:"past"},{ending:"e",stem:"ar",confidence:.72,type:"subjunctive"},{ending:"es",stem:"ar",confidence:.78,type:"subjunctive"},{ending:"emos",stem:"ar",confidence:.82,type:"subjunctive"},{ending:"eis",stem:"ar",confidence:.82,type:"subjunctive"},{ending:"em",stem:"ar",confidence:.78,type:"subjunctive"},{ending:"a",stem:"ar",confidence:.75,type:"imperative"},{ending:"ai",stem:"ar",confidence:.85,type:"imperative"},{ending:"ar",stem:"ar",confidence:.92,type:"dictionary"}],vh=[{ending:"endo",stem:"er",confidence:.88,type:"gerund"},{ending:"ido",stem:"er",confidence:.85,type:"participle"},{ending:"ida",stem:"er",confidence:.85,type:"participle"},{ending:"idos",stem:"er",confidence:.85,type:"participle"},{ending:"idas",stem:"er",confidence:.85,type:"participle"},{ending:"o",stem:"er",confidence:.72,type:"present"},{ending:"es",stem:"er",confidence:.78,type:"present"},{ending:"e",stem:"er",confidence:.72,type:"present"},{ending:"emos",stem:"er",confidence:.85,type:"present"},{ending:"eis",stem:"er",confidence:.82,type:"present"},{ending:"em",stem:"er",confidence:.78,type:"present"},{ending:"i",stem:"er",confidence:.85,type:"past"},{ending:"este",stem:"er",confidence:.88,type:"past"},{ending:"eu",stem:"er",confidence:.88,type:"past"},{ending:"emos",stem:"er",confidence:.85,type:"past"},{ending:"estes",stem:"er",confidence:.88,type:"past"},{ending:"eram",stem:"er",confidence:.88,type:"past"},{ending:"ia",stem:"er",confidence:.85,type:"past"},{ending:"ias",stem:"er",confidence:.85,type:"past"},{ending:"íamos",stem:"er",confidence:.88,type:"past"},{ending:"iamos",stem:"er",confidence:.85,type:"past"},{ending:"íeis",stem:"er",confidence:.88,type:"past"},{ending:"ieis",stem:"er",confidence:.85,type:"past"},{ending:"iam",stem:"er",confidence:.85,type:"past"},{ending:"er",stem:"er",confidence:.92,type:"dictionary"}],gh=[{ending:"indo",stem:"ir",confidence:.88,type:"gerund"},{ending:"ido",stem:"ir",confidence:.85,type:"participle"},{ending:"ida",stem:"ir",confidence:.85,type:"participle"},{ending:"idos",stem:"ir",confidence:.85,type:"participle"},{ending:"idas",stem:"ir",confidence:.85,type:"participle"},{ending:"o",stem:"ir",confidence:.72,type:"present"},{ending:"es",stem:"ir",confidence:.78,type:"present"},{ending:"e",stem:"ir",confidence:.72,type:"present"},{ending:"imos",stem:"ir",confidence:.85,type:"present"},{ending:"is",stem:"ir",confidence:.82,type:"present"},{ending:"em",stem:"ir",confidence:.78,type:"present"},{ending:"i",stem:"ir",confidence:.85,type:"past"},{ending:"iste",stem:"ir",confidence:.88,type:"past"},{ending:"iu",stem:"ir",confidence:.88,type:"past"},{ending:"imos",stem:"ir",confidence:.85,type:"past"},{ending:"istes",stem:"ir",confidence:.88,type:"past"},{ending:"iram",stem:"ir",confidence:.88,type:"past"},{ending:"ia",stem:"ir",confidence:.85,type:"past"},{ending:"ias",stem:"ir",confidence:.85,type:"past"},{ending:"íamos",stem:"ir",confidence:.88,type:"past"},{ending:"iamos",stem:"ir",confidence:.85,type:"past"},{ending:"íeis",stem:"ir",confidence:.88,type:"past"},{ending:"ieis",stem:"ir",confidence:.85,type:"past"},{ending:"iam",stem:"ir",confidence:.85,type:"past"},{ending:"ir",stem:"ir",confidence:.92,type:"dictionary"}],bh=[...yh,...vh,...gh].sort((e,t)=>t.ending.length-e.ending.length),new(kh=class{constructor(){this.language="pt"}isNormalizable(e){return!(e.length<3)&&function(e){const t=e.toLowerCase();if(t.endsWith("ar")||t.endsWith("er")||t.endsWith("ir"))return!0;if(t.endsWith("ando")||t.endsWith("endo")||t.endsWith("indo"))return!0;if(t.endsWith("ado")||t.endsWith("ido"))return!0;if(t.endsWith("ar-se")||t.endsWith("er-se")||t.endsWith("ir-se"))return!0;for(const t of e)if(zh(t))return!0;return!1}(e)}normalize(e){const t=e.toLowerCase();if((t.endsWith("ar")||t.endsWith("er")||t.endsWith("ir"))&&!fh.some(e=>t.endsWith(e)))return Yl(e);const n=this.tryReflexiveNormalization(t);if(n)return n;const r=this.tryConjugationNormalization(t);return r||Yl(e)}tryReflexiveNormalization(e){for(const t of fh)if(e.endsWith(t)){const n=e.slice(0,-t.length);if(n.endsWith("ar")||n.endsWith("er")||n.endsWith("ir"))return Zl(n,.88,{removedSuffixes:[t],conjugationType:"reflexive"});const r=this.tryConjugationNormalization(n);if(r&&r.stem!==n)return Zl(r.stem,.95*r.confidence,{removedSuffixes:[t,...r.metadata?.removedSuffixes||[]],conjugationType:"reflexive"})}return null}tryConjugationNormalization(e){for(const t of bh)if(e.endsWith(t.ending)){const n=e.slice(0,-t.ending.length);if(n.length<2)continue;return Zl(n+t.stem,t.confidence,{removedSuffixes:[t.ending],conjugationType:t.type})}return null}})}}),Ph={};yl(Ph,{PortugueseTokenizer:()=>Ah,portugueseTokenizer:()=>jh});var Ih,Nh=fl({"src/tokenizers/portuguese.ts"(){Jl(),wh(),Lh(),({isLetter:xh,isIdentifierChar:Eh}=_l(/[a-zA-ZáàâãéêíóôõúüçÁÀÂÃÉÊÍÓÔÕÚÜÇ]/)),Sh=new Set(["em","a","de","desde","até","ate","com","sem","por","para","sobre","entre","antes","depois","dentro","fora","ao","do","no","na"]),Th=[{native:"verdadeiro",normalized:"true"},{native:"falso",normalized:"false"},{native:"nulo",normalized:"null"},{native:"indefinido",normalized:"undefined"},{native:"primeiro",normalized:"first"},{native:"primeira",normalized:"first"},{native:"último",normalized:"last"},{native:"ultima",normalized:"last"},{native:"próximo",normalized:"next"},{native:"proximo",normalized:"next"},{native:"anterior",normalized:"previous"},{native:"mais próximo",normalized:"closest"},{native:"mais proximo",normalized:"closest"},{native:"pai",normalized:"parent"},{native:"clique",normalized:"click"},{native:"click",normalized:"click"},{native:"entrada",normalized:"input"},{native:"mudança",normalized:"change"},{native:"mudanca",normalized:"change"},{native:"envio",normalized:"submit"},{native:"tecla baixo",normalized:"keydown"},{native:"tecla cima",normalized:"keyup"},{native:"mouse sobre",normalized:"mouseover"},{native:"mouse fora",normalized:"mouseout"},{native:"foco",normalized:"focus"},{native:"desfoque",normalized:"blur"},{native:"carregar",normalized:"load"},{native:"rolagem",normalized:"scroll"},{native:"meu",normalized:"my"},{native:"minha",normalized:"my"},{native:"isso",normalized:"it"},{native:"segundo",normalized:"s"},{native:"segundos",normalized:"s"},{native:"milissegundo",normalized:"ms"},{native:"milissegundos",normalized:"ms"},{native:"minuto",normalized:"m"},{native:"minutos",normalized:"m"},{native:"hora",normalized:"h"},{native:"horas",normalized:"h"},{native:"senao",normalized:"else"},{native:"transicao",normalized:"transition"},{native:"ate",normalized:"until"},{native:"entao",normalized:"then"},{native:"lancar",normalized:"throw"},{native:"assincrono",normalized:"async"},{native:"padrao",normalized:"default"},{native:"até que",normalized:"until"},{native:"dentro de",normalized:"into"}],Ch=[{pattern:"milissegundos",suffix:"ms",length:13,caseInsensitive:!0},{pattern:"milissegundo",suffix:"ms",length:12,caseInsensitive:!0},{pattern:"segundos",suffix:"s",length:8,caseInsensitive:!0},{pattern:"segundo",suffix:"s",length:7,caseInsensitive:!0},{pattern:"minutos",suffix:"m",length:7,caseInsensitive:!0},{pattern:"minuto",suffix:"m",length:6,caseInsensitive:!0},{pattern:"horas",suffix:"h",length:5,caseInsensitive:!0},{pattern:"hora",suffix:"h",length:4,caseInsensitive:!0}],jh=new(Ah=class extends Kl{constructor(){super(),this.language="pt",this.direction="ltr",this.initializeKeywordsFromProfile(mh,Th),this.normalizer=new kh}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])||"-"===e[n]&&n+1<e.length&&Wl(e[n+1])){const r=this.extractNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}if(xh(e[n])){const r=this.extractWord(e,n);if(r){t.push(r),n=r.position.end;continue}}const i=this.tryOperator(e,n);i?(t.push(i),n=i.position.end):n++}return new Ll(t,"pt")}classifyToken(e){const t=e.toLowerCase();return Sh.has(t)?"particle":this.isKeyword(t)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||/^\d/.test(e)?"literal":"identifier"}extractWord(e,t){let n=t,r="";for(;n<e.length&&Eh(e[n]);)r+=e[n++];if(!r)return null;const i=r.toLowerCase(),a=this.lookupKeyword(i);return a?Nl(r,"keyword",Il(t,n),a.normalized):Sh.has(i)?Nl(r,"particle",Il(t,n)):Nl(r,"identifier",Il(t,n))}extractNumber(e,t){return this.tryNumberWithTimeUnits(e,t,Ch,{allowSign:!0,skipWhitespace:!0})}})}}),Oh={};yl(Oh,{quechuaProfile:()=>Ih});var Rh,Mh,Wh,$h,Hh,qh,Dh=fl({"src/generators/profiles/quechua.ts"(){Ih={code:"qu",name:"Quechua",nativeName:"Runasimi",direction:"ltr",wordOrder:"SOV",markingStrategy:"postposition",usesSpaces:!0,verb:{position:"end",subjectDrop:!0},references:{me:"ñuqa",it:"pay",you:"qam",result:"rurasqa",event:"ruwakuq",target:"ñawpaqman",body:"ukhu"},possessive:{marker:"-pa",markerPosition:"after-object",keywords:{"ñuqapa":"me","ñuqaypa":"me",qampa:"you",paypa:"it"}},roleMarkers:{patient:{primary:"ta",position:"after"},destination:{primary:"man",alternatives:["pa"],position:"after"},source:{primary:"manta",position:"after"},style:{primary:"wan",position:"after"},event:{primary:"pi",position:"after"}},keywords:{toggle:{primary:"t'ikray",alternatives:["tikray","kutichiy"],normalized:"toggle"},add:{primary:"yapay",alternatives:["yapaykuy"],normalized:"add"},remove:{primary:"qichuy",alternatives:["hurquy","anchuchiy"],normalized:"remove"},put:{primary:"churay",alternatives:["tiyachiy"],normalized:"put"},append:{primary:"qatichiy",alternatives:["qhipaman_yapay"],normalized:"append"},prepend:{primary:"ñawpachiy",normalized:"prepend"},take:{primary:"hapiy",normalized:"take"},make:{primary:"ruray",alternatives:["kamay"],normalized:"make"},clone:{primary:"kikinchay",alternatives:["qillqay"],normalized:"clone"},swap:{primary:"t'inkuy",alternatives:["rantikunakuy","rantin_tikray"],normalized:"swap"},morph:{primary:"tikray",alternatives:["kutichiy"],normalized:"morph"},set:{primary:"churay",alternatives:["kamaykuy"],normalized:"set"},get:{primary:"taripay",normalized:"get"},increment:{primary:"yapachiy",normalized:"increment"},decrement:{primary:"pisiyachiy",normalized:"decrement"},log:{primary:"qillqakuy",alternatives:["willakuy"],normalized:"log"},show:{primary:"rikuchiy",alternatives:["qawachiy"],normalized:"show"},hide:{primary:"pakay",alternatives:["pakakuy"],normalized:"hide"},transition:{primary:"tikray",alternatives:["kuyuchiy"],normalized:"transition"},on:{primary:"chaypim",alternatives:["kaypi"],normalized:"on"},trigger:{primary:"qallarichiy",alternatives:["kichay"],normalized:"trigger"},send:{primary:"kachay",alternatives:["apachiy"],normalized:"send"},focus:{primary:"qhawachiy",alternatives:["qhaway"],normalized:"focus"},blur:{primary:"paqariy",alternatives:["mana qhawachiy"],normalized:"blur"},go:{primary:"riy",alternatives:["puriy"],normalized:"go"},wait:{primary:"suyay",normalized:"wait"},fetch:{primary:"apamuy",alternatives:["taripakaramuy"],normalized:"fetch"},settle:{primary:"tiyakuy",normalized:"settle"},if:{primary:"sichus",normalized:"if"},when:{primary:"maykama",normalized:"when"},where:{primary:"maypi",normalized:"where"},else:{primary:"manachus",alternatives:["hukniraq"],normalized:"else"},repeat:{primary:"kutipay",alternatives:["muyu"],normalized:"repeat"},for:{primary:"sapankaq",normalized:"for"},while:{primary:"kaykamaqa",normalized:"while"},continue:{primary:"qatipay",normalized:"continue"},halt:{primary:"sayay",alternatives:["tukuy"],normalized:"halt"},throw:{primary:"chanqay",normalized:"throw"},call:{primary:"waqyay",alternatives:["qayay"],normalized:"call"},return:{primary:"kutichiy",alternatives:["kutimuy"],normalized:"return"},then:{primary:"chaymantataq",alternatives:["hinaspa","chaymanta"],normalized:"then"},and:{primary:"hinallataq",alternatives:["ima","chaymantawan"],normalized:"and"},end:{primary:"tukukuy",alternatives:["tukuy","puchukay"],normalized:"end"},js:{primary:"js",normalized:"js"},async:{primary:"mana waqtalla",normalized:"async"},tell:{primary:"niy",alternatives:["willakuy"],normalized:"tell"},default:{primary:"qallariy",normalized:"default"},init:{primary:"qallarichiy",normalized:"init"},behavior:{primary:"ruwana",normalized:"behavior"},install:{primary:"churay",normalized:"install"},measure:{primary:"tupuy",normalized:"measure"},beep:{primary:"waqay",normalized:"beep"},break:{primary:"p'akiy",normalized:"break"},copy:{primary:"qillqay",normalized:"copy"},exit:{primary:"lluqsiy",normalized:"exit"},pick:{primary:"akllay",normalized:"pick"},render:{primary:"rikuchiy",normalized:"render"},into:{primary:"ukuman",normalized:"into"},before:{primary:"ñawpaq",normalized:"before"},after:{primary:"qhipa",normalized:"after"},until:{primary:"kama",alternatives:["-kama"],normalized:"until"},event:{primary:"ruwakuq",alternatives:["imayna"],normalized:"event"},from:{primary:"manta",alternatives:["-manta"],normalized:"from"},click:{primary:"ñitiy",normalized:"click"},load:{primary:"apakuy",normalized:"load"},submit:{primary:"kachay",normalized:"submit"},hover:{primary:"hawachiy",normalized:"hover"},input:{primary:"yaykuchiy",normalized:"input"},change:{primary:"tikray",normalized:"change"}},eventHandler:{keyword:{primary:"pi",alternatives:["kaqtin"]},sourceMarker:{primary:"manta",position:"after"},eventMarker:{primary:"pi",alternatives:["kaqtin","kaqpi"],position:"after"}}}}}),_h={};yl(_h,{QuechuaTokenizer:()=>Hh,quechuaTokenizer:()=>qh});var Vh,Bh=fl({"src/tokenizers/quechua.ts"(){Jl(),Dh(),({isLetter:Rh,isIdentifierChar:Mh}=_l(/[a-zA-ZñÑ']/)),Wh=new Set(["-ta","-man","-manta","-pi","-wan","-paq","-kama","-rayku","-hina","ta","man","manta","pi","wan","paq","kama","hina","pa"]),$h=[{native:"arí",normalized:"true"},{native:"ari",normalized:"true"},{native:"manan",normalized:"false"},{native:"mana",normalized:"false"},{native:"ch'usaq",normalized:"null"},{native:"chusaq",normalized:"null"},{native:"mana riqsisqa",normalized:"undefined"},{native:"ñawpaq",normalized:"first"},{native:"nawpaq",normalized:"first"},{native:"qhipa",normalized:"last"},{native:"hamuq",normalized:"next"},{native:"ñawpaq kaq",normalized:"previous"},{native:"ñawpaq_kaq",normalized:"previous"},{native:"aswan qayllaqa",normalized:"closest"},{native:"tayta",normalized:"parent"},{native:"llikllay",normalized:"click"},{native:"ñitiy",normalized:"click"},{native:"click",normalized:"click"},{native:"yaykuy",normalized:"input"},{native:"llave uray",normalized:"keydown"},{native:"llave hawa",normalized:"keyup"},{native:"mausiri yayku",normalized:"mouseover"},{native:"mausiri lluqsi",normalized:"mouseout"},{native:"qhaway",normalized:"focus"},{native:"mana qhaway",normalized:"blur"},{native:"kargay",normalized:"load"},{native:"muyuy",normalized:"scroll"},{native:"ñuqa",normalized:"me"},{native:"nuqa",normalized:"me"},{native:"ñuqap",normalized:"my"},{native:"nuqap",normalized:"my"},{native:"chay",normalized:"it"},{native:"chaymi",normalized:"it"},{native:"lluqsiy",normalized:"result"},{native:"ruway",normalized:"event"},{native:"maypi",normalized:"target"},{native:"sikundu",normalized:"s"},{native:"segundu",normalized:"s"},{native:"waranqa sikundu",normalized:"ms"},{native:"minutu",normalized:"m"},{native:"ura",normalized:"h"},{native:"hora",normalized:"h"},{native:"chaypim",normalized:"on"},{native:"kaypi",normalized:"on"},{native:"chayqa",normalized:"then"},{native:"chaymanta",normalized:"then"},{native:"chaymantataq",normalized:"then"},{native:"hinaspa",normalized:"then"},{native:"tukukuy",normalized:"end"},{native:"puchukay",normalized:"end"},{native:"kaykama",normalized:"until"},{native:"yapay",normalized:"add"},{native:"t'ikray",normalized:"toggle"},{native:"tikray",normalized:"toggle"},{native:"qhawachiy",normalized:"focus"},{native:"mana qhawachiy",normalized:"blur"},{native:"-manta",normalized:"from"}],qh=new(Hh=class extends Kl{constructor(){super(),this.language="qu",this.direction="ltr",this.initializeKeywordsFromProfile(Ih,$h)}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){const e=this.splitSelectorSuffix(i);2===e.length?(t.push(e[0]),t.push(e[1]),n=e[1].position.end):(t.push(i),n=i.position.end);continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])||"-"===e[n]&&n+1<e.length&&Wl(e[n+1])){const r=this.extractNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}if("-"===e[n]){const r=this.trySuffix(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Rh(e[n])){const r=this.tryMultiWordKeyword(e,n);if(r){t.push(r),n=r.position.end;continue}const i=this.extractWord(e,n);if(i){t.push(i),n=i.position.end;continue}}const i=this.tryOperator(e,n);i?(t.push(i),n=i.position.end):n++}return new Ll(t,"qu")}classifyToken(e){const t=e.toLowerCase();return Wh.has(t)?"particle":this.isKeyword(t)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||/^\d/.test(e)?"literal":"identifier"}trySuffix(e,t){for(const n of Wh)if(e.slice(t,t+n.length).toLowerCase()===n)return Nl(e.slice(t,t+n.length),"particle",Il(t,t+n.length));return null}splitSelectorSuffix(e){const t=e.value;for(const n of Wh)if(t.toLowerCase().endsWith(n)){const r=t.length-n.length,i=t.slice(0,r),a=t.slice(r);return[Nl(i,"selector",Il(e.position.start,e.position.start+r)),Nl(a,"particle",Il(e.position.start+r,e.position.end))]}return[e]}tryMultiWordKeyword(e,t){const n=[{pattern:"mana qhawachiy",normalized:"blur"},{pattern:"mana qhaway",normalized:"blur"},{pattern:"mana riqsisqa",normalized:"undefined"},{pattern:"mana waqtalla",normalized:"async"},{pattern:"ñawpaq kaq",normalized:"previous"},{pattern:"aswan qayllaqa",normalized:"closest"},{pattern:"llave uray",normalized:"keydown"},{pattern:"llave hawa",normalized:"keyup"},{pattern:"mausiri yayku",normalized:"mouseover"},{pattern:"mausiri lluqsi",normalized:"mouseout"},{pattern:"waranqa sikundu",normalized:"ms"}],r=e.toLowerCase();for(const{pattern:i,normalized:a}of n)if(r.slice(t,t+i.length)===i){const n=t+i.length;if(n>=e.length||Ol(e[n])||!Rh(e[n]))return Nl(e.slice(t,n),"keyword",Il(t,n),a)}return null}extractWord(e,t){let n=t,r="";for(;n<e.length&&Mh(e[n]);)r+=e[n++];if(!r)return null;const i=r.toLowerCase();if(Wh.has(i))return Nl(r,"particle",Il(t,n));const a=this.lookupKeyword(i);return a?Nl(r,"keyword",Il(t,n),a.normalized):Nl(r,"identifier",Il(t,n))}extractNumber(e,t){let n=t,r="";for("-"!==e[n]&&"+"!==e[n]||(r+=e[n++]);n<e.length&&Wl(e[n]);)r+=e[n++];if(n<e.length&&"."===e[n])for(r+=e[n++];n<e.length&&Wl(e[n]);)r+=e[n++];let i=n;for(;i<e.length&&Ol(e[i]);)i++;const a=e.slice(i).toLowerCase();return a.startsWith("sikundu")||a.startsWith("segundu")?(r+="s",n=i+7):a.startsWith("minutu")?(r+="m",n=i+6):(a.startsWith("hora")||a.startsWith("ura"))&&(r+="h",n=i+(a.startsWith("hora")?4:3)),r&&"-"!==r&&"+"!==r?Nl(r,"literal",Il(t,n)):null}})}}),Fh={};yl(Fh,{russianProfile:()=>Vh});var Uh,Kh,Gh=fl({"src/generators/profiles/russian.ts"(){Vh={code:"ru",name:"Russian",nativeName:"Русский",direction:"ltr",wordOrder:"SVO",markingStrategy:"preposition",usesSpaces:!0,defaultVerbForm:"infinitive",verb:{position:"start",subjectDrop:!0,suffixes:["ть","ться","ить","иться","ать","аться","еть","еться"]},references:{me:"я",it:"это",you:"ты",result:"результат",event:"событие",target:"цель",body:"body"},possessive:{marker:"",markerPosition:"after-object",usePossessiveAdjectives:!0,specialForms:{me:"мой",it:"его",you:"твой"},keywords:{"мой":"me","моя":"me","моё":"me","мои":"me","твой":"you","твоя":"you","твоё":"you","твои":"you","его":"it","её":"it"}},roleMarkers:{destination:{primary:"в",alternatives:["на","к"],position:"before"},source:{primary:"из",alternatives:["от","с"],position:"before"},patient:{primary:"",position:"before"},style:{primary:"с",alternatives:["со"],position:"before"}},keywords:{toggle:{primary:"переключить",alternatives:["переключи"],normalized:"toggle",form:"infinitive"},add:{primary:"добавить",alternatives:["добавь"],normalized:"add",form:"infinitive"},remove:{primary:"удалить",alternatives:["удали","убрать","убери"],normalized:"remove",form:"infinitive"},put:{primary:"положить",alternatives:["положи","поместить","помести","вставить","вставь"],normalized:"put",form:"infinitive"},append:{primary:"добавить_в_конец",alternatives:["дописать"],normalized:"append",form:"infinitive"},prepend:{primary:"добавить_в_начало",normalized:"prepend",form:"infinitive"},take:{primary:"взять",alternatives:["возьми"],normalized:"take",form:"infinitive"},make:{primary:"создать",alternatives:["создай"],normalized:"make",form:"infinitive"},clone:{primary:"клонировать",alternatives:["клонируй"],normalized:"clone",form:"infinitive"},swap:{primary:"поменять",alternatives:["поменяй"],normalized:"swap",form:"infinitive"},morph:{primary:"трансформировать",alternatives:["трансформируй"],normalized:"morph",form:"infinitive"},set:{primary:"установить",alternatives:["установи","задать","задай"],normalized:"set",form:"infinitive"},get:{primary:"получить",alternatives:["получи"],normalized:"get",form:"infinitive"},increment:{primary:"увеличить",alternatives:["увеличь"],normalized:"increment",form:"infinitive"},decrement:{primary:"уменьшить",alternatives:["уменьши"],normalized:"decrement",form:"infinitive"},log:{primary:"записать",alternatives:["запиши"],normalized:"log",form:"infinitive"},show:{primary:"показать",alternatives:["покажи"],normalized:"show",form:"infinitive"},hide:{primary:"скрыть",alternatives:["скрой","спрятать","спрячь"],normalized:"hide",form:"infinitive"},transition:{primary:"анимировать",alternatives:["анимируй"],normalized:"transition",form:"infinitive"},on:{primary:"при",alternatives:["когда"],normalized:"on"},trigger:{primary:"вызвать",alternatives:["вызови"],normalized:"trigger",form:"infinitive"},send:{primary:"отправить",alternatives:["отправь"],normalized:"send",form:"infinitive"},focus:{primary:"сфокусировать",alternatives:["сфокусируй","фокус"],normalized:"focus",form:"infinitive"},blur:{primary:"размыть",alternatives:["размой"],normalized:"blur",form:"infinitive"},click:{primary:"клик",alternatives:["клике","нажатии"],normalized:"click"},hover:{primary:"наведении",alternatives:["наведение"],normalized:"hover"},submit:{primary:"отправке",alternatives:["отправка"],normalized:"submit"},input:{primary:"вводе",alternatives:["ввод"],normalized:"input"},change:{primary:"изменении",alternatives:["изменение"],normalized:"change"},go:{primary:"перейти",alternatives:["перейди","идти","иди"],normalized:"go",form:"infinitive"},wait:{primary:"ждать",alternatives:["жди","подожди"],normalized:"wait",form:"infinitive"},fetch:{primary:"загрузить",alternatives:["загрузи"],normalized:"fetch",form:"infinitive"},settle:{primary:"стабилизировать",normalized:"settle",form:"infinitive"},if:{primary:"если",normalized:"if"},when:{primary:"когда",normalized:"when"},where:{primary:"где",normalized:"where"},else:{primary:"иначе",normalized:"else"},repeat:{primary:"повторить",alternatives:["повтори"],normalized:"repeat",form:"infinitive"},for:{primary:"для",alternatives:["каждый"],normalized:"for"},while:{primary:"пока",normalized:"while"},continue:{primary:"продолжить",alternatives:["продолжи"],normalized:"continue",form:"infinitive"},halt:{primary:"остановить",alternatives:["остановись","стоп"],normalized:"halt",form:"infinitive"},throw:{primary:"бросить",alternatives:["брось"],normalized:"throw",form:"infinitive"},call:{primary:"вызвать",alternatives:["вызови"],normalized:"call",form:"infinitive"},return:{primary:"вернуть",alternatives:["верни"],normalized:"return",form:"infinitive"},then:{primary:"затем",alternatives:["потом","тогда"],normalized:"then"},and:{primary:"и",normalized:"and"},end:{primary:"конец",normalized:"end"},js:{primary:"js",normalized:"js"},async:{primary:"асинхронно",alternatives:["async"],normalized:"async"},tell:{primary:"сказать",alternatives:["скажи"],normalized:"tell",form:"infinitive"},default:{primary:"по_умолчанию",normalized:"default"},init:{primary:"инициализировать",alternatives:["инициализируй"],normalized:"init",form:"infinitive"},behavior:{primary:"поведение",normalized:"behavior"},install:{primary:"установить_пакет",normalized:"install",form:"infinitive"},measure:{primary:"измерить",alternatives:["измерь"],normalized:"measure",form:"infinitive"},beep:{primary:"звук",normalized:"beep"},break:{primary:"прервать",normalized:"break"},copy:{primary:"копировать",normalized:"copy"},exit:{primary:"выйти",normalized:"exit"},pick:{primary:"выбрать",normalized:"pick"},render:{primary:"отобразить",normalized:"render"},into:{primary:"в",alternatives:["во"],normalized:"into"},before:{primary:"до",alternatives:["перед"],normalized:"before"},after:{primary:"после",normalized:"after"},until:{primary:"до",alternatives:["пока_не"],normalized:"until"},event:{primary:"событие",normalized:"event"},from:{primary:"из",alternatives:["от","с"],normalized:"from"}},eventHandler:{keyword:{primary:"при",alternatives:["когда"],normalized:"on"},sourceMarker:{primary:"на",alternatives:["в","при"],position:"before"},eventMarker:{primary:"при",alternatives:["когда"],position:"before"},temporalMarkers:["когда","если"]}}}});function Qh(e){return/[а-яА-ЯёЁ]/.test(e)}var Jh,Yh,Zh,Xh,ef,tf,nf=fl({"src/tokenizers/morphology/russian-normalizer.ts"(){ic(),Uh=new Map([["переключи","переключить"],["добавь","добавить"],["удали","удалить"],["убери","убрать"],["положи","положить"],["помести","поместить"],["вставь","вставить"],["возьми","взять"],["создай","создать"],["клонируй","клонировать"],["поменяй","поменять"],["трансформируй","трансформировать"],["установи","установить"],["задай","задать"],["получи","получить"],["увеличь","увеличить"],["уменьши","уменьшить"],["запиши","записать"],["покажи","показать"],["скрой","скрыть"],["спрячь","спрятать"],["анимируй","анимировать"],["вызови","вызвать"],["отправь","отправить"],["сфокусируй","сфокусировать"],["размой","размыть"],["перейди","перейти"],["иди","идти"],["жди","ждать"],["подожди","подождать"],["загрузи","загрузить"],["повтори","повторить"],["продолжи","продолжить"],["брось","бросить"],["верни","вернуть"],["скажи","сказать"],["инициализируй","инициализировать"],["измерь","измерить"]]),new(Kh=class{constructor(){this.language="ru"}isNormalizable(e){return!(e.length<3)&&function(e){for(const t of e)if(Qh(t))return!0;return!1}(e)}normalize(e){const t=e.toLowerCase();if(t.endsWith("ся")||t.endsWith("сь")){const e=this.tryReflexiveNormalization(t);if(e)return e}if(t.endsWith("ть")||t.endsWith("ти")||t.endsWith("чь"))return Yl(e);const n=this.tryImperativeLookup(t);if(n)return n;const r=this.tryPastTenseNormalization(t);if(r)return r;const i=this.tryPresentTenseNormalization(t);if(i)return i;const a=this.tryGenericImperativeNormalization(t);return a||Yl(e)}tryReflexiveNormalization(e){e.endsWith("ся");const t=e.slice(0,-2);if(e.endsWith("ться")||e.endsWith("тись")||e.endsWith("чься"))return Yl(e);const n=this.normalizeNonReflexive(t);if(n.confidence<1){return Zl(n.stem.endsWith("ть")?n.stem.slice(0,-2)+"ться":n.stem+"ся",.95*n.confidence,{removedSuffixes:["ся",...n.metadata?.removedSuffixes||[]],conjugationType:"reflexive"})}return null}normalizeNonReflexive(e){if(e.endsWith("ть")||e.endsWith("ти")||e.endsWith("чь"))return Yl(e);const t=this.tryImperativeLookup(e);if(t)return t;const n=this.tryPastTenseNormalization(e);if(n)return n;const r=this.tryPresentTenseNormalization(e);if(r)return r;const i=this.tryGenericImperativeNormalization(e);return i||Yl(e)}tryImperativeLookup(e){return Uh.has(e)?Zl(Uh.get(e),.95,{removedSuffixes:["imperative"],conjugationType:"imperative"}):null}tryGenericImperativeNormalization(e){return e.endsWith("йте")&&e.length>5?Zl(e.slice(0,-3)+"ть",.8,{removedSuffixes:["йте"],conjugationType:"imperative"}):e.endsWith("ите")&&e.length>5?Zl(e.slice(0,-3)+"ить",.8,{removedSuffixes:["ите"],conjugationType:"imperative"}):e.endsWith("й")&&e.length>3?Zl(e.slice(0,-1)+"ть",.75,{removedSuffixes:["й"],conjugationType:"imperative"}):e.endsWith("и")&&e.length>3?Zl(e+"ть",.7,{removedSuffixes:["и→ить"],conjugationType:"imperative"}):null}tryPastTenseNormalization(e){return e.endsWith("ала")&&e.length>4?Zl(e.slice(0,-3)+"ать",.85,{removedSuffixes:["ала"],conjugationType:"past"}):e.endsWith("ила")&&e.length>4?Zl(e.slice(0,-3)+"ить",.85,{removedSuffixes:["ила"],conjugationType:"past"}):e.endsWith("ело")&&e.length>4?Zl(e.slice(0,-3)+"еть",.82,{removedSuffixes:["ело"],conjugationType:"past"}):e.endsWith("або")&&e.length>4?Zl(e.slice(0,-3)+"ать",.82,{removedSuffixes:["або"],conjugationType:"past"}):e.endsWith("али")&&e.length>4?Zl(e.slice(0,-3)+"ать",.85,{removedSuffixes:["али"],conjugationType:"past"}):e.endsWith("или")&&e.length>4?Zl(e.slice(0,-3)+"ить",.85,{removedSuffixes:["или"],conjugationType:"past"}):e.endsWith("ал")&&e.length>3?Zl(e.slice(0,-2)+"ать",.82,{removedSuffixes:["ал"],conjugationType:"past"}):e.endsWith("ил")&&e.length>3?Zl(e.slice(0,-2)+"ить",.82,{removedSuffixes:["ил"],conjugationType:"past"}):null}tryPresentTenseNormalization(e){return e.endsWith("ишь")&&e.length>4?Zl(e.slice(0,-3)+"ить",.8,{removedSuffixes:["ишь"],conjugationType:"present"}):e.endsWith("ит")&&e.length>3?Zl(e.slice(0,-2)+"ить",.78,{removedSuffixes:["ит"],conjugationType:"present"}):e.endsWith("им")&&e.length>3?Zl(e.slice(0,-2)+"ить",.78,{removedSuffixes:["им"],conjugationType:"present"}):e.endsWith("ят")&&e.length>3?Zl(e.slice(0,-2)+"ить",.78,{removedSuffixes:["ят"],conjugationType:"present"}):e.endsWith("ешь")&&e.length>4?Zl(e.slice(0,-3)+"ать",.75,{removedSuffixes:["ешь"],conjugationType:"present"}):e.endsWith("ет")&&e.length>3?Zl(e.slice(0,-2)+"ать",.72,{removedSuffixes:["ет"],conjugationType:"present"}):e.endsWith("ем")&&e.length>3?Zl(e.slice(0,-2)+"ать",.72,{removedSuffixes:["ем"],conjugationType:"present"}):e.endsWith("ют")&&e.length>3?Zl(e.slice(0,-2)+"ать",.75,{removedSuffixes:["ют"],conjugationType:"present"}):e.endsWith("ут")&&e.length>3?Zl(e.slice(0,-2)+"ать",.72,{removedSuffixes:["ут"],conjugationType:"present"}):null}})}}),rf={};yl(rf,{RussianTokenizer:()=>ef,russianTokenizer:()=>tf});var af,of=fl({"src/tokenizers/russian.ts"(){Jl(),Gh(),nf(),({isLetter:Jh,isIdentifierChar:Yh}=_l(/[a-zA-Zа-яА-ЯёЁ]/)),Zh=new Set(["в","во","на","с","со","к","ко","о","об","обо","у","от","до","из","за","по","под","над","перед","передо","между","через","без","для","при","про","после","вокруг","против","вместо","кроме","среди"]),Xh=[{native:"истина",normalized:"true"},{native:"правда",normalized:"true"},{native:"ложь",normalized:"false"},{native:"null",normalized:"null"},{native:"неопределено",normalized:"undefined"},{native:"первый",normalized:"first"},{native:"первая",normalized:"first"},{native:"первое",normalized:"first"},{native:"последний",normalized:"last"},{native:"последняя",normalized:"last"},{native:"последнее",normalized:"last"},{native:"следующий",normalized:"next"},{native:"следующая",normalized:"next"},{native:"предыдущий",normalized:"previous"},{native:"предыдущая",normalized:"previous"},{native:"ближайший",normalized:"closest"},{native:"родитель",normalized:"parent"},{native:"клик",normalized:"click"},{native:"нажатие",normalized:"click"},{native:"click",normalized:"click"},{native:"изменение",normalized:"change"},{native:"отправка",normalized:"submit"},{native:"клавиша",normalized:"keydown"},{native:"наведение",normalized:"mouseover"},{native:"уход",normalized:"mouseout"},{native:"загрузка",normalized:"load"},{native:"прокрутка",normalized:"scroll"},{native:"ввод",normalized:"input"},{native:"мой",normalized:"my"},{native:"моя",normalized:"my"},{native:"моё",normalized:"my"},{native:"мои",normalized:"my"},{native:"секунда",normalized:"s"},{native:"секунды",normalized:"s"},{native:"секунд",normalized:"s"},{native:"миллисекунда",normalized:"ms"},{native:"миллисекунды",normalized:"ms"},{native:"миллисекунд",normalized:"ms"},{native:"минута",normalized:"m"},{native:"минуты",normalized:"m"},{native:"минут",normalized:"m"},{native:"час",normalized:"h"},{native:"часа",normalized:"h"},{native:"часов",normalized:"h"},{native:"или",normalized:"or"},{native:"не",normalized:"not"},{native:"есть",normalized:"is"},{native:"существует",normalized:"exists"},{native:"пустой",normalized:"empty"},{native:"пустая",normalized:"empty"},{native:"пустое",normalized:"empty"}],tf=new(ef=class extends Kl{constructor(){super(),this.language="ru",this.direction="ltr",this.initializeKeywordsFromProfile(Vh,Xh),this.normalizer=new Kh}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])||"-"===e[n]&&n+1<e.length&&Wl(e[n+1])){const r=this.extractNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}if(Jh(e[n])){const r=this.extractWord(e,n);if(r){t.push(r),n=r.position.end;continue}}const i=this.tryOperator(e,n);i?(t.push(i),n=i.position.end):n++}return new Ll(t,"ru")}classifyToken(e){const t=e.toLowerCase();return Zh.has(t)?"particle":this.isKeyword(t)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||/^\d/.test(e)?"literal":"identifier"}extractWord(e,t){let n=t,r="";for(;n<e.length&&Yh(e[n]);)r+=e[n++];if(!r)return null;const i=r.toLowerCase();if(Zh.has(i))return Nl(r,"particle",Il(t,n));const a=this.lookupKeyword(i);return a?Nl(r,"keyword",Il(t,n),a.normalized):Nl(r,"identifier",Il(t,n))}extractNumber(e,t){let n=t,r="";for("-"!==e[n]&&"+"!==e[n]||(r+=e[n++]);n<e.length&&Wl(e[n]);)r+=e[n++];if(n<e.length&&"."===e[n])for(r+=e[n++];n<e.length&&Wl(e[n]);)r+=e[n++];let i=n;for(;i<e.length&&Ol(e[i]);)i++;const a=e.slice(i).toLowerCase();return a.startsWith("миллисекунд")||a.startsWith("мс")?a.startsWith("миллисекунд")?(r+="ms",n=i+11,a.length>11&&/[аы]/.test(a[11])&&n++):(r+="ms",n=i+2):a.startsWith("секунд")||a.startsWith("сек")?a.startsWith("секунд")?(r+="s",n=i+6,a.length>6&&/[аы]/.test(a[6])&&n++):(r+="s",n=i+3):a.startsWith("минут")||a.startsWith("мин")?a.startsWith("минут")?(r+="m",n=i+5,a.length>5&&/[аы]/.test(a[5])&&n++):(r+="m",n=i+3):a.startsWith("час")?(r+="h",n=i+3,a.length>3&&"а"===a[3]?n++:a.length>3&&"ов"===a.slice(3,5)&&(n+=2)):a.startsWith("ms")?(r+="ms",n=i+2):a.startsWith("s")&&!a.startsWith("se")&&(r+="s",n=i+1),r&&"-"!==r&&"+"!==r?Nl(r,"literal",Il(t,n)):null}})}}),sf={};yl(sf,{swahiliProfile:()=>af});var lf,cf,uf,pf,mf,df,hf=fl({"src/generators/profiles/swahili.ts"(){af={code:"sw",name:"Swahili",nativeName:"Kiswahili",direction:"ltr",wordOrder:"SVO",markingStrategy:"preposition",usesSpaces:!0,verb:{position:"start",subjectDrop:!0},references:{me:"mimi",it:"hiyo",you:"wewe",result:"matokeo",event:"tukio",target:"lengo",body:"mwili"},possessive:{marker:"",markerPosition:"after-object",usePossessiveAdjectives:!0,specialForms:{me:"yangu",it:"yake",you:"yako"},keywords:{wangu:"me",yangu:"me",langu:"me",changu:"me",wako:"you",yako:"you",lako:"you",chako:"you",wake:"it",yake:"it",lake:"it",chake:"it"}},roleMarkers:{destination:{primary:"kwenye",alternatives:["kwa"],position:"before"},source:{primary:"kutoka",position:"before"},patient:{primary:"",position:"before"},style:{primary:"na",position:"before"}},keywords:{toggle:{primary:"badilisha",alternatives:["geuza"],normalized:"toggle"},add:{primary:"ongeza",alternatives:["weka"],normalized:"add"},remove:{primary:"ondoa",alternatives:["futa","toa"],normalized:"remove"},put:{primary:"weka",alternatives:["tia"],normalized:"put"},append:{primary:"ambatanisha",normalized:"append"},prepend:{primary:"tanguliza",normalized:"prepend"},take:{primary:"chukua",normalized:"take"},make:{primary:"tengeneza",alternatives:["unda"],normalized:"make"},clone:{primary:"nakili",alternatives:["rudufu"],normalized:"clone"},swap:{primary:"badilisha",alternatives:["badalisha"],normalized:"swap"},morph:{primary:"geuza",alternatives:["badilisha umbo"],normalized:"morph"},set:{primary:"seti",alternatives:["weka"],normalized:"set"},get:{primary:"pata",alternatives:["pokea"],normalized:"get"},increment:{primary:"ongezeko",alternatives:["ongeza"],normalized:"increment"},decrement:{primary:"punguza",normalized:"decrement"},log:{primary:"andika",alternatives:["rekodi"],normalized:"log"},show:{primary:"onyesha",normalized:"show"},hide:{primary:"ficha",alternatives:["mficho"],normalized:"hide"},transition:{primary:"hamisha",alternatives:["animisha"],normalized:"transition"},on:{primary:"wakati",alternatives:["kwenye","unapo"],normalized:"on"},trigger:{primary:"chochea",alternatives:["anzisha"],normalized:"trigger"},send:{primary:"tuma",alternatives:["peleka"],normalized:"send"},focus:{primary:"lenga",alternatives:["angazia"],normalized:"focus"},blur:{primary:"blur",normalized:"blur"},go:{primary:"nenda",alternatives:["enda","elekea"],normalized:"go"},wait:{primary:"subiri",alternatives:["ngoja"],normalized:"wait"},fetch:{primary:"leta",alternatives:["pakia"],normalized:"fetch"},settle:{primary:"tulia",alternatives:["imarika"],normalized:"settle"},if:{primary:"kama",alternatives:["ikiwa"],normalized:"if"},when:{primary:"wakati",normalized:"when"},where:{primary:"wapi",normalized:"where"},else:{primary:"vinginevyo",alternatives:["sivyo"],normalized:"else"},repeat:{primary:"rudia",normalized:"repeat"},for:{primary:"kwa",normalized:"for"},while:{primary:"wakati",normalized:"while"},continue:{primary:"endelea",normalized:"continue"},halt:{primary:"simama",alternatives:["acha"],normalized:"halt"},throw:{primary:"tupa",normalized:"throw"},call:{primary:"ita",normalized:"call"},return:{primary:"rudisha",alternatives:["rejea"],normalized:"return"},then:{primary:"kisha",alternatives:["halafu","baadaye"],normalized:"then"},and:{primary:"na",alternatives:["pia","vilevile"],normalized:"and"},end:{primary:"mwisho",alternatives:["maliza","tamati"],normalized:"end"},js:{primary:"js",alternatives:["javascript"],normalized:"js"},async:{primary:"isiyo sawia",normalized:"async"},tell:{primary:"sema",alternatives:["ambia"],normalized:"tell"},default:{primary:"chaguo-msingi",normalized:"default"},init:{primary:"anzisha",alternatives:["anza"],normalized:"init"},behavior:{primary:"tabia",normalized:"behavior"},install:{primary:"sakinisha",alternatives:["weka"],normalized:"install"},measure:{primary:"pima",normalized:"measure"},beep:{primary:"lia",normalized:"beep"},break:{primary:"vunja",normalized:"break"},copy:{primary:"nakili",normalized:"copy"},exit:{primary:"toka",normalized:"exit"},pick:{primary:"chagua",normalized:"pick"},render:{primary:"chora",normalized:"render"},into:{primary:"ndani",normalized:"into"},before:{primary:"kabla",normalized:"before"},after:{primary:"baada",normalized:"after"},until:{primary:"hadi",normalized:"until"},event:{primary:"tukio",normalized:"event"},from:{primary:"kutoka",normalized:"from"}},eventHandler:{keyword:{primary:"wakati",alternatives:["kwenye","kwa"]},sourceMarker:{primary:"kutoka",position:"before"},conditionalKeyword:{primary:"unapo",alternatives:["anapo","tunapo","mnapo","wanapo"]},eventMarker:{primary:"wakati",alternatives:["kwenye","kwa","unapo"],position:"before"}}}}}),ff={};yl(ff,{SwahiliTokenizer:()=>mf,swahiliTokenizer:()=>df});var yf,vf=fl({"src/tokenizers/swahili.ts"(){Jl(),hf(),({isLetter:lf,isIdentifierChar:cf}=_l(/[a-zA-Z]/)),uf=new Set(["kwa","na","katika","kwenye","kutoka","hadi","mpaka","kabla","baada","wakati","bila","kuhusu","karibu","mbele","nyuma","ndani","nje","juu","chini","kati"]),pf=[{native:"kweli",normalized:"true"},{native:"uongo",normalized:"false"},{native:"null",normalized:"null"},{native:"tupu",normalized:"null"},{native:"haijafafanuliwa",normalized:"undefined"},{native:"kwanza",normalized:"first"},{native:"mwisho",normalized:"last"},{native:"inayofuata",normalized:"next"},{native:"iliyopita",normalized:"previous"},{native:"karibu zaidi",normalized:"closest"},{native:"mzazi",normalized:"parent"},{native:"bonyeza",normalized:"click"},{native:"click",normalized:"click"},{native:"ingiza",normalized:"input"},{native:"badiliko",normalized:"change"},{native:"wasilisha",normalized:"submit"},{native:"funguo chini",normalized:"keydown"},{native:"funguo juu",normalized:"keyup"},{native:"kipanya juu",normalized:"mouseover"},{native:"kipanya nje",normalized:"mouseout"},{native:"ukungu",normalized:"blur"},{native:"sogeza",normalized:"scroll"},{native:"yenyewe",normalized:"it"},{native:"wangu",normalized:"my"},{native:"langu",normalized:"my"},{native:"changu",normalized:"my"},{native:"sekunde",normalized:"s"},{native:"milisekunde",normalized:"ms"},{native:"dakika",normalized:"m"},{native:"saa",normalized:"h"},{native:"ondoa lenga",normalized:"blur"},{native:"piga simu",normalized:"call"},{native:"basi",normalized:"then"},{native:"mpaka",normalized:"until"}],df=new(mf=class extends Kl{constructor(){super(),this.language="sw",this.direction="ltr",this.initializeKeywordsFromProfile(af,pf)}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])||"-"===e[n]&&n+1<e.length&&Wl(e[n+1])){const r=this.extractNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}if(lf(e[n])){const r=this.extractWord(e,n);if(r){t.push(r),n=r.position.end;continue}}const i=this.tryOperator(e,n);i?(t.push(i),n=i.position.end):n++}return new Ll(t,"sw")}classifyToken(e){const t=e.toLowerCase();return uf.has(t)?"particle":this.isKeyword(t)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||/^\d/.test(e)?"literal":"identifier"}extractWord(e,t){let n=t,r="";for(;n<e.length&&cf(e[n]);)r+=e[n++];if(!r)return null;const i=r.toLowerCase(),a=this.lookupKeyword(i);return a?Nl(r,"keyword",Il(t,n),a.normalized):uf.has(i)?Nl(r,"particle",Il(t,n)):Nl(r,"identifier",Il(t,n))}extractNumber(e,t){let n=t,r="";for("-"!==e[n]&&"+"!==e[n]||(r+=e[n++]);n<e.length&&Wl(e[n]);)r+=e[n++];if(n<e.length&&"."===e[n])for(r+=e[n++];n<e.length&&Wl(e[n]);)r+=e[n++];let i=n;for(;i<e.length&&Ol(e[i]);)i++;const a=e.slice(i).toLowerCase();return a.startsWith("milisekunde")?(r+="ms",n=i+11):a.startsWith("sekunde")?(r+="s",n=i+7):a.startsWith("dakika")?(r+="m",n=i+6):a.startsWith("saa")&&(r+="h",n=i+3),r&&"-"!==r&&"+"!==r?Nl(r,"literal",Il(t,n)):null}})}}),gf={};yl(gf,{thaiProfile:()=>yf});var bf,kf,wf,zf,xf=fl({"src/generators/profiles/thai.ts"(){yf={code:"th",name:"Thai",nativeName:"ไทย",direction:"ltr",wordOrder:"SVO",markingStrategy:"preposition",usesSpaces:!1,defaultVerbForm:"base",verb:{position:"second",subjectDrop:!0},references:{me:"ฉัน",it:"มัน",you:"คุณ",result:"ผลลัพธ์",event:"เหตุการณ์",target:"เป้าหมาย",body:"บอดี้"},possessive:{marker:"ของ",markerPosition:"between",keywords:{"ของฉัน":"me","ของผม":"me","ของคุณ":"you","ของมัน":"it","ของเขา":"it","ของเธอ":"it"}},roleMarkers:{patient:{primary:"",position:"before"},destination:{primary:"ใน",alternatives:["ไปยัง"],position:"before"},source:{primary:"จาก",position:"before"},style:{primary:"ด้วย",position:"before"},event:{primary:"เมื่อ",position:"before"}},keywords:{toggle:{primary:"สลับ",alternatives:[],normalized:"toggle"},add:{primary:"เพิ่ม",alternatives:[],normalized:"add"},remove:{primary:"ลบ",alternatives:["ลบออก"],normalized:"remove"},put:{primary:"ใส่",alternatives:["วาง"],normalized:"put"},append:{primary:"เพิ่มท้าย",alternatives:[],normalized:"append"},prepend:{primary:"เพิ่มหน้า",alternatives:[],normalized:"prepend"},take:{primary:"รับ",alternatives:[],normalized:"take"},make:{primary:"สร้าง",alternatives:[],normalized:"make"},clone:{primary:"คัดลอก",alternatives:["สำเนา"],normalized:"clone"},swap:{primary:"สลับที่",alternatives:[],normalized:"swap"},morph:{primary:"แปลงร่าง",alternatives:[],normalized:"morph"},set:{primary:"ตั้ง",alternatives:["กำหนด"],normalized:"set"},get:{primary:"รับค่า",alternatives:[],normalized:"get"},increment:{primary:"เพิ่มค่า",alternatives:[],normalized:"increment"},decrement:{primary:"ลดค่า",alternatives:[],normalized:"decrement"},log:{primary:"บันทึก",alternatives:[],normalized:"log"},show:{primary:"แสดง",alternatives:[],normalized:"show"},hide:{primary:"ซ่อน",alternatives:[],normalized:"hide"},transition:{primary:"เปลี่ยน",alternatives:[],normalized:"transition"},on:{primary:"เมื่อ",alternatives:["ตอน"],normalized:"on"},trigger:{primary:"ทริกเกอร์",alternatives:[],normalized:"trigger"},send:{primary:"ส่ง",alternatives:[],normalized:"send"},focus:{primary:"โฟกัส",alternatives:[],normalized:"focus"},blur:{primary:"เบลอ",alternatives:[],normalized:"blur"},click:{primary:"คลิก",normalized:"click"},hover:{primary:"โฮเวอร์",alternatives:["วางเมาส์"],normalized:"hover"},submit:{primary:"ส่ง",alternatives:["ส่งข้อมูล"],normalized:"submit"},input:{primary:"ป้อน",alternatives:["กรอก"],normalized:"input"},change:{primary:"เปลี่ยน",alternatives:["เปลี่ยนแปลง"],normalized:"change"},go:{primary:"ไป",alternatives:["ไปที่"],normalized:"go"},wait:{primary:"รอ",alternatives:[],normalized:"wait"},fetch:{primary:"ดึงข้อมูล",alternatives:[],normalized:"fetch"},settle:{primary:"คงที่",alternatives:[],normalized:"settle"},if:{primary:"ถ้า",alternatives:["หาก"],normalized:"if"},when:{primary:"เมื่อ",normalized:"when"},where:{primary:"ที่ไหน",normalized:"where"},else:{primary:"ไม่งั้น",alternatives:["ไม่เช่นนั้น"],normalized:"else"},repeat:{primary:"ทำซ้ำ",alternatives:[],normalized:"repeat"},for:{primary:"สำหรับ",alternatives:[],normalized:"for"},while:{primary:"ในขณะที่",alternatives:[],normalized:"while"},continue:{primary:"ต่อไป",alternatives:[],normalized:"continue"},halt:{primary:"หยุด",alternatives:[],normalized:"halt"},throw:{primary:"โยน",alternatives:[],normalized:"throw"},call:{primary:"เรียก",alternatives:[],normalized:"call"},return:{primary:"คืนค่า",alternatives:["กลับ"],normalized:"return"},then:{primary:"แล้ว",alternatives:[],normalized:"then"},and:{primary:"และ",alternatives:[],normalized:"and"},end:{primary:"จบ",alternatives:[],normalized:"end"},js:{primary:"เจเอส",alternatives:["js"],normalized:"js"},async:{primary:"อะซิงค์",alternatives:[],normalized:"async"},tell:{primary:"บอก",alternatives:[],normalized:"tell"},default:{primary:"ค่าเริ่มต้น",alternatives:[],normalized:"default"},init:{primary:"เริ่มต้น",alternatives:[],normalized:"init"},behavior:{primary:"พฤติกรรม",alternatives:[],normalized:"behavior"},install:{primary:"ติดตั้ง",alternatives:[],normalized:"install"},measure:{primary:"วัด",alternatives:[],normalized:"measure"},beep:{primary:"บี๊บ",alternatives:[],normalized:"beep"},break:{primary:"หยุด",alternatives:[],normalized:"break"},copy:{primary:"คัดลอก",alternatives:[],normalized:"copy"},exit:{primary:"ออก",alternatives:[],normalized:"exit"},pick:{primary:"เลือก",alternatives:[],normalized:"pick"},render:{primary:"แสดงผล",alternatives:[],normalized:"render"},into:{primary:"ใน",alternatives:[],normalized:"into"},before:{primary:"ก่อน",alternatives:[],normalized:"before"},after:{primary:"หลัง",alternatives:[],normalized:"after"},until:{primary:"จนถึง",alternatives:[],normalized:"until"},event:{primary:"เหตุการณ์",alternatives:[],normalized:"event"},from:{primary:"จาก",normalized:"from"}},tokenization:{boundaryStrategy:"character"},eventHandler:{keyword:{primary:"เมื่อ",alternatives:["ตอน"],normalized:"on"},sourceMarker:{primary:"จาก",position:"before"},eventMarker:{primary:"เมื่อ",alternatives:["ตอน"],position:"before"},temporalMarkers:["เมื่อ","ตอน"]}}}}),Ef={};yl(Ef,{ThaiTokenizer:()=>wf,thaiTokenizer:()=>zf});var Sf,Tf=fl({"src/tokenizers/thai.ts"(){Jl(),xf(),bf=ql([[3584,3711]]),kf=[{native:"จริง",normalized:"true"},{native:"เท็จ",normalized:"false"},{native:"ว่าง",normalized:"null"},{native:"ไม่กำหนด",normalized:"undefined"},{native:"แรก",normalized:"first"},{native:"สุดท้าย",normalized:"last"},{native:"ถัดไป",normalized:"next"},{native:"ก่อนหน้า",normalized:"previous"},{native:"ใกล้สุด",normalized:"closest"},{native:"ต้นทาง",normalized:"parent"},{native:"คลิก",normalized:"click"},{native:"เปลี่ยนแปลง",normalized:"change"},{native:"ส่ง",normalized:"submit"},{native:"อินพุต",normalized:"input"},{native:"โหลด",normalized:"load"},{native:"เลื่อน",normalized:"scroll"},{native:"เวลา",normalized:"when"},{native:"ไปยัง",normalized:"to"},{native:"ด้วย",normalized:"with"},{native:"และ",normalized:"and"}],zf=new(wf=class extends Kl{constructor(){super(),this.language="th",this.direction="ltr",this.initializeKeywordsFromProfile(yf,kf)}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])||"-"===e[n]&&n+1<e.length&&Wl(e[n+1])){const r=this.tryNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}if(":"===e[n]){const r=n;n++;let i="";for(;n<e.length&&($l(e[n])||bf(e[n]));)i+=e[n],n++;if(i){t.push(Nl(":"+i,"identifier",Il(r,n),":"+i));continue}n=r}if(bf(e[n])){const r=n,i=this.tryProfileKeyword(e,n);if(i){t.push(i),n=i.position.end;continue}let a="";for(;n<e.length&&bf(e[n])&&!(a.length>0&&this.isKeywordStart(e,n));)a+=e[n],n++;a&&t.push(Nl(a,"identifier",Il(r,n)));continue}if($l(e[n])){const r=n;let i="";for(;n<e.length&&$l(e[n]);)i+=e[n],n++;t.push(Nl(i,"identifier",Il(r,n),i.toLowerCase()));continue}const r=n;t.push(Nl(e[n],"operator",Il(r,n+1))),n++}return new Ll(t,this.language)}classifyToken(e){return this.isKeyword(e)?"keyword":e.startsWith(".")||e.startsWith("#")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith(":")?"identifier":e.startsWith('"')||e.startsWith("'")||/^-?\d/.test(e)?"literal":"identifier"}})}}),Cf={};yl(Cf,{tagalogProfile:()=>Sf});var Af,jf,Lf,Pf=fl({"src/generators/profiles/tl.ts"(){Sf={code:"tl",name:"Tagalog",nativeName:"Tagalog",direction:"ltr",wordOrder:"VSO",markingStrategy:"preposition",usesSpaces:!0,defaultVerbForm:"base",verb:{position:"start",subjectDrop:!0},references:{me:"ako",it:"ito",you:"ikaw",result:"resulta",event:"pangyayari",target:"target",body:"body"},possessive:{marker:"ng",markerPosition:"between",keywords:{ko:"me",akin:"me",aking:"me",mo:"you",iyo:"you",niya:"it",nito:"it",kaniya:"it"}},roleMarkers:{destination:{primary:"sa",position:"before"},source:{primary:"mula_sa",position:"before"},patient:{primary:"",position:"before"},style:{primary:"nang",position:"before"}},keywords:{toggle:{primary:"palitan",alternatives:["itoggle"],normalized:"toggle"},add:{primary:"idagdag",alternatives:["magdagdag"],normalized:"add"},remove:{primary:"alisin",alternatives:["tanggalin"],normalized:"remove"},put:{primary:"ilagay",alternatives:["maglagay"],normalized:"put"},append:{primary:"idagdag_sa_dulo",normalized:"append"},prepend:{primary:"idagdag_sa_simula",normalized:"prepend"},take:{primary:"kumuha",normalized:"take"},make:{primary:"gumawa",alternatives:["lumikha"],normalized:"make"},clone:{primary:"kopyahin",normalized:"clone"},swap:{primary:"palitan_pwesto",alternatives:["magpalit"],normalized:"swap"},morph:{primary:"baguhin",normalized:"morph"},set:{primary:"itakda",alternatives:["magtakda"],normalized:"set"},get:{primary:"kunin",alternatives:["kumuha"],normalized:"get"},increment:{primary:"dagdagan",alternatives:["taasan"],normalized:"increment"},decrement:{primary:"bawasan",alternatives:["ibaba"],normalized:"decrement"},log:{primary:"itala",normalized:"log"},show:{primary:"ipakita",alternatives:["magpakita"],normalized:"show"},hide:{primary:"itago",alternatives:["magtago"],normalized:"hide"},transition:{primary:"baguhin",alternatives:["lumipat"],normalized:"transition"},on:{primary:"kapag",alternatives:["kung","sa"],normalized:"on"},trigger:{primary:"palitawin",alternatives:["magpatugtog"],normalized:"trigger"},send:{primary:"ipadala",alternatives:["magpadala"],normalized:"send"},focus:{primary:"ituon",normalized:"focus"},blur:{primary:"alisin_tuon",normalized:"blur"},go:{primary:"pumunta",alternatives:["punta"],normalized:"go"},wait:{primary:"maghintay",alternatives:["hintay"],normalized:"wait"},fetch:{primary:"kuhanin_mula",alternatives:["kunin_mula"],normalized:"fetch"},settle:{primary:"magpatahimik",normalized:"settle"},if:{primary:"kung",alternatives:["kapag"],normalized:"if"},when:{primary:"kapag",normalized:"when"},where:{primary:"kung_saan",normalized:"where"},else:{primary:"kung_hindi",alternatives:["kundi"],normalized:"else"},repeat:{primary:"ulitin",alternatives:["paulit-ulit"],normalized:"repeat"},for:{primary:"para_sa",normalized:"for"},while:{primary:"habang",normalized:"while"},continue:{primary:"magpatuloy",normalized:"continue"},halt:{primary:"itigil",alternatives:["huminto"],normalized:"halt"},throw:{primary:"ihagis",alternatives:["itapon"],normalized:"throw"},call:{primary:"tawagin",alternatives:["tawagan","tumawag"],normalized:"call"},return:{primary:"ibalik",alternatives:["bumalik"],normalized:"return"},then:{primary:"pagkatapos",alternatives:["saka"],normalized:"then"},and:{primary:"at",normalized:"and"},end:{primary:"wakas",alternatives:["tapos"],normalized:"end"},js:{primary:"js",normalized:"js"},async:{primary:"async",normalized:"async"},tell:{primary:"sabihin",alternatives:["magsabi"],normalized:"tell"},default:{primary:"pamantayan",alternatives:["default","unang_halaga"],normalized:"default"},init:{primary:"simulan",alternatives:["magsimula"],normalized:"init"},behavior:{primary:"ugali",alternatives:["kilos"],normalized:"behavior"},install:{primary:"ikabit",alternatives:["mag-install"],normalized:"install"},measure:{primary:"sukatin",normalized:"measure"},beep:{primary:"tunog",normalized:"beep"},break:{primary:"itigil",normalized:"break"},copy:{primary:"kopyahin",normalized:"copy"},exit:{primary:"lumabas",normalized:"exit"},pick:{primary:"pumili",normalized:"pick"},render:{primary:"ipakita",normalized:"render"},into:{primary:"sa",normalized:"into"},before:{primary:"bago",normalized:"before"},after:{primary:"matapos",alternatives:["pagkatapos"],normalized:"after"},until:{primary:"hanggang",normalized:"until"},event:{primary:"pangyayari",normalized:"event"},from:{primary:"mula",alternatives:["galing"],normalized:"from"}},eventHandler:{keyword:{primary:"kapag",normalized:"on"},sourceMarker:{primary:"mula_sa",alternatives:["galing_sa"],position:"before"},eventMarker:{primary:"kapag",alternatives:["kung","sa"],position:"before"}}}}}),If={};yl(If,{TagalogTokenizer:()=>jf,tagalogTokenizer:()=>Lf});var Nf,Of,Rf=fl({"src/tokenizers/tl.ts"(){Jl(),Pf(),Af=[{native:"totoo",normalized:"true"},{native:"mali",normalized:"false"},{native:"wala",normalized:"null"},{native:"hindi_tinukoy",normalized:"undefined"},{native:"una",normalized:"first"},{native:"huli",normalized:"last"},{native:"susunod",normalized:"next"},{native:"nakaraan",normalized:"previous"},{native:"pinakamalapit",normalized:"closest"},{native:"magulang",normalized:"parent"},{native:"pindot",normalized:"click"},{native:"pagbabago",normalized:"change"},{native:"isumite",normalized:"submit"},{native:"input",normalized:"input"},{native:"karga",normalized:"load"},{native:"mag_scroll",normalized:"scroll"}],Lf=new(jf=class extends Kl{constructor(){super(),this.language="tl",this.direction="ltr",this.initializeKeywordsFromProfile(Sf,Af)}tokenize(e){const t=[];let n=0;for(;n<e.length;)if(Ol(e[n]))n++;else{if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])||"-"===e[n]&&n+1<e.length&&Wl(e[n+1])){const r=this.tryNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(":"===e[n]){const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}}if("()[]{}:,;".includes(e[n]))t.push(Nl(e[n],"operator",Il(n,n+1))),n++;else{if($l(e[n])){const r=n,i=this.tryProfileKeyword(e,n);if(i){t.push(i),n=i.position.end;continue}let a="";for(;n<e.length&&$l(e[n]);)a+=e[n],n++;a&&t.push(Nl(a,"identifier",Il(r,n)));continue}n++}}return new Ll(t,"tl")}classifyToken(e){return this.isKeyword(e)?"keyword":e.startsWith(".")||e.startsWith("#")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith(":")?"identifier":e.startsWith('"')||e.startsWith("'")||/^-?\d/.test(e)?"literal":"identifier"}})}});function Mf(e){const t=e.charCodeAt(0);if(t>=65&&t<=90||t>=97&&t<=122)return!0;return"çÇğĞıİöÖşŞüÜ".includes(e)}function Wf(e){return"aıouAIOU".includes(e)}function $f(e){return"eiöüEİÖÜ".includes(e)}function Hf(e){return Wf(e)||$f(e)}function qf(e,t){const n=function(e){for(let t=e.length-1;t>=0;t--)if(Hf(e[t]))return e[t];return null}(e);if(!n)return!0;const r=t.split("").find(e=>Hf(e));return!r||(Wf(n)?Wf(r):$f(r))}var Df,_f=fl({"src/tokenizers/morphology/turkish-normalizer.ts"(){ic(),Nf=[{pattern:"iyorsunuz",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"ıyorsunuz",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"üyorsunuz",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"uyorsunuz",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"iyorsun",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"ıyorsun",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"üyorsun",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"uyorsun",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"iyoruz",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"ıyoruz",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"üyoruz",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"uyoruz",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"iyorum",confidence:.85,conjugationType:"progressive",minStemLength:2},{pattern:"ıyorum",confidence:.85,conjugationType:"progressive",minStemLength:2},{pattern:"üyorum",confidence:.85,conjugationType:"progressive",minStemLength:2},{pattern:"uyorum",confidence:.85,conjugationType:"progressive",minStemLength:2},{pattern:"iyorlar",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"ıyorlar",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"üyorlar",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"uyorlar",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"eceksiniz",confidence:.82,conjugationType:"future",minStemLength:2},{pattern:"acaksınız",confidence:.82,conjugationType:"future",minStemLength:2},{pattern:"eceksin",confidence:.82,conjugationType:"future",minStemLength:2},{pattern:"acaksın",confidence:.82,conjugationType:"future",minStemLength:2},{pattern:"eceğiz",confidence:.82,conjugationType:"future",minStemLength:2},{pattern:"acağız",confidence:.82,conjugationType:"future",minStemLength:2},{pattern:"eceğim",confidence:.85,conjugationType:"future",minStemLength:2},{pattern:"acağım",confidence:.85,conjugationType:"future",minStemLength:2},{pattern:"ecekler",confidence:.82,conjugationType:"future",minStemLength:2},{pattern:"acaklar",confidence:.82,conjugationType:"future",minStemLength:2},{pattern:"mişsiniz",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"mışsınız",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"müşsünüz",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"muşsunuz",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"mişsin",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"mışsın",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"müşsün",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"muşsun",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"mişiz",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"mışız",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"müşüz",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"muşuz",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"mişim",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"mışım",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"müşüm",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"muşum",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"mişler",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"mışlar",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"müşler",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"muşlar",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"diniz",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"dınız",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"dünüz",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"dunuz",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"tiniz",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"tınız",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"tünüz",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"tunuz",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"diler",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"dılar",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"düler",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"dular",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"tiler",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"tılar",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"tüler",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"tular",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"din",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"dın",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"dün",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"dun",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"tin",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"tın",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"tün",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"tun",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"dik",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"dık",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"dük",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"duk",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"tik",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"tık",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"tük",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"tuk",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"dim",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"dım",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"düm",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"dum",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"tim",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"tım",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"tüm",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"tum",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"iyor",confidence:.85,conjugationType:"progressive",minStemLength:2},{pattern:"ıyor",confidence:.85,conjugationType:"progressive",minStemLength:2},{pattern:"üyor",confidence:.85,conjugationType:"progressive",minStemLength:2},{pattern:"uyor",confidence:.85,conjugationType:"progressive",minStemLength:2},{pattern:"ecek",confidence:.85,conjugationType:"future",minStemLength:2},{pattern:"acak",confidence:.85,conjugationType:"future",minStemLength:2},{pattern:"miş",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"mış",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"müş",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"muş",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"di",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"dı",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"dü",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"du",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"ti",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"tı",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"tü",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"tu",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"mek",confidence:.88,conjugationType:"dictionary",minStemLength:2},{pattern:"mak",confidence:.88,conjugationType:"dictionary",minStemLength:2},{pattern:"eyelim",confidence:.82,conjugationType:"optative",minStemLength:2},{pattern:"ayalım",confidence:.82,conjugationType:"optative",minStemLength:2},{pattern:"eyim",confidence:.82,conjugationType:"optative",minStemLength:2},{pattern:"ayım",confidence:.82,conjugationType:"optative",minStemLength:2},{pattern:"elim",confidence:.82,conjugationType:"optative",minStemLength:2},{pattern:"alım",confidence:.82,conjugationType:"optative",minStemLength:2},{pattern:"melisiniz",confidence:.82,conjugationType:"necessitative",minStemLength:2},{pattern:"malısınız",confidence:.82,conjugationType:"necessitative",minStemLength:2},{pattern:"melisin",confidence:.82,conjugationType:"necessitative",minStemLength:2},{pattern:"malısın",confidence:.82,conjugationType:"necessitative",minStemLength:2},{pattern:"meliyiz",confidence:.82,conjugationType:"necessitative",minStemLength:2},{pattern:"malıyız",confidence:.82,conjugationType:"necessitative",minStemLength:2},{pattern:"meliyim",confidence:.85,conjugationType:"necessitative",minStemLength:2},{pattern:"malıyım",confidence:.85,conjugationType:"necessitative",minStemLength:2},{pattern:"meliler",confidence:.82,conjugationType:"necessitative",minStemLength:2},{pattern:"malılar",confidence:.82,conjugationType:"necessitative",minStemLength:2},{pattern:"meli",confidence:.85,conjugationType:"necessitative",minStemLength:2},{pattern:"malı",confidence:.85,conjugationType:"necessitative",minStemLength:2},{pattern:"ebiliyor",confidence:.82,conjugationType:"potential",minStemLength:2},{pattern:"abiliyor",confidence:.82,conjugationType:"potential",minStemLength:2},{pattern:"ebilir",confidence:.85,conjugationType:"potential",minStemLength:2},{pattern:"abilir",confidence:.85,conjugationType:"potential",minStemLength:2},{pattern:"ebildi",confidence:.82,conjugationType:"potential",minStemLength:2},{pattern:"abildi",confidence:.82,conjugationType:"potential",minStemLength:2},{pattern:"ebilmek",confidence:.85,conjugationType:"potential",minStemLength:2},{pattern:"abilmek",confidence:.85,conjugationType:"potential",minStemLength:2},{pattern:"iniz",confidence:.82,conjugationType:"imperative",minStemLength:2},{pattern:"ınız",confidence:.82,conjugationType:"imperative",minStemLength:2},{pattern:"ünüz",confidence:.82,conjugationType:"imperative",minStemLength:2},{pattern:"unuz",confidence:.82,conjugationType:"imperative",minStemLength:2},{pattern:"in",confidence:.8,conjugationType:"imperative",minStemLength:2},{pattern:"ın",confidence:.8,conjugationType:"imperative",minStemLength:2},{pattern:"ün",confidence:.8,conjugationType:"imperative",minStemLength:2},{pattern:"un",confidence:.8,conjugationType:"imperative",minStemLength:2},{pattern:"ildi",confidence:.82,conjugationType:"passive",minStemLength:2},{pattern:"ıldı",confidence:.82,conjugationType:"passive",minStemLength:2},{pattern:"üldü",confidence:.82,conjugationType:"passive",minStemLength:2},{pattern:"uldu",confidence:.82,conjugationType:"passive",minStemLength:2},{pattern:"ilir",confidence:.82,conjugationType:"passive",minStemLength:2},{pattern:"ılır",confidence:.82,conjugationType:"passive",minStemLength:2},{pattern:"ülür",confidence:.82,conjugationType:"passive",minStemLength:2},{pattern:"ulur",confidence:.82,conjugationType:"passive",minStemLength:2},{pattern:"tirmek",confidence:.82,conjugationType:"causative",minStemLength:2},{pattern:"tırmak",confidence:.82,conjugationType:"causative",minStemLength:2},{pattern:"türmek",confidence:.82,conjugationType:"causative",minStemLength:2},{pattern:"turmak",confidence:.82,conjugationType:"causative",minStemLength:2},{pattern:"dirmek",confidence:.82,conjugationType:"causative",minStemLength:2},{pattern:"dırmak",confidence:.82,conjugationType:"causative",minStemLength:2},{pattern:"dürmek",confidence:.82,conjugationType:"causative",minStemLength:2},{pattern:"durmak",confidence:.82,conjugationType:"causative",minStemLength:2},{pattern:"miyorsunuz",confidence:.8,conjugationType:"negative",minStemLength:2},{pattern:"mıyorsunuz",confidence:.8,conjugationType:"negative",minStemLength:2},{pattern:"müyorsunuz",confidence:.8,conjugationType:"negative",minStemLength:2},{pattern:"muyorsunuz",confidence:.8,conjugationType:"negative",minStemLength:2},{pattern:"miyorsun",confidence:.8,conjugationType:"negative",minStemLength:2},{pattern:"mıyorsun",confidence:.8,conjugationType:"negative",minStemLength:2},{pattern:"müyorsun",confidence:.8,conjugationType:"negative",minStemLength:2},{pattern:"muyorsun",confidence:.8,conjugationType:"negative",minStemLength:2},{pattern:"miyoruz",confidence:.8,conjugationType:"negative",minStemLength:2},{pattern:"mıyoruz",confidence:.8,conjugationType:"negative",minStemLength:2},{pattern:"müyoruz",confidence:.8,conjugationType:"negative",minStemLength:2},{pattern:"muyoruz",confidence:.8,conjugationType:"negative",minStemLength:2},{pattern:"miyorum",confidence:.82,conjugationType:"negative",minStemLength:2},{pattern:"mıyorum",confidence:.82,conjugationType:"negative",minStemLength:2},{pattern:"müyorum",confidence:.82,conjugationType:"negative",minStemLength:2},{pattern:"muyorum",confidence:.82,conjugationType:"negative",minStemLength:2},{pattern:"miyor",confidence:.82,conjugationType:"negative",minStemLength:2},{pattern:"mıyor",confidence:.82,conjugationType:"negative",minStemLength:2},{pattern:"müyor",confidence:.82,conjugationType:"negative",minStemLength:2},{pattern:"muyor",confidence:.82,conjugationType:"negative",minStemLength:2},{pattern:"medi",confidence:.82,conjugationType:"negative",minStemLength:2},{pattern:"madı",confidence:.82,conjugationType:"negative",minStemLength:2},{pattern:"me",confidence:.75,conjugationType:"negative",minStemLength:3},{pattern:"ma",confidence:.75,conjugationType:"negative",minStemLength:3}],new(Of=class{constructor(){this.language="tr"}isNormalizable(e){return!!function(e){for(const t of e)if(Mf(t))return!0;return!1}(e)&&!(e.length<3)}normalize(e){const t=e.toLowerCase();for(const e of Nf)if(t.endsWith(e.pattern)){const n=t.slice(0,-e.pattern.length),r=e.minStemLength??2;if(n.length<r)continue;if(!qf(n,e.pattern)){const t=.9*e.confidence,r={removedSuffixes:[e.pattern]};return e.conjugationType&&(r.conjugationType=e.conjugationType),Zl(n,t,r)}const i={removedSuffixes:[e.pattern]};return e.conjugationType&&(i.conjugationType=e.conjugationType),Zl(n,e.confidence,i)}return Yl(e)}})}}),Vf={};yl(Vf,{turkishProfile:()=>Df});var Bf,Ff,Uf,Kf,Gf,Qf,Jf,Yf=fl({"src/generators/profiles/turkish.ts"(){Df={code:"tr",name:"Turkish",nativeName:"Türkçe",direction:"ltr",wordOrder:"SOV",markingStrategy:"case-suffix",usesSpaces:!0,verb:{position:"end",suffixes:["mek","mak","yor","di","miş"],subjectDrop:!0},references:{me:"ben",it:"o",you:"sen",result:"sonuç",event:"olay",target:"hedef",body:"gövde"},possessive:{marker:"",markerPosition:"after-object",usePossessiveAdjectives:!0,specialForms:{me:"benim",it:"onun",you:"senin"},keywords:{benim:"me",senin:"you",onun:"it"}},roleMarkers:{patient:{primary:"i",alternatives:["ı","u","ü","yi","yı","yu","yü","ni","nı","nu","nü"],position:"after"},destination:{primary:"e",alternatives:["a","ye","ya","ne","na","de","da","te","ta","ın","in","un","ün","nın","nin","nun","nün"],position:"after"},source:{primary:"den",alternatives:["dan","ten","tan"],position:"after"},style:{primary:"le",alternatives:["la","yle","yla"],position:"after"},event:{primary:"i",alternatives:["ı","u","ü"],position:"after"}},keywords:{toggle:{primary:"değiştir",alternatives:["aç/kapat"],normalized:"toggle"},add:{primary:"ekle",normalized:"add"},remove:{primary:"kaldır",alternatives:["sil"],normalized:"remove"},put:{primary:"koy",normalized:"put"},append:{primary:"ekle",normalized:"append"},take:{primary:"tut",normalized:"take"},make:{primary:"yap",normalized:"make"},clone:{primary:"kopyala",normalized:"clone"},swap:{primary:"takas",normalized:"swap"},morph:{primary:"dönüştür",alternatives:["şekil değiştir"],normalized:"morph"},set:{primary:"ayarla",alternatives:["yap","belirle"],normalized:"set"},get:{primary:"al",normalized:"get"},increment:{primary:"artır",normalized:"increment"},decrement:{primary:"azalt",normalized:"decrement"},log:{primary:"kaydet",normalized:"log"},show:{primary:"göster",normalized:"show"},hide:{primary:"gizle",normalized:"hide"},transition:{primary:"geçiş",normalized:"transition"},on:{primary:"üzerinde",alternatives:["olduğunda","zaman"],normalized:"on"},trigger:{primary:"tetikle",normalized:"trigger"},send:{primary:"gönder",normalized:"send"},focus:{primary:"odak",alternatives:["odaklanma"],normalized:"focus"},blur:{primary:"bulanık",alternatives:["bulanıklık"],normalized:"blur"},click:{primary:"tıklama",alternatives:["tıkla"],normalized:"click"},hover:{primary:"üzerine gelme",alternatives:["üzerinde gezinme"],normalized:"hover"},submit:{primary:"gönderme",alternatives:["gönder"],normalized:"submit"},input:{primary:"giriş",alternatives:["girdi"],normalized:"input"},change:{primary:"değişiklik",alternatives:["değişim"],normalized:"change"},go:{primary:"git",normalized:"go"},wait:{primary:"bekle",normalized:"wait"},fetch:{primary:"getir",normalized:"fetch"},settle:{primary:"sabitlen",normalized:"settle"},if:{primary:"eğer",normalized:"if"},when:{primary:"iken",alternatives:["durumunda","olduğunda"],normalized:"when"},where:{primary:"nerede",normalized:"where"},else:{primary:"yoksa",normalized:"else"},repeat:{primary:"tekrarla",normalized:"repeat"},for:{primary:"için",normalized:"for"},while:{primary:"iken",normalized:"while"},continue:{primary:"devam",normalized:"continue"},halt:{primary:"durdur",normalized:"halt"},throw:{primary:"fırlat",normalized:"throw"},call:{primary:"çağır",normalized:"call"},return:{primary:"dön",normalized:"return"},then:{primary:"sonra",alternatives:["ardından","daha sonra"],normalized:"then"},and:{primary:"ve",alternatives:["ayrıca","hem de"],normalized:"and"},end:{primary:"son",alternatives:["bitiş","bitti"],normalized:"end"},js:{primary:"js",normalized:"js"},async:{primary:"asenkron",normalized:"async"},tell:{primary:"söyle",normalized:"tell"},default:{primary:"varsayılan",normalized:"default"},init:{primary:"başlat",normalized:"init"},behavior:{primary:"davranış",normalized:"behavior"},install:{primary:"yükle",alternatives:["kur","yüklemek"],normalized:"install"},measure:{primary:"ölç",normalized:"measure"},beep:{primary:"bip",normalized:"beep"},break:{primary:"dur",normalized:"break"},copy:{primary:"kopyala",normalized:"copy"},exit:{primary:"çık",normalized:"exit"},pick:{primary:"seç",normalized:"pick"},render:{primary:"render",normalized:"render"},into:{primary:"içine",normalized:"into"},before:{primary:"önce",normalized:"before"},after:{primary:"sonra",normalized:"after"},until:{primary:"kadar",normalized:"until"},event:{primary:"olay",normalized:"event"},from:{primary:"den",alternatives:["dan"],normalized:"from"}},eventHandler:{eventMarker:{primary:"da",alternatives:["de","ta","te"],position:"after"},temporalMarkers:["dığında","diğinde"]}}}}),Zf={};yl(Zf,{TurkishTokenizer:()=>Qf,turkishTokenizer:()=>Jf});var Xf,ey=fl({"src/tokenizers/turkish.ts"(){Jl(),_f(),Yf(),({isLetter:Bf}=_l(/[a-zA-ZçÇğĞıİöÖşŞüÜ]/)),Ff=new Set(["ile","için","kadar","gibi","önce","üzerinde","altında","içinde","dışında","arasında","karşı","göre","rağmen","doğru","boyunca"]),Uf=new Set(["de","da","te","ta","den","dan","ten","tan","e","a","ye","ya","i","ı","u","ü","in","ın","un","ün","le","la","yle","yla"]),Kf=[{native:"doğru",normalized:"true"},{native:"dogru",normalized:"true"},{native:"yanlış",normalized:"false"},{native:"yanlis",normalized:"false"},{native:"null",normalized:"null"},{native:"boş",normalized:"null"},{native:"bos",normalized:"null"},{native:"tanımsız",normalized:"undefined"},{native:"tanimsiz",normalized:"undefined"},{native:"ilk",normalized:"first"},{native:"son",normalized:"last"},{native:"sonraki",normalized:"next"},{native:"önceki",normalized:"previous"},{native:"onceki",normalized:"previous"},{native:"en_yakın",normalized:"closest"},{native:"en_yakin",normalized:"closest"},{native:"ebeveyn",normalized:"parent"},{native:"tıklama",normalized:"click"},{native:"tiklama",normalized:"click"},{native:"tık",normalized:"click"},{native:"tik",normalized:"click"},{native:"giriş",normalized:"input"},{native:"giris",normalized:"input"},{native:"değişim",normalized:"change"},{native:"degisim",normalized:"change"},{native:"odak",normalized:"focus"},{native:"bulanık",normalized:"blur"},{native:"bulanik",normalized:"blur"},{native:"fare üzerinde",normalized:"mouseover"},{native:"fare uzerinde",normalized:"mouseover"},{native:"fare dışında",normalized:"mouseout"},{native:"fare disinda",normalized:"mouseout"},{native:"kaydır",normalized:"scroll"},{native:"kaydir",normalized:"scroll"},{native:"tuş_bas",normalized:"keydown"},{native:"tus_bas",normalized:"keydown"},{native:"tuş_bırak",normalized:"keyup"},{native:"tus_birak",normalized:"keyup"},{native:"benim",normalized:"my"},{native:"onun",normalized:"its"},{native:"saniye",normalized:"s"},{native:"milisaniye",normalized:"ms"},{native:"dakika",normalized:"m"},{native:"saat",normalized:"h"},{native:"sonra",normalized:"then"},{native:"ardından",normalized:"then"},{native:"ardindan",normalized:"then"},{native:"daha sonra",normalized:"then"},{native:"ve",normalized:"and"},{native:"veya",normalized:"or"},{native:"değil",normalized:"not"},{native:"degil",normalized:"not"}],Gf=[{pattern:"milisaniye",suffix:"ms",length:10,caseInsensitive:!0},{pattern:"dakika",suffix:"m",length:6,caseInsensitive:!0},{pattern:"saniye",suffix:"s",length:6,caseInsensitive:!0},{pattern:"saat",suffix:"h",length:4,caseInsensitive:!0},{pattern:"dk",suffix:"m",length:2,checkBoundary:!0},{pattern:"sa",suffix:"h",length:2,checkBoundary:!0}],Jf=new(Qf=class extends Kl{constructor(){super(),this.language="tr",this.direction="ltr",this.initializeKeywordsFromProfile(Df,Kf),this.normalizer=new Of}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])){const r=this.extractTurkishNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}const i=this.tryMultiWordPhrase(e,n);if(i)t.push(i),n=i.position.end;else{if(Bf(e[n])){const r=this.extractTurkishWord(e,n);if(r){t.push(r),n=r.position.end;continue}}n++}}return new Ll(t,"tr")}classifyToken(e){const t=e.toLowerCase();return Ff.has(t)||Uf.has(t)?"particle":this.isKeyword(t)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||/^\d/.test(e)?"literal":"identifier"}tryMultiWordPhrase(e,t){for(const n of this.profileKeywords){if(!n.native.includes(" "))continue;const r=n.native;if(e.slice(t,t+r.length).toLowerCase()===r.toLowerCase()){const i=t+r.length;if(i>=e.length||Ol(e[i])||!Bf(e[i]))return Nl(e.slice(t,t+r.length),"keyword",Il(t,i),n.normalized)}}return null}extractTurkishWord(e,t){let n=t,r="";for(;n<e.length&&(Bf(e[n])||"_"===e[n]);)r+=e[n++];if(!r)return null;const i=r.toLowerCase();if(Uf.has(i))return Nl(r,"particle",Il(t,n));if(Ff.has(i))return Nl(r,"particle",Il(t,n));const a=this.lookupKeyword(i);if(a)return Nl(r,"keyword",Il(t,n),a.normalized);const o=this.tryMorphKeywordMatch(i,t,n);return o||Nl(r,"identifier",Il(t,n))}extractTurkishNumber(e,t){return this.tryNumberWithTimeUnits(e,t,Gf,{allowSign:!1,skipWhitespace:!0})}})}}),ty={};yl(ty,{ukrainianProfile:()=>Xf});var ny,ry,iy=fl({"src/generators/profiles/ukrainian.ts"(){Xf={code:"uk",name:"Ukrainian",nativeName:"Українська",direction:"ltr",wordOrder:"SVO",markingStrategy:"preposition",usesSpaces:!0,defaultVerbForm:"infinitive",verb:{position:"start",subjectDrop:!0,suffixes:["ти","тися","ити","итися","ати","атися","іти","ітися"]},references:{me:"я",it:"це",you:"ти",result:"результат",event:"подія",target:"ціль",body:"body"},possessive:{marker:"",markerPosition:"after-object",usePossessiveAdjectives:!0,specialForms:{me:"мій",it:"його",you:"твій"},keywords:{"мій":"me","моя":"me","моє":"me","мої":"me","твій":"you","твоя":"you","твоє":"you","твої":"you","його":"it","її":"it"}},roleMarkers:{destination:{primary:"в",alternatives:["на","до"],position:"before"},source:{primary:"з",alternatives:["від","із"],position:"before"},patient:{primary:"",position:"before"},style:{primary:"з",alternatives:["із"],position:"before"}},keywords:{toggle:{primary:"перемкнути",alternatives:["перемкни"],normalized:"toggle",form:"infinitive"},add:{primary:"додати",alternatives:["додай"],normalized:"add",form:"infinitive"},remove:{primary:"видалити",alternatives:["видали","прибрати","прибери"],normalized:"remove",form:"infinitive"},put:{primary:"покласти",alternatives:["поклади","помістити","помісти","вставити","встав"],normalized:"put",form:"infinitive"},append:{primary:"додати_в_кінець",alternatives:["дописати"],normalized:"append",form:"infinitive"},prepend:{primary:"додати_на_початок",normalized:"prepend",form:"infinitive"},take:{primary:"взяти",alternatives:["візьми"],normalized:"take",form:"infinitive"},make:{primary:"створити",alternatives:["створи"],normalized:"make",form:"infinitive"},clone:{primary:"клонувати",alternatives:["клонуй"],normalized:"clone",form:"infinitive"},swap:{primary:"поміняти",alternatives:["поміняй"],normalized:"swap",form:"infinitive"},morph:{primary:"трансформувати",alternatives:["трансформуй"],normalized:"morph",form:"infinitive"},set:{primary:"встановити",alternatives:["встанови","задати","задай"],normalized:"set",form:"infinitive"},get:{primary:"отримати",alternatives:["отримай"],normalized:"get",form:"infinitive"},increment:{primary:"збільшити",alternatives:["збільш"],normalized:"increment",form:"infinitive"},decrement:{primary:"зменшити",alternatives:["зменш"],normalized:"decrement",form:"infinitive"},log:{primary:"записати",alternatives:["запиши"],normalized:"log",form:"infinitive"},show:{primary:"показати",alternatives:["покажи"],normalized:"show",form:"infinitive"},hide:{primary:"сховати",alternatives:["сховай","приховати","приховай"],normalized:"hide",form:"infinitive"},transition:{primary:"анімувати",alternatives:["анімуй"],normalized:"transition",form:"infinitive"},on:{primary:"при",alternatives:["коли"],normalized:"on"},trigger:{primary:"викликати",alternatives:["виклич"],normalized:"trigger",form:"infinitive"},send:{primary:"надіслати",alternatives:["надішли"],normalized:"send",form:"infinitive"},focus:{primary:"сфокусувати",alternatives:["сфокусуй","фокус"],normalized:"focus",form:"infinitive"},blur:{primary:"розфокусувати",alternatives:["розфокусуй"],normalized:"blur",form:"infinitive"},click:{primary:"кліку",alternatives:["клік","натисканні"],normalized:"click"},hover:{primary:"наведенні",alternatives:["наведення"],normalized:"hover"},submit:{primary:"відправці",alternatives:["відправка"],normalized:"submit"},input:{primary:"введенні",alternatives:["введення"],normalized:"input"},change:{primary:"зміні",alternatives:["зміна"],normalized:"change"},go:{primary:"перейти",alternatives:["перейди","йти","йди"],normalized:"go",form:"infinitive"},wait:{primary:"чекати",alternatives:["чекай","зачекай"],normalized:"wait",form:"infinitive"},fetch:{primary:"завантажити",alternatives:["завантаж"],normalized:"fetch",form:"infinitive"},settle:{primary:"стабілізувати",normalized:"settle",form:"infinitive"},if:{primary:"якщо",normalized:"if"},when:{primary:"коли",normalized:"when"},where:{primary:"де",normalized:"where"},else:{primary:"інакше",normalized:"else"},repeat:{primary:"повторити",alternatives:["повтори"],normalized:"repeat",form:"infinitive"},for:{primary:"для",alternatives:["кожний"],normalized:"for"},while:{primary:"поки",normalized:"while"},continue:{primary:"продовжити",alternatives:["продовжуй"],normalized:"continue",form:"infinitive"},halt:{primary:"зупинити",alternatives:["зупинись","стоп"],normalized:"halt",form:"infinitive"},throw:{primary:"кинути",alternatives:["кинь"],normalized:"throw",form:"infinitive"},call:{primary:"викликати",alternatives:["виклич"],normalized:"call",form:"infinitive"},return:{primary:"повернути",alternatives:["поверни"],normalized:"return",form:"infinitive"},then:{primary:"потім",alternatives:["далі","тоді"],normalized:"then"},and:{primary:"і",alternatives:["та"],normalized:"and"},end:{primary:"кінець",normalized:"end"},js:{primary:"js",normalized:"js"},async:{primary:"асинхронно",alternatives:["async"],normalized:"async"},tell:{primary:"сказати",alternatives:["скажи"],normalized:"tell",form:"infinitive"},default:{primary:"за_замовчуванням",normalized:"default"},init:{primary:"ініціалізувати",alternatives:["ініціалізуй"],normalized:"init",form:"infinitive"},behavior:{primary:"поведінка",normalized:"behavior"},install:{primary:"встановити_пакет",normalized:"install",form:"infinitive"},measure:{primary:"виміряти",alternatives:["виміряй"],normalized:"measure",form:"infinitive"},beep:{primary:"звук",normalized:"beep"},break:{primary:"перервати",normalized:"break"},copy:{primary:"копіювати",normalized:"copy"},exit:{primary:"вийти",normalized:"exit"},pick:{primary:"вибрати",normalized:"pick"},render:{primary:"відобразити",normalized:"render"},into:{primary:"в",alternatives:["у"],normalized:"into"},before:{primary:"до",alternatives:["перед"],normalized:"before"},after:{primary:"після",normalized:"after"},until:{primary:"до",alternatives:["поки_не"],normalized:"until"},event:{primary:"подія",normalized:"event"},from:{primary:"з",alternatives:["від","із"],normalized:"from"}},eventHandler:{keyword:{primary:"при",alternatives:["коли"],normalized:"on"},sourceMarker:{primary:"на",alternatives:["в","при"],position:"before"},eventMarker:{primary:"при",alternatives:["коли"],position:"before"},temporalMarkers:["коли","якщо"]}}}});var ay,oy,sy,ly,cy,uy,py=fl({"src/tokenizers/morphology/ukrainian-normalizer.ts"(){ic(),ny=new Map([["перемкни","перемкнути"],["додай","додати"],["видали","видалити"],["прибери","прибрати"],["поклади","покласти"],["помісти","помістити"],["встав","вставити"],["візьми","взяти"],["створи","створити"],["клонуй","клонувати"],["поміняй","поміняти"],["трансформуй","трансформувати"],["встанови","встановити"],["задай","задати"],["отримай","отримати"],["збільш","збільшити"],["зменш","зменшити"],["запиши","записати"],["покажи","показати"],["сховай","сховати"],["приховай","приховати"],["анімуй","анімувати"],["виклич","викликати"],["надішли","надіслати"],["сфокусуй","сфокусувати"],["розфокусуй","розфокусувати"],["перейди","перейти"],["йди","йти"],["чекай","чекати"],["зачекай","зачекати"],["завантаж","завантажити"],["повтори","повторити"],["продовжуй","продовжити"],["кинь","кинути"],["поверни","повернути"],["скажи","сказати"],["ініціалізуй","ініціалізувати"],["виміряй","виміряти"]]),new(ry=class{constructor(){this.language="uk"}isNormalizable(e){return!(e.length<3)&&function(e){return/[а-яА-ЯіІїЇєЄґҐьЬ']/.test(e)}(e)}normalize(e){const t=e.toLowerCase();if(t.endsWith("ся")||t.endsWith("сь")){const e=this.tryReflexiveNormalization(t);if(e)return e}if(t.endsWith("ти")||t.endsWith("чи"))return Yl(e);const n=this.tryImperativeLookup(t);if(n)return n;const r=this.tryPastTenseNormalization(t);if(r)return r;const i=this.tryPresentTenseNormalization(t);if(i)return i;const a=this.tryGenericImperativeNormalization(t);return a||Yl(e)}tryReflexiveNormalization(e){const t=e.slice(0,-2);if(e.endsWith("тися")||e.endsWith("чися"))return Yl(e);const n=this.normalizeNonReflexive(t);if(n.confidence<1){return Zl(n.stem.endsWith("ти")?n.stem.slice(0,-2)+"тися":n.stem+"ся",.95*n.confidence,{removedSuffixes:["ся",...n.metadata?.removedSuffixes||[]],conjugationType:"reflexive"})}return null}normalizeNonReflexive(e){if(e.endsWith("ти")||e.endsWith("чи"))return Yl(e);const t=this.tryImperativeLookup(e);if(t)return t;const n=this.tryPastTenseNormalization(e);if(n)return n;const r=this.tryPresentTenseNormalization(e);if(r)return r;const i=this.tryGenericImperativeNormalization(e);return i||Yl(e)}tryImperativeLookup(e){return ny.has(e)?Zl(ny.get(e),.95,{removedSuffixes:["imperative"],conjugationType:"imperative"}):null}tryGenericImperativeNormalization(e){return e.endsWith("йте")&&e.length>5?Zl(e.slice(0,-3)+"ти",.8,{removedSuffixes:["йте"],conjugationType:"imperative"}):e.endsWith("іть")&&e.length>5?Zl(e.slice(0,-3)+"ити",.8,{removedSuffixes:["іть"],conjugationType:"imperative"}):e.endsWith("й")&&e.length>3?Zl(e.slice(0,-1)+"ти",.75,{removedSuffixes:["й"],conjugationType:"imperative"}):e.endsWith("и")&&e.length>3?Zl(e+"ти",.7,{removedSuffixes:["и→ити"],conjugationType:"imperative"}):null}tryPastTenseNormalization(e){return e.endsWith("ала")&&e.length>4?Zl(e.slice(0,-3)+"ати",.85,{removedSuffixes:["ала"],conjugationType:"past"}):e.endsWith("ила")&&e.length>4?Zl(e.slice(0,-3)+"ити",.85,{removedSuffixes:["ила"],conjugationType:"past"}):e.endsWith("али")&&e.length>4?Zl(e.slice(0,-3)+"ати",.85,{removedSuffixes:["али"],conjugationType:"past"}):e.endsWith("или")&&e.length>4?Zl(e.slice(0,-3)+"ити",.85,{removedSuffixes:["или"],conjugationType:"past"}):e.endsWith("ав")&&e.length>3?Zl(e.slice(0,-2)+"ати",.82,{removedSuffixes:["ав"],conjugationType:"past"}):e.endsWith("ив")&&e.length>3?Zl(e.slice(0,-2)+"ити",.82,{removedSuffixes:["ив"],conjugationType:"past"}):null}tryPresentTenseNormalization(e){return e.endsWith("иш")&&e.length>3?Zl(e.slice(0,-2)+"ити",.8,{removedSuffixes:["иш"],conjugationType:"present"}):e.endsWith("ить")&&e.length>4?Zl(e.slice(0,-3)+"ити",.78,{removedSuffixes:["ить"],conjugationType:"present"}):e.endsWith("имо")&&e.length>4?Zl(e.slice(0,-3)+"ити",.8,{removedSuffixes:["имо"],conjugationType:"present"}):e.endsWith("ять")&&e.length>4?Zl(e.slice(0,-3)+"ити",.78,{removedSuffixes:["ять"],conjugationType:"present"}):e.endsWith("єш")&&e.length>3?Zl(e.slice(0,-2)+"ати",.78,{removedSuffixes:["єш"],conjugationType:"present"}):e.endsWith("еш")&&e.length>3?Zl(e.slice(0,-2)+"ати",.75,{removedSuffixes:["еш"],conjugationType:"present"}):e.endsWith("є")&&e.length>2?Zl(e.slice(0,-1)+"ати",.72,{removedSuffixes:["є"],conjugationType:"present"}):e.endsWith("ємо")&&e.length>4?Zl(e.slice(0,-3)+"ати",.8,{removedSuffixes:["ємо"],conjugationType:"present"}):e.endsWith("ють")&&e.length>4?Zl(e.slice(0,-3)+"ати",.78,{removedSuffixes:["ють"],conjugationType:"present"}):e.endsWith("уть")&&e.length>4?Zl(e.slice(0,-3)+"ати",.75,{removedSuffixes:["уть"],conjugationType:"present"}):null}})}}),my={};yl(my,{UkrainianTokenizer:()=>cy,ukrainianTokenizer:()=>uy});var dy,hy=fl({"src/tokenizers/ukrainian.ts"(){Jl(),iy(),py(),({isLetter:ay,isIdentifierChar:oy}=_l(/[a-zA-Zа-яА-ЯіІїЇєЄґҐьЬ']/)),sy=new Set(["в","у","на","з","із","зі","до","від","о","об","при","для","під","над","перед","між","через","без","по","за","про","після","навколо","проти","замість","крім","серед","к"]),ly=[{native:"істина",normalized:"true"},{native:"правда",normalized:"true"},{native:"хибність",normalized:"false"},{native:"null",normalized:"null"},{native:"невизначено",normalized:"undefined"},{native:"перший",normalized:"first"},{native:"перша",normalized:"first"},{native:"перше",normalized:"first"},{native:"останній",normalized:"last"},{native:"остання",normalized:"last"},{native:"останнє",normalized:"last"},{native:"наступний",normalized:"next"},{native:"наступна",normalized:"next"},{native:"попередній",normalized:"previous"},{native:"попередня",normalized:"previous"},{native:"найближчий",normalized:"closest"},{native:"батько",normalized:"parent"},{native:"клік",normalized:"click"},{native:"натискання",normalized:"click"},{native:"click",normalized:"click"},{native:"зміна",normalized:"change"},{native:"надсилання",normalized:"submit"},{native:"клавіша",normalized:"keydown"},{native:"наведення",normalized:"mouseover"},{native:"відведення",normalized:"mouseout"},{native:"завантаження",normalized:"load"},{native:"прокрутка",normalized:"scroll"},{native:"введення",normalized:"input"},{native:"мій",normalized:"my"},{native:"моя",normalized:"my"},{native:"моє",normalized:"my"},{native:"мої",normalized:"my"},{native:"секунда",normalized:"s"},{native:"секунди",normalized:"s"},{native:"секунд",normalized:"s"},{native:"мілісекунда",normalized:"ms"},{native:"мілісекунди",normalized:"ms"},{native:"мілісекунд",normalized:"ms"},{native:"хвилина",normalized:"m"},{native:"хвилини",normalized:"m"},{native:"хвилин",normalized:"m"},{native:"година",normalized:"h"},{native:"години",normalized:"h"},{native:"годин",normalized:"h"},{native:"або",normalized:"or"},{native:"не",normalized:"not"},{native:"є",normalized:"is"},{native:"існує",normalized:"exists"},{native:"порожній",normalized:"empty"},{native:"порожня",normalized:"empty"},{native:"порожнє",normalized:"empty"}],uy=new(cy=class extends Kl{constructor(){super(),this.language="uk",this.direction="ltr",this.initializeKeywordsFromProfile(Xf,ly),this.normalizer=new ry}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])||"-"===e[n]&&n+1<e.length&&Wl(e[n+1])){const r=this.extractNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}if(ay(e[n])){const r=this.extractWord(e,n);if(r){t.push(r),n=r.position.end;continue}}const i=this.tryOperator(e,n);i?(t.push(i),n=i.position.end):n++}return new Ll(t,"uk")}classifyToken(e){const t=e.toLowerCase();return sy.has(t)?"particle":this.isKeyword(t)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||/^\d/.test(e)?"literal":"identifier"}extractWord(e,t){let n=t,r="";for(;n<e.length&&oy(e[n]);)r+=e[n++];if(!r)return null;const i=r.toLowerCase();if(sy.has(i))return Nl(r,"particle",Il(t,n));const a=this.lookupKeyword(i);return a?Nl(r,"keyword",Il(t,n),a.normalized):Nl(r,"identifier",Il(t,n))}extractNumber(e,t){let n=t,r="";for("-"!==e[n]&&"+"!==e[n]||(r+=e[n++]);n<e.length&&Wl(e[n]);)r+=e[n++];if(n<e.length&&"."===e[n])for(r+=e[n++];n<e.length&&Wl(e[n]);)r+=e[n++];let i=n;for(;i<e.length&&Ol(e[i]);)i++;const a=e.slice(i).toLowerCase();return a.startsWith("мілісекунд")||a.startsWith("мс")?a.startsWith("мілісекунд")?(r+="ms",n=i+10,a.length>10&&/[аи]/.test(a[10])&&n++):(r+="ms",n=i+2):a.startsWith("секунд")||a.startsWith("сек")?a.startsWith("секунд")?(r+="s",n=i+6,a.length>6&&/[аи]/.test(a[6])&&n++):(r+="s",n=i+3):a.startsWith("хвилин")||a.startsWith("хв")?a.startsWith("хвилин")?(r+="m",n=i+6,a.length>6&&/[аи]/.test(a[6])&&n++):(r+="m",n=i+2):a.startsWith("годин")?(r+="h",n=i+5,a.length>5&&/[аи]/.test(a[5])&&n++):a.startsWith("ms")?(r+="ms",n=i+2):a.startsWith("s")&&!a.startsWith("se")&&(r+="s",n=i+1),r&&"-"!==r&&"+"!==r?Nl(r,"literal",Il(t,n)):null}})}}),fy={};yl(fy,{vietnameseProfile:()=>dy});var yy,vy,gy,by,ky,wy,zy=fl({"src/generators/profiles/vietnamese.ts"(){dy={code:"vi",name:"Vietnamese",nativeName:"Tiếng Việt",direction:"ltr",wordOrder:"SVO",markingStrategy:"preposition",usesSpaces:!0,defaultVerbForm:"base",verb:{position:"start",subjectDrop:!0},references:{me:"tôi",it:"nó",you:"bạn",result:"kết quả",event:"sự kiện",target:"mục tiêu",body:"body"},possessive:{marker:"của",markerPosition:"between",specialForms:{me:"của tôi",it:"của nó",you:"của bạn"},keywords:{"của tôi":"me","của bạn":"you","của anh":"you","của chị":"you","của nó":"it"}},roleMarkers:{destination:{primary:"vào",alternatives:["cho","đến"],position:"before"},source:{primary:"từ",alternatives:["khỏi"],position:"before"},patient:{primary:"",position:"before"},style:{primary:"với",position:"before"}},keywords:{toggle:{primary:"chuyển đổi",alternatives:["bật tắt","chuyển"],normalized:"toggle"},add:{primary:"thêm",alternatives:["bổ sung"],normalized:"add"},remove:{primary:"xóa",alternatives:["gỡ bỏ","loại bỏ","bỏ"],normalized:"remove"},put:{primary:"đặt",alternatives:["để","đưa"],normalized:"put"},append:{primary:"nối",normalized:"append"},prepend:{primary:"thêm vào đầu",normalized:"prepend"},take:{primary:"lấy",normalized:"take"},make:{primary:"tạo",normalized:"make"},clone:{primary:"sao chép",normalized:"clone"},swap:{primary:"hoán đổi",normalized:"swap"},morph:{primary:"biến đổi",normalized:"morph"},set:{primary:"gán",alternatives:["thiết lập","đặt"],normalized:"set"},get:{primary:"lấy giá trị",alternatives:["nhận","lấy"],normalized:"get"},increment:{primary:"tăng",alternatives:["tăng lên"],normalized:"increment"},decrement:{primary:"giảm",alternatives:["giảm đi"],normalized:"decrement"},log:{primary:"in ra",normalized:"log"},show:{primary:"hiển thị",alternatives:["hiện"],normalized:"show"},hide:{primary:"ẩn",alternatives:["che","giấu"],normalized:"hide"},transition:{primary:"chuyển tiếp",normalized:"transition"},on:{primary:"khi",alternatives:["lúc","trên"],normalized:"on"},trigger:{primary:"kích hoạt",normalized:"trigger"},send:{primary:"gửi",normalized:"send"},focus:{primary:"tập trung",normalized:"focus"},blur:{primary:"mất tập trung",normalized:"blur"},click:{primary:"nhấp",alternatives:["bấm"],normalized:"click"},hover:{primary:"di chuột",alternatives:["rê chuột"],normalized:"hover"},submit:{primary:"gửi",alternatives:["nộp"],normalized:"submit"},input:{primary:"nhập",alternatives:["nhập liệu"],normalized:"input"},change:{primary:"thay đổi",alternatives:["đổi"],normalized:"change"},go:{primary:"đi đến",alternatives:["đi"],normalized:"go"},wait:{primary:"chờ",alternatives:["đợi"],normalized:"wait"},fetch:{primary:"tải",normalized:"fetch"},settle:{primary:"ổn định",normalized:"settle"},if:{primary:"nếu",normalized:"if"},when:{primary:"khi",normalized:"when"},where:{primary:"ở_đâu",normalized:"where"},else:{primary:"không thì",alternatives:["nếu không"],normalized:"else"},repeat:{primary:"lặp lại",normalized:"repeat"},for:{primary:"với mỗi",normalized:"for"},while:{primary:"trong khi",normalized:"while"},continue:{primary:"tiếp tục",normalized:"continue"},halt:{primary:"dừng",alternatives:["dừng lại"],normalized:"halt"},throw:{primary:"ném",normalized:"throw"},call:{primary:"gọi",normalized:"call"},return:{primary:"trả về",normalized:"return"},then:{primary:"rồi",alternatives:["sau đó","thì"],normalized:"then"},and:{primary:"và",normalized:"and"},end:{primary:"kết thúc",normalized:"end"},js:{primary:"js",normalized:"js"},async:{primary:"bất đồng bộ",normalized:"async"},tell:{primary:"nói với",normalized:"tell"},default:{primary:"mặc định",normalized:"default"},init:{primary:"khởi tạo",normalized:"init"},behavior:{primary:"hành vi",normalized:"behavior"},install:{primary:"cài đặt",normalized:"install"},measure:{primary:"đo lường",normalized:"measure"},beep:{primary:"beep",normalized:"beep"},break:{primary:"dừng",normalized:"break"},copy:{primary:"sao chép",normalized:"copy"},exit:{primary:"thoát",normalized:"exit"},pick:{primary:"chọn",normalized:"pick"},render:{primary:"kết xuất",normalized:"render"},into:{primary:"vào",alternatives:["vào trong"],normalized:"into"},before:{primary:"trước",alternatives:["trước khi"],normalized:"before"},after:{primary:"sau",alternatives:["sau khi"],normalized:"after"},until:{primary:"cho đến khi",normalized:"until"},event:{primary:"sự kiện",normalized:"event"},from:{primary:"từ",alternatives:["khỏi"],normalized:"from"}},eventHandler:{keyword:{primary:"khi",alternatives:["lúc","trên"],normalized:"on"},sourceMarker:{primary:"trên",alternatives:["tại"],position:"before"},eventMarker:{primary:"khi",alternatives:["lúc"],position:"before"},temporalMarkers:["khi","lúc"]}}}}),xy={};yl(xy,{VietnameseTokenizer:()=>ky,vietnameseTokenizer:()=>wy});var Ey,Sy=fl({"src/tokenizers/vietnamese.ts"(){Jl(),zy(),({isLetter:yy,isIdentifierChar:vy}=_l(/[a-zA-ZàáảãạăằắẳẵặâầấẩẫậèéẻẽẹêềếểễệìíỉĩịòóỏõọôồốổỗộơờớởỡợùúủũụưừứửữựỳýỷỹỵđÀÁẢÃẠĂẰẮẲẴẶÂẦẤẨẪẬÈÉẺẼẸÊỀẾỂỄỆÌÍỈĨỊÒÓỎÕỌÔỒỐỔỖỘƠỜỚỞỠỢÙÚỦŨỤƯỪỨỬỮỰỲÝỶỸỴĐ]/)),gy=new Set(["trong","ngoài","trên","dưới","vào","ra","đến","từ","với","cho","bởi","qua","trước","sau","giữa","bên","theo","về","tới","lên","xuống"]),by=[{native:"đúng",normalized:"true"},{native:"sai",normalized:"false"},{native:"null",normalized:"null"},{native:"không xác định",normalized:"undefined"},{native:"đầu tiên",normalized:"first"},{native:"cuối cùng",normalized:"last"},{native:"tiếp theo",normalized:"next"},{native:"trước đó",normalized:"previous"},{native:"gần nhất",normalized:"closest"},{native:"cha",normalized:"parent"},{native:"nhấp",normalized:"click"},{native:"nhấp chuột",normalized:"click"},{native:"click",normalized:"click"},{native:"nhấp đúp",normalized:"dblclick"},{native:"nhập",normalized:"input"},{native:"thay đổi",normalized:"change"},{native:"gửi biểu mẫu",normalized:"submit"},{native:"phím xuống",normalized:"keydown"},{native:"phím lên",normalized:"keyup"},{native:"chuột vào",normalized:"mouseover"},{native:"chuột ra",normalized:"mouseout"},{native:"tải trang",normalized:"load"},{native:"cuộn",normalized:"scroll"},{native:"của tôi",normalized:"my"},{native:"của nó",normalized:"its"},{native:"giây",normalized:"s"},{native:"mili giây",normalized:"ms"},{native:"phút",normalized:"m"},{native:"giờ",normalized:"h"},{native:"thêm vào cuối",normalized:"append"},{native:"nhân bản",normalized:"clone"},{native:"tạo ra",normalized:"make"},{native:"đặt giá trị",normalized:"set"},{native:"ghi nhật ký",normalized:"log"},{native:"chuyển tới",normalized:"go"},{native:"ngược lại",normalized:"else"},{native:"lặp",normalized:"repeat"},{native:"hoặc",normalized:"or"},{native:"không",normalized:"not"},{native:"là",normalized:"is"},{native:"tồn tại",normalized:"exists"},{native:"rỗng",normalized:"empty"},{native:"javascript",normalized:"js"}],wy=new(ky=class extends Kl{constructor(){super(),this.language="vi",this.direction="ltr",this.initializeKeywordsFromProfile(dy,by)}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])){const r=this.tryString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])){const r=this.extractVietnameseNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}const i=this.tryOperator(e,n);if(i){t.push(i),n=i.position.end;continue}const a=this.tryMultiWordPhrase(e,n);if(a)t.push(a),n=a.position.end;else{if(yy(e[n])){const r=this.extractVietnameseWord(e,n);if(r){t.push(r),n=r.position.end;continue}}n++}}return new Ll(t,"vi")}classifyToken(e){const t=e.toLowerCase();return gy.has(t)?"particle":this.isKeyword(t)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||/^\d/.test(e)?"literal":"identifier"}tryMultiWordPhrase(e,t){for(const n of this.profileKeywords){if(!n.native.includes(" "))continue;const r=n.native;if(e.slice(t,t+r.length).toLowerCase()===r.toLowerCase()){const i=e[t+r.length];if(i&&yy(i))continue;return Nl(e.slice(t,t+r.length),"keyword",Il(t,t+r.length),n.normalized)}}return null}extractVietnameseWord(e,t){let n=t,r="";for(;n<e.length&&vy(e[n]);)r+=e[n++];if(!r)return null;const i=r.toLowerCase();if(gy.has(i))return Nl(r,"particle",Il(t,n));const a=this.lookupKeyword(i);return a?Nl(r,"keyword",Il(t,n),a.normalized):Nl(r,"identifier",Il(t,n))}extractVietnameseNumber(e,t){let n=t,r="";for(;n<e.length&&Wl(e[n]);)r+=e[n++];if(n<e.length&&"."===e[n])for(r+=e[n++];n<e.length&&Wl(e[n]);)r+=e[n++];if(n<e.length){const t=e.slice(n).toLowerCase();t.startsWith(" mili giây")||t.startsWith(" miligiây")?(r+="ms",n+=t.startsWith(" mili giây")?10:9):t.startsWith(" giây")?(r+="s",n+=5):t.startsWith(" phút")?(r+="m",n+=5):t.startsWith(" giờ")?(r+="h",n+=4):t.startsWith("ms")?(r+="ms",n+=2):"s"!==t[0]||yy(t[1]||"")?"m"!==t[0]||"s"===t[1]||yy(t[1]||"")?"h"!==t[0]||yy(t[1]||"")||(r+="h",n+=1):(r+="m",n+=1):(r+="s",n+=1)}return r?Nl(r,"literal",Il(t,n)):null}})}}),Ty={};yl(Ty,{chineseProfile:()=>Ey});var Cy,Ay,jy,Ly,Py,Iy,Ny,Oy=fl({"src/generators/profiles/chinese.ts"(){Ey={code:"zh",name:"Chinese",nativeName:"中文",direction:"ltr",wordOrder:"SVO",markingStrategy:"preposition",usesSpaces:!1,verb:{position:"second",subjectDrop:!0},references:{me:"我",it:"它",you:"你",result:"结果",event:"事件",target:"目标",body:"主体"},possessive:{marker:"的",markerPosition:"between",keywords:{"我的":"me","你的":"you","它的":"it","他的":"it","她的":"it"}},roleMarkers:{destination:{primary:"在",alternatives:["到","于"],position:"before"},source:{primary:"从",alternatives:["由"],position:"before"},patient:{primary:"把",position:"before"},style:{primary:"用",alternatives:["以"],position:"before"}},keywords:{toggle:{primary:"切换",normalized:"toggle"},add:{primary:"添加",alternatives:["加"],normalized:"add"},remove:{primary:"移除",alternatives:["删除","去掉"],normalized:"remove"},put:{primary:"放置",alternatives:["放","放入"],normalized:"put"},append:{primary:"追加",alternatives:["附加"],normalized:"append"},prepend:{primary:"前置",alternatives:["预置"],normalized:"prepend"},take:{primary:"获取",normalized:"take"},make:{primary:"制作",normalized:"make"},clone:{primary:"复制",normalized:"clone"},swap:{primary:"交换",normalized:"swap"},morph:{primary:"变形",alternatives:["转换"],normalized:"morph"},set:{primary:"设置",alternatives:["设定"],normalized:"set"},get:{primary:"获得",alternatives:["获取","取得"],normalized:"get"},increment:{primary:"增加",normalized:"increment"},decrement:{primary:"减少",normalized:"decrement"},log:{primary:"日志",normalized:"log"},show:{primary:"显示",alternatives:["展示"],normalized:"show"},hide:{primary:"隐藏",normalized:"hide"},transition:{primary:"过渡",normalized:"transition"},on:{primary:"当",alternatives:["在...时"],normalized:"on"},trigger:{primary:"触发",normalized:"trigger"},send:{primary:"发送",normalized:"send"},focus:{primary:"聚焦",normalized:"focus"},blur:{primary:"失焦",normalized:"blur"},click:{primary:"点击",normalized:"click"},hover:{primary:"悬停",alternatives:["悬浮"],normalized:"hover"},submit:{primary:"提交",normalized:"submit"},input:{primary:"输入",normalized:"input"},change:{primary:"改变",alternatives:["变化"],normalized:"change"},go:{primary:"前往",normalized:"go"},wait:{primary:"等待",normalized:"wait"},fetch:{primary:"获取",normalized:"fetch"},settle:{primary:"稳定",normalized:"settle"},if:{primary:"如果",normalized:"if"},when:{primary:"当",normalized:"when"},where:{primary:"哪里",normalized:"where"},else:{primary:"否则",normalized:"else"},repeat:{primary:"重复",normalized:"repeat"},for:{primary:"为",normalized:"for"},while:{primary:"当",normalized:"while"},continue:{primary:"继续",normalized:"continue"},halt:{primary:"停止",normalized:"halt"},throw:{primary:"抛出",normalized:"throw"},call:{primary:"调用",normalized:"call"},return:{primary:"返回",normalized:"return"},then:{primary:"然后",alternatives:["接着","之后"],normalized:"then"},and:{primary:"并且",alternatives:["和","而且"],normalized:"and"},end:{primary:"结束",alternatives:["终止","完"],normalized:"end"},js:{primary:"JS执行",alternatives:["js"],normalized:"js"},async:{primary:"异步",normalized:"async"},tell:{primary:"告诉",normalized:"tell"},default:{primary:"默认",normalized:"default"},init:{primary:"初始化",normalized:"init"},behavior:{primary:"行为",normalized:"behavior"},install:{primary:"安装",normalized:"install"},measure:{primary:"测量",normalized:"measure"},beep:{primary:"蜂鸣",normalized:"beep"},break:{primary:"中断",normalized:"break"},copy:{primary:"复制",normalized:"copy"},exit:{primary:"退出",normalized:"exit"},pick:{primary:"选取",normalized:"pick"},render:{primary:"渲染",normalized:"render"},into:{primary:"进入",normalized:"into"},before:{primary:"之前",normalized:"before"},after:{primary:"之后",normalized:"after"},until:{primary:"直到",normalized:"until"},event:{primary:"事件",normalized:"event"},from:{primary:"从",normalized:"from"}},tokenization:{boundaryStrategy:"character"},eventHandler:{keyword:{primary:"当",alternatives:["在...时"],normalized:"on"},sourceMarker:{primary:"从",position:"before"},eventMarker:{primary:"当",alternatives:["在"],position:"before"},temporalMarkers:["当","在...时"]}}}}),Ry={};yl(Ry,{ChineseTokenizer:()=>Iy,chineseTokenizer:()=>Ny});var My,Wy=fl({"src/tokenizers/chinese.ts"(){Jl(),Oy(),Cy=ql([[19968,40959],[13312,19903],[131072,173791],[63744,64255],[194560,195103]]),Ay=new Set(["把","在","从","到","向","给","对","用","被","让","的","地","得","了","着","过","吗","呢","吧"]),jy=["然后","接着","并且","或者","如果","那么","否则"],Ly=[{native:"真",normalized:"true"},{native:"假",normalized:"false"},{native:"空",normalized:"null"},{native:"未定义",normalized:"undefined"},{native:"第一个",normalized:"first"},{native:"首个",normalized:"first"},{native:"最后一个",normalized:"last"},{native:"末个",normalized:"last"},{native:"下一个",normalized:"next"},{native:"上一个",normalized:"previous"},{native:"最近的",normalized:"closest"},{native:"父级",normalized:"parent"},{native:"点击",normalized:"click"},{native:"双击",normalized:"dblclick"},{native:"输入",normalized:"input"},{native:"变更",normalized:"change"},{native:"改变",normalized:"change"},{native:"提交",normalized:"submit"},{native:"按键",normalized:"keydown"},{native:"释放键",normalized:"keyup"},{native:"鼠标移入",normalized:"mouseover"},{native:"鼠标移出",normalized:"mouseout"},{native:"获得焦点",normalized:"focus"},{native:"失去焦点",normalized:"blur"},{native:"加载",normalized:"load"},{native:"滚动",normalized:"scroll"},{native:"我的",normalized:"my"},{native:"它的",normalized:"its"},{native:"秒",normalized:"s"},{native:"毫秒",normalized:"ms"},{native:"分钟",normalized:"m"},{native:"小时",normalized:"h"},{native:"和",normalized:"and"},{native:"或者",normalized:"or"},{native:"或",normalized:"or"},{native:"不",normalized:"not"},{native:"非",normalized:"not"},{native:"是",normalized:"is"},{native:"若",normalized:"if"},{native:"不然",normalized:"else"},{native:"循环",normalized:"repeat"},{native:"遍历",normalized:"for"},{native:"每个",normalized:"for"},{native:"为每",normalized:"for"},{native:"中止",normalized:"halt"},{native:"抛",normalized:"throw"},{native:"呼叫",normalized:"call"},{native:"回",normalized:"return"},{native:"脚本",normalized:"js"},{native:"通知",normalized:"tell"},{native:"缺省",normalized:"default"},{native:"初始",normalized:"init"},{native:"动作",normalized:"behavior"},{native:"激发",normalized:"trigger"},{native:"对焦",normalized:"focus"},{native:"模糊",normalized:"blur"},{native:"跳转",normalized:"go"},{native:"导航",normalized:"go"},{native:"抓取",normalized:"fetch"},{native:"获取数据",normalized:"fetch"},{native:"安定",normalized:"settle"},{native:"拿取",normalized:"take"},{native:"取",normalized:"take"},{native:"创建",normalized:"make"},{native:"克隆",normalized:"clone"},{native:"记录",normalized:"log"},{native:"打印",normalized:"log"},{native:"动画",normalized:"transition"},{native:"到里面",normalized:"into"},{native:"里",normalized:"into"},{native:"前",normalized:"before"},{native:"后",normalized:"after"},{native:"那么",normalized:"then"},{native:"完",normalized:"end"}],Py=[{pattern:"毫秒",suffix:"ms",length:2},{pattern:"分钟",suffix:"m",length:2},{pattern:"小时",suffix:"h",length:2},{pattern:"秒",suffix:"s",length:1},{pattern:"分",suffix:"m",length:1}],Ny=new(Iy=class extends Kl{constructor(){super(),this.language="zh",this.direction="ltr",this.initializeKeywordsFromProfile(Ey,Ly)}tokenize(e){const t=[];let n=0;for(;n<e.length;){if(Ol(e[n])){n++;continue}if(Rl(e[n])){const r=this.tryEventModifier(e,n);if(r){t.push(r),n=r.position.end;continue}if(this.tryPropertyAccess(e,n,t)){n++;continue}const i=this.trySelector(e,n);if(i){t.push(i),n=i.position.end;continue}}if(Ml(e[n])||"“"===e[n]||"”"===e[n]||"‘"===e[n]||"’"===e[n]){const r=this.tryChineseString(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Fl(e,n)){const r=this.tryUrl(e,n);if(r){t.push(r),n=r.position.end;continue}}if(Wl(e[n])){const r=this.extractChineseNumber(e,n);if(r){t.push(r),n=r.position.end;continue}}const r=this.tryVariableRef(e,n);if(r){t.push(r),n=r.position.end;continue}const i=this.tryMultiCharParticle(e,n,jy);if(i)t.push(i),n=i.position.end;else{if(Cy(e[n])){const r=this.extractChineseWord(e,n);if(r){t.push(r),n=r.position.end;continue}}if($l(e[n])){const r=this.extractAsciiWord(e,n);if(r){t.push(r),n=r.position.end;continue}}n++}}return new Ll(t,"zh")}classifyToken(e){return Ay.has(e)?"particle":this.isKeyword(e)?"keyword":e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("*")||e.startsWith("<")?"selector":e.startsWith('"')||e.startsWith("'")||e.startsWith("“")||e.startsWith("‘")||/^\d/.test(e)?"literal":"identifier"}extractChineseWord(e,t){for(const n of this.profileKeywords){const r=n.native,i=e.slice(t,t+r.length);if(i===r){let e=!0;for(let t=0;t<r.length;t++)if(!Cy(r[t])){e=!1;break}if(e)return Nl(i,"keyword",Il(t,t+r.length),n.normalized)}}let n=t,r="";for(;n<e.length;){const t=e[n];if(Ay.has(t)&&r.length>0)break;if(!Cy(t))break;r+=t,n++}return r?Ay.has(r)?Nl(r,"particle",Il(t,n)):Nl(r,"identifier",Il(t,n)):null}extractAsciiWord(e,t){let n=t,r="";for(;n<e.length&&$l(e[n]);)r+=e[n++];return r?Nl(r,"identifier",Il(t,n)):null}tryChineseString(e,t){const n=e[t];if('"'===n||"'"===n||"`"===n)return this.tryString(e,t);if("“"===n){let n=t+1;for(;n<e.length&&"”"!==e[n];)n++;if(n>=e.length)return null;return Nl(e.slice(t,n+1),"literal",Il(t,n+1))}if("‘"===n){let n=t+1;for(;n<e.length&&"’"!==e[n];)n++;if(n>=e.length)return null;return Nl(e.slice(t,n+1),"literal",Il(t,n+1))}return null}extractChineseNumber(e,t){return this.tryNumberWithTimeUnits(e,t,Py,{allowSign:!1,skipWhitespace:!1})}})}});function $y(e){let t="complex";return e.startsWith("#")&&!e.includes(" ")?t="id":e.startsWith(".")&&!e.includes(" ")?t="class":e.startsWith("[")&&e.endsWith("]")?t="attribute":/^[a-z][a-z0-9]*$/i.test(e)&&(t="element"),{type:"selector",value:e,selectorKind:t}}function Hy(e,t){return void 0!==t?{type:"literal",value:e,dataType:t}:{type:"literal",value:e}}function qy(e){return My.has(e)}function Dy(e){return{type:"reference",value:e}}function _y(e,t){return{type:"property-path",object:e,property:t}}function Vy(e,t,n){const r={kind:"command",action:e,roles:new Map(Object.entries(t))};return void 0!==n?{...r,metadata:n}:r}function By(e,t,n,r,i,a){const o=new Map;o.set("event",e);const s={kind:"event-handler",action:"on",roles:o,body:t};return void 0!==n&&(s.eventModifiers=n),void 0!==r&&(s.metadata=r),void 0!==i&&i.length>0&&(s.parameterNames=i),void 0!==a&&a.length>0&&(s.additionalEvents=a),s}function Fy(e,t="then",n){const r={kind:"compound",action:"compound",roles:new Map,statements:e,chainType:t};return void 0!==n&&(r.metadata=n),r}var Uy,Ky=fl({"src/types.ts"(){My=new Set(["me","you","it","result","event","target","body"])}});var Gy=fl({"src/patterns/event-handler/shared.ts"(){Uy={ko:{"클릭":"click","입력":"input","변경":"change","제출":"submit","키다운":"keydown","키업":"keyup","마우스오버":"mouseover","마우스아웃":"mouseout","마우스다운":"mousedown","마우스업":"mouseup","포커스":"focus","블러":"blur","로드":"load","리사이즈":"resize","스크롤":"scroll"},ja:{"クリック":"click","入力":"input","変更":"change","送信":"submit","キーダウン":"keydown","キーアップ":"keyup","キープレス":"keypress","マウスオーバー":"mouseover","マウスアウト":"mouseout","マウス押下":"mousedown","マウス解放":"mouseup","フォーカス":"focus","ブラー":"blur","ロード":"load","読み込み":"load","サイズ変更":"resize","スクロール":"scroll"},ar:{"النقر":"click","نقر":"click","الإدخال":"input","إدخال":"input","التغيير":"change","تغيير":"change","الإرسال":"submit","إرسال":"submit","ضغط المفتاح":"keydown","رفع المفتاح":"keyup","تمرير الماوس":"mouseover","التركيز":"focus","تحميل":"load","تمرير":"scroll"},es:{clic:"click",click:"click",entrada:"input",cambio:"change","envío":"submit",enviar:"submit","tecla abajo":"keydown","tecla arriba":"keyup","ratón encima":"mouseover","ratón fuera":"mouseout",enfoque:"focus",desenfoque:"blur",carga:"load",desplazamiento:"scroll"},tr:{"tıklama":"click","tıkla":"click","tık":"click","giriş":"input",girdi:"input","değişiklik":"change","değişim":"change","gönderme":"submit","gönder":"submit","tuşbasma":"keydown","tuşbırakma":"keyup",fare_bas:"mousedown","fare_bırak":"mouseup","fareiçinde":"mouseover","faredışında":"mouseout",odaklanma:"focus",odak:"focus","bulanıklık":"blur","yükleme":"load","yükle":"load","boyut_değiştir":"resize","kaydırma":"scroll"},pt:{clique:"click",clicar:"click",click:"click",entrada:"input",inserir:"input","mudança":"change",mudanca:"change",alterar:"change",envio:"submit",enviar:"submit","tecla baixo":"keydown","tecla cima":"keyup","pressionar tecla":"keydown","soltar tecla":"keyup","mouse sobre":"mouseover","mouse fora":"mouseout",foco:"focus",focar:"focus",desfoque:"blur",desfocar:"blur",carregar:"load",carregamento:"load",rolagem:"scroll",rolar:"scroll"},zh:{"点击":"click","单击":"click","双击":"dblclick","输入":"input","改变":"change","变化":"change","变更":"change","提交":"submit","发送":"submit","按键":"keydown","键入":"keydown","松键":"keyup","鼠标进入":"mouseover","鼠标移入":"mouseover","鼠标离开":"mouseout","鼠标移出":"mouseout","焦点":"focus","聚焦":"focus","失焦":"blur","模糊":"blur","加载":"load","载入":"load","滚动":"scroll"},fr:{clic:"click",cliquer:"click",click:"click",saisie:"input","entrée":"input",changement:"change",changer:"change",soumettre:"submit",soumission:"submit",envoi:"submit","touche bas":"keydown","touche haut":"keyup","souris dessus":"mouseover","souris dehors":"mouseout",focus:"focus",focaliser:"focus","défocus":"blur","défocaliser":"blur",chargement:"load",charger:"load","défilement":"scroll","défiler":"scroll"},de:{klick:"click",klicken:"click",click:"click",eingabe:"input",eingeben:"input","änderung":"change","ändern":"change",absenden:"submit",einreichen:"submit","taste runter":"keydown","taste hoch":"keyup","maus über":"mouseover","maus raus":"mouseout",fokus:"focus",fokussieren:"focus",defokussieren:"blur","unschärfe":"blur",laden:"load",ladung:"load",scrollen:"scroll","blättern":"scroll"},id:{klik:"click",click:"click",masukan:"input",input:"input",ubah:"change",perubahan:"change",kirim:"submit","tekan tombol":"keydown","lepas tombol":"keyup","mouse masuk":"mouseover","mouse keluar":"mouseout",fokus:"focus",blur:"blur",muat:"load",memuat:"load",gulir:"scroll",menggulir:"scroll"},bn:{"ক্লিক":"click","ইনপুট":"input","জমা":"submit","লোড":"load","স্ক্রোল":"scroll","রিসাইজ":"resize","ঝাপসা":"blur","ফোকাস":"focus","পরিবর্তন":"change"},qu:{click:"click","ñit'iy":"click","ñitiy":"click",yaykuchiy:"input",yaykuy:"input",tikray:"change","t'ikray":"change",apachiy:"submit",kachay:"submit","llave uray":"keydown","llave hawa":"keyup","q'away":"focus",qhaway:"focus",paqariy:"blur","mana q'away":"blur",cargay:"load",apakuy:"load",apamuy:"load",kunray:"scroll",muyuy:"scroll",hatun_kay:"resize"},sw:{bofya:"click",click:"click",kubofya:"click",ingiza:"input",kubadilisha:"change",mabadiliko:"change",tuma:"submit",kutuma:"submit","bonyeza chini":"keydown","bonyeza juu":"keyup","panya juu":"mouseover","panya nje":"mouseout",lenga:"focus",kulenga:"focus",blur:"blur",pakia:"load",kupakia:"load",sogeza:"scroll",kusogeza:"scroll"}}}});function Qy(e){return function(e){let t=ol.get(e);return!t&&El(e)&&(t=ol.get(xl(e))),t}(e)}function Jy(e,t){return Al(e,t)}function Yy(){return Tl()}var Zy=fl({"src/tokenizers/index.ts"(){Pl(),au(),Sd(),Fd(),wc(),Rp(),ey(),Wy(),Jl()}});function Xy(e,t){return!t||0===t.length||(!!t.includes(e)||(!!t.includes("expression")||"property-path"===e&&t.some(e=>["selector","reference","expression"].includes(e))))}var ev=fl({"src/parser/utils/type-validation.ts"(){}});var tv,nv,rv,iv=fl({"src/parser/utils/possessive-keywords.ts"(){}});var av,ov,sv=fl({"src/parser/pattern-matcher.ts"(){Ky(),ev(),iv(),Pl(),(tv=class e{constructor(){this.stemMatchCount=0,this.totalKeywordMatches=0}matchPattern(e,t){const n=e.mark(),r=new Map;this.currentProfile=Sl(t.language),this.stemMatchCount=0,this.totalKeywordMatches=0;if(!this.matchTokenSequence(e,t.template.tokens,r))return e.reset(n),null;const i=this.calculateConfidence(t,r);return this.applyExtractionRules(t,r),{pattern:t,captured:r,consumedTokens:e.position()-n.position,confidence:i}}matchBest(e,t){const n=[];for(const r of t){const t=e.mark(),i=this.matchPattern(e,r);i&&n.push(i),e.reset(t)}if(0===n.length)return null;n.sort((e,t)=>{const n=t.pattern.priority-e.pattern.priority;return 0!==n?n:t.confidence-e.confidence});const r=n[0];return this.matchPattern(e,r.pattern),r}matchTokenSequence(e,t,n){const r=t[0],i="literal"===r?.type&&("and"===r.value||"then"===r.value||r.alternatives?.includes("and")||r.alternatives?.includes("then"));if("ar"===this.currentProfile?.code&&!i)for(;"conjunction"===e.peek()?.kind;)e.advance();for(const r of t){if(!this.matchPatternToken(e,r,n)){if(this.isOptional(r))continue;return!1}}return!0}matchPatternToken(e,t,n){switch(t.type){case"literal":return this.matchLiteralToken(e,t);case"role":return this.matchRoleToken(e,t,n);case"group":return this.matchGroupToken(e,t,n);default:return!1}}matchLiteralToken(e,t){const n=e.peek();if(!n)return!1;const r=this.getMatchType(n,t.value);if("none"!==r)return this.totalKeywordMatches++,"stem"===r&&this.stemMatchCount++,e.advance(),!0;if(t.alternatives)for(const r of t.alternatives){const t=this.getMatchType(n,r);if("none"!==t)return this.totalKeywordMatches++,"stem"===t&&this.stemMatchCount++,e.advance(),!0}return!1}matchRoleToken(e,t,n){this.skipNoiseWords(e);const r=e.peek();if(!r)return t.optional||!1;const i=this.tryMatchPossessiveExpression(e);if(i)return t.expectedTypes&&t.expectedTypes.length>0&&!t.expectedTypes.includes(i.type)&&!t.expectedTypes.includes("expression")?t.optional||!1:(n.set(t.role,i),!0);const a=this.tryMatchMethodCallExpression(e);if(a)return t.expectedTypes&&t.expectedTypes.length>0&&!t.expectedTypes.includes(a.type)&&!t.expectedTypes.includes("expression")?t.optional||!1:(n.set(t.role,a),!0);const o=this.tryMatchPossessiveSelectorExpression(e);if(o)return t.expectedTypes&&t.expectedTypes.length>0&&!Xy(o.type,t.expectedTypes)?t.optional||!1:(n.set(t.role,o),!0);const s=this.tryMatchPropertyAccessExpression(e);if(s)return t.expectedTypes&&t.expectedTypes.length>0&&!t.expectedTypes.includes(s.type)&&!t.expectedTypes.includes("expression")?t.optional||!1:(n.set(t.role,s),!0);const l=this.tryMatchSelectorPropertyExpression(e);if(l)return t.expectedTypes&&t.expectedTypes.length>0&&!Xy(l.type,t.expectedTypes)?t.optional||!1:(n.set(t.role,l),!0);const c=this.tokenToSemanticValue(r);return c?t.expectedTypes&&t.expectedTypes.length>0&&!t.expectedTypes.includes(c.type)?t.optional||!1:(n.set(t.role,c),e.advance(),!0):t.optional||!1}tryMatchPossessiveExpression(e){const t=e.peek();if(!t)return null;if(!this.currentProfile)return null;const n=(t.normalized||t.value).toLowerCase(),r=(i=this.currentProfile,a=n,i.possessive?.keywords?.[a]);var i,a;if(!r)return null;const o=e.mark();e.advance();const s=e.peek();if(!s)return e.reset(o),null;if("identifier"===s.kind||"keyword"===s.kind&&!this.isStructuralKeyword(s.value)||"selector"===s.kind&&s.value.startsWith("*")||"selector"===s.kind&&s.value.startsWith("@")||"selector"===s.kind&&s.value.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(s.value)){e.advance();let t=s.value;"selector"===s.kind&&t.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(t)&&(t=t.substring(1));let n=t;for(;"selector"===e.peek()?.kind&&e.peek().value.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(e.peek().value);)n+=e.peek().value,e.advance();const i=e.peek();return"literal"===i?.kind&&i.value.startsWith("(")&&(n+=i.value,e.advance()),_y(Dy(r),n)}return e.reset(o),null}isStructuralKeyword(e){return new Set(["into","in","to","from","at","by","with","without","before","after","of","as","on","then","end","else","if","repeat","while","for","toggle","add","remove","put","set","show","hide","increment","decrement","send","trigger","call"]).has(e.toLowerCase())}tryMatchMethodCallExpression(t){const n=t.peek();if(!n||"selector"!==n.kind)return null;const r=t.mark();t.advance();const i=t.peek();if(!i||"operator"!==i.kind||"."!==i.value)return t.reset(r),null;t.advance();const a=t.peek();if(!a||"identifier"!==a.kind)return t.reset(r),null;t.advance();const o=t.peek();if(!o||"punctuation"!==o.kind||"("!==o.value)return t.reset(r),null;t.advance();const s=[];for(;!t.isAtEnd()&&s.length<e.MAX_METHOD_ARGS;){const e=t.peek();if(!e)break;if("punctuation"===e.kind&&")"===e.value){t.advance();break}"punctuation"!==e.kind||","!==e.value?(s.push(e.value),t.advance()):t.advance()}return{type:"expression",raw:`${n.value}.${a.value}(${s.join(", ")})`}}tryMatchPropertyAccessExpression(t){const n=t.peek();if(!n)return null;if("identifier"!==n.kind&&"keyword"!==n.kind)return null;const r=t.mark();t.advance();const i=t.peek();if(!i||"operator"!==i.kind||"."!==i.value)return t.reset(r),null;t.advance();const a=t.peek();if(!a||"identifier"!==a.kind)return t.reset(r),null;t.advance();let o=`${n.value}.${a.value}`,s=1;for(;!t.isAtEnd()&&s<e.MAX_PROPERTY_DEPTH;){const e=t.peek();if(!e||"operator"!==e.kind||"."!==e.value)break;t.advance();const n=t.peek();if(!n||"identifier"!==n.kind)break;t.advance(),o+=`.${n.value}`,s++}const l=t.peek();if(l&&"punctuation"===l.kind&&"("===l.value){t.advance();const n=[];let r=0;for(;!t.isAtEnd()&&n.length<e.MAX_METHOD_ARGS;){const e=t.peek();if(!e)break;if("punctuation"===e.kind&&")"===e.value){if(0===r){t.advance();break}r--}"punctuation"===e.kind&&"("===e.value&&r++,"punctuation"!==e.kind||","!==e.value?(n.push(e.value),t.advance()):t.advance()}return{type:"expression",raw:`${o}(${n.join(", ")})`}}return{type:"expression",raw:o}}tryMatchPossessiveSelectorExpression(e){const t=e.peek();if(!t||"selector"!==t.kind)return null;const n=e.mark();e.advance();const r=e.peek();if(!r||"punctuation"!==r.kind||"'s"!==r.value)return e.reset(n),null;e.advance();const i=e.peek();return i?"selector"!==i.kind&&"identifier"!==i.kind?(e.reset(n),null):(e.advance(),_y($y(t.value),i.value)):(e.reset(n),null)}tryMatchSelectorPropertyExpression(e){const t=e.peek();if(!t||"selector"!==t.kind)return null;if(!t.value.startsWith("#"))return null;const n=e.mark();e.advance();const r=e.peek();if(!r||"selector"!==r.kind)return e.reset(n),null;if(!r.value.startsWith("."))return e.reset(n),null;const i=e.peek(1);i&&i.kind,e.advance();const a=r.value.slice(1);return _y($y(t.value),a)}matchGroupToken(e,t,n){const r=e.mark(),i=new Set(n.keys());if(!this.matchTokenSequence(e,t.tokens,n)){e.reset(r);for(const e of n.keys())i.has(e)||n.delete(e);return t.optional||!1}return!0}getMatchType(e,t){return e.value===t?"exact":e.normalized===t?"normalized":e.stem===t&&void 0!==e.stemConfidence&&e.stemConfidence>=.7?"stem":"keyword"===e.kind&&e.value.toLowerCase()===t.toLowerCase()?"case-insensitive":"none"}tokenToSemanticValue(e){switch(e.kind){case"selector":return $y(e.value);case"literal":return this.parseLiteralValue(e.value);case"keyword":const t=(e.normalized||e.value).toLowerCase();return qy(t)?Dy(t):Hy(e.normalized||e.value);case"identifier":if(e.value.startsWith(":"))return Dy(e.value);const n=e.value.toLowerCase();return qy(n)?Dy(n):{type:"expression",raw:e.value};case"url":return Hy(e.value,"string");default:return null}}parseLiteralValue(e){if(e.startsWith('"')||e.startsWith("'")||e.startsWith("`")||e.startsWith("「")){return Hy(e.slice(1,-1),"string")}if("true"===e)return Hy(!0,"boolean");if("false"===e)return Hy(!1,"boolean");const t=e.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);if(t){const n=parseFloat(t[1]);return t[2]?Hy(e,"duration"):Hy(n,"number")}const n=parseFloat(e);return isNaN(n)?Hy(e,"string"):Hy(n,"number")}applyExtractionRules(e,t){for(const[n,r]of Object.entries(e.extraction))t.has(n)||(void 0!==r.value?t.set(n,{type:"literal",value:r.value}):r.default&&t.set(n,r.default))}isOptional(e){return"literal"!==e.type&&!0===e.optional}calculateConfidence(e,t){let n=0,r=0;const i=t=>void 0!==e.extraction?.[t]?.default;for(const a of e.template.tokens)if("role"===a.type)r+=1,t.has(a.role)&&(n+=1);else if("group"===a.type)for(const e of a.tokens)if("role"===e.type){const a=i(e.role),o=.8;r+=o,t.has(e.role)?n+=o:a&&(n+=.6*o)}let a=r>0?n/r:1;if(this.stemMatchCount>0&&this.totalKeywordMatches>0){const e=this.stemMatchCount/this.totalKeywordMatches*.15;a=Math.max(.5,a-e)}const o=this.calculateVSOConfidenceBoost(e);a=Math.min(1,a+o);const s=this.arabicPrepositionDisambiguation(e,t);return a=Math.max(0,Math.min(1,a+s)),a}calculateVSOConfidenceBoost(e){if("ar"!==e.language)return 0;const t=e.template.tokens[0];if(!t||"literal"!==t.type)return 0;const n=new Set(["بدل","غير","أضف","أزل","ضع","اجعل","عين","زد","انقص","سجل","أظهر","أخف","شغل","أرسل","ركز","شوش","توقف","انسخ","احذف","اصنع","انتظر","انتقال","أو"]);if(n.has(t.value))return.15;if(t.alternatives)for(const e of t.alternatives)if(n.has(e))return.15;return 0}arabicPrepositionDisambiguation(e,t){if("ar"!==e.language)return 0;let n=0;const r={patient:["على"],destination:["إلى","الى"],source:["من"],agent:["من"],manner:["ب"],style:["ب"],goal:["إلى","الى"],method:["ب"]};for(const[e,i]of t.entries()){const t=r[e];if(!t||0===t.length)continue;const a="metadata"in i?i.metadata:void 0;if(a&&"string"==typeof a.prepositionValue){const e=a.prepositionValue;t.includes(e)?n+=.1:n-=.1}}return Math.max(-.1,Math.min(.1,n))}skipNoiseWords(t){const n=t.peek();if(!n)return;const r=n.value.toLowerCase();if(e.ENGLISH_NOISE_WORDS.has(r)){const e=t.mark();t.advance();const n=t.peek();if(n&&"selector"===n.kind)return;t.reset(e)}"class"===r&&t.advance()}extractEventModifiers(e){const t={};let n=!1;for(;!e.isAtEnd();){const r=e.peek();if(!r||"event-modifier"!==r.kind)break;const i=r.metadata;if(!i)break;switch(n=!0,i.modifierName){case"once":t.once=!0;break;case"debounce":"number"==typeof i.value&&(t.debounce=i.value);break;case"throttle":"number"==typeof i.value&&(t.throttle=i.value);break;case"queue":"first"!==i.value&&"last"!==i.value&&"all"!==i.value&&"none"!==i.value||(t.queue=i.value)}e.advance()}return n?t:void 0}}).MAX_PROPERTY_DEPTH=10,tv.MAX_METHOD_ARGS=20,tv.ENGLISH_NOISE_WORDS=new Set(["the","a","an"]),rv=new(nv=tv)}});function lv(e,t){return ov.render(e,t)}function cv(e){return ov.renderExplicit(e)}var uv=fl({"src/explicit/renderer.ts"(){Pl(),Zy(),av=class{render(e,t){if("compound"===e.kind)return this.renderCompound(e,t);const n=function(e,t){return jl(e).filter(e=>e.command===t).sort((e,t)=>t.priority-e.priority)}(t,e.action);if(0===n.length)return this.renderExplicit(e);const r=this.findBestPattern(e,n);return r?this.renderWithPattern(e,r):this.renderExplicit(e)}renderCompound(e,t){const n=e.statements.map(e=>this.render(e,t)),r=this.getChainWord(e.chainType,t);return n.join(` ${r} `)}getChainWord(e,t){const n=Sl(t);if(!n?.keywords)return e;const r=n.keywords[e];return r?.primary??e}renderExplicit(e){if("compound"===e.kind){const t=e;return t.statements.map(e=>this.renderExplicit(e)).join(` ${t.chainType} `)}const t=[e.action];for(const[n,r]of e.roles)t.push(`${n}:${this.valueToString(r)}`);if("event-handler"===e.kind){const n=e;if(n.body&&n.body.length>0){const e=n.body.map(e=>this.renderExplicit(e));t.push(`body:${e.join(" ")}`)}}return`[${t.join(" ")}]`}supportedLanguages(){return Yy()}findBestPattern(e,t){const n=t.map(t=>{let n=t.priority;for(const r of t.template.tokens)"role"===r.type&&(e.roles.has(r.role)?n+=10:r.optional||(n-=50));return"en"===t.language&&((t.id.includes("standard")||t.id.includes("en-source"))&&(n+=20),(t.id.includes("-when")||t.id.includes("-if")||t.id.includes("-upon"))&&(n-=15)),{pattern:t,score:n}});return n.sort((e,t)=>t.score-e.score),n.length>0?n[0].pattern:null}renderWithPattern(e,t){const n=[],r=t.language;for(const i of t.template.tokens){const t=this.renderPatternToken(i,e,r);null!==t&&n.push(t)}if("event-handler"===e.kind){const t=e;if(t.body&&t.body.length>0){const e=t.body.map(e=>this.render(e,r));n.push(e.join(" "))}}return n.join(" ")}renderPatternToken(e,t,n){switch(e.type){case"literal":return e.value;case"role":{const r=t.roles.get(e.role);return r?this.valueToNaturalString(r,n):(e.optional,null)}case"group":{if(!e.tokens.filter(e=>"role"===e.type&&!e.optional).every(e=>t.roles.has(e.role))&&e.optional)return null;if(e.optional){if(e.tokens.find(e=>"role"===e.type&&"destination"===e.role)){const e=t.roles.get("destination");if("reference"===e?.type&&"me"===e.value)return null}}const r=[];for(const i of e.tokens){const e=this.renderPatternToken(i,t,n);null!==e&&r.push(e)}return r.length>0?r.join(" "):null}default:return null}}valueToString(e){switch(e.type){case"literal":return"string"==typeof e.value?"string"===e.dataType||/\s/.test(e.value)?`"${e.value}"`:e.value:String(e.value);case"selector":case"reference":return e.value;case"property-path":return`${this.valueToString(e.object)}'s ${e.property}`;case"expression":return e.raw}}valueToNaturalString(e,t="en"){switch(e.type){case"literal":return"string"==typeof e.value&&"string"===e.dataType?`"${e.value}"`:String(e.value);case"selector":return e.value;case"reference":return this.renderReference(e,t);case"property-path":return this.renderPropertyPath(e,t);case"expression":return e.raw}}renderReference(e,t){const n=Sl(t);return n?.references?n.references[e.value]??e.value:e.value}renderPropertyPath(e,t){const n=Sl(t),r=e.property,i="reference"===e.object.type?e.object.value:null;if(n?.possessive?.specialForms&&i){const e=n.possessive.specialForms[i];if(e){const{markerPosition:t,usePossessiveAdjectives:i}=n.possessive;return i&&"after-object"===t?`${r} ${e}`:`${e} ${r}`}}const a=this.valueToNaturalString(e.object,t);if(n?.possessive){const{marker:e,markerPosition:t,usePossessiveAdjectives:o}=n.possessive;if(o&&i&&"after-object"===t)return`${r} ${a}`;if(e)switch(t){case"between":return n.usesSpaces?`${a}${e} ${r}`:`${a}${e}${r}`;case"after-object":return`${a}${e} ${r}`;case"before-property":return`${a} ${e} ${r}`}}return"en"!==t&&n?.possessive?`${a} ${r}`:"me"===a?`my ${r}`:"it"===a?`its ${r}`:`${a}'s ${r}`}},ov=new av}});function pv(e){const t=e.trim();if(!t.startsWith("[")||!t.endsWith("]"))throw new Error("Explicit syntax must be wrapped in brackets: [command role:value ...]");const n=t.slice(1,-1).trim();if(!n)throw new Error("Empty explicit statement");const r=function(e){const t=[];let n="",r=!1,i="",a=0;for(let o=0;o<e.length;o++){const s=e[o];r?(n+=s,s===i&&"\\"!==e[o-1]&&(r=!1)):'"'!==s&&"'"!==s?"["!==s?"]"!==s?" "!==s||0!==a?n+=s:n&&(t.push(n),n=""):(a--,n+=s):(a++,n+=s):(r=!0,i=s,n+=s)}n&&t.push(n);return t}(n);if(0===r.length)throw new Error("No command specified in explicit statement");const i=r[0].toLowerCase(),a=new Map;for(let e=1;e<r.length;e++){const t=r[e],n=t.indexOf(":");if(-1===n)throw new Error(`Invalid role format: "${t}". Expected role:value`);const i=t.slice(0,n),o=t.slice(n+1);if("body"===i&&o.startsWith("[")){const e=dv(t,n+1),r=t.slice(n+1,e+1);a.set(i,{type:"expression",raw:r});continue}const s=mv(o);a.set(i,s)}if("on"===i){const e=a.get("event");if(!e)throw new Error("Event handler requires event role: [on event:click ...]");const t=a.get("body"),n=[];return t&&"expression"===t.type&&n.push(pv(t.raw)),a.delete("body"),By(e,n,void 0,{sourceLanguage:"explicit"})}const o={};for(const[e,t]of a)o[e]=t;return Vy(i,o,{sourceLanguage:"explicit"})}function mv(e){if(e.startsWith("#")||e.startsWith(".")||e.startsWith("[")||e.startsWith("@")||e.startsWith("*"))return $y(e);if(e.startsWith('"')||e.startsWith("'")){return Hy(e.slice(1,-1),"string")}if("true"===e)return Hy(!0,"boolean");if("false"===e)return Hy(!1,"boolean");const t=e.toLowerCase();if(qy(t))return Dy(t);const n=e.match(/^(-?\d+(?:\.\d+)?)(ms|s|m|h)?$/);if(n){const t=parseFloat(n[1]);return n[2]?Hy(e,"duration"):Hy(t,"number")}return Hy(e,"string")}function dv(e,t){let n=0;for(let r=t;r<e.length;r++)if("["===e[r])n++;else if("]"===e[r]&&(n--,0===n))return r;return e.length-1}function hv(e){const t=e.trim();return t.startsWith("[")&&t.endsWith("]")}var fv,yv,vv,gv=fl({"src/explicit/parser.ts"(){Ky()}}),bv={};function kv(e,t){return vv.parse(e,t)}function wv(e,t){return vv.canParse(e,t)}function zv(e,t){try{return vv.parse(e,t).action}catch{return null}}function xv(e,t){return Jy(e,t)}function Ev(){return Yy()}function Sv(e,t,n){return Av(kv(e,t),n)}function Tv(e,t){const n=kv(e,t),r={};for(const e of Ev())try{r[e]=Av(n,e)}catch{}return r}function Cv(){return{analyze(e,t){try{return{node:kv(e,t),confidence:1,success:!0}}catch(e){return{node:null,confidence:0,success:!1,error:e}}}}}function Av(e,t){return lv(e,t)}function jv(e){return lv(e,"explicit")}function Lv(e){return pv(e)}function Pv(e,t){return jv(kv(e,t))}function Iv(e,t){return Av(Lv(e),t)}function Nv(e,t){return Iv(Pv(e,t),t)}yl(bv,{SemanticParserImpl:()=>yv,canParse:()=>wv,createSemanticAnalyzer:()=>Cv,fromExplicit:()=>Iv,getAllTranslations:()=>Tv,getCommandType:()=>zv,getSupportedLanguages:()=>Ev,parse:()=>kv,parseExplicit:()=>Lv,render:()=>Av,renderExplicit:()=>jv,roundTrip:()=>Nv,semanticParser:()=>vv,toExplicit:()=>Pv,tokenize:()=>xv,translate:()=>Sv});var Ov=fl({"src/parser/semantic-parser.ts"(){Ky(),Zy(),Pl(),sv(),Gy(),uv(),gv(),(fv=class e{parse(e,t){const{modifiers:n,remainingInput:r}=this.extractStandaloneModifiers(e,t),i=r||e,a=Jy(i,t),o=jl(t);if(0===o.length)throw new Error(`No patterns available for language: ${t}`);const s=[...o].sort((e,t)=>t.priority-e.priority),l=s.filter(e=>"on"===e.command),c=rv.matchBest(a,l);if(c){const e=this.buildEventHandler(c,a,t);return n?this.applyModifiers(e,n):e}const u=s.filter(e=>"on"!==e.command),p=rv.matchBest(a,u);if(p)return this.buildCommand(p,t);const m=this.trySOVEventExtraction(i,t,s);if(m)return n?this.applyModifiers(m,n):m;const d=this.tryCompoundCommandParsing(a,u,t);if(d)return d;throw new Error(`Could not parse input in ${t}: ${i}`)}canParse(e,t){try{return this.parse(e,t),!0}catch{return!1}}supportedLanguages(){return Yy()}buildCommand(e,t){if(!e)throw new Error("No match to build command from");const n={};for(const[t,r]of e.captured)n[t]=r;return Vy(e.pattern.command,n,{sourceLanguage:t,patternId:e.pattern.id,confidence:e.confidence})}buildEventHandler(e,t,n){if(!e)throw new Error("No match to build event handler from");const r=e.captured.get("event");if(!r)throw new Error("Event handler pattern matched but no event captured");const i=rv.extractEventModifiers(t),a=this.extractOrConjunctionEvents(t,n);let o,s=r;if(a.length>0&&"literal"===r.type){s={type:"literal",value:[String(r.value),...a.map(e=>String("value"in e?e.value:""))].join(" or ")}}const l=e.captured.get("action");if(l&&"literal"===l.type){const r=l.value,i={};for(const[t,n]of e.captured)"event"!==t&&"action"!==t&&"continues"!==t&&(i[t]=n);const a=Vy(r,i,{sourceLanguage:n,patternId:e.pattern.id,confidence:e.confidence}),s=e.captured.get("continues");if(s&&"literal"===s.type&&"then"===s.value){const e=jl(n).filter(e=>"on"!==e.command).sort((e,t)=>t.priority-e.priority),r=jl(n).filter(e=>e.id.startsWith("grammar-")&&e.id.includes("-continuation")).sort((e,t)=>t.priority-e.priority),i=this.parseBodyWithGrammarPatterns(t,e,r,n);o=i.length>0?[a,...i]:[a]}else o=[a]}else{const e=jl(n).filter(e=>"on"!==e.command).sort((e,t)=>t.priority-e.priority);o=this.parseBodyWithClauses(t,e,n)}return By(s,o,i,{sourceLanguage:n,patternId:e.pattern.id,confidence:e.confidence})}parseBodyWithClauses(e,t,n){const r=[],i=[];for(;!e.isAtEnd();){const a=e.peek();if(!a)break;const o="conjunction"===a.kind||"keyword"===a.kind&&this.isThenKeyword(a.value,n),s="keyword"===a.kind&&this.isEndKeyword(a.value,n);if(o){if(i.length>0){const e=this.parseClause(i,t,n);r.push(...e),i.length=0}e.advance()}else{if(s){if(i.length>0){const e=this.parseClause(i,t,n);r.push(...e)}e.advance();break}i.push(a),e.advance()}}if(i.length>0){const e=this.parseClause(i,t,n);r.push(...e)}return r.length>1?[Fy(r,"then",{sourceLanguage:n})]:r}parseClause(e,t,n){if(0===e.length)return[];const r=new Ll(e,n),i=[];for(;!r.isAtEnd();){const e=rv.matchBest(r,t);e?i.push(this.buildCommand(e,n)):r.advance()}if(0===i.length){const t=this.parseSOVClauseByVerbAnchoring(e,n);if(t.length>0)return t}return i}static buildVerbLookup(e){const t=new Map;for(const[n,r]of Object.entries(e.keywords))if(!["on","if","else","when","where","while","for","end","then","and"].includes(n)&&(t.set(r.primary.toLowerCase(),n),r.alternatives))for(const e of r.alternatives)t.set(e.toLowerCase(),n);return t}static buildMarkerToRoleLookup(e){const t=new Map;for(const[n,r]of Object.entries(e.roleMarkers))if(r&&(t.set(r.primary,n),r.alternatives))for(const e of r.alternatives)t.has(e)||t.set(e,n);return t}parseSOVClauseByVerbAnchoring(t,n){const r=Sl(n);if(!r||"SOV"!==r.wordOrder)return[];const i=e.buildVerbLookup(r),a=e.buildMarkerToRoleLookup(r),o=[];let s=0;for(;s<t.length;){let e=-1,r="";for(let n=s;n<t.length;n++){const a=t[n],o=i.get(a.value.toLowerCase()),s=a.normalized?i.get(a.normalized.toLowerCase()):void 0,l=o||s;if(l){e=n,r=l;break}}if(-1===e)break;const l=t.slice(s,e);let c=t.length;for(let r=e+1;r<t.length;r++){const a=t[r];if("conjunction"===a.kind||this.isThenKeyword(a.value,n)){c=r;break}if(r>e+1){if(i.get(a.value.toLowerCase())||(a.normalized?i.get(a.normalized.toLowerCase()):void 0)){c=r;break}}}const u=t.slice(e+1,c),p=this.extractRolesFromMarkedTokens(l,u,a,r,n);if(o.push(Vy(r,p,{sourceLanguage:n,confidence:.7})),s=c,s<t.length){const e=t[s];("conjunction"===e.kind||this.isThenKeyword(e.value,n))&&s++}}return o}extractRolesFromMarkedTokens(e,t,n,r,i){const a={},o=e=>{let t=[];for(const i of e){const e=n.get(i.value);if(e&&"particle"===i.kind&&t.length>0){const n=this.tokensToSemanticValue(t);if(n){const t=this.mapRoleForCommand(e,r,a);t&&(a[t]=n)}t=[]}else t.push(i)}if(t.length>0){const e=this.tokensToSemanticValue(t);e&&(a.patient?a.destination||(a.destination=e):a.patient=e)}};return o(e),o(t),a}mapRoleForCommand(e,t,n){return n[e]?"patient"!==e||n.destination?"destination"!==e||n.patient?"source"!==e||n.source?null:"source":"patient":"destination":e}tokensToSemanticValue(e){if(0===e.length)return null;const t=e.filter(e=>"whitespace"!==e.kind);if(0===t.length)return null;if(1===t.length)return this.tokenToSemanticValue(t[0]);const n=t.map(e=>e.value).join(""),r=t[0];return"selector"===r.kind||r.value.startsWith("#")||r.value.startsWith(".")||r.value.startsWith("@")||r.value.startsWith("*")?$y(n):"literal"===r.kind||r.value.startsWith('"')||r.value.startsWith("'")?Hy(n):"reference"===r.kind?Dy(n):Hy(n)}tokenToSemanticValue(e){const t=e.value;if("selector"===e.kind||t.startsWith("#")||t.startsWith(".")||t.startsWith("@")||t.startsWith("*"))return $y(t);if(t.startsWith('"')||t.startsWith("'"))return Hy(t);if(/^-?\d+(\.\d+)?$/.test(t))return Hy(parseFloat(t));if("true"===t||"真"===t||"참"===t||"doğru"===t)return Hy(!0);if("false"===t||"偽"===t||"거짓"===t||"yanlış"===t)return Hy(!1);const n=e.normalized?.toLowerCase();return"me"===n||"it"===n||"you"===n||"result"===n||"body"===n?Dy(n):"reference"===e.kind?Dy(e.normalized||"me"):Hy(t)}parseBodyWithGrammarPatterns(e,t,n,r){const i=[];for(;!e.isAtEnd();){const a=e.peek();if(a&&this.isThenKeyword(a.value,r)){e.advance();continue}if(a&&this.isEndKeyword(a.value,r)){e.advance();break}let o=!1;if(n.length>0){const t=rv.matchBest(e,n);if(t){const e=t.pattern.command,n={};for(const[e,r]of t.captured)"event"!==e&&"action"!==e&&"continues"!==e&&(n[e]=r);const a=Vy(e,n,{sourceLanguage:r,patternId:t.pattern.id});i.push(a),o=!0;const s=t.captured.get("continues");if(s&&"literal"===s.type&&"then"===s.value)continue}}if(!o){const n=rv.matchBest(e,t);n&&(i.push(this.buildCommand(n,r)),o=!0)}o||e.advance()}return i}tryCompoundCommandParsing(e,t,n){const r=e.tokens;if(!r.some(e=>"conjunction"===e.kind||"keyword"===e.kind&&this.isThenKeyword(e.value,n)))return null;const i=new Ll(r,n),a=this.parseBodyWithClauses(i,t,n);return 0===a.length?null:1===a.length?a[0]:Fy(a,"then",{sourceLanguage:n,confidence:.65})}trySOVEventExtraction(t,n,r){const i=e.SOV_EVENT_MARKERS[n];if(!i)return null;const a=Jy(t,n).tokens,o=Uy[n],s=new Set;if(o)for(const e of Object.keys(o))s.add(e.toLowerCase());const l=e.SOV_SOURCE_MARKERS[n];let c=-1,u="",p="",m=1;for(let t=0;t<a.length;t++){const n=a[t],r=n.value.toLowerCase();let l=r,d="";const h=r.indexOf("[");h>0&&(l=r.slice(0,h),d=n.value.slice(h));const f=n.normalized?.toLowerCase(),y=f&&e.KNOWN_EVENTS.has(f),v=s.has(r)||s.has(l),g=e.KNOWN_EVENTS.has(l);if(y||v||g){let e;if(e=y?f:v?o?.[r]??o?.[l]??l:l,!(i.size>0)){c=t,u=e,p=d,m=1;break}{let n=1;const r=a[t+1];r&&"selector"===r.kind&&r.value.startsWith("[")&&(n=2);const o=a[t+n];if(o&&("particle"===o.kind||"keyword"===o.kind)&&i.has(o.value)){c=t,u=e,p=d||(2===n?a[t+1].value:""),m=n+1;break}}}}if(-1===c)return null;const d=new Set;for(let e=c;e<c+m;e++)d.add(e);if(l){const e=c+m;if(e<a.length){const t=a[e];"particle"!==t.kind&&"keyword"!==t.kind||!l.markers.has(t.value)||d.add(e)}for(let e=0;e<c;e++){const t=a[e],n=t.value.toLowerCase(),r=t.normalized?.toLowerCase();if(l.windowTokens.has(n)||r&&l.windowTokens.has(r)){d.add(e);break}}}const h=a.filter((e,t)=>!d.has(t));if(0===h.length)return null;const f=r.filter(e=>"on"!==e.command),y=new Ll(h,n),v=this.parseBodyWithClauses(y,f,n);if(0===v.length)return null;const g={sourceLanguage:n,confidence:.75};return p&&(g.keyFilter=p),By({type:"literal",value:u},v,void 0,g)}isThenKeyword(e,t){const n={en:new Set(["then"]),ja:new Set(["それから","次に","そして"]),ar:new Set(["ثم","بعدها","ثمّ"]),es:new Set(["entonces","luego","después"]),ko:new Set(["그다음","그리고","그런후","그러면"]),zh:new Set(["然后","接着","之后"]),tr:new Set(["sonra","ardından","daha sonra"]),pt:new Set(["então","depois","logo"]),fr:new Set(["puis","ensuite","alors"]),de:new Set(["dann","danach","anschließend"]),id:new Set(["lalu","kemudian","setelah itu"]),tl:new Set(["pagkatapos","tapos"]),bn:new Set(["তারপর","পরে"]),qu:new Set(["chaymantataq","hinaspa","chaymanta","chayqa"]),sw:new Set(["kisha","halafu","baadaye"])};return(n[t]||n.en).has(e.toLowerCase())}isEndKeyword(e,t){const n={en:new Set(["end"]),ja:new Set(["終わり","終了","おわり"]),ar:new Set(["نهاية","انتهى","آخر"]),es:new Set(["fin","final","terminar"]),ko:new Set(["끝","종료","마침"]),zh:new Set(["结束","终止","完"]),tr:new Set(["son","bitiş","bitti"]),pt:new Set(["fim","final","término"]),fr:new Set(["fin","terminer","finir"]),de:new Set(["ende","beenden","fertig"]),id:new Set(["selesai","akhir","tamat"]),tl:new Set(["wakas","tapos"]),bn:new Set(["সমাপ্ত"]),qu:new Set(["tukukuy","tukuy","puchukay"]),sw:new Set(["mwisho","maliza","tamati"])};return(n[t]||n.en).has(e.toLowerCase())}extractStandaloneModifiers(t,n){const r=Jy(t,n).tokens;if(0===r.length)return{modifiers:null,remainingInput:null};const i=r[0].value.toLowerCase(),a=e.STANDALONE_MODIFIERS[i];if(!a)return{modifiers:null,remainingInput:null};const o={};let s=1;if("once"===a)o.once=!0;else{let e=1;if(e<r.length){const t=r[e];"keyword"!==t.kind&&"particle"!==t.kind||(e++,s++)}if(e<r.length){const t=r[e];if("literal"===t.kind){const n=t.value.match(/^(\d+)(ms|s|m)?$/);if(n){let t=parseInt(n[1],10);const r=n[2]||"ms";"s"===r?t*=1e3:"m"===r&&(t*=6e4),o[a]=t,s=e+1}}}o[a]||(o[a]="debounce"===a?300:100)}const l=r.slice(s);if(0===l.length)return{modifiers:null,remainingInput:null};const c=l[0].position.start;return{modifiers:o,remainingInput:t.slice(c)}}applyModifiers(e,t){return{...e,eventModifiers:{...e.eventModifiers,...t}}}extractOrConjunctionEvents(t,n){const r=[];for(;;){const n=t.mark(),i=t.peek();if(!i)break;const a=(i.normalized||i.value).toLowerCase();if(!e.OR_KEYWORDS.has(a)){t.reset(n);break}t.advance();const o=t.peek();if(!o){t.reset(n);break}const s=(o.normalized||o.value).toLowerCase();t.advance(),r.push({type:"literal",value:s})}return r}}).KNOWN_EVENTS=new Set(["click","dblclick","input","change","submit","keydown","keyup","keypress","mouseover","mouseout","mousedown","mouseup","focus","blur","load","scroll","resize","contextmenu"]),fv.SOV_EVENT_MARKERS={ja:new Set(["で"]),ko:new Set,tr:new Set(["de","da","te","ta"]),bn:new Set(["এ"]),qu:new Set(["pi"])},fv.SOV_SOURCE_MARKERS={ja:{markers:new Set(["から"]),windowTokens:new Set(["ウィンドウ","ドキュメント","window","document"])},ko:{markers:new Set(["에서"]),windowTokens:new Set(["창","윈도우","문서","window","document"])},tr:{markers:new Set(["den","dan","ten","tan"]),windowTokens:new Set(["pencere","belge","window","document"])},bn:{markers:new Set(["থেকে","মধ্যে"]),windowTokens:new Set(["উইন্ডো","ডকুমেন্ট","window","document"])},qu:{markers:new Set(["manta"]),windowTokens:new Set(["k_iri","ventana","window","document"])}},fv.STANDALONE_MODIFIERS={once:"once",debounced:"debounce",debounce:"debounce",throttled:"throttle",throttle:"throttle"},fv.OR_KEYWORDS=new Set(["or","أو","o","ou","oder","atau","atau","或","または","또는","veya","অথবা","utaq","au","або","или","hoặc","lub","או","หรือ","o"]),vv=new(yv=fv)}});Pl(),wc(),gc(),wl("ar",vc,oc),Pl(),Pc(),Ac(),wl("bn",Cc,kc),Pl(),Qc(),$c(),wl("de",Fc,Lc),Pl(),au(),eu(),kp(),wl("en",Xc,Gc),zl("en",dp()),Pl(),Rp(),Ip(),wl("es",Pp,zp),Pl(),Rp();var Rv={code:"es-MX",name:"Spanish (Mexico)",nativeName:"Español (México)",direction:"ltr",wordOrder:"SVO",markingStrategy:"preposition",usesSpaces:!0,defaultVerbForm:"infinitive",extends:"es",verb:{position:"start",subjectDrop:!0},references:{me:"yo",it:"ello",you:"tú",result:"resultado",event:"evento",target:"objetivo",body:"cuerpo"},possessive:{marker:"de",markerPosition:"before-property",usePossessiveAdjectives:!0,specialForms:{me:"mi",it:"su",you:"tu"},keywords:{mi:"me",tu:"you",su:"it"}},roleMarkers:{destination:{primary:"en",alternatives:["sobre","a"],position:"before"},source:{primary:"de",alternatives:["desde"],position:"before"},patient:{primary:"",position:"before"},style:{primary:"con",position:"before"}},keywords:{toggle:{primary:"alternar",alternatives:["cambiar","conmutar","switchear"],normalized:"toggle"},add:{primary:"agregar",alternatives:["añadir","meter"],normalized:"add"},remove:{primary:"quitar",alternatives:["eliminar","borrar","sacar"],normalized:"remove"},put:{primary:"poner",alternatives:["colocar","meter"],normalized:"put"},append:{primary:"añadir",normalized:"append"},prepend:{primary:"anteponer",normalized:"prepend"},take:{primary:"tomar",alternatives:["agarrar"],normalized:"take"},make:{primary:"hacer",alternatives:["crear"],normalized:"make"},clone:{primary:"clonar",alternatives:["copiar"],normalized:"clone"},swap:{primary:"intercambiar",alternatives:["cambiar"],normalized:"swap"},morph:{primary:"transformar",alternatives:["convertir"],normalized:"morph"},set:{primary:"establecer",alternatives:["fijar","definir","setear"],normalized:"set"},get:{primary:"obtener",alternatives:["conseguir","jalar"],normalized:"get"},increment:{primary:"incrementar",alternatives:["aumentar","subir"],normalized:"increment"},decrement:{primary:"decrementar",alternatives:["disminuir","bajar"],normalized:"decrement"},log:{primary:"registrar",alternatives:["imprimir","loguear"],normalized:"log"},show:{primary:"mostrar",alternatives:["enseñar"],normalized:"show"},hide:{primary:"ocultar",alternatives:["esconder"],normalized:"hide"},transition:{primary:"transición",alternatives:["animar"],normalized:"transition"},on:{primary:"en",alternatives:["cuando","al"],normalized:"on"},trigger:{primary:"disparar",alternatives:["activar"],normalized:"trigger"},send:{primary:"enviar",alternatives:["mandar"],normalized:"send"},focus:{primary:"enfocar",normalized:"focus"},blur:{primary:"desenfocar",normalized:"blur"},click:{primary:"clic",alternatives:["hacer clic","dar clic"],normalized:"click"},hover:{primary:"sobrevolar",alternatives:["pasar encima"],normalized:"hover"},submit:{primary:"envío",alternatives:["enviar"],normalized:"submit"},input:{primary:"entrada",alternatives:["introducir"],normalized:"input"},change:{primary:"cambio",alternatives:["cambiar"],normalized:"change"},go:{primary:"ir",alternatives:["navegar"],normalized:"go"},wait:{primary:"esperar",alternatives:["ahorita","aguantar"],normalized:"wait"},fetch:{primary:"buscar",alternatives:["obtener","jalar","traer"],normalized:"fetch"},settle:{primary:"estabilizar",normalized:"settle"},if:{primary:"si",normalized:"if"},when:{primary:"cuando",normalized:"when"},where:{primary:"donde",normalized:"where"},else:{primary:"sino",alternatives:["de lo contrario","si no"],normalized:"else"},repeat:{primary:"repetir",normalized:"repeat"},for:{primary:"para",normalized:"for"},while:{primary:"mientras",normalized:"while"},continue:{primary:"continuar",alternatives:["seguir"],normalized:"continue"},halt:{primary:"detener",alternatives:["parar"],normalized:"halt"},throw:{primary:"lanzar",alternatives:["aventar","arrojar"],normalized:"throw"},call:{primary:"llamar",normalized:"call"},return:{primary:"retornar",alternatives:["devolver","regresar"],normalized:"return"},then:{primary:"entonces",alternatives:["luego","después"],normalized:"then"},and:{primary:"y",alternatives:["además","también"],normalized:"and"},end:{primary:"fin",alternatives:["final","terminar"],normalized:"end"},js:{primary:"js",normalized:"js"},async:{primary:"asíncrono",normalized:"async"},tell:{primary:"decir",normalized:"tell"},default:{primary:"predeterminar",alternatives:["por defecto"],normalized:"default"},init:{primary:"iniciar",alternatives:["inicializar","arrancar"],normalized:"init"},behavior:{primary:"comportamiento",normalized:"behavior"},install:{primary:"instalar",normalized:"install"},measure:{primary:"medir",normalized:"measure"},beep:{primary:"pitido",normalized:"beep"},break:{primary:"romper",normalized:"break"},copy:{primary:"copiar",normalized:"copy"},exit:{primary:"salir",normalized:"exit"},pick:{primary:"escoger",normalized:"pick"},render:{primary:"renderizar",normalized:"render"},into:{primary:"en",alternatives:["dentro de"],normalized:"into"},before:{primary:"antes",normalized:"before"},after:{primary:"después",normalized:"after"},until:{primary:"hasta",normalized:"until"},event:{primary:"evento",normalized:"event"},from:{primary:"de",alternatives:["desde"],normalized:"from"}},eventHandler:{keyword:{primary:"al",alternatives:["cuando","en"],normalized:"on"},sourceMarker:{primary:"de",alternatives:["desde"],position:"before"},eventMarker:{primary:"al",alternatives:["cuando"],position:"before"},temporalMarkers:["cuando","al"]}};function Mv(e){switch(e){case"ar":case"ja":case"ko":case"tr":default:return[];case"bn":return[{id:"toggle-bn-full",language:"bn",command:"toggle",priority:100,template:{format:"{patient} কে টগল করুন",tokens:[{type:"role",role:"patient"},{type:"literal",value:"কে"},{type:"literal",value:"টগল",alternatives:["পরিবর্তন"]},{type:"literal",value:"করুন"}]},extraction:{patient:{position:0}}},{id:"toggle-bn-simple",language:"bn",command:"toggle",priority:90,template:{format:"টগল {patient}",tokens:[{type:"literal",value:"টগল",alternatives:["পরিবর্তন"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}},{id:"toggle-bn-with-dest",language:"bn",command:"toggle",priority:95,template:{format:"{destination} এ {patient} কে টগল করুন",tokens:[{type:"role",role:"destination"},{type:"literal",value:"এ",alternatives:["তে"]},{type:"role",role:"patient"},{type:"literal",value:"কে"},{type:"literal",value:"টগল",alternatives:["পরিবর্তন"]},{type:"literal",value:"করুন"}]},extraction:{destination:{position:0},patient:{position:2}}}];case"en":return[{id:"toggle-en-full",language:"en",command:"toggle",priority:100,template:{format:"toggle {patient} on {target}",tokens:[{type:"literal",value:"toggle"},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"on",alternatives:["from"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"on",markerAlternatives:["from"],default:{type:"reference",value:"me"}}}},{id:"toggle-en-simple",language:"en",command:"toggle",priority:90,template:{format:"toggle {patient}",tokens:[{type:"literal",value:"toggle"},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}}];case"es":return[{id:"toggle-es-full",language:"es",command:"toggle",priority:100,template:{format:"alternar {patient} en {target}",tokens:[{type:"literal",value:"alternar",alternatives:["cambiar","toggle"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"en",alternatives:["sobre","de"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"en",markerAlternatives:["sobre","de"],default:{type:"reference",value:"me"}}}},{id:"toggle-es-simple",language:"es",command:"toggle",priority:90,template:{format:"alternar {patient}",tokens:[{type:"literal",value:"alternar",alternatives:["cambiar","toggle"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}}];case"hi":return[{id:"toggle-hi-full",language:"hi",command:"toggle",priority:100,template:{format:"{patient} को {destination} पर टॉगल करें",tokens:[{type:"role",role:"patient"},{type:"literal",value:"को"},{type:"role",role:"destination"},{type:"literal",value:"पर"},{type:"literal",value:"टॉगल",alternatives:["बदलें","बदल"]},{type:"group",optional:!0,tokens:[{type:"literal",value:"करें",alternatives:["करो"]}]}]},extraction:{patient:{position:0},destination:{marker:"को",position:2}}},{id:"toggle-hi-simple",language:"hi",command:"toggle",priority:90,template:{format:"{patient} टॉगल करें",tokens:[{type:"role",role:"patient"},{type:"literal",value:"टॉगल",alternatives:["बदलें","बदल"]},{type:"group",optional:!0,tokens:[{type:"literal",value:"करें",alternatives:["करो"]}]}]},extraction:{patient:{position:0},destination:{default:{type:"reference",value:"me"}}}},{id:"toggle-hi-bare",language:"hi",command:"toggle",priority:80,template:{format:"टॉगल {patient}",tokens:[{type:"literal",value:"टॉगल",alternatives:["बदलें","बदल"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}}];case"it":return[{id:"toggle-it-full",language:"it",command:"toggle",priority:100,template:{format:"commutare {patient} su {target}",tokens:[{type:"literal",value:"commutare",alternatives:["alternare","toggle","cambiare"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"su",alternatives:["in","di"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"su",markerAlternatives:["in","di"],default:{type:"reference",value:"me"}}}},{id:"toggle-it-simple",language:"it",command:"toggle",priority:90,template:{format:"commutare {patient}",tokens:[{type:"literal",value:"commutare",alternatives:["alternare","toggle","cambiare"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}}];case"pl":return[{id:"toggle-pl-full",language:"pl",command:"toggle",priority:100,template:{format:"przełącz {patient} na {destination}",tokens:[{type:"literal",value:"przełącz",alternatives:["przelacz","przełączaj"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"na",alternatives:["w","dla"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"na",markerAlternatives:["w","dla"],default:{type:"reference",value:"me"}}}},{id:"toggle-pl-simple",language:"pl",command:"toggle",priority:90,template:{format:"przełącz {patient}",tokens:[{type:"literal",value:"przełącz",alternatives:["przelacz","przełączaj"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}}];case"qu":return[{id:"toggle-qu-sov",language:"qu",command:"toggle",priority:100,template:{format:"{patient} ta t'ikray",tokens:[{type:"role",role:"patient"},{type:"literal",value:"ta"},{type:"literal",value:"t'ikray",alternatives:["tikray","kutichiy"]}]},extraction:{patient:{position:0}}},{id:"toggle-qu-simple",language:"qu",command:"toggle",priority:90,template:{format:"t'ikray {patient}",tokens:[{type:"literal",value:"t'ikray",alternatives:["tikray","kutichiy"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}},{id:"toggle-qu-with-dest",language:"qu",command:"toggle",priority:95,template:{format:"{destination} pi {patient} ta t'ikray",tokens:[{type:"role",role:"destination"},{type:"literal",value:"pi"},{type:"role",role:"patient"},{type:"literal",value:"ta"},{type:"literal",value:"t'ikray",alternatives:["tikray","kutichiy"]}]},extraction:{destination:{position:0},patient:{position:2}}},{id:"toggle-qu-dest-man",language:"qu",command:"toggle",priority:93,template:{format:"{destination} man {patient} ta t'ikray",tokens:[{type:"role",role:"destination"},{type:"literal",value:"man"},{type:"role",role:"patient"},{type:"literal",value:"ta"},{type:"literal",value:"t'ikray",alternatives:["tikray","kutichiy"]}]},extraction:{destination:{position:0},patient:{position:2}}}];case"ru":return[{id:"toggle-ru-full",language:"ru",command:"toggle",priority:100,template:{format:"переключить {patient} на {destination}",tokens:[{type:"literal",value:"переключить",alternatives:["переключи"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"на",alternatives:["в","для"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"на",markerAlternatives:["в","для"],default:{type:"reference",value:"me"}}}},{id:"toggle-ru-simple",language:"ru",command:"toggle",priority:90,template:{format:"переключить {patient}",tokens:[{type:"literal",value:"переключить",alternatives:["переключи"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}}];case"th":return[{id:"toggle-th-simple",language:"th",command:"toggle",priority:100,template:{format:"สลับ {patient}",tokens:[{type:"literal",value:"สลับ"},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}},{id:"toggle-th-with-dest",language:"th",command:"toggle",priority:95,template:{format:"สลับ {patient} ใน {destination}",tokens:[{type:"literal",value:"สลับ"},{type:"role",role:"patient"},{type:"literal",value:"ใน"},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"ใน",position:3}}}];case"uk":return[{id:"toggle-uk-full",language:"uk",command:"toggle",priority:100,template:{format:"перемкнути {patient} на {destination}",tokens:[{type:"literal",value:"перемкнути",alternatives:["перемкни"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"на",alternatives:["в","для"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"на",markerAlternatives:["в","для"],default:{type:"reference",value:"me"}}}},{id:"toggle-uk-simple",language:"uk",command:"toggle",priority:90,template:{format:"перемкнути {patient}",tokens:[{type:"literal",value:"перемкнути",alternatives:["перемкни"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}}];case"vi":return[{id:"toggle-vi-full",language:"vi",command:"toggle",priority:100,template:{format:"chuyển đổi {patient} trên {target}",tokens:[{type:"literal",value:"chuyển đổi",alternatives:["chuyển","bật tắt"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"trên",alternatives:["tại","ở"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"trên",markerAlternatives:["tại","ở"],default:{type:"reference",value:"me"}}}},{id:"toggle-vi-simple",language:"vi",command:"toggle",priority:90,template:{format:"chuyển đổi {patient}",tokens:[{type:"literal",value:"chuyển đổi",alternatives:["chuyển","bật tắt"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}}];case"zh":return[{id:"toggle-zh-full",language:"zh",command:"toggle",priority:100,template:{format:"切换 {patient} 在 {target}",tokens:[{type:"literal",value:"切换"},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"在",alternatives:["到","于"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"在",markerAlternatives:["到","于"],default:{type:"reference",value:"me"}}}},{id:"toggle-zh-simple",language:"zh",command:"toggle",priority:90,template:{format:"切换 {patient}",tokens:[{type:"literal",value:"切换"},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}},{id:"toggle-zh-ba",language:"zh",command:"toggle",priority:95,template:{format:"把 {patient} 切换",tokens:[{type:"literal",value:"把"},{type:"role",role:"patient"},{type:"literal",value:"切换"}]},extraction:{patient:{marker:"把"},destination:{default:{type:"reference",value:"me"}}}},{id:"toggle-zh-full-ba",language:"zh",command:"toggle",priority:98,template:{format:"在 {target} 把 {patient} 切换",tokens:[{type:"literal",value:"在",alternatives:["到","于"]},{type:"role",role:"destination"},{type:"literal",value:"把"},{type:"role",role:"patient"},{type:"literal",value:"切换"}]},extraction:{destination:{marker:"在",markerAlternatives:["到","于"]},patient:{marker:"把"}}}]}}function Wv(e){switch(e){case"ar":case"ja":case"ko":case"tr":default:return[];case"bn":return[{id:"put-bn-full",language:"bn",command:"put",priority:100,template:{format:"{patient} কে {destination} এ রাখুন",tokens:[{type:"role",role:"patient"},{type:"literal",value:"কে"},{type:"role",role:"destination"},{type:"literal",value:"এ",alternatives:["তে"]},{type:"literal",value:"রাখুন",alternatives:["রাখ"]}]},extraction:{patient:{position:0},destination:{marker:"এ",position:2}}},{id:"put-bn-simple",language:"bn",command:"put",priority:90,template:{format:"রাখুন {patient} {destination} এ",tokens:[{type:"literal",value:"রাখুন",alternatives:["রাখ"]},{type:"role",role:"patient"},{type:"role",role:"destination"},{type:"literal",value:"এ",alternatives:["তে"]}]},extraction:{patient:{position:1},destination:{position:2}}}];case"en":return[{id:"put-en-into",language:"en",command:"put",priority:100,template:{format:"put {patient} into {destination}",tokens:[{type:"literal",value:"put"},{type:"role",role:"patient"},{type:"literal",value:"into",alternatives:["in","to"]},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"into",markerAlternatives:["in","to"]}}},{id:"put-en-before",language:"en",command:"put",priority:95,template:{format:"put {patient} before {destination}",tokens:[{type:"literal",value:"put"},{type:"role",role:"patient"},{type:"literal",value:"before"},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"before"},manner:{default:{type:"literal",value:"before"}}}},{id:"put-en-after",language:"en",command:"put",priority:95,template:{format:"put {patient} after {destination}",tokens:[{type:"literal",value:"put"},{type:"role",role:"patient"},{type:"literal",value:"after"},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"after"},manner:{default:{type:"literal",value:"after"}}}}];case"es":return[{id:"put-es-full",language:"es",command:"put",priority:100,template:{format:"poner {patient} en {destination}",tokens:[{type:"literal",value:"poner",alternatives:["pon","colocar","put"]},{type:"role",role:"patient"},{type:"literal",value:"en",alternatives:["dentro de","a"]},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"en",markerAlternatives:["dentro de","a"]}}},{id:"put-es-before",language:"es",command:"put",priority:95,template:{format:"poner {patient} antes de {destination}",tokens:[{type:"literal",value:"poner",alternatives:["pon","colocar"]},{type:"role",role:"patient"},{type:"literal",value:"antes de",alternatives:["antes"]},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"antes de",markerAlternatives:["antes"]},manner:{default:{type:"literal",value:"before"}}}},{id:"put-es-after",language:"es",command:"put",priority:95,template:{format:"poner {patient} después de {destination}",tokens:[{type:"literal",value:"poner",alternatives:["pon","colocar"]},{type:"role",role:"patient"},{type:"literal",value:"después de",alternatives:["despues de","después"]},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"después de",markerAlternatives:["despues de","después"]},manner:{default:{type:"literal",value:"after"}}}}];case"hi":return[{id:"put-hi-full",language:"hi",command:"put",priority:100,template:{format:"{patient} को {destination} में रखें",tokens:[{type:"role",role:"patient"},{type:"literal",value:"को"},{type:"role",role:"destination"},{type:"literal",value:"में"},{type:"literal",value:"रखें",alternatives:["रख","डालें","डाल"]}]},extraction:{patient:{position:0},destination:{marker:"में",position:3}}},{id:"put-hi-simple",language:"hi",command:"put",priority:90,template:{format:"{patient} रखें",tokens:[{type:"role",role:"patient"},{type:"literal",value:"रखें",alternatives:["रख","डालें","डाल"]}]},extraction:{patient:{position:0},destination:{default:{type:"reference",value:"me"}}}},{id:"put-hi-bare",language:"hi",command:"put",priority:80,template:{format:"रखें {patient}",tokens:[{type:"literal",value:"रखें",alternatives:["रख","डालें","डाल"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}}];case"id":return[{id:"put-id-full",language:"id",command:"put",priority:100,template:{format:"taruh {patient} ke dalam {destination}",tokens:[{type:"literal",value:"taruh",alternatives:["letakkan","masukkan","tempatkan","put"]},{type:"role",role:"patient",expectedTypes:["literal","selector","reference","expression"]},{type:"literal",value:"ke"},{type:"literal",value:"dalam",alternatives:["di"]},{type:"role",role:"destination",expectedTypes:["selector","reference"]}]},extraction:{patient:{position:1},destination:{position:4}}},{id:"put-id-simple-ke",language:"id",command:"put",priority:95,template:{format:"taruh {patient} ke {destination}",tokens:[{type:"literal",value:"taruh",alternatives:["letakkan","masukkan","tempatkan"]},{type:"role",role:"patient",expectedTypes:["literal","selector","reference","expression"]},{type:"literal",value:"ke",alternatives:["di","pada"]},{type:"role",role:"destination",expectedTypes:["selector","reference"]}]},extraction:{patient:{position:1},destination:{position:3}}},{id:"put-id-di",language:"id",command:"put",priority:90,template:{format:"taruh {patient} di {destination}",tokens:[{type:"literal",value:"taruh",alternatives:["letakkan","masukkan"]},{type:"role",role:"patient",expectedTypes:["literal","selector","reference","expression"]},{type:"literal",value:"di"},{type:"role",role:"destination",expectedTypes:["selector","reference"]}]},extraction:{patient:{position:1},destination:{position:3}}}];case"it":return[{id:"put-it-full",language:"it",command:"put",priority:100,template:{format:"mettere {patient} in {target}",tokens:[{type:"literal",value:"mettere",alternatives:["metti","inserire","put"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"in",alternatives:["dentro","nel"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"in",markerAlternatives:["dentro","nel"]}}},{id:"put-it-simple",language:"it",command:"put",priority:90,template:{format:"mettere {patient}",tokens:[{type:"literal",value:"mettere",alternatives:["metti","inserire","put"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"pl":return[{id:"put-pl-full",language:"pl",command:"put",priority:100,template:{format:"umieść {patient} w {destination}",tokens:[{type:"literal",value:"umieść",alternatives:["umiesc","wstaw","włóż","wloz"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"w",alternatives:["do","na"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"w",markerAlternatives:["do","na"]}}},{id:"put-pl-before",language:"pl",command:"put",priority:95,template:{format:"umieść {patient} przed {destination}",tokens:[{type:"literal",value:"umieść",alternatives:["umiesc","wstaw"]},{type:"role",role:"patient"},{type:"literal",value:"przed"},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"przed"},manner:{default:{type:"literal",value:"before"}}}},{id:"put-pl-after",language:"pl",command:"put",priority:95,template:{format:"umieść {patient} po {destination}",tokens:[{type:"literal",value:"umieść",alternatives:["umiesc","wstaw"]},{type:"role",role:"patient"},{type:"literal",value:"po"},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"po"},manner:{default:{type:"literal",value:"after"}}}}];case"ru":return[{id:"put-ru-full",language:"ru",command:"put",priority:100,template:{format:"положить {patient} в {destination}",tokens:[{type:"literal",value:"положить",alternatives:["положи","поместить","помести","вставить","вставь"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"в",alternatives:["во","на"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"в",markerAlternatives:["во","на"]}}},{id:"put-ru-before",language:"ru",command:"put",priority:95,template:{format:"положить {patient} перед {destination}",tokens:[{type:"literal",value:"положить",alternatives:["положи","поместить","помести"]},{type:"role",role:"patient"},{type:"literal",value:"перед",alternatives:["до"]},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"перед",markerAlternatives:["до"]},manner:{default:{type:"literal",value:"before"}}}},{id:"put-ru-after",language:"ru",command:"put",priority:95,template:{format:"положить {patient} после {destination}",tokens:[{type:"literal",value:"положить",alternatives:["положи","поместить","помести"]},{type:"role",role:"patient"},{type:"literal",value:"после"},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"после"},manner:{default:{type:"literal",value:"after"}}}}];case"th":return[{id:"put-th-full",language:"th",command:"put",priority:100,template:{format:"ใส่ {patient} ใน {destination}",tokens:[{type:"literal",value:"ใส่",alternatives:["วาง"]},{type:"role",role:"patient"},{type:"literal",value:"ใน"},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"ใน",position:3}}}];case"uk":return[{id:"put-uk-full",language:"uk",command:"put",priority:100,template:{format:"покласти {patient} в {destination}",tokens:[{type:"literal",value:"покласти",alternatives:["поклади","помістити","помісти","вставити","встав"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"в",alternatives:["у","на"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"в",markerAlternatives:["у","на"]}}},{id:"put-uk-before",language:"uk",command:"put",priority:95,template:{format:"покласти {patient} перед {destination}",tokens:[{type:"literal",value:"покласти",alternatives:["поклади","помістити","помісти"]},{type:"role",role:"patient"},{type:"literal",value:"перед",alternatives:["до"]},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"перед",markerAlternatives:["до"]},manner:{default:{type:"literal",value:"before"}}}},{id:"put-uk-after",language:"uk",command:"put",priority:95,template:{format:"покласти {patient} після {destination}",tokens:[{type:"literal",value:"покласти",alternatives:["поклади","помістити","помісти"]},{type:"role",role:"patient"},{type:"literal",value:"після"},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"після"},manner:{default:{type:"literal",value:"after"}}}}];case"vi":return[{id:"put-vi-into",language:"vi",command:"put",priority:100,template:{format:"đặt {patient} vào {target}",tokens:[{type:"literal",value:"đặt",alternatives:["để","đưa"]},{type:"role",role:"patient"},{type:"literal",value:"vào",alternatives:["vào trong"]},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"vào",markerAlternatives:["vào trong"]}}},{id:"put-vi-before",language:"vi",command:"put",priority:95,template:{format:"đặt {patient} trước {target}",tokens:[{type:"literal",value:"đặt",alternatives:["để","đưa"]},{type:"role",role:"patient"},{type:"literal",value:"trước",alternatives:["trước khi"]},{type:"role",role:"manner"}]},extraction:{patient:{position:1},manner:{marker:"trước",markerAlternatives:["trước khi"]}}},{id:"put-vi-after",language:"vi",command:"put",priority:95,template:{format:"đặt {patient} sau {target}",tokens:[{type:"literal",value:"đặt",alternatives:["để","đưa"]},{type:"role",role:"patient"},{type:"literal",value:"sau",alternatives:["sau khi"]},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"sau",markerAlternatives:["sau khi"]}}}];case"zh":return[{id:"put-zh-full",language:"zh",command:"put",priority:100,template:{format:"放置 {patient} 到 {destination}",tokens:[{type:"literal",value:"放置",alternatives:["放","放入","置入","put"]},{type:"role",role:"patient",expectedTypes:["literal","selector","reference","expression"]},{type:"literal",value:"到",alternatives:["在","于","入"]},{type:"role",role:"destination",expectedTypes:["selector","reference"]}]},extraction:{patient:{position:1},destination:{position:3}}},{id:"put-zh-ba",language:"zh",command:"put",priority:95,template:{format:"把 {patient} 放到 {destination}",tokens:[{type:"literal",value:"把"},{type:"role",role:"patient",expectedTypes:["literal","selector","reference","expression"]},{type:"literal",value:"放到",alternatives:["放在","放入"]},{type:"role",role:"destination",expectedTypes:["selector","reference"]}]},extraction:{patient:{position:1},destination:{position:3}}}]}}function $v(e){switch(e){case"ar":case"he":case"ja":case"ko":case"tr":default:return[];case"bn":return[{id:"event-handler-bn-sov",language:"bn",command:"on",priority:100,template:{format:"{event} তে {action}",tokens:[{type:"role",role:"event"},{type:"literal",value:"তে",alternatives:["এ"]},{type:"role",role:"action"}]},extraction:{event:{position:0},action:{position:2}}},{id:"event-handler-bn-with-source",language:"bn",command:"on",priority:95,template:{format:"{source} থেকে {event} তে {action}",tokens:[{type:"role",role:"source"},{type:"literal",value:"থেকে"},{type:"role",role:"event"},{type:"literal",value:"তে",alternatives:["এ"]},{type:"role",role:"action"}]},extraction:{source:{position:0},event:{marker:"তে",position:2},action:{position:4}}},{id:"event-handler-bn-when",language:"bn",command:"on",priority:90,template:{format:"যখন {event} {action}",tokens:[{type:"literal",value:"যখন"},{type:"role",role:"event"},{type:"role",role:"action"}]},extraction:{event:{position:1},action:{position:2}}}];case"de":return[{id:"event-de-wenn-source",language:"de",command:"on",priority:115,template:{format:"wenn {event} von {source} {body}",tokens:[{type:"literal",value:"wenn",alternatives:["falls","sobald"]},{type:"role",role:"event"},{type:"literal",value:"von",alternatives:["aus"]},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"von",markerAlternatives:["aus"]}}},{id:"event-de-wenn",language:"de",command:"on",priority:105,template:{format:"wenn {event} {body}",tokens:[{type:"literal",value:"wenn",alternatives:["falls","sobald"]},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-de-bei-source",language:"de",command:"on",priority:110,template:{format:"bei {event} von {source} {body}",tokens:[{type:"literal",value:"bei",alternatives:["beim"]},{type:"role",role:"event"},{type:"literal",value:"von",alternatives:["aus"]},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"von",markerAlternatives:["aus"]}}},{id:"event-de-bei",language:"de",command:"on",priority:100,template:{format:"bei {event} {body}",tokens:[{type:"literal",value:"bei",alternatives:["beim"]},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-de-auf",language:"de",command:"on",priority:95,template:{format:"auf {event} {body}",tokens:[{type:"literal",value:"auf"},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-de-im-falle",language:"de",command:"on",priority:90,template:{format:"im Falle von {event} {body}",tokens:[{type:"literal",value:"im Falle von",alternatives:["im Fall von"]},{type:"role",role:"event"}]},extraction:{event:{position:1}}}];case"en":return[{id:"event-en-when-source",language:"en",command:"on",priority:115,template:{format:"when {event} from {source} {body}",tokens:[{type:"literal",value:"when"},{type:"role",role:"event"},{type:"literal",value:"from"},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"from"}}},{id:"event-en-when",language:"en",command:"on",priority:105,template:{format:"when {event} {body}",tokens:[{type:"literal",value:"when"},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-en-source",language:"en",command:"on",priority:110,template:{format:"on {event} from {source} {body}",tokens:[{type:"literal",value:"on"},{type:"role",role:"event"},{type:"literal",value:"from"},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"from"}}},{id:"event-en-standard",language:"en",command:"on",priority:100,template:{format:"on {event} {body}",tokens:[{type:"literal",value:"on"},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-en-upon",language:"en",command:"on",priority:98,template:{format:"upon {event} {body}",tokens:[{type:"literal",value:"upon"},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-en-if",language:"en",command:"on",priority:95,template:{format:"if {event} {body}",tokens:[{type:"literal",value:"if"},{type:"role",role:"event"}]},extraction:{event:{position:1}}}];case"es":return[{id:"event-es-native-al-source",language:"es",command:"on",priority:115,template:{format:"al {event} en {source} {body}",tokens:[{type:"literal",value:"al"},{type:"role",role:"event"},{type:"literal",value:"en",alternatives:["de"]},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"en",markerAlternatives:["de"]}}},{id:"event-es-cuando-source",language:"es",command:"on",priority:112,template:{format:"cuando {event} en {source} {body}",tokens:[{type:"literal",value:"cuando"},{type:"role",role:"event"},{type:"literal",value:"en",alternatives:["de"]},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"en",markerAlternatives:["de"]}}},{id:"event-es-native-al",language:"es",command:"on",priority:108,template:{format:"al {event} {body}",tokens:[{type:"literal",value:"al"},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-es-standard",language:"es",command:"on",priority:100,template:{format:"en {event} {body}",tokens:[{type:"literal",value:"en",alternatives:["al","cuando"]},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-es-source",language:"es",command:"on",priority:110,template:{format:"en {event} desde {source} {body}",tokens:[{type:"literal",value:"en",alternatives:["al"]},{type:"role",role:"event"},{type:"literal",value:"desde",alternatives:["de"]},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"desde",markerAlternatives:["de"]}}},{id:"event-es-when",language:"es",command:"on",priority:95,template:{format:"cuando {event} {body}",tokens:[{type:"literal",value:"cuando"},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-es-conditional-si",language:"es",command:"on",priority:85,template:{format:"si {event} {body}",tokens:[{type:"literal",value:"si"},{type:"role",role:"event"}]},extraction:{event:{position:1}}}];case"fr":return[{id:"event-fr-quand-source",language:"fr",command:"on",priority:115,template:{format:"quand {event} de {source} {body}",tokens:[{type:"literal",value:"quand",alternatives:["lorsque"]},{type:"role",role:"event"},{type:"literal",value:"de",alternatives:["depuis"]},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"de",markerAlternatives:["depuis"]}}},{id:"event-fr-quand",language:"fr",command:"on",priority:105,template:{format:"quand {event} {body}",tokens:[{type:"literal",value:"quand",alternatives:["lorsque"]},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-fr-sur-source",language:"fr",command:"on",priority:110,template:{format:"sur {event} de {source} {body}",tokens:[{type:"literal",value:"sur",alternatives:["lors de"]},{type:"role",role:"event"},{type:"literal",value:"de",alternatives:["depuis"]},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"de",markerAlternatives:["depuis"]}}},{id:"event-fr-sur",language:"fr",command:"on",priority:100,template:{format:"sur {event} {body}",tokens:[{type:"literal",value:"sur",alternatives:["lors de"]},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-fr-si",language:"fr",command:"on",priority:95,template:{format:"si {event} {body}",tokens:[{type:"literal",value:"si"},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-fr-a",language:"fr",command:"on",priority:90,template:{format:"à {event} {body}",tokens:[{type:"literal",value:"à",alternatives:["au"]},{type:"role",role:"event"}]},extraction:{event:{position:1}}}];case"hi":return[{id:"event-hi-standard",language:"hi",command:"on",priority:100,template:{format:"{event} पर",tokens:[{type:"role",role:"event"},{type:"literal",value:"पर",alternatives:["में","जब"]}]},extraction:{event:{position:0}}},{id:"event-hi-with-source",language:"hi",command:"on",priority:95,template:{format:"{source} से {event} पर",tokens:[{type:"role",role:"source"},{type:"literal",value:"से"},{type:"role",role:"event"},{type:"literal",value:"पर",alternatives:["में","जब"]}]},extraction:{source:{position:0},event:{marker:"से",position:2}}},{id:"event-hi-bare",language:"hi",command:"on",priority:80,template:{format:"{event}",tokens:[{type:"role",role:"event"}]},extraction:{event:{position:0}}}];case"id":return[{id:"event-id-ketika-source",language:"id",command:"on",priority:115,template:{format:"ketika {event} dari {source} {body}",tokens:[{type:"literal",value:"ketika",alternatives:["saat","waktu"]},{type:"role",role:"event"},{type:"literal",value:"dari"},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"dari"}}},{id:"event-id-ketika",language:"id",command:"on",priority:105,template:{format:"ketika {event} {body}",tokens:[{type:"literal",value:"ketika",alternatives:["saat","waktu"]},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-id-pada-source",language:"id",command:"on",priority:110,template:{format:"pada {event} dari {source} {body}",tokens:[{type:"literal",value:"pada"},{type:"role",role:"event"},{type:"literal",value:"dari"},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"dari"}}},{id:"event-id-pada",language:"id",command:"on",priority:100,template:{format:"pada {event} {body}",tokens:[{type:"literal",value:"pada"},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-id-jika",language:"id",command:"on",priority:95,template:{format:"jika {event} {body}",tokens:[{type:"literal",value:"jika",alternatives:["kalau","apabila"]},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-id-bila",language:"id",command:"on",priority:90,template:{format:"bila {event} {body}",tokens:[{type:"literal",value:"bila"},{type:"role",role:"event"}]},extraction:{event:{position:1}}}];case"it":return[{id:"event-handler-it-full",language:"it",command:"on",priority:100,template:{format:"su {event} {action}",tokens:[{type:"literal",value:"su",alternatives:["quando","al","on"]},{type:"role",role:"event"},{type:"role",role:"action"}]},extraction:{event:{position:1},action:{position:2}}},{id:"event-handler-it-from",language:"it",command:"on",priority:95,template:{format:"su {event} da {source} {action}",tokens:[{type:"literal",value:"su",alternatives:["quando","al","on"]},{type:"role",role:"event"},{type:"literal",value:"da",alternatives:["di"]},{type:"role",role:"source"},{type:"role",role:"action"}]},extraction:{event:{position:1},source:{marker:"da",markerAlternatives:["di"]},action:{position:-1}}}];case"ms":return[{id:"event-ms-apabila",language:"ms",command:"on",priority:100,template:{format:"apabila {event} {body}",tokens:[{type:"literal",value:"apabila",alternatives:["bila","ketika"]},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-ms-apabila-source",language:"ms",command:"on",priority:110,template:{format:"apabila {event} dari {source} {body}",tokens:[{type:"literal",value:"apabila",alternatives:["bila","ketika"]},{type:"role",role:"event"},{type:"literal",value:"dari"},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"dari"}}}];case"pl":return[{id:"event-handler-pl-full",language:"pl",command:"on",priority:100,template:{format:"gdy {event} na {source}",tokens:[{type:"literal",value:"gdy",alternatives:["kiedy","przy","na"]},{type:"role",role:"event"},{type:"group",optional:!0,tokens:[{type:"literal",value:"na",alternatives:["w","przy","z"]},{type:"role",role:"source"}]}]},extraction:{event:{position:1},source:{marker:"na",markerAlternatives:["w","przy","z"],default:{type:"reference",value:"me"}}}},{id:"event-handler-pl-simple",language:"pl",command:"on",priority:90,template:{format:"gdy {event}",tokens:[{type:"literal",value:"gdy",alternatives:["kiedy","przy","na"]},{type:"role",role:"event"}]},extraction:{event:{position:1},source:{default:{type:"reference",value:"me"}}}}];case"pt":return[{id:"event-pt-ao-source",language:"pt",command:"on",priority:115,template:{format:"ao {event} em {source} {body}",tokens:[{type:"literal",value:"ao",alternatives:["à"]},{type:"role",role:"event"},{type:"literal",value:"em",alternatives:["de","no","na"]},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"em",markerAlternatives:["de","no","na"]}}},{id:"event-pt-quando-source",language:"pt",command:"on",priority:110,template:{format:"quando {event} de {source} {body}",tokens:[{type:"literal",value:"quando"},{type:"role",role:"event"},{type:"literal",value:"de",alternatives:["em","no","na"]},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"de",markerAlternatives:["em","no","na"]}}},{id:"event-pt-ao",language:"pt",command:"on",priority:105,template:{format:"ao {event} {body}",tokens:[{type:"literal",value:"ao",alternatives:["à"]},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-pt-quando",language:"pt",command:"on",priority:100,template:{format:"quando {event} {body}",tokens:[{type:"literal",value:"quando"},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-pt-em",language:"pt",command:"on",priority:95,template:{format:"em {event} {body}",tokens:[{type:"literal",value:"em",alternatives:["no","na"]},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-pt-se",language:"pt",command:"on",priority:90,template:{format:"se {event} {body}",tokens:[{type:"literal",value:"se"},{type:"role",role:"event"}]},extraction:{event:{position:1}}}];case"qu":return[{id:"event-qu-source",language:"qu",command:"on",priority:110,template:{format:"{event} pi {source} manta {body}",tokens:[{type:"role",role:"event"},{type:"literal",value:"pi"},{type:"role",role:"source"},{type:"literal",value:"manta"}]},extraction:{event:{position:0},source:{marker:"manta"}}},{id:"event-qu-kaqtin",language:"qu",command:"on",priority:105,template:{format:"{event} kaqtin {body}",tokens:[{type:"role",role:"event"},{type:"literal",value:"kaqtin",alternatives:["qtin","ptin"]}]},extraction:{event:{position:0}}},{id:"event-qu-standard",language:"qu",command:"on",priority:100,template:{format:"{event} pi {body}",tokens:[{type:"role",role:"event"},{type:"literal",value:"pi",alternatives:["kaqpi","kaqpim"]}]},extraction:{event:{position:0}}}];case"ru":return[{id:"event-handler-ru-full",language:"ru",command:"on",priority:100,template:{format:"при {event} на {source}",tokens:[{type:"literal",value:"при",alternatives:["когда"]},{type:"role",role:"event"},{type:"group",optional:!0,tokens:[{type:"literal",value:"на",alternatives:["в","от"]},{type:"role",role:"source"}]}]},extraction:{event:{position:1},source:{marker:"на",markerAlternatives:["в","от"],default:{type:"reference",value:"me"}}}},{id:"event-handler-ru-simple",language:"ru",command:"on",priority:90,template:{format:"при {event}",tokens:[{type:"literal",value:"при",alternatives:["когда"]},{type:"role",role:"event"}]},extraction:{event:{position:1},source:{default:{type:"reference",value:"me"}}}}];case"sw":return[{id:"event-sw-unapo-source",language:"sw",command:"on",priority:115,template:{format:"unapo {event} kutoka {source} {body}",tokens:[{type:"literal",value:"unapo",alternatives:["wakati wa","wakati"]},{type:"role",role:"event"},{type:"literal",value:"kutoka"},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"kutoka"}}},{id:"event-sw-unapo",language:"sw",command:"on",priority:105,template:{format:"unapo {event} {body}",tokens:[{type:"literal",value:"unapo",alternatives:["wakati wa","wakati"]},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-sw-kwa-source",language:"sw",command:"on",priority:110,template:{format:"kwa {event} kutoka {source} {body}",tokens:[{type:"literal",value:"kwa"},{type:"role",role:"event"},{type:"literal",value:"kutoka"},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"kutoka"}}},{id:"event-sw-kwa",language:"sw",command:"on",priority:100,template:{format:"kwa {event} {body}",tokens:[{type:"literal",value:"kwa"},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-sw-ikiwa",language:"sw",command:"on",priority:95,template:{format:"ikiwa {event} {body}",tokens:[{type:"literal",value:"ikiwa",alternatives:["kama"]},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-sw-baada-ya",language:"sw",command:"on",priority:90,template:{format:"baada ya {event} {body}",tokens:[{type:"literal",value:"baada ya"},{type:"role",role:"event"}]},extraction:{event:{position:1}}}];case"th":return[{id:"event-handler-th-svo",language:"th",command:"on",priority:100,template:{format:"เมื่อ {event} {action}",tokens:[{type:"literal",value:"เมื่อ",alternatives:["ตอน"]},{type:"role",role:"event"},{type:"role",role:"action"}]},extraction:{event:{position:1},action:{position:2}}},{id:"event-handler-th-with-source",language:"th",command:"on",priority:95,template:{format:"เมื่อ {event} จาก {source} {action}",tokens:[{type:"literal",value:"เมื่อ",alternatives:["ตอน"]},{type:"role",role:"event"},{type:"literal",value:"จาก"},{type:"role",role:"source"},{type:"role",role:"action"}]},extraction:{event:{position:1},source:{marker:"จาก",position:3},action:{position:4}}}];case"tl":return[{id:"event-tl-kapag-source",language:"tl",command:"on",priority:115,template:{format:"kapag {event} mula_sa {source} {body}",tokens:[{type:"literal",value:"kapag",alternatives:["kung","sa"]},{type:"role",role:"event"},{type:"literal",value:"mula_sa",alternatives:["galing_sa"]},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"mula_sa"}}},{id:"event-tl-kapag",language:"tl",command:"on",priority:105,template:{format:"kapag {event} {body}",tokens:[{type:"literal",value:"kapag",alternatives:["kung","sa"]},{type:"role",role:"event"}]},extraction:{event:{position:1}}}];case"uk":return[{id:"event-handler-uk-full",language:"uk",command:"on",priority:100,template:{format:"при {event} на {source}",tokens:[{type:"literal",value:"при",alternatives:["коли"]},{type:"role",role:"event"},{type:"group",optional:!0,tokens:[{type:"literal",value:"на",alternatives:["в","від"]},{type:"role",role:"source"}]}]},extraction:{event:{position:1},source:{marker:"на",markerAlternatives:["в","від"],default:{type:"reference",value:"me"}}}},{id:"event-handler-uk-simple",language:"uk",command:"on",priority:90,template:{format:"при {event}",tokens:[{type:"literal",value:"при",alternatives:["коли"]},{type:"role",role:"event"}]},extraction:{event:{position:1},source:{default:{type:"reference",value:"me"}}}}];case"vi":return[{id:"event-handler-vi-full",language:"vi",command:"on",priority:100,template:{format:"khi {event} trên {source}",tokens:[{type:"literal",value:"khi",alternatives:["lúc","trên"]},{type:"role",role:"event"},{type:"group",optional:!0,tokens:[{type:"literal",value:"trên",alternatives:["tại"]},{type:"role",role:"source"}]}]},extraction:{event:{position:1},source:{marker:"trên",markerAlternatives:["tại"],default:{type:"reference",value:"me"}}}},{id:"event-handler-vi-simple",language:"vi",command:"on",priority:90,template:{format:"khi {event}",tokens:[{type:"literal",value:"khi",alternatives:["lúc","trên"]},{type:"role",role:"event"}]},extraction:{event:{position:1},source:{default:{type:"reference",value:"me"}}}}];case"zh":return[{id:"event-zh-temporal-source",language:"zh",command:"on",priority:115,template:{format:"{event} 的时候 从 {source} {body}",tokens:[{type:"role",role:"event"},{type:"literal",value:"的时候",alternatives:["时候","时"]},{type:"literal",value:"从",alternatives:["在"]},{type:"role",role:"source"}]},extraction:{event:{position:0},source:{marker:"从",markerAlternatives:["在"]}}},{id:"event-zh-source",language:"zh",command:"on",priority:110,template:{format:"当 {event} 从 {source} {body}",tokens:[{type:"literal",value:"当"},{type:"role",role:"event"},{type:"literal",value:"从",alternatives:["在"]},{type:"role",role:"source"}]},extraction:{event:{position:1},source:{marker:"从",markerAlternatives:["在"]}}},{id:"event-zh-immediate",language:"zh",command:"on",priority:108,template:{format:"一 {event} 就 {body}",tokens:[{type:"literal",value:"一"},{type:"role",role:"event"},{type:"literal",value:"就"}]},extraction:{event:{position:1}}},{id:"event-zh-temporal",language:"zh",command:"on",priority:105,template:{format:"{event} 的时候 {body}",tokens:[{type:"role",role:"event"},{type:"literal",value:"的时候",alternatives:["时候","时"]}]},extraction:{event:{position:0}}},{id:"event-zh-whenever",language:"zh",command:"on",priority:103,template:{format:"每当 {event} {body}",tokens:[{type:"literal",value:"每当",alternatives:["每次"]},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-zh-standard",language:"zh",command:"on",priority:100,template:{format:"当 {event} {body}",tokens:[{type:"literal",value:"当"},{type:"role",role:"event"}]},extraction:{event:{position:1}}},{id:"event-zh-completion",language:"zh",command:"on",priority:95,template:{format:"{event} 了 {body}",tokens:[{type:"role",role:"event"},{type:"literal",value:"了"}]},extraction:{event:{position:0}}},{id:"event-zh-conditional",language:"zh",command:"on",priority:90,template:{format:"如果 {event} {body}",tokens:[{type:"literal",value:"如果",alternatives:["若","假如"]},{type:"role",role:"event"}]},extraction:{event:{position:1}}}]}}wl("es-MX",Pp,Rv),Pl(),cm(),Vp(),wl("fr",Jp,Op),Pl(),pm(),um(),wl("he",sm,Xp),Pl(),zm(),bm(),wl("hi",gm,lm),Pl(),$m(),Lm(),wl("id",jm,wm),Pl(),td(),Jm(),wl("it",Qm,qm),Pl(),Sd(),kd(),wl("ja",bd,ad),Pl(),Fd(),_d(),wl("ko",Dd,Cd),Pl(),Xd(),Jd(),wl("ms",Qd,Bd),Pl(),dh(),ch(),wl("pl",lh,Zd),Pl(),Nh(),wh(),wl("pt",jh,mh),Pl(),Bh(),Dh(),wl("qu",qh,Ih),Pl(),of(),Gh(),wl("ru",tf,Vh),Pl(),vf(),hf(),wl("sw",df,af),Pl(),Tf(),xf(),wl("th",zf,yf),Pl(),Rf(),Pf(),wl("tl",Lf,Sf),Pl(),ey(),Yf(),wl("tr",Jf,Df),Pl(),hy(),iy(),wl("uk",uy,Xf),Pl(),Sy(),zy(),wl("vi",wy,dy),Pl(),Wy(),Oy(),wl("zh",Ny,Ey),Ky(),Zu(),Xu(),pp();var Hv=[...[{id:"fetch-en-with-response-type",language:"en",command:"fetch",priority:90,template:{format:"fetch {source} as {responseType}",tokens:[{type:"literal",value:"fetch"},{type:"role",role:"source",expectedTypes:["literal","expression"]},{type:"literal",value:"as"},{type:"role",role:"responseType",expectedTypes:["literal","expression"]}]},extraction:{source:{position:1},responseType:{marker:"as"}}},{id:"fetch-en-simple",language:"en",command:"fetch",priority:80,template:{format:"fetch {source}",tokens:[{type:"literal",value:"fetch"},{type:"role",role:"source"}]},extraction:{source:{position:1}}}],...[{id:"swap-en-handcrafted",language:"en",command:"swap",priority:110,template:{format:"swap {method} {destination}",tokens:[{type:"literal",value:"swap"},{type:"role",role:"method"},{type:"role",role:"destination"}]},extraction:{method:{position:1},destination:{position:2}}}],...[{id:"repeat-en-until-event-from",language:"en",command:"repeat",priority:120,template:{format:"repeat until event {event} from {source}",tokens:[{type:"literal",value:"repeat"},{type:"literal",value:"until"},{type:"literal",value:"event"},{type:"role",role:"event",expectedTypes:["literal","expression"]},{type:"literal",value:"from"},{type:"role",role:"source",expectedTypes:["selector","reference","expression"]}]},extraction:{event:{marker:"event"},source:{marker:"from"},loopType:{default:{type:"literal",value:"until-event"}}}},{id:"repeat-en-until-event",language:"en",command:"repeat",priority:110,template:{format:"repeat until event {event}",tokens:[{type:"literal",value:"repeat"},{type:"literal",value:"until"},{type:"literal",value:"event"},{type:"role",role:"event",expectedTypes:["literal","expression"]}]},extraction:{event:{marker:"event"},loopType:{default:{type:"literal",value:"until-event"}}}}],...[{id:"set-en-possessive",language:"en",command:"set",priority:100,template:{format:"set {destination} to {patient}",tokens:[{type:"literal",value:"set"},{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"literal",value:"to"},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:1},patient:{marker:"to"}}}],...[{id:"for-en-basic",language:"en",command:"for",priority:100,template:{format:"for {patient} in {source}",tokens:[{type:"literal",value:"for"},{type:"role",role:"patient",expectedTypes:["expression","reference"]},{type:"literal",value:"in"},{type:"role",role:"source",expectedTypes:["selector","expression","reference"]}]},extraction:{patient:{position:1},source:{marker:"in"},loopType:{default:{type:"literal",value:"for"}}}},{id:"if-en-basic",language:"en",command:"if",priority:100,template:{format:"if {condition}",tokens:[{type:"literal",value:"if"},{type:"role",role:"condition",expectedTypes:["expression","reference","selector"]}]},extraction:{condition:{position:1}}},{id:"unless-en-basic",language:"en",command:"unless",priority:100,template:{format:"unless {condition}",tokens:[{type:"literal",value:"unless"},{type:"role",role:"condition",expectedTypes:["expression","reference","selector"]}]},extraction:{condition:{position:1}}}],...[{id:"temporal-en-in",language:"en",command:"wait",priority:95,template:{format:"in {duration}",tokens:[{type:"literal",value:"in"},{type:"role",role:"duration",expectedTypes:["literal","expression"]}]},extraction:{duration:{position:1}}},{id:"temporal-en-after",language:"en",command:"wait",priority:95,template:{format:"after {duration}",tokens:[{type:"literal",value:"after"},{type:"role",role:"duration",expectedTypes:["literal","expression"]}]},extraction:{duration:{position:1}}}]];Yu(),Pl();var qv=[Mv,function(e){return[]},Wv,$v,function(e){switch(e){case"ar":case"ja":case"ko":case"tr":default:return[];case"bn":return[{id:"add-bn-full",language:"bn",command:"add",priority:100,template:{format:"{patient} কে যোগ করুন",tokens:[{type:"role",role:"patient"},{type:"literal",value:"কে"},{type:"literal",value:"যোগ"},{type:"literal",value:"করুন"}]},extraction:{patient:{position:0}}},{id:"add-bn-simple",language:"bn",command:"add",priority:90,template:{format:"যোগ {patient}",tokens:[{type:"literal",value:"যোগ"},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}},{id:"add-bn-with-dest",language:"bn",command:"add",priority:95,template:{format:"{destination} এ {patient} কে যোগ করুন",tokens:[{type:"role",role:"destination"},{type:"literal",value:"এ",alternatives:["তে"]},{type:"role",role:"patient"},{type:"literal",value:"কে"},{type:"literal",value:"যোগ"},{type:"literal",value:"করুন"}]},extraction:{destination:{position:0},patient:{position:2}}}];case"hi":return[{id:"add-hi-full",language:"hi",command:"add",priority:100,template:{format:"{patient} को {destination} में जोड़ें",tokens:[{type:"role",role:"patient"},{type:"literal",value:"को"},{type:"role",role:"destination"},{type:"literal",value:"में"},{type:"literal",value:"जोड़ें",alternatives:["जोड़"]}]},extraction:{patient:{position:0},destination:{marker:"में",position:3}}},{id:"add-hi-simple",language:"hi",command:"add",priority:90,template:{format:"{patient} जोड़ें",tokens:[{type:"role",role:"patient"},{type:"literal",value:"जोड़ें",alternatives:["जोड़"]}]},extraction:{patient:{position:0},destination:{default:{type:"reference",value:"me"}}}},{id:"add-hi-bare",language:"hi",command:"add",priority:80,template:{format:"जोड़ें {patient}",tokens:[{type:"literal",value:"जोड़ें",alternatives:["जोड़"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}}];case"it":return[{id:"add-it-full",language:"it",command:"add",priority:100,template:{format:"aggiungere {patient} a {target}",tokens:[{type:"literal",value:"aggiungere",alternatives:["aggiungi","add"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"a",alternatives:["su","in"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"a",markerAlternatives:["su","in"],default:{type:"reference",value:"me"}}}},{id:"add-it-simple",language:"it",command:"add",priority:90,template:{format:"aggiungere {patient}",tokens:[{type:"literal",value:"aggiungere",alternatives:["aggiungi","add"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}}];case"pl":return[{id:"add-pl-full",language:"pl",command:"add",priority:100,template:{format:"dodaj {patient} do {destination}",tokens:[{type:"literal",value:"dodaj",alternatives:["dołącz","dolacz"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"do",alternatives:["na","w"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"do",markerAlternatives:["na","w"],default:{type:"reference",value:"me"}}}},{id:"add-pl-simple",language:"pl",command:"add",priority:90,template:{format:"dodaj {patient}",tokens:[{type:"literal",value:"dodaj",alternatives:["dołącz","dolacz"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}}];case"qu":return[{id:"add-qu-sov",language:"qu",command:"add",priority:100,template:{format:"{patient} ta yapay",tokens:[{type:"role",role:"patient"},{type:"literal",value:"ta"},{type:"literal",value:"yapay",alternatives:["yapaykuy"]}]},extraction:{patient:{position:0}}},{id:"add-qu-simple",language:"qu",command:"add",priority:90,template:{format:"yapay {patient}",tokens:[{type:"literal",value:"yapay",alternatives:["yapaykuy"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}},{id:"add-qu-with-dest",language:"qu",command:"add",priority:95,template:{format:"{destination} man {patient} ta yapay",tokens:[{type:"role",role:"destination"},{type:"literal",value:"man"},{type:"role",role:"patient"},{type:"literal",value:"ta"},{type:"literal",value:"yapay",alternatives:["yapaykuy"]}]},extraction:{destination:{position:0},patient:{position:2}}}];case"ru":return[{id:"add-ru-full",language:"ru",command:"add",priority:100,template:{format:"добавить {patient} к {destination}",tokens:[{type:"literal",value:"добавить",alternatives:["добавь"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"к",alternatives:["на","в"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"к",markerAlternatives:["на","в"],default:{type:"reference",value:"me"}}}},{id:"add-ru-simple",language:"ru",command:"add",priority:90,template:{format:"добавить {patient}",tokens:[{type:"literal",value:"добавить",alternatives:["добавь"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}}];case"th":return[{id:"add-th-simple",language:"th",command:"add",priority:100,template:{format:"เพิ่ม {patient}",tokens:[{type:"literal",value:"เพิ่ม"},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}},{id:"add-th-with-dest",language:"th",command:"add",priority:95,template:{format:"เพิ่ม {patient} ใน {destination}",tokens:[{type:"literal",value:"เพิ่ม"},{type:"role",role:"patient"},{type:"literal",value:"ใน"},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"ใน",position:3}}}];case"uk":return[{id:"add-uk-full",language:"uk",command:"add",priority:100,template:{format:"додати {patient} до {destination}",tokens:[{type:"literal",value:"додати",alternatives:["додай"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"до",alternatives:["на","в"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"до",markerAlternatives:["на","в"],default:{type:"reference",value:"me"}}}},{id:"add-uk-simple",language:"uk",command:"add",priority:90,template:{format:"додати {patient}",tokens:[{type:"literal",value:"додати",alternatives:["додай"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}}];case"vi":return[{id:"add-vi-full",language:"vi",command:"add",priority:100,template:{format:"thêm {patient} vào {target}",tokens:[{type:"literal",value:"thêm",alternatives:["bổ sung"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"vào",alternatives:["cho"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"vào",markerAlternatives:["cho"],default:{type:"reference",value:"me"}}}},{id:"add-vi-simple",language:"vi",command:"add",priority:90,template:{format:"thêm {patient}",tokens:[{type:"literal",value:"thêm",alternatives:["bổ sung"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}}];case"zh":return[{id:"add-zh-full",language:"zh",command:"add",priority:100,template:{format:"给 {destination} 添加 {patient}",tokens:[{type:"literal",value:"给",alternatives:["為","为"]},{type:"role",role:"destination"},{type:"literal",value:"添加",alternatives:["加","增加","加上"]},{type:"role",role:"patient"}]},extraction:{destination:{position:1},patient:{position:3}}},{id:"add-zh-simple",language:"zh",command:"add",priority:90,template:{format:"添加 {patient}",tokens:[{type:"literal",value:"添加",alternatives:["加","增加"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}},{id:"add-zh-ba",language:"zh",command:"add",priority:95,template:{format:"把 {patient} 添加到 {destination}",tokens:[{type:"literal",value:"把"},{type:"role",role:"patient"},{type:"literal",value:"添加到",alternatives:["加到","增加到"]},{type:"role",role:"destination"}]},extraction:{patient:{position:1},destination:{marker:"添加到",markerAlternatives:["加到","增加到"]}}}]}},function(e){switch(e){case"ar":case"ja":case"ko":case"tr":default:return[];case"bn":return[{id:"remove-bn-full",language:"bn",command:"remove",priority:100,template:{format:"{patient} কে সরান",tokens:[{type:"role",role:"patient"},{type:"literal",value:"কে"},{type:"literal",value:"সরান",alternatives:["মুছুন"]}]},extraction:{patient:{position:0}}},{id:"remove-bn-simple",language:"bn",command:"remove",priority:90,template:{format:"সরান {patient}",tokens:[{type:"literal",value:"সরান",alternatives:["মুছুন"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}},{id:"remove-bn-with-source",language:"bn",command:"remove",priority:95,template:{format:"{source} থেকে {patient} কে সরান",tokens:[{type:"role",role:"source"},{type:"literal",value:"থেকে"},{type:"role",role:"patient"},{type:"literal",value:"কে"},{type:"literal",value:"সরান",alternatives:["মুছুন"]}]},extraction:{source:{position:0},patient:{position:2}}}];case"hi":return[{id:"remove-hi-full",language:"hi",command:"remove",priority:100,template:{format:"{patient} को {source} से हटाएं",tokens:[{type:"role",role:"patient"},{type:"literal",value:"को"},{type:"role",role:"source"},{type:"literal",value:"से"},{type:"literal",value:"हटाएं",alternatives:["हटा","मिटाएं"]}]},extraction:{patient:{position:0},source:{marker:"से",position:3}}},{id:"remove-hi-simple",language:"hi",command:"remove",priority:90,template:{format:"{patient} हटाएं",tokens:[{type:"role",role:"patient"},{type:"literal",value:"हटाएं",alternatives:["हटा","मिटाएं"]}]},extraction:{patient:{position:0},source:{default:{type:"reference",value:"me"}}}},{id:"remove-hi-bare",language:"hi",command:"remove",priority:80,template:{format:"हटाएं {patient}",tokens:[{type:"literal",value:"हटाएं",alternatives:["हटा","मिटाएं"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},source:{default:{type:"reference",value:"me"}}}}];case"it":return[{id:"remove-it-full",language:"it",command:"remove",priority:100,template:{format:"rimuovere {patient} da {target}",tokens:[{type:"literal",value:"rimuovere",alternatives:["rimuovi","eliminare","togliere","remove"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"da",alternatives:["di"]},{type:"role",role:"destination"}]}]},extraction:{patient:{position:1},destination:{marker:"da",markerAlternatives:["di"],default:{type:"reference",value:"me"}}}},{id:"remove-it-simple",language:"it",command:"remove",priority:90,template:{format:"rimuovere {patient}",tokens:[{type:"literal",value:"rimuovere",alternatives:["rimuovi","eliminare","togliere","remove"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}}];case"pl":return[{id:"remove-pl-full",language:"pl",command:"remove",priority:100,template:{format:"usuń {patient} z {source}",tokens:[{type:"literal",value:"usuń",alternatives:["usun","wyczyść","wyczysc"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"z",alternatives:["od","ze"]},{type:"role",role:"source"}]}]},extraction:{patient:{position:1},source:{marker:"z",markerAlternatives:["od","ze"],default:{type:"reference",value:"me"}}}},{id:"remove-pl-simple",language:"pl",command:"remove",priority:90,template:{format:"usuń {patient}",tokens:[{type:"literal",value:"usuń",alternatives:["usun","wyczyść","wyczysc"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},source:{default:{type:"reference",value:"me"}}}}];case"qu":return[{id:"remove-qu-sov",language:"qu",command:"remove",priority:100,template:{format:"{patient} ta qichuy",tokens:[{type:"role",role:"patient"},{type:"literal",value:"ta"},{type:"literal",value:"qichuy",alternatives:["hurquy","anchuchiy"]}]},extraction:{patient:{position:0}}},{id:"remove-qu-simple",language:"qu",command:"remove",priority:90,template:{format:"qichuy {patient}",tokens:[{type:"literal",value:"qichuy",alternatives:["hurquy","anchuchiy"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}},{id:"remove-qu-with-source",language:"qu",command:"remove",priority:95,template:{format:"{source} manta {patient} ta qichuy",tokens:[{type:"role",role:"source"},{type:"literal",value:"manta"},{type:"role",role:"patient"},{type:"literal",value:"ta"},{type:"literal",value:"qichuy",alternatives:["hurquy","anchuchiy"]}]},extraction:{source:{position:0},patient:{position:2}}}];case"ru":return[{id:"remove-ru-full",language:"ru",command:"remove",priority:100,template:{format:"удалить {patient} из {source}",tokens:[{type:"literal",value:"удалить",alternatives:["удали","убрать","убери"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"из",alternatives:["от","с"]},{type:"role",role:"source"}]}]},extraction:{patient:{position:1},source:{marker:"из",markerAlternatives:["от","с"],default:{type:"reference",value:"me"}}}},{id:"remove-ru-simple",language:"ru",command:"remove",priority:90,template:{format:"удалить {patient}",tokens:[{type:"literal",value:"удалить",alternatives:["удали","убрать","убери"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},source:{default:{type:"reference",value:"me"}}}}];case"th":return[{id:"remove-th-simple",language:"th",command:"remove",priority:100,template:{format:"ลบ {patient}",tokens:[{type:"literal",value:"ลบ",alternatives:["ลบออก"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}},{id:"remove-th-with-source",language:"th",command:"remove",priority:95,template:{format:"ลบ {patient} จาก {source}",tokens:[{type:"literal",value:"ลบ",alternatives:["ลบออก"]},{type:"role",role:"patient"},{type:"literal",value:"จาก"},{type:"role",role:"source"}]},extraction:{patient:{position:1},source:{marker:"จาก",position:3}}}];case"uk":return[{id:"remove-uk-full",language:"uk",command:"remove",priority:100,template:{format:"видалити {patient} з {source}",tokens:[{type:"literal",value:"видалити",alternatives:["видали","прибрати","прибери"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"з",alternatives:["від","із"]},{type:"role",role:"source"}]}]},extraction:{patient:{position:1},source:{marker:"з",markerAlternatives:["від","із"],default:{type:"reference",value:"me"}}}},{id:"remove-uk-simple",language:"uk",command:"remove",priority:90,template:{format:"видалити {patient}",tokens:[{type:"literal",value:"видалити",alternatives:["видали","прибрати","прибери"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},source:{default:{type:"reference",value:"me"}}}}];case"vi":return[{id:"remove-vi-full",language:"vi",command:"remove",priority:100,template:{format:"xóa {patient} khỏi {target}",tokens:[{type:"literal",value:"xóa",alternatives:["gỡ bỏ","loại bỏ","bỏ"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"khỏi",alternatives:["từ"]},{type:"role",role:"source"}]}]},extraction:{patient:{position:1},source:{marker:"khỏi",markerAlternatives:["từ"],default:{type:"reference",value:"me"}}}},{id:"remove-vi-simple",language:"vi",command:"remove",priority:90,template:{format:"xóa {patient}",tokens:[{type:"literal",value:"xóa",alternatives:["gỡ bỏ","loại bỏ","bỏ"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},source:{default:{type:"reference",value:"me"}}}}];case"zh":return[{id:"remove-zh-full",language:"zh",command:"remove",priority:100,template:{format:"从 {destination} 删除 {patient}",tokens:[{type:"literal",value:"从",alternatives:["從"]},{type:"role",role:"destination"},{type:"literal",value:"删除",alternatives:["刪除","移除","去掉"]},{type:"role",role:"patient"}]},extraction:{destination:{position:1},patient:{position:3}}},{id:"remove-zh-simple",language:"zh",command:"remove",priority:90,template:{format:"删除 {patient}",tokens:[{type:"literal",value:"删除",alternatives:["刪除","移除","去掉"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},destination:{default:{type:"reference",value:"me"}}}},{id:"remove-zh-ba",language:"zh",command:"remove",priority:95,template:{format:"把 {patient} 从 {destination} 删除",tokens:[{type:"literal",value:"把"},{type:"role",role:"patient"},{type:"literal",value:"从",alternatives:["從"]},{type:"role",role:"destination"},{type:"literal",value:"删除",alternatives:["刪除","移除"]}]},extraction:{patient:{position:1},destination:{position:3}}}]}},function(e){switch(e){case"ar":case"ja":case"ko":case"tr":default:return[];case"bn":return[{id:"show-bn-full",language:"bn",command:"show",priority:100,template:{format:"{patient} কে দেখান",tokens:[{type:"role",role:"patient"},{type:"literal",value:"কে"},{type:"literal",value:"দেখান",alternatives:["দেখাও"]}]},extraction:{patient:{position:0}}},{id:"show-bn-simple",language:"bn",command:"show",priority:90,template:{format:"দেখান {patient}",tokens:[{type:"literal",value:"দেখান",alternatives:["দেখাও"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"de":return[{id:"show-de-full",language:"de",command:"show",priority:100,template:{format:"zeige {patient}",tokens:[{type:"literal",value:"zeige",alternatives:["zeigen","anzeigen","show"]},{type:"role",role:"patient",expectedTypes:["selector","reference"]}]},extraction:{patient:{position:1}}}];case"fr":return[{id:"show-fr-full",language:"fr",command:"show",priority:100,template:{format:"afficher {patient}",tokens:[{type:"literal",value:"afficher",alternatives:["montrer","présenter","show"]},{type:"role",role:"patient",expectedTypes:["selector","reference"]}]},extraction:{patient:{position:1}}}];case"hi":return[{id:"show-hi-full",language:"hi",command:"show",priority:100,template:{format:"{patient} को दिखाएं",tokens:[{type:"role",role:"patient"},{type:"literal",value:"को"},{type:"literal",value:"दिखाएं",alternatives:["दिखा"]}]},extraction:{patient:{position:0}}},{id:"show-hi-simple",language:"hi",command:"show",priority:90,template:{format:"दिखाएं {patient}",tokens:[{type:"literal",value:"दिखाएं",alternatives:["दिखा"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}},{id:"show-hi-bare",language:"hi",command:"show",priority:80,template:{format:"दिखाएं",tokens:[{type:"literal",value:"दिखाएं",alternatives:["दिखा"]}]},extraction:{patient:{default:{type:"reference",value:"me"}}}}];case"it":return[{id:"show-it-full",language:"it",command:"show",priority:100,template:{format:"mostrare {patient} con {style}",tokens:[{type:"literal",value:"mostrare",alternatives:["mostra","visualizzare","show"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"con"},{type:"role",role:"style"}]}]},extraction:{patient:{position:1},style:{marker:"con"}}},{id:"show-it-simple",language:"it",command:"show",priority:90,template:{format:"mostrare {patient}",tokens:[{type:"literal",value:"mostrare",alternatives:["mostra","visualizzare","show"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"pl":return[{id:"show-pl-full",language:"pl",command:"show",priority:100,template:{format:"pokaż {patient} z {style}",tokens:[{type:"literal",value:"pokaż",alternatives:["pokaz","wyświetl","wyswietl"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"z",alternatives:["ze","jako"]},{type:"role",role:"style"}]}]},extraction:{patient:{position:1},style:{marker:"z",markerAlternatives:["ze","jako"]}}},{id:"show-pl-simple",language:"pl",command:"show",priority:90,template:{format:"pokaż {patient}",tokens:[{type:"literal",value:"pokaż",alternatives:["pokaz","wyświetl","wyswietl"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"ru":return[{id:"show-ru-full",language:"ru",command:"show",priority:100,template:{format:"показать {patient} с {style}",tokens:[{type:"literal",value:"показать",alternatives:["покажи"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"с",alternatives:["со","как"]},{type:"role",role:"style"}]}]},extraction:{patient:{position:1},style:{marker:"с",markerAlternatives:["со","как"]}}},{id:"show-ru-simple",language:"ru",command:"show",priority:90,template:{format:"показать {patient}",tokens:[{type:"literal",value:"показать",alternatives:["покажи"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"th":return[{id:"show-th-simple",language:"th",command:"show",priority:100,template:{format:"แสดง {patient}",tokens:[{type:"literal",value:"แสดง"},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"uk":return[{id:"show-uk-full",language:"uk",command:"show",priority:100,template:{format:"показати {patient} з {style}",tokens:[{type:"literal",value:"показати",alternatives:["покажи"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"з",alternatives:["із","як"]},{type:"role",role:"style"}]}]},extraction:{patient:{position:1},style:{marker:"з",markerAlternatives:["із","як"]}}},{id:"show-uk-simple",language:"uk",command:"show",priority:90,template:{format:"показати {patient}",tokens:[{type:"literal",value:"показати",alternatives:["покажи"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"vi":return[{id:"show-vi-full",language:"vi",command:"show",priority:100,template:{format:"hiển thị {patient} với {effect}",tokens:[{type:"literal",value:"hiển thị",alternatives:["hiện"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"với"},{type:"role",role:"style"}]}]},extraction:{patient:{position:1},style:{marker:"với"}}},{id:"show-vi-simple",language:"vi",command:"show",priority:90,template:{format:"hiển thị {patient}",tokens:[{type:"literal",value:"hiển thị",alternatives:["hiện"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"zh":return[{id:"show-zh-full",language:"zh",command:"show",priority:100,template:{format:"显示 {patient}",tokens:[{type:"literal",value:"显示",alternatives:["顯示","展示","呈现","呈現"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}},{id:"show-zh-ba",language:"zh",command:"show",priority:95,template:{format:"把 {patient} 显示",tokens:[{type:"literal",value:"把"},{type:"role",role:"patient"},{type:"literal",value:"显示",alternatives:["顯示","展示"]}]},extraction:{patient:{position:1}}},{id:"show-zh-with-给",language:"zh",command:"show",priority:90,template:{format:"给 {destination} 显示 {patient}",tokens:[{type:"literal",value:"给",alternatives:["給"]},{type:"role",role:"destination"},{type:"literal",value:"显示",alternatives:["顯示"]},{type:"role",role:"patient"}]},extraction:{destination:{position:1},patient:{position:3}}}]}},function(e){switch(e){case"ar":case"ja":case"ko":case"tr":default:return[];case"bn":return[{id:"hide-bn-full",language:"bn",command:"hide",priority:100,template:{format:"{patient} কে লুকান",tokens:[{type:"role",role:"patient"},{type:"literal",value:"কে"},{type:"literal",value:"লুকান",alternatives:["লুকাও"]}]},extraction:{patient:{position:0}}},{id:"hide-bn-simple",language:"bn",command:"hide",priority:90,template:{format:"লুকান {patient}",tokens:[{type:"literal",value:"লুকান",alternatives:["লুকাও"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"de":return[{id:"hide-de-full",language:"de",command:"hide",priority:100,template:{format:"verstecke {patient}",tokens:[{type:"literal",value:"verstecke",alternatives:["verstecken","verberge","verbergen","hide"]},{type:"role",role:"patient",expectedTypes:["selector","reference"]}]},extraction:{patient:{position:1}}}];case"hi":return[{id:"hide-hi-full",language:"hi",command:"hide",priority:100,template:{format:"{patient} को छिपाएं",tokens:[{type:"role",role:"patient"},{type:"literal",value:"को"},{type:"literal",value:"छिपाएं",alternatives:["छिपा"]}]},extraction:{patient:{position:0}}},{id:"hide-hi-simple",language:"hi",command:"hide",priority:90,template:{format:"छिपाएं {patient}",tokens:[{type:"literal",value:"छिपाएं",alternatives:["छिपा"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}},{id:"hide-hi-bare",language:"hi",command:"hide",priority:80,template:{format:"छिपाएं",tokens:[{type:"literal",value:"छिपाएं",alternatives:["छिपा"]}]},extraction:{patient:{default:{type:"reference",value:"me"}}}}];case"it":return[{id:"hide-it-full",language:"it",command:"hide",priority:100,template:{format:"nascondere {patient} con {style}",tokens:[{type:"literal",value:"nascondere",alternatives:["nascondi","hide"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"con"},{type:"role",role:"style"}]}]},extraction:{patient:{position:1},style:{marker:"con"}}},{id:"hide-it-simple",language:"it",command:"hide",priority:90,template:{format:"nascondere {patient}",tokens:[{type:"literal",value:"nascondere",alternatives:["nascondi","hide"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"pl":return[{id:"hide-pl-full",language:"pl",command:"hide",priority:100,template:{format:"ukryj {patient} z {style}",tokens:[{type:"literal",value:"ukryj",alternatives:["schowaj","zasłoń","zaslon"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"z",alternatives:["ze","jako"]},{type:"role",role:"style"}]}]},extraction:{patient:{position:1},style:{marker:"z",markerAlternatives:["ze","jako"]}}},{id:"hide-pl-simple",language:"pl",command:"hide",priority:90,template:{format:"ukryj {patient}",tokens:[{type:"literal",value:"ukryj",alternatives:["schowaj","zasłoń","zaslon"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"ru":return[{id:"hide-ru-full",language:"ru",command:"hide",priority:100,template:{format:"скрыть {patient} с {style}",tokens:[{type:"literal",value:"скрыть",alternatives:["скрой","спрятать","спрячь"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"с",alternatives:["со","как"]},{type:"role",role:"style"}]}]},extraction:{patient:{position:1},style:{marker:"с",markerAlternatives:["со","как"]}}},{id:"hide-ru-simple",language:"ru",command:"hide",priority:90,template:{format:"скрыть {patient}",tokens:[{type:"literal",value:"скрыть",alternatives:["скрой","спрятать","спрячь"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"th":return[{id:"hide-th-simple",language:"th",command:"hide",priority:100,template:{format:"ซ่อน {patient}",tokens:[{type:"literal",value:"ซ่อน"},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"uk":return[{id:"hide-uk-full",language:"uk",command:"hide",priority:100,template:{format:"сховати {patient} з {style}",tokens:[{type:"literal",value:"сховати",alternatives:["сховай","приховати","приховай"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"з",alternatives:["із","як"]},{type:"role",role:"style"}]}]},extraction:{patient:{position:1},style:{marker:"з",markerAlternatives:["із","як"]}}},{id:"hide-uk-simple",language:"uk",command:"hide",priority:90,template:{format:"сховати {patient}",tokens:[{type:"literal",value:"сховати",alternatives:["сховай","приховати","приховай"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"vi":return[{id:"hide-vi-full",language:"vi",command:"hide",priority:100,template:{format:"ẩn {patient} với {effect}",tokens:[{type:"literal",value:"ẩn",alternatives:["che","giấu"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"với"},{type:"role",role:"style"}]}]},extraction:{patient:{position:1},style:{marker:"với"}}},{id:"hide-vi-simple",language:"vi",command:"hide",priority:90,template:{format:"ẩn {patient}",tokens:[{type:"literal",value:"ẩn",alternatives:["che","giấu"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"zh":return[{id:"hide-zh-full",language:"zh",command:"hide",priority:100,template:{format:"隐藏 {patient}",tokens:[{type:"literal",value:"隐藏",alternatives:["隱藏","藏起","藏"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}},{id:"hide-zh-ba",language:"zh",command:"hide",priority:95,template:{format:"把 {patient} 隐藏",tokens:[{type:"literal",value:"把"},{type:"role",role:"patient"},{type:"literal",value:"隐藏",alternatives:["隱藏","藏起"]}]},extraction:{patient:{position:1}}},{id:"hide-zh-from",language:"zh",command:"hide",priority:90,template:{format:"从 {destination} 隐藏 {patient}",tokens:[{type:"literal",value:"从",alternatives:["從"]},{type:"role",role:"destination"},{type:"literal",value:"隐藏",alternatives:["隱藏"]},{type:"role",role:"patient"}]},extraction:{destination:{position:1},patient:{position:3}}}]}},function(e){switch(e){case"ar":case"ja":case"ko":case"tr":default:return[];case"bn":return[{id:"set-bn-full",language:"bn",command:"set",priority:100,template:{format:"{patient} কে {goal} এ সেট করুন",tokens:[{type:"role",role:"patient"},{type:"literal",value:"কে"},{type:"role",role:"goal"},{type:"literal",value:"এ",alternatives:["তে"]},{type:"literal",value:"সেট",alternatives:["নির্ধারণ"]},{type:"literal",value:"করুন"}]},extraction:{patient:{position:0},goal:{marker:"এ",position:2}}},{id:"set-bn-simple",language:"bn",command:"set",priority:90,template:{format:"সেট {patient} {goal}",tokens:[{type:"literal",value:"সেট",alternatives:["নির্ধারণ"]},{type:"role",role:"patient"},{type:"role",role:"goal"}]},extraction:{patient:{position:1},goal:{position:2}}}];case"de":return[{id:"set-de-full",language:"de",command:"set",priority:100,template:{format:"setze {destination} auf {patient}",tokens:[{type:"literal",value:"setze",alternatives:["setzen","stelle","stellen","set"]},{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"literal",value:"auf",alternatives:["zu","an"]},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:1},patient:{position:3}}},{id:"set-de-festlegen-auf",language:"de",command:"set",priority:99,template:{format:"festlegen auf {destination} {patient}",tokens:[{type:"literal",value:"festlegen",alternatives:["einstellen","setzen"]},{type:"literal",value:"auf",alternatives:["an"]},{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:2},patient:{position:3}}},{id:"set-de-equals",language:"de",command:"set",priority:95,template:{format:"{destination} = {patient}",tokens:[{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"literal",value:"="},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:0},patient:{position:2}}}];case"es":return[{id:"set-es-full",language:"es",command:"set",priority:100,template:{format:"establecer {destination} a {patient}",tokens:[{type:"literal",value:"establecer",alternatives:["fijar","definir","poner","set"]},{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"literal",value:"a",alternatives:["en","como"]},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:1},patient:{position:3}}},{id:"set-es-prep-first",language:"es",command:"set",priority:95,template:{format:"establecer en {destination} {patient}",tokens:[{type:"literal",value:"establecer",alternatives:["fijar","definir","poner","set"]},{type:"literal",value:"en",alternatives:["a"]},{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:2},patient:{position:3}}},{id:"set-es-equals",language:"es",command:"set",priority:95,template:{format:"{destination} = {patient}",tokens:[{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"literal",value:"="},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:0},patient:{position:2}}}];case"fr":return[{id:"set-fr-full",language:"fr",command:"set",priority:100,template:{format:"définir {destination} à {patient}",tokens:[{type:"literal",value:"définir",alternatives:["definir","mettre","fixer","set"]},{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"literal",value:"à",alternatives:["a","sur","comme"]},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:1},patient:{position:3}}},{id:"set-fr-sur-direct",language:"fr",command:"set",priority:98,template:{format:"définir sur {destination} {patient}",tokens:[{type:"literal",value:"définir",alternatives:["definir","mettre","fixer"]},{type:"literal",value:"sur",alternatives:["à","en"]},{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:2},patient:{position:3}}},{id:"set-fr-equals",language:"fr",command:"set",priority:95,template:{format:"{destination} = {patient}",tokens:[{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"literal",value:"="},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:0},patient:{position:2}}}];case"hi":return[{id:"set-hi-full",language:"hi",command:"set",priority:100,template:{format:"{destination} को {patient} सेट करें",tokens:[{type:"role",role:"destination"},{type:"literal",value:"को"},{type:"role",role:"patient"},{type:"literal",value:"सेट",alternatives:["निर्धारित"]},{type:"group",optional:!0,tokens:[{type:"literal",value:"करें",alternatives:["करो"]}]}]},extraction:{destination:{position:0},patient:{marker:"को",position:2}}},{id:"set-hi-simple",language:"hi",command:"set",priority:90,template:{format:"सेट {destination} {patient}",tokens:[{type:"literal",value:"सेट",alternatives:["निर्धारित"]},{type:"role",role:"destination"},{type:"role",role:"patient"}]},extraction:{destination:{position:1},patient:{position:2}}}];case"id":return[{id:"set-id-full",language:"id",command:"set",priority:100,template:{format:"atur {destination} ke {patient}",tokens:[{type:"literal",value:"atur",alternatives:["tetapkan","setel","set"]},{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"literal",value:"ke",alternatives:["menjadi","jadi","pada"]},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:1},patient:{position:3}}},{id:"set-id-pada-direct",language:"id",command:"set",priority:98,template:{format:"atur pada {destination} {patient}",tokens:[{type:"literal",value:"atur",alternatives:["tetapkan","setel"]},{type:"literal",value:"pada",alternatives:["ke","di"]},{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:2},patient:{position:3}}},{id:"set-id-equals",language:"id",command:"set",priority:95,template:{format:"{destination} = {patient}",tokens:[{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"literal",value:"="},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:0},patient:{position:2}}}];case"it":return[{id:"set-it-full",language:"it",command:"set",priority:100,template:{format:"impostare {patient} a {goal}",tokens:[{type:"literal",value:"impostare",alternatives:["imposta","set","definire"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"a",alternatives:["su","come"]},{type:"role",role:"goal"}]}]},extraction:{patient:{position:1},goal:{marker:"a",markerAlternatives:["su","come"]}}},{id:"set-it-simple",language:"it",command:"set",priority:90,template:{format:"impostare {patient}",tokens:[{type:"literal",value:"impostare",alternatives:["imposta","set"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"pl":return[{id:"set-pl-full",language:"pl",command:"set",priority:100,template:{format:"ustaw {patient} na {goal}",tokens:[{type:"literal",value:"ustaw",alternatives:["określ","okresl","przypisz"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"na",alternatives:["do","jako"]},{type:"role",role:"goal"}]}]},extraction:{patient:{position:1},goal:{marker:"na",markerAlternatives:["do","jako"]}}},{id:"set-pl-simple",language:"pl",command:"set",priority:90,template:{format:"ustaw {patient}",tokens:[{type:"literal",value:"ustaw",alternatives:["określ","okresl"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"pt":return[{id:"set-pt-full",language:"pt",command:"set",priority:100,template:{format:"definir {destination} para {patient}",tokens:[{type:"literal",value:"definir",alternatives:["estabelecer","colocar","set"]},{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"literal",value:"para",alternatives:["como","a","em"]},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:1},patient:{position:3}}},{id:"set-pt-em-direct",language:"pt",command:"set",priority:98,template:{format:"definir em {destination} {patient}",tokens:[{type:"literal",value:"definir",alternatives:["estabelecer","colocar"]},{type:"literal",value:"em",alternatives:["para","a"]},{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:2},patient:{position:3}}},{id:"set-pt-equals",language:"pt",command:"set",priority:95,template:{format:"{destination} = {patient}",tokens:[{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"literal",value:"="},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:0},patient:{position:2}}}];case"ru":return[{id:"set-ru-full",language:"ru",command:"set",priority:100,template:{format:"установить {patient} в {goal}",tokens:[{type:"literal",value:"установить",alternatives:["установи","задать","задай"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"в",alternatives:["на","как"]},{type:"role",role:"goal"}]}]},extraction:{patient:{position:1},goal:{marker:"в",markerAlternatives:["на","как"]}}},{id:"set-ru-simple",language:"ru",command:"set",priority:90,template:{format:"установить {patient}",tokens:[{type:"literal",value:"установить",alternatives:["установи","задать","задай"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"th":return[{id:"set-th-simple",language:"th",command:"set",priority:100,template:{format:"ตั้ง {patient} {goal}",tokens:[{type:"literal",value:"ตั้ง",alternatives:["กำหนด"]},{type:"role",role:"patient"},{type:"role",role:"goal"}]},extraction:{patient:{position:1},goal:{position:2}}}];case"uk":return[{id:"set-uk-full",language:"uk",command:"set",priority:100,template:{format:"встановити {patient} в {goal}",tokens:[{type:"literal",value:"встановити",alternatives:["встанови","задати","задай"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"в",alternatives:["на","як"]},{type:"role",role:"goal"}]}]},extraction:{patient:{position:1},goal:{marker:"в",markerAlternatives:["на","як"]}}},{id:"set-uk-simple",language:"uk",command:"set",priority:90,template:{format:"встановити {patient}",tokens:[{type:"literal",value:"встановити",alternatives:["встанови","задати","задай"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"vi":return[{id:"set-vi-full",language:"vi",command:"set",priority:100,template:{format:"gán {target} thành {value}",tokens:[{type:"literal",value:"gán",alternatives:["thiết lập","đặt giá trị"]},{type:"role",role:"patient"},{type:"literal",value:"thành",alternatives:["bằng","là"]},{type:"role",role:"goal"}]},extraction:{patient:{position:1},goal:{marker:"thành",markerAlternatives:["bằng","là"]}}},{id:"set-vi-simple",language:"vi",command:"set",priority:90,template:{format:"đặt {target} là {value}",tokens:[{type:"literal",value:"đặt"},{type:"role",role:"patient"},{type:"literal",value:"là"},{type:"role",role:"goal"}]},extraction:{patient:{position:1},goal:{marker:"là"}}}];case"zh":return[{id:"set-zh-full",language:"zh",command:"set",priority:100,template:{format:"设置 {destination} 为 {patient}",tokens:[{type:"literal",value:"设置",alternatives:["設置","设定","設定"]},{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"literal",value:"为",alternatives:["為","到","成"]},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:1},patient:{marker:"为",markerAlternatives:["為","到","成"]}}},{id:"set-zh-ba",language:"zh",command:"set",priority:95,template:{format:"把 {destination} 设置为 {patient}",tokens:[{type:"literal",value:"把"},{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"literal",value:"设置为",alternatives:["設置為","设定为","設定為"]},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:1},patient:{marker:"设置为",markerAlternatives:["設置為","设定为","設定為"]}}},{id:"set-zh-simple",language:"zh",command:"set",priority:90,template:{format:"{destination} = {patient}",tokens:[{type:"role",role:"destination",expectedTypes:["property-path","selector","reference","expression"]},{type:"literal",value:"="},{type:"role",role:"patient",expectedTypes:["literal","expression","reference"]}]},extraction:{destination:{position:0},patient:{position:2}}}]}},function(e){switch(e){case"ar":case"ja":case"ko":default:return[];case"bn":return[{id:"get-bn-full",language:"bn",command:"get",priority:100,template:{format:"{source} থেকে পান",tokens:[{type:"role",role:"source"},{type:"literal",value:"থেকে"},{type:"literal",value:"পান",alternatives:["নিন"]}]},extraction:{source:{position:0}}},{id:"get-bn-simple",language:"bn",command:"get",priority:90,template:{format:"পান {source}",tokens:[{type:"literal",value:"পান",alternatives:["নিন"]},{type:"role",role:"source"}]},extraction:{source:{position:1}}}];case"de":return[{id:"get-de-full",language:"de",command:"get",priority:100,template:{format:"hole {source}",tokens:[{type:"literal",value:"hole",alternatives:["holen","get","bekomme","bekommen"]},{type:"role",role:"source",expectedTypes:["selector","reference","expression"]}]},extraction:{source:{position:1}}}];case"hi":return[{id:"get-hi-full",language:"hi",command:"get",priority:100,template:{format:"{source} से प्राप्त करें",tokens:[{type:"role",role:"source"},{type:"literal",value:"से"},{type:"literal",value:"प्राप्त",alternatives:["पाएं"]},{type:"group",optional:!0,tokens:[{type:"literal",value:"करें",alternatives:["करो"]}]}]},extraction:{source:{position:0}}},{id:"get-hi-simple",language:"hi",command:"get",priority:90,template:{format:"प्राप्त {source}",tokens:[{type:"literal",value:"प्राप्त",alternatives:["पाएं"]},{type:"role",role:"source"}]},extraction:{source:{position:1}}}];case"it":return[{id:"get-it-full",language:"it",command:"get",priority:100,template:{format:"ottenere {patient} da {source}",tokens:[{type:"literal",value:"ottenere",alternatives:["ottieni","get","prendere"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"da",alternatives:["di"]},{type:"role",role:"source"}]}]},extraction:{patient:{position:1},source:{marker:"da",markerAlternatives:["di"]}}},{id:"get-it-simple",language:"it",command:"get",priority:90,template:{format:"ottenere {patient}",tokens:[{type:"literal",value:"ottenere",alternatives:["ottieni","get"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"pl":return[{id:"get-pl-full",language:"pl",command:"get",priority:100,template:{format:"pobierz {patient} z {source}",tokens:[{type:"literal",value:"pobierz",alternatives:["weź","wez","uzyskaj"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"z",alternatives:["od","ze"]},{type:"role",role:"source"}]}]},extraction:{patient:{position:1},source:{marker:"z",markerAlternatives:["od","ze"]}}},{id:"get-pl-simple",language:"pl",command:"get",priority:90,template:{format:"pobierz {patient}",tokens:[{type:"literal",value:"pobierz",alternatives:["weź","wez","uzyskaj"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"ru":return[{id:"get-ru-full",language:"ru",command:"get",priority:100,template:{format:"получить {patient} из {source}",tokens:[{type:"literal",value:"получить",alternatives:["получи","взять","возьми"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"из",alternatives:["от","с"]},{type:"role",role:"source"}]}]},extraction:{patient:{position:1},source:{marker:"из",markerAlternatives:["от","с"]}}},{id:"get-ru-simple",language:"ru",command:"get",priority:90,template:{format:"получить {patient}",tokens:[{type:"literal",value:"получить",alternatives:["получи","взять","возьми"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"th":return[{id:"get-th-simple",language:"th",command:"get",priority:100,template:{format:"รับค่า {source}",tokens:[{type:"literal",value:"รับค่า"},{type:"role",role:"source"}]},extraction:{source:{position:1}}}];case"uk":return[{id:"get-uk-full",language:"uk",command:"get",priority:100,template:{format:"отримати {patient} з {source}",tokens:[{type:"literal",value:"отримати",alternatives:["отримай","взяти","візьми"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"з",alternatives:["від","із"]},{type:"role",role:"source"}]}]},extraction:{patient:{position:1},source:{marker:"з",markerAlternatives:["від","із"]}}},{id:"get-uk-simple",language:"uk",command:"get",priority:90,template:{format:"отримати {patient}",tokens:[{type:"literal",value:"отримати",alternatives:["отримай","взяти","візьми"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"vi":return[{id:"get-vi-full",language:"vi",command:"get",priority:100,template:{format:"lấy giá trị của {target}",tokens:[{type:"literal",value:"lấy giá trị",alternatives:["nhận","lấy"]},{type:"group",optional:!0,tokens:[{type:"literal",value:"của"}]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}},{id:"get-vi-simple",language:"vi",command:"get",priority:90,template:{format:"lấy {target}",tokens:[{type:"literal",value:"lấy",alternatives:["nhận","lấy giá trị"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}]}},function(e){switch(e){case"bn":return[{id:"increment-bn-full",language:"bn",command:"increment",priority:100,template:{format:"{patient} কে বৃদ্ধি করুন",tokens:[{type:"role",role:"patient"},{type:"literal",value:"কে"},{type:"literal",value:"বৃদ্ধি",alternatives:["বাড়ান"]},{type:"literal",value:"করুন"}]},extraction:{patient:{position:0}}},{id:"increment-bn-with-quantity",language:"bn",command:"increment",priority:95,template:{format:"{patient} কে {quantity} দিয়ে বৃদ্ধি করুন",tokens:[{type:"role",role:"patient"},{type:"literal",value:"কে"},{type:"role",role:"quantity"},{type:"literal",value:"দিয়ে"},{type:"literal",value:"বৃদ্ধি",alternatives:["বাড়ান"]},{type:"literal",value:"করুন"}]},extraction:{patient:{position:0},quantity:{marker:"দিয়ে",position:2}}},{id:"increment-bn-simple",language:"bn",command:"increment",priority:90,template:{format:"বৃদ্ধি {patient}",tokens:[{type:"literal",value:"বৃদ্ধি",alternatives:["বাড়ান"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"de":return[{id:"increment-de-full",language:"de",command:"increment",priority:100,template:{format:"erhöhe {patient}",tokens:[{type:"literal",value:"erhöhe",alternatives:["erhoehe","erhöhen","inkrementiere","inkrementieren","increment"]},{type:"role",role:"patient",expectedTypes:["selector","reference","expression"]}]},extraction:{patient:{position:1}}}];case"hi":return[{id:"increment-hi-full",language:"hi",command:"increment",priority:100,template:{format:"{patient} को बढ़ाएं",tokens:[{type:"role",role:"patient"},{type:"literal",value:"को"},{type:"literal",value:"बढ़ाएं",alternatives:["बढ़ा"]}]},extraction:{patient:{position:0}}},{id:"increment-hi-with-quantity",language:"hi",command:"increment",priority:95,template:{format:"{patient} को {quantity} से बढ़ाएं",tokens:[{type:"role",role:"patient"},{type:"literal",value:"को"},{type:"role",role:"quantity"},{type:"literal",value:"से"},{type:"literal",value:"बढ़ाएं",alternatives:["बढ़ा"]}]},extraction:{patient:{position:0},quantity:{marker:"से",position:2}}},{id:"increment-hi-simple",language:"hi",command:"increment",priority:90,template:{format:"बढ़ाएं {patient}",tokens:[{type:"literal",value:"बढ़ाएं",alternatives:["बढ़ा"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"it":return[{id:"increment-it-full",language:"it",command:"increment",priority:100,template:{format:"incrementare {patient} di {quantity}",tokens:[{type:"literal",value:"incrementare",alternatives:["incrementa","aumentare","increment"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"di",alternatives:["per"]},{type:"role",role:"quantity"}]}]},extraction:{patient:{position:1},quantity:{marker:"di",markerAlternatives:["per"],default:{type:"literal",value:"1"}}}},{id:"increment-it-simple",language:"it",command:"increment",priority:90,template:{format:"incrementare {patient}",tokens:[{type:"literal",value:"incrementare",alternatives:["incrementa","aumentare","increment"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},quantity:{default:{type:"literal",value:"1"}}}}];case"pl":return[{id:"increment-pl-full",language:"pl",command:"increment",priority:100,template:{format:"zwiększ {patient} o {quantity}",tokens:[{type:"literal",value:"zwiększ",alternatives:["zwieksz","podnieś","podnies"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"o"},{type:"role",role:"quantity"}]}]},extraction:{patient:{position:1},quantity:{marker:"o",default:{type:"literal",value:1}}}},{id:"increment-pl-simple",language:"pl",command:"increment",priority:90,template:{format:"zwiększ {patient}",tokens:[{type:"literal",value:"zwiększ",alternatives:["zwieksz","podnieś","podnies"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},quantity:{default:{type:"literal",value:1}}}}];case"ru":return[{id:"increment-ru-full",language:"ru",command:"increment",priority:100,template:{format:"увеличить {patient} на {quantity}",tokens:[{type:"literal",value:"увеличить",alternatives:["увеличь"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"на"},{type:"role",role:"quantity"}]}]},extraction:{patient:{position:1},quantity:{marker:"на",default:{type:"literal",value:1}}}},{id:"increment-ru-simple",language:"ru",command:"increment",priority:90,template:{format:"увеличить {patient}",tokens:[{type:"literal",value:"увеличить",alternatives:["увеличь"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},quantity:{default:{type:"literal",value:1}}}}];case"th":return[{id:"increment-th-simple",language:"th",command:"increment",priority:100,template:{format:"เพิ่มค่า {patient}",tokens:[{type:"literal",value:"เพิ่มค่า"},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}},{id:"increment-th-with-quantity",language:"th",command:"increment",priority:95,template:{format:"เพิ่มค่า {patient} ด้วย {quantity}",tokens:[{type:"literal",value:"เพิ่มค่า"},{type:"role",role:"patient"},{type:"literal",value:"ด้วย"},{type:"role",role:"quantity"}]},extraction:{patient:{position:1},quantity:{marker:"ด้วย",position:3}}}];case"tr":default:return[];case"uk":return[{id:"increment-uk-full",language:"uk",command:"increment",priority:100,template:{format:"збільшити {patient} на {quantity}",tokens:[{type:"literal",value:"збільшити",alternatives:["збільш"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"на"},{type:"role",role:"quantity"}]}]},extraction:{patient:{position:1},quantity:{marker:"на",default:{type:"literal",value:1}}}},{id:"increment-uk-simple",language:"uk",command:"increment",priority:90,template:{format:"збільшити {patient}",tokens:[{type:"literal",value:"збільшити",alternatives:["збільш"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},quantity:{default:{type:"literal",value:1}}}}];case"vi":return[{id:"increment-vi-full",language:"vi",command:"increment",priority:100,template:{format:"tăng {target} thêm {amount}",tokens:[{type:"literal",value:"tăng",alternatives:["tăng lên"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"thêm",alternatives:["lên"]},{type:"role",role:"quantity"}]}]},extraction:{patient:{position:1},quantity:{marker:"thêm",markerAlternatives:["lên"],default:{type:"literal",value:"1"}}}},{id:"increment-vi-simple",language:"vi",command:"increment",priority:90,template:{format:"tăng {target}",tokens:[{type:"literal",value:"tăng",alternatives:["tăng lên"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},quantity:{default:{type:"literal",value:"1"}}}}];case"zh":return[{id:"increment-zh-full",language:"zh",command:"increment",priority:100,template:{format:"增加 {patient}",tokens:[{type:"literal",value:"增加",alternatives:["递增","加","增","increment"]},{type:"role",role:"patient",expectedTypes:["selector","reference","expression"]}]},extraction:{patient:{position:1}}}]}},function(e){switch(e){case"bn":return[{id:"decrement-bn-full",language:"bn",command:"decrement",priority:100,template:{format:"{patient} কে হ্রাস করুন",tokens:[{type:"role",role:"patient"},{type:"literal",value:"কে"},{type:"literal",value:"হ্রাস",alternatives:["কমান"]},{type:"literal",value:"করুন"}]},extraction:{patient:{position:0}}},{id:"decrement-bn-with-quantity",language:"bn",command:"decrement",priority:95,template:{format:"{patient} কে {quantity} দিয়ে হ্রাস করুন",tokens:[{type:"role",role:"patient"},{type:"literal",value:"কে"},{type:"role",role:"quantity"},{type:"literal",value:"দিয়ে"},{type:"literal",value:"হ্রাস",alternatives:["কমান"]},{type:"literal",value:"করুন"}]},extraction:{patient:{position:0},quantity:{marker:"দিয়ে",position:2}}},{id:"decrement-bn-simple",language:"bn",command:"decrement",priority:90,template:{format:"হ্রাস {patient}",tokens:[{type:"literal",value:"হ্রাস",alternatives:["কমান"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"de":return[{id:"decrement-de-full",language:"de",command:"decrement",priority:100,template:{format:"verringere {patient}",tokens:[{type:"literal",value:"verringere",alternatives:["verringern","dekrementiere","dekrementieren","reduziere","decrement"]},{type:"role",role:"patient",expectedTypes:["selector","reference","expression"]}]},extraction:{patient:{position:1}}}];case"hi":return[{id:"decrement-hi-full",language:"hi",command:"decrement",priority:100,template:{format:"{patient} को घटाएं",tokens:[{type:"role",role:"patient"},{type:"literal",value:"को"},{type:"literal",value:"घटाएं",alternatives:["घटा"]}]},extraction:{patient:{position:0}}},{id:"decrement-hi-with-quantity",language:"hi",command:"decrement",priority:95,template:{format:"{patient} को {quantity} से घटाएं",tokens:[{type:"role",role:"patient"},{type:"literal",value:"को"},{type:"role",role:"quantity"},{type:"literal",value:"से"},{type:"literal",value:"घटाएं",alternatives:["घटा"]}]},extraction:{patient:{position:0},quantity:{marker:"से",position:2}}},{id:"decrement-hi-simple",language:"hi",command:"decrement",priority:90,template:{format:"घटाएं {patient}",tokens:[{type:"literal",value:"घटाएं",alternatives:["घटा"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}}];case"it":return[{id:"decrement-it-full",language:"it",command:"decrement",priority:100,template:{format:"decrementare {patient} di {quantity}",tokens:[{type:"literal",value:"decrementare",alternatives:["decrementa","diminuire","decrement"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"di",alternatives:["per"]},{type:"role",role:"quantity"}]}]},extraction:{patient:{position:1},quantity:{marker:"di",markerAlternatives:["per"],default:{type:"literal",value:"1"}}}},{id:"decrement-it-simple",language:"it",command:"decrement",priority:90,template:{format:"decrementare {patient}",tokens:[{type:"literal",value:"decrementare",alternatives:["decrementa","diminuire","decrement"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},quantity:{default:{type:"literal",value:"1"}}}}];case"pl":return[{id:"decrement-pl-full",language:"pl",command:"decrement",priority:100,template:{format:"zmniejsz {patient} o {quantity}",tokens:[{type:"literal",value:"zmniejsz",alternatives:["obniż","obniz"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"o"},{type:"role",role:"quantity"}]}]},extraction:{patient:{position:1},quantity:{marker:"o",default:{type:"literal",value:1}}}},{id:"decrement-pl-simple",language:"pl",command:"decrement",priority:90,template:{format:"zmniejsz {patient}",tokens:[{type:"literal",value:"zmniejsz",alternatives:["obniż","obniz"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},quantity:{default:{type:"literal",value:1}}}}];case"ru":return[{id:"decrement-ru-full",language:"ru",command:"decrement",priority:100,template:{format:"уменьшить {patient} на {quantity}",tokens:[{type:"literal",value:"уменьшить",alternatives:["уменьши"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"на"},{type:"role",role:"quantity"}]}]},extraction:{patient:{position:1},quantity:{marker:"на",default:{type:"literal",value:1}}}},{id:"decrement-ru-simple",language:"ru",command:"decrement",priority:90,template:{format:"уменьшить {patient}",tokens:[{type:"literal",value:"уменьшить",alternatives:["уменьши"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},quantity:{default:{type:"literal",value:1}}}}];case"th":return[{id:"decrement-th-simple",language:"th",command:"decrement",priority:100,template:{format:"ลดค่า {patient}",tokens:[{type:"literal",value:"ลดค่า"},{type:"role",role:"patient"}]},extraction:{patient:{position:1}}},{id:"decrement-th-with-quantity",language:"th",command:"decrement",priority:95,template:{format:"ลดค่า {patient} ด้วย {quantity}",tokens:[{type:"literal",value:"ลดค่า"},{type:"role",role:"patient"},{type:"literal",value:"ด้วย"},{type:"role",role:"quantity"}]},extraction:{patient:{position:1},quantity:{marker:"ด้วย",position:3}}}];case"tr":default:return[];case"uk":return[{id:"decrement-uk-full",language:"uk",command:"decrement",priority:100,template:{format:"зменшити {patient} на {quantity}",tokens:[{type:"literal",value:"зменшити",alternatives:["зменш"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"на"},{type:"role",role:"quantity"}]}]},extraction:{patient:{position:1},quantity:{marker:"на",default:{type:"literal",value:1}}}},{id:"decrement-uk-simple",language:"uk",command:"decrement",priority:90,template:{format:"зменшити {patient}",tokens:[{type:"literal",value:"зменшити",alternatives:["зменш"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},quantity:{default:{type:"literal",value:1}}}}];case"vi":return[{id:"decrement-vi-full",language:"vi",command:"decrement",priority:100,template:{format:"giảm {target} đi {amount}",tokens:[{type:"literal",value:"giảm",alternatives:["giảm đi"]},{type:"role",role:"patient"},{type:"group",optional:!0,tokens:[{type:"literal",value:"đi",alternatives:["xuống"]},{type:"role",role:"quantity"}]}]},extraction:{patient:{position:1},quantity:{marker:"đi",markerAlternatives:["xuống"],default:{type:"literal",value:"1"}}}},{id:"decrement-vi-simple",language:"vi",command:"decrement",priority:90,template:{format:"giảm {target}",tokens:[{type:"literal",value:"giảm",alternatives:["giảm đi"]},{type:"role",role:"patient"}]},extraction:{patient:{position:1},quantity:{default:{type:"literal",value:"1"}}}}];case"zh":return[{id:"decrement-zh-full",language:"zh",command:"decrement",priority:100,template:{format:"减少 {patient}",tokens:[{type:"literal",value:"减少",alternatives:["递减","减","降低","decrement"]},{type:"role",role:"patient",expectedTypes:["selector","reference","expression"]}]},extraction:{patient:{position:1}}}]}},function(e){return[]}],Dv=new Map;function _v(e){const t=qv.flatMap(t=>t(e));return"en"===e&&t.push(...Hv),t.push(...function(e){const t=Dv.get(e);if(t)return t;const n=Sl(e);if(!n)return[];const r=Ku(n);return Dv.set(e,r),r}(e)),t}var Vv=["en","ja","ar","es","ko","zh","tr","pt","fr","de","id","qu","sw","it","vi","pl","ru","uk","hi","bn","th","ms","tl","he"];function Bv(){const e=[];for(const t of Vv)e.push(..._v(t));return e}var Fv=new Map,Uv=null;function Kv(){return null===Uv&&(Uv=Bv()),Uv}var Gv=new Proxy([],{get(e,t){const n=Kv(),r=Reflect.get(n,t);return"function"==typeof r?r.bind(n):r},ownKeys:()=>Reflect.ownKeys(Kv()),getOwnPropertyDescriptor:(e,t)=>Reflect.getOwnPropertyDescriptor(Kv(),t)});function Qv(e){if(Fv.has(e))return Fv.get(e);const t=_v(e);return Fv.set(e,t),t}function Jv(e,t){return lv(pv(e),t)}function Yv(e,t){return hv(e)?pv(e):kv(e,t)}function Zv(e,t){if(e.type!==t.type)return!1;switch(e.type){case"literal":case"selector":case"reference":return e.value===t.value;case"property-path":return Zv(e.object,t.object)&&e.property===t.property;case"expression":return e.raw===t.raw;default:return!1}}Gy(),Pl(),cl=function(e){return _v(e.code)},Zy(),sv(),Ov(),gv(),uv(),uv(),gv(),Pl(),sv(),Ov(),Zy(),Pl();var Xv=class{constructor(e={}){this.cache=new Map,this.config={maxSize:e.maxSize??1e3,ttlMs:e.ttlMs??0,enabled:e.enabled??!0},this.stats={hits:0,misses:0,evictions:0,expirations:0}}makeKey(e,t){return`${t}:${e}`}isExpired(e){return 0!==this.config.ttlMs&&Date.now()-e.createdAt>this.config.ttlMs}evictLRU(){const e=this.cache.keys().next().value;void 0!==e&&(this.cache.delete(e),this.stats.evictions++)}get(e,t){if(!this.config.enabled)return void this.stats.misses++;const n=this.makeKey(e,t),r=this.cache.get(n);if(r)return this.isExpired(r)?(this.cache.delete(n),this.stats.expirations++,void this.stats.misses++):(this.cache.delete(n),r.lastAccessed=Date.now(),this.cache.set(n,r),this.stats.hits++,r.result);this.stats.misses++}set(e,t,n){if(!this.config.enabled)return;if(0===n.confidence)return;const r=this.makeKey(e,t),i=Date.now();for(;this.cache.size>=this.config.maxSize;)this.evictLRU();this.cache.set(r,{result:n,createdAt:i,lastAccessed:i})}has(e,t){if(!this.config.enabled)return!1;const n=this.makeKey(e,t),r=this.cache.get(n);return!!r&&(!this.isExpired(r)||(this.cache.delete(n),this.stats.expirations++,!1))}delete(e,t){const n=this.makeKey(e,t);return this.cache.delete(n)}clear(){this.cache.clear()}resetStats(){this.stats={hits:0,misses:0,evictions:0,expirations:0}}getStats(){const e=this.stats.hits+this.stats.misses;return{hits:this.stats.hits,misses:this.stats.misses,size:this.cache.size,maxSize:this.config.maxSize,hitRate:e>0?this.stats.hits/e:0,evictions:this.stats.evictions,expirations:this.stats.expirations,enabled:this.config.enabled}}configure(e){if(void 0!==e.maxSize)for(this.config.maxSize=e.maxSize;this.cache.size>this.config.maxSize;)this.evictLRU();void 0!==e.ttlMs&&(this.config.ttlMs=e.ttlMs),void 0!==e.enabled&&(this.config.enabled=e.enabled)}enable(){this.config.enabled=!0}disable(){this.config.enabled=!1}getConfig(){return{...this.config}}},eg=new Xv;var tg=class{constructor(e={}){this.patternMatcher=new nv,this.languages=new Set(Tl()),!1===e.cache?this.cache=new Xv({enabled:!1}):this.cache=e.cache?new Xv(e.cache):eg}analyze(e,t){if(!this.supportsLanguage(t))return{confidence:0,errors:[`Language '${t}' is not supported for semantic parsing`]};const n=this.cache.get(e,t);if(n)return n;const r=this.analyzeUncached(e,t);return this.cache.set(e,t,r),r}analyzeUncached(e,t){try{try{const n=kv(e,t),r={confidence:n.metadata?.confidence??.8,node:n};return"command"===n.kind?{...r,command:{name:n.action,roles:n.roles}}:r}catch{}const n=Qy(t);if(!n)return{confidence:0,errors:[`No tokenizer available for language '${t}'`]};const r=n.tokenize(e),i=jl(t);if(0===i.length)return{confidence:0,errors:[`No patterns available for language '${t}'`]};const a=this.patternMatcher.matchBest(r,i);if(a){const e=this.buildSemanticNode(a);return{confidence:a.confidence,command:{name:a.pattern.command,roles:a.captured},node:e,tokensConsumed:a.consumedTokens}}return{confidence:0,errors:["No pattern matched the input"]}}catch(e){return{confidence:0,errors:[e instanceof Error?e.message:String(e)]}}}supportsLanguage(e){return this.languages.has(e)}supportedLanguages(){return Array.from(this.languages)}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}configureCache(e){this.cache.configure(e)}buildSemanticNode(e){return{kind:"command",action:e.pattern.command,roles:e.captured,metadata:{patternId:e.pattern.id}}}};function ng(e){return new tg(e)}var rg=.5;gc(),Oy(),eu(),Vp(),$c(),Lm(),kd(),_d(),wh(),Dh(),Ip(),hf(),Yf(),gc(),Ac(),Oy(),eu(),Vp(),$c(),um(),bm(),Lm(),Jm(),kd(),_d(),Jd(),ch(),wh(),Dh(),Gh(),Ip(),hf(),xf(),Pf(),Yf(),iy(),zy();var ig={ar:oc,bn:kc,zh:Ey,en:Gc,fr:Op,de:Lc,he:Xp,hi:lm,id:wm,it:qm,ja:ad,ko:Cd,ms:Bd,pl:Zd,pt:mh,qu:Ih,ru:Vh,es:zp,"es-MX":Rv,sw:af,th:yf,tl:Sf,tr:Df,uk:Xf,vi:dy};Ou(),Yu(),Iu(),Ou();var ag=new Map(Object.entries(Pu));function og(e){return ag.get(e)}function sg(e){return"literal"===e.type&&"string"==typeof e.value||"selector"===e.type||"reference"===e.type?e.value:void 0}function lg(e,t){if(null==e)return!1;for(const n of t)switch(n){case"selector":if("selector"===e.type)return!0;const t=sg(e);if(t&&(t.startsWith(".")||t.startsWith("#")||t.startsWith("[")))return!0;break;case"literal":if("literal"===e.type)return!0;if("property-path"===e.type)return!0;break;case"reference":if("reference"===e.type)return!0;if("property-path"===e.type)return!0;const n=sg(e);if(n&&["me","you","it","my","its","result","event","target"].includes(n.toLowerCase()))return!0;break;case"expression":if("expression"===e.type)return!0;if("property-path"===e.type)return!0}return!1}function cg(e){const t=[],n=[],r=[];let i=0;const a=og(e.action);if(!a)return n.push({code:"UNKNOWN_ROLE",message:`No schema found for action '${e.action}'. Skipping validation.`,severity:"warning"}),{valid:!0,errors:t,warnings:n,confidenceAdjustment:-.1,suggestions:r};const o=new Map;for(const t of e.arguments)t.role&&o.set(t.role,t);for(const e of a.roles){const a=o.get(e.role);!e.required||a?a&&!lg(a,e.expectedTypes)&&(n.push({code:"INVALID_TYPE",message:`Role '${e.role}' expected ${e.expectedTypes.join(" or ")}, got ${a.type}.`,role:e.role,expected:e.expectedTypes,actual:a,severity:"warning"}),i-=.1):e.default?n.push({code:"MISSING_REQUIRED_ROLE",message:`Role '${e.role}' not provided, using default.`,role:e.role,severity:"warning"}):(t.push({code:"MISSING_REQUIRED_ROLE",message:`Required role '${e.role}' (${e.description}) is missing.`,role:e.role,expected:e.expectedTypes,severity:"error"}),r.push(`Add ${e.description.toLowerCase()} to the command.`),i-=.2)}for(const t of e.arguments)if(t.role){a.roles.some(e=>e.role===t.role)||(n.push({code:"UNKNOWN_ROLE",message:`Role '${t.role}' is not recognized for command '${e.action}'.`,role:t.role,severity:"warning"}),i-=.05)}return a.roles.filter(e=>e.required&&!e.default).every(e=>o.has(e.role))&&0===t.length&&(i+=.1),{valid:0===t.length,errors:t,warnings:n,confidenceAdjustment:Math.max(-1,Math.min(1,i)),suggestions:r}}function ug(e){switch(e){case"preposition":return"preposition";case"postposition":case"particle":case"case-suffix":return"postposition";default:return"none"}}function pg(e,t,n){const r={form:t.primary,role:e,position:ug(n),required:t.required??!1};return t.alternatives&&(r.alternatives=t.alternatives),r}var mg={accessibility:!0,performance:!0,schema:!0,strict:!1},dg=new Set(["scroll","mousemove","touchmove","resize","input","keydown","keyup","keypress"]),hg=new Set(["scroll","mousemove","touchmove","resize"]);function fg(e,t){const n=[];if("event-handler"===e.kind){const r=e.roles.get("event");if(r&&"literal"===r.type){const e=String(r.value).toLowerCase();"mouseenter"!==e&&"mouseover"!==e&&"hover"!==e||n.push({code:"HOVER_ONLY_INTERACTION",severity:"warning",message:`Hover-only interaction detected (${e}). Not accessible to keyboard or touch users.`,suggestion:"Add keyboard equivalent (focus) or use a click-based interaction.",location:{input:t,role:"event"}})}}return n}function yg(e,t){const n=[];if("event-handler"===e.kind){const r=e.roles.get("event");if(r&&"literal"===r.type){const e=String(r.value).toLowerCase();if(dg.has(e)){const r=hg.has(e)?"warning":"info";n.push({code:"HIGH_FREQUENCY_TRIGGER",severity:r,message:`High-frequency event '${e}' may cause performance issues.`,suggestion:hg.has(e)?`Consider using 'on ${e} throttled:100ms' to limit execution frequency.`:"Consider debouncing or throttling this handler.",location:{input:t,role:"event"}})}}}return n}function vg(e,t){const n=[];if("command"!==e.kind)return n;const r=og(e.action);if(!r)return n;const i=Array.isArray(r.roles)?r.roles:[],a=new Set;for(const r of i)r&&"object"==typeof r&&"role"in r&&(a.add(r.role),r.required&&!e.roles.has(r.role)&&n.push({code:"MISSING_REQUIRED_ROLE",severity:"error",message:`Command '${e.action}' requires '${r.role}' but it was not provided.`,suggestion:r.description,location:{input:t}}));return e.roles.forEach((r,i)=>{a.has(i)||n.push({code:"INVALID_ROLE_FOR_COMMAND",severity:"warning",message:`Role '${i}' is not typically used with '${e.action}' command.`,location:{input:t,role:i}})}),n}function gg(e){if("event-handler"===e.kind){return e.body??[]}return[]}function bg(e,t={}){const n=[],r=new Map;for(const t of e)if("event-handler"===t.kind){const e=t.roles.get("event"),n=t.roles.get("source"),i=`${"literal"===e?.type?e.value:"unknown"}:${"selector"===n?.type?n.value:"self"}`;r.has(i)||r.set(i,[]);const a=gg(t);r.get(i).push({handler:t,commands:a})}return r.forEach((e,t)=>{if(e.length>1){const r=[],i=[];for(const{commands:t}of e)for(const e of t){r.push(e.action);const t=e.roles.get("patient");i.push("selector"===t?.type?t.value:"unknown")}const a=r.includes("toggle"),o=r.includes("show"),s=r.includes("hide");if(a&&(o||s)){i.filter((e,t)=>("toggle"===r[t]||"show"===r[t]||"hide"===r[t])&&i.some((n,r)=>t!==r&&e===n)).length>0&&n.push({code:"CONFLICTING_ACTIONS",severity:"warning",message:`Conflicting actions on '${t}': ${[...new Set(r)].join(", ")} may interfere with each other.`,suggestion:"Consider using a single toggle or conditional logic."})}r.some(e=>["fetch","wait","send"].includes(e))&&e.length>1&&n.push({code:"POTENTIAL_RACE_CONDITION",severity:"info",message:`Multiple handlers on '${t}' include async operations. Consider sequencing.`,suggestion:'Use "then" to chain operations or add loading states.'})}}),n}function kg(e,t="en",n={}){const r={...mg,...n},i=[];let a=null;try{a=kv(e,t)}catch{}if(!a)return{valid:!1,warnings:[{code:"UNREACHABLE_BEHAVIOR",severity:"error",message:"Could not parse input to semantic representation.",location:{input:e}}],node:null};r.accessibility&&i.push(...fg(a,e)),r.performance&&i.push(...yg(a,e)),r.schema&&i.push(...vg(a,e));const o=i.some(e=>"error"===e.severity),s=i.some(e=>"warning"===e.severity);return{valid:r.strict?!o&&!s:!o,warnings:i,node:a}}var wg=!1,zg={};var xg=new Set(["me","my","myself","you","your","yourself","it","its","result","event","target","body","detail","window","document"]),Eg=new Set(["and","or","not","no"]),Sg=new Set(["true","false","null","undefined"]),Tg=new Set(["ms","s","seconds","second","milliseconds","millisecond","minutes","minute","hours","hour"]);var Cg=class{constructor(){this.tokens=[],this.current=0}parse(e){try{if(this.tokens=function(e){const t=[];let n=0,r=1,i=1;function a(){if(0===t.length)return!0;const e=t[t.length-1];return["OPERATOR","COMPARISON","LOGICAL","LPAREN","LBRACKET","LBRACE","COMMA","COLON"].includes(e.type)}function o(t=0){return e[n+t]??""}function s(){const t=e[n];return n++,"\n"===t?(r++,i=1):i++,t}function l(){for(;n<e.length&&/\s/.test(e[n]);)s()}function c(t){let r="";for(;n<e.length&&t(e[n]);)r+=s();return r}function u(t){let r=t;for(s();n<e.length&&e[n]!==t;)"\\"===e[n]&&n+1<e.length?(r+=s(),r+=s()):r+=s();return n<e.length&&(r+=s()),r}function p(){let t="`";for(s();n<e.length&&"`"!==e[n];)"\\"===e[n]&&n+1<e.length?(t+=s(),t+=s()):t+=s();return n<e.length&&(t+=s()),t}function m(){let t="<";for(s();n<e.length&&(t+=s(),!t.endsWith("/>")););return t}function d(e,t,a){return{type:e,value:t,start:a,end:n,line:r,column:i-t.length}}for(;n<e.length&&(l(),!(n>=e.length));){const r=n,i=o();if("'"!==i||"s"!==o(1)||/\w/.test(o(2))){if('"'===i||"'"===i){const e=u(i);t.push(d("STRING",e,r));continue}if("`"===i){const e=p();t.push(d("TEMPLATE_LITERAL",e,r));continue}if("<"===i&&/[a-zA-Z.#\[]/.test(o(1))){const e=m();t.push(d("QUERY_SELECTOR",e,r));continue}if("#"===i&&a()){s();const e=c(e=>/[\w-]/.test(e));t.push(d("ID_SELECTOR","#"+e,r));continue}if("."===i&&/[a-zA-Z_-]/.test(o(1))&&a()){s();const e=c(e=>/[\w-]/.test(e));t.push(d("CLASS_SELECTOR","."+e,r));continue}if("["===i&&a()){const i=o(1);if("@"===i||/[a-zA-Z]/.test(i)){let i="";for(i+=s();n<e.length&&"]"!==e[n];)'"'===e[n]||"'"===e[n]?i+=u(e[n]):i+=s();n<e.length&&(i+=s()),t.push(d("ATTRIBUTE_SELECTOR",i,r));continue}}if("["!==i)if("]"!==i){if(/\d/.test(i)){const e=c(e=>/[\d.]/.test(e)),i=n,a=c(e=>/[a-zA-Z]/.test(e));Tg.has(a)?t.push(d("TIME_EXPRESSION",e+a,r)):(n=i,t.push(d("NUMBER",e,r)));continue}if("("!==i)if(")"!==i)if("{"!==i)if("}"!==i)if(","!==i)if(":"!==i)if("."!==i)if("+"!==i&&"-"!==i&&"*"!==i&&"/"!==i&&"%"!==i){if("="===i||"!"===i||"<"===i||">"===i){let e=s();"="===o()&&(e+=s()),t.push(d("COMPARISON",e,r));continue}if(/[a-zA-Z_$]/.test(i)){const e=c(e=>/[\w$]/.test(e)),n=e.toLowerCase();xg.has(n)?t.push(d("CONTEXT_VAR",e,r)):Eg.has(n)?t.push(d("LOGICAL",e,r)):Sg.has(n)?t.push(d("BOOLEAN",e,r)):t.push(d("IDENTIFIER",e,r));continue}s()}else s(),t.push(d("OPERATOR",i,r));else s(),t.push(d("DOT",".",r));else s(),t.push(d("COLON",":",r));else s(),t.push(d("COMMA",",",r));else s(),t.push(d("RBRACE","}",r));else s(),t.push(d("LBRACE","{",r));else s(),t.push(d("RPAREN",")",r));else s(),t.push(d("LPAREN","(",r))}else s(),t.push(d("RBRACKET","]",r));else s(),t.push(d("LBRACKET","[",r))}else s(),s(),t.push(d("POSSESSIVE","'s",r))}return t.push(d("EOF","",n)),t}(e),this.current=0,this.isAtEnd())return{success:!1,error:"Empty expression"};return{success:!0,node:this.parseExpression(),consumed:this.current}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Parse error"}}}peek(){return this.tokens[this.current]??{type:"EOF",value:"",start:0,end:0}}previous(){return this.tokens[this.current-1]??{type:"EOF",value:"",start:0,end:0}}isAtEnd(){return"EOF"===this.peek().type}advance(){return this.isAtEnd()||this.current++,this.previous()}check(e){return this.peek().type===e}checkValue(e){return this.peek().value.toLowerCase()===e.toLowerCase()}match(...e){for(const t of e)if(this.check(t))return this.advance(),!0;return!1}parseExpression(){return this.parseOr()}parseOr(){let e=this.parseAnd();for(;this.checkValue("or");){const t=this.advance().value,n=this.parseAnd();e=this.createBinaryExpression(t,e,n)}return e}parseAnd(){let e=this.parseEquality();for(;this.checkValue("and");){const t=this.advance().value,n=this.parseEquality();e=this.createBinaryExpression(t,e,n)}return e}parseEquality(){let e=this.parseComparison();for(;this.match("COMPARISON")||this.checkValue("is")||this.checkValue("matches")||this.checkValue("contains")||this.checkValue("in");){const t=this.previous().value,n=this.parseComparison();e=this.createBinaryExpression(t,e,n)}return e}parseComparison(){let e=this.parseAddition();for(;this.check("COMPARISON");){const t=this.advance().value,n=this.parseAddition();e=this.createBinaryExpression(t,e,n)}return e}parseAddition(){let e=this.parseMultiplication();for(;"+"===this.peek().value||"-"===this.peek().value;){const t=this.advance().value,n=this.parseMultiplication();e=this.createBinaryExpression(t,e,n)}return e}parseMultiplication(){let e=this.parseUnary();for(;"*"===this.peek().value||"/"===this.peek().value||"%"===this.peek().value;){const t=this.advance().value,n=this.parseUnary();e=this.createBinaryExpression(t,e,n)}return e}parseUnary(){if(this.checkValue("not")||this.checkValue("no")||"-"===this.peek().value){const e=this.advance().value,t=this.parseUnary();return this.createUnaryExpression(e,t)}return this.parsePostfix()}parsePostfix(){let e=this.parsePrimary();for(;;)if(this.match("DOT")){if(!this.check("IDENTIFIER")&&!this.check("CONTEXT_VAR"))break;{const t=this.advance().value;e=this.createPropertyAccess(e,t)}}else if(this.match("POSSESSIVE")){if(!this.check("IDENTIFIER")&&!this.check("CONTEXT_VAR"))break;{const t=this.advance().value;e=this.createPossessiveExpression(e,t)}}else if(this.match("LPAREN")){const t=this.parseArguments();e=this.createCallExpression(e,t)}else{if(!this.match("LBRACKET"))break;{const t=this.parseExpression();if(!this.match("RBRACKET"))throw new Error("Expected ] after index");e=this.createPropertyAccess(e,t)}}return e}parsePrimary(){const e=this.peek();if(this.match("NUMBER"))return this.createLiteral(parseFloat(e.value),"number",e);if(this.match("STRING")){const t=e.value.slice(1,-1);return this.createLiteral(t,"string",e)}if(this.match("BOOLEAN")){const t="true"===e.value||"false"!==e.value&&("null"===e.value?null:void 0),n={true:"boolean",false:"boolean",null:"null",undefined:"undefined"};return this.createLiteral(t,n[e.value]??"string",e)}if(this.match("TEMPLATE_LITERAL")){return{type:"templateLiteral",value:e.value,start:e.start,end:e.end,line:e.line,column:e.column}}if(this.match("TIME_EXPRESSION"))return this.parseTimeExpression(e);if(this.match("ID_SELECTOR"))return this.createSelector(e.value,"id",e);if(this.match("CLASS_SELECTOR"))return this.createSelector(e.value,"class",e);if(this.match("ATTRIBUTE_SELECTOR"))return this.createSelector(e.value,"attribute",e);if(this.match("QUERY_SELECTOR")){const t=e.value.slice(1,-2);return this.createSelector(t,"query",e)}if(this.match("CONTEXT_VAR"))return this.createContextReference(e.value,e);if(this.match("IDENTIFIER"))return this.createIdentifier(e.value,e);if(this.match("LPAREN")){const e=this.parseExpression();if(!this.match("RPAREN"))throw new Error("Expected ) after expression");return e}if(this.match("LBRACKET"))return this.parseArrayLiteral();if(this.match("LBRACE"))return this.parseObjectLiteral();throw new Error(`Unexpected token: ${e.value}`)}parseArguments(){const e=[];if(!this.check("RPAREN"))do{e.push(this.parseExpression())}while(this.match("COMMA"));if(!this.match("RPAREN"))throw new Error("Expected ) after arguments");return e}parseArrayLiteral(){const e=[],t=this.previous().start;if(!this.check("RBRACKET"))do{e.push(this.parseExpression())}while(this.match("COMMA"));if(!this.match("RBRACKET"))throw new Error("Expected ] after array elements");return{type:"arrayLiteral",elements:e,start:t,end:this.previous().end}}parseObjectLiteral(){const e=[],t=this.previous().start;if(!this.check("RBRACE"))do{let t;if(this.check("STRING"))t=this.advance().value.slice(1,-1);else{if(!this.check("IDENTIFIER"))throw new Error("Expected property name");t=this.advance().value}if(!this.match("COLON"))throw new Error("Expected : after property name");const n=this.parseExpression();e.push({key:t,value:n})}while(this.match("COMMA"));if(!this.match("RBRACE"))throw new Error("Expected } after object properties");return{type:"objectLiteral",properties:e.map(e=>({type:"objectProperty",key:e.key,value:e.value})),start:t,end:this.previous().end}}parseTimeExpression(e){const t=e.value.match(/^(\d+(?:\.\d+)?)(ms|s|seconds?|milliseconds?|minutes?|hours?)$/i);if(!t)throw new Error(`Invalid time expression: ${e.value}`);return{type:"timeExpression",value:parseFloat(t[1]),unit:t[2].toLowerCase(),raw:e.value,start:e.start,end:e.end,line:e.line,column:e.column}}createLiteral(e,t,n){return{type:"literal",value:e,dataType:t,raw:n.value,start:n.start,end:n.end,line:n.line,column:n.column}}createSelector(e,t,n){return{type:"selector",value:e,selector:e,selectorType:t,start:n.start,end:n.end,line:n.line,column:n.column}}createContextReference(e,t){return{type:"contextReference",contextType:e,name:t.value,start:t.start,end:t.end,line:t.line,column:t.column}}createIdentifier(e,t){return{type:"identifier",name:e,start:t.start,end:t.end,line:t.line,column:t.column}}createPropertyAccess(e,t){return{type:"propertyAccess",object:e,property:"string"==typeof t?t:"identifier"===t.type?t.name:"",start:e.start,end:this.previous().end}}createPossessiveExpression(e,t){return{type:"possessiveExpression",object:e,property:t,start:e.start,end:this.previous().end}}createBinaryExpression(e,t,n){return{type:"binaryExpression",operator:e,left:t,right:n,start:t.start,end:n.end}}createUnaryExpression(e,t){return{type:"unaryExpression",operator:e,operand:t,prefix:!0,start:this.previous().start,end:t.end}}createCallExpression(e,t){return{type:"callExpression",callee:e,arguments:t,start:e.start,end:this.previous().end}}};function Ag(e,t){switch(e.type){case"literal":return jg(e);case"selector":return Lg(e,t);case"reference":return Pg(e);case"property-path":return Ig(e,t);case"expression":return Ng(e);default:throw new Error(`Unknown semantic value type: ${e.type}`)}}function jg(e){const t={type:"literal",value:e.value};return e.dataType?{...t,dataType:e.dataType}:t}function Lg(e,t){return t&&e.value.startsWith("*")&&/^[a-zA-Z-]/.test(e.value.slice(1))&&t.push(`Converted '${e.value}' to a CSS selector, but it looks like a CSS property name. CSS properties in commands like 'transition' should be literal strings, not selectors. Consider using expectedTypes: ['literal'] instead of ['literal', 'selector'] in the command schema.`),{type:"selector",value:e.value,selector:e.value,selectorType:e.selectorKind}}function Pg(e){return{type:"contextReference",contextType:e.value,name:e.value}}function Ig(e,t){return{type:"propertyAccess",object:Ag(e.object,t),property:e.property}}function Ng(e){const t=(n=e.raw,(new Cg).parse(n));var n;if(!t.success||!t.node){return{type:"identifier",name:e.raw}}return t.node}function Og(e,t){return e.roles.get(t)}function Rg(e,t,n){const r=Og(e,t);return r?Ag(r,n):void 0}function Mg(e,t=[],n,r={}){const i={type:"command",name:e,args:t};return n&&Object.keys(n).length>0&&(i.modifiers=n),r.isBlocking&&(i.isBlocking=r.isBlocking),r.implicitTarget&&(i.implicitTarget=r.implicitTarget),r.semanticRoles&&Object.keys(r.semanticRoles).length>0&&(i.semanticRoles=r.semanticRoles),i}var Wg={action:"toggle",toAST(e,t){const n=Rg(e,"patient"),r=Rg(e,"destination"),i=Rg(e,"duration"),a=n?[n]:[],o={};return r&&(o.on=r),i&&(o.for=i),Mg("toggle",a,o)}},$g={action:"add",toAST(e,t){const n=Rg(e,"patient"),r=Rg(e,"destination"),i=n?[n]:[],a={};return r&&(a.to=r),Mg("add",i,a)}},Hg={action:"remove",toAST(e,t){const n=Rg(e,"patient"),r=Rg(e,"source"),i=n?[n]:[],a={};return r&&(a.from=r),Mg("remove",i,a)}},qg={action:"set",toAST(e,t){const n=Rg(e,"destination"),r=Rg(e,"patient"),i=[],a={};return n&&i.push(n),r&&(a.to=r),Mg("set",i,a)}},Dg={action:"show",toAST(e,t){const n=Rg(e,"destination"),r=Rg(e,"patient"),i=Rg(e,"duration"),a=[],o={},s=n??r;return s&&a.push(s),i&&(o.with=i),Mg("show",a,o)}},_g={action:"hide",toAST(e,t){const n=Rg(e,"destination"),r=Rg(e,"patient"),i=Rg(e,"duration"),a=[],o={},s=n??r;return s&&a.push(s),i&&(o.with=i),Mg("hide",a,o)}},Vg={action:"increment",toAST(e,t){const n=Rg(e,"destination"),r=Rg(e,"patient"),i=Rg(e,"quantity"),a=[],o={},s=n??r;return s&&a.push(s),i&&(o.by=i),Mg("increment",a,o)}},Bg={action:"decrement",toAST(e,t){const n=Rg(e,"destination"),r=Rg(e,"patient"),i=Rg(e,"quantity"),a=[],o={},s=n??r;return s&&a.push(s),i&&(o.by=i),Mg("decrement",a,o)}},Fg={action:"wait",toAST(e,t){const n=Rg(e,"duration");return Mg("wait",n?[n]:[],void 0,{isBlocking:!0})}},Ug={action:"log",toAST(e,t){const n=Rg(e,"patient"),r=[];return n&&r.push(n),Mg("log",r)}},Kg={action:"put",toAST(e,t){const n=Rg(e,"patient"),r=Rg(e,"destination"),i=Og(e,"method"),a=n?[n]:[],o={};if(r){o["literal"===i?.type?String(i.value):"into"]=r}return Mg("put",a,o)}},Gg={action:"fetch",toAST(e,t){const n=Rg(e,"source"),r=Rg(e,"method"),i=Rg(e,"responseType"),a=Rg(e,"patient"),o=n?[n]:[],s={};return r&&(s.with=r),i&&(s.as=i),a&&(s.body=a),Mg("fetch",o,s,{isBlocking:!0})}},Qg={action:"append",toAST(e,t){const n=Rg(e,"patient"),r=Rg(e,"destination"),i=n?[n]:[],a={};return r&&(a.to=r),Mg("append",i,a)}},Jg={action:"prepend",toAST(e,t){const n=Rg(e,"patient"),r=Rg(e,"destination"),i=n?[n]:[],a={};return r&&(a.to=r),Mg("prepend",i,a)}},Yg={action:"trigger",toAST(e,t){const n=Rg(e,"event"),r=Rg(e,"destination"),i=n?[n]:[],a={};return r&&(a.on=r),Mg("trigger",i,a)}},Zg={action:"send",toAST(e,t){const n=Rg(e,"event"),r=Rg(e,"destination"),i=Rg(e,"patient"),a=n?[n]:[],o={};return r&&(o.to=r),i&&(o.detail=i),Mg("send",a,o)}},Xg={action:"go",toAST(e,t){const n=Rg(e,"source"),r=Rg(e,"destination"),i=[],a={};return n&&i.push(n),r&&(a.to=r),Mg("go",i,a)}},eb={action:"transition",toAST(e,t){const n=Rg(e,"patient"),r=Rg(e,"goal"),i=Rg(e,"duration"),a=Rg(e,"destination"),o=n?[n]:[],s={};return r&&(s.to=r),i&&(s.over=i),a&&(s.on=a),Mg("transition",o,s)}},tb={action:"focus",toAST(e,t){const n=Rg(e,"destination"),r=Rg(e,"patient"),i=[],a=n??r;return a&&i.push(a),Mg("focus",i,{})}},nb={action:"blur",toAST(e,t){const n=Rg(e,"destination"),r=Rg(e,"patient"),i=[],a=n??r;return a&&i.push(a),Mg("blur",i)}},rb={action:"get",toAST(e,t){const n=Rg(e,"source"),r=Rg(e,"patient"),i=[],a=n??r;return a&&i.push(a),Mg("get",i)}},ib={action:"take",toAST(e,t){const n=Rg(e,"patient"),r=Rg(e,"source"),i=n?[n]:[],a={};return r&&(a.from=r),Mg("take",i,a)}},ab={action:"call",toAST(e,t){const n=Rg(e,"patient");return Mg("call",n?[n]:[])}},ob={action:"return",toAST(e,t){const n=Rg(e,"patient");return Mg("return",n?[n]:[])}},sb={action:"halt",toAST:(e,t)=>Mg("halt",[])},lb={action:"throw",toAST(e,t){const n=Rg(e,"patient");return Mg("throw",n?[n]:[])}},cb={action:"settle",toAST(e,t){const n=Rg(e,"destination"),r=Rg(e,"patient"),i=[],a=n??r;return a&&i.push(a),Mg("settle",i,void 0,{isBlocking:!0})}},ub={action:"swap",toAST(e,t){const n=Rg(e,"patient"),r=Rg(e,"source"),i=Rg(e,"destination"),a=Rg(e,"style"),o=[],s={};return n&&o.push(n),r&&o.push(r),i&&(s.on=i),a&&(s.with=a),Mg("swap",o,s)}},pb={action:"morph",toAST(e,t){const n=Rg(e,"source"),r=Rg(e,"destination"),i=Rg(e,"patient"),a=[],o={},s=n??i;return s&&a.push(s),r&&(o.on=r),Mg("morph",a,o)}},mb={action:"clone",toAST(e,t){const n=Rg(e,"source"),r=Rg(e,"destination"),i=Rg(e,"patient"),a=[],o={},s=n??i;return s&&a.push(s),r&&(o.into=r),Mg("clone",a,o)}},db={action:"make",toAST(e,t){const n=Rg(e,"patient");return Mg("make",n?[n]:[])}},hb={action:"measure",toAST(e,t){const n=Rg(e,"patient"),r=Rg(e,"destination"),i=Rg(e,"source"),a=[],o={};n&&a.push(n);const s=r??i;return s&&(o.of=s),Mg("measure",a,o)}},fb={action:"tell",toAST(e,t){const n=Rg(e,"destination"),r=Rg(e,"patient"),i=[],a=n??r;return a&&i.push(a),Mg("tell",i)}},yb={action:"js",toAST(e,t){const n=Rg(e,"patient");return Mg("js",n?[n]:[])}},vb={action:"async",toAST:(e,t)=>Mg("async",[])},gb={action:"if",toAST(e,t){const n=Rg(e,"condition");return Mg("if",n?[n]:[])}},bb={action:"unless",toAST(e,t){const n=Rg(e,"condition");return Mg("unless",n?[n]:[])}},kb={action:"repeat",toAST(e,t){const n=Rg(e,"quantity"),r=Rg(e,"patient"),i=[],a=n??r;return a&&i.push(a),Mg("repeat",i)}},wb={action:"for",toAST(e,t){const n=Rg(e,"patient"),r=Rg(e,"source"),i=n?[n]:[],a={};return r&&(a.in=r),Mg("for",i,a)}},zb={action:"while",toAST(e,t){const n=Rg(e,"condition");return Mg("while",n?[n]:[])}},xb={action:"continue",toAST:(e,t)=>Mg("continue",[])},Eb={action:"default",toAST(e,t){const n=Rg(e,"patient"),r=Rg(e,"source"),i=n?[n]:[],a={};return r&&(a.to=r),Mg("default",i,a)}},Sb={action:"init",toAST:(e,t)=>Mg("init",[])},Tb={action:"behavior",toAST(e,t){const n=Rg(e,"patient");return Mg("behavior",n?[n]:[])}},Cb={action:"install",toAST(e,t){const n=Rg(e,"patient"),r=Rg(e,"destination"),i=n?[n]:[],a={};return r&&(a.on=r),Mg("install",i,a)}},Ab=new Map([["toggle",Wg],["add",$g],["remove",Hg],["set",qg],["show",Dg],["hide",_g],["increment",Vg],["decrement",Bg],["wait",Fg],["log",Ug],["put",Kg],["fetch",Gg],["append",Qg],["prepend",Jg],["get",rb],["take",ib],["trigger",Yg],["send",Zg],["on",{action:"on",toAST(e,t){const n=Rg(e,"event"),r=Rg(e,"source"),i=n?[n]:[],a={};return r&&(a.from=r),Mg("on",i,a)}}],["go",Xg],["transition",eb],["focus",tb],["blur",nb],["call",ab],["return",ob],["halt",sb],["throw",lb],["settle",cb],["swap",ub],["morph",pb],["clone",mb],["measure",hb],["make",db],["tell",fb],["default",Eb],["js",yb],["async",vb],["if",gb],["unless",bb],["repeat",kb],["for",wb],["while",zb],["continue",xb],["init",Sb],["behavior",Tb],["install",Cb]]);function jb(e){return Ab.get(e)}var Lb=class{constructor(e={}){this.warnings=[]}build(e){switch(e.kind){case"command":return this.buildCommand(e);case"event-handler":return this.buildEventHandler(e);case"conditional":return this.buildConditional(e);case"compound":return this.buildCompound(e);case"loop":return this.buildLoop(e);default:throw new Error(`Unknown semantic node kind: ${e.kind}`)}}buildCommand(e){const t=jb(e.action);let n;if(t){const r=t.toAST(e,this);if("ast"in r&&"warnings"in r){const e=r;this.warnings.push(...e.warnings),n=e.ast}else n=r}else n=this.buildGenericCommand(e);if(e.roles&&e.roles.size>0){const t={};for(const[n,r]of e.roles)t[n]=Ag(r);Object.keys(t).length>0&&(n.semanticRoles=t)}return n}buildGenericCommand(e){const t=[],n={},r=["patient","source","quantity"],i=["destination","duration","method","style"];for(const n of r){const r=e.roles.get(n);r&&t.push(Ag(r))}for(const t of i){const r=e.roles.get(t);if(r){n[this.roleToModifierKey(t)]=Ag(r)}}const a={type:"command",name:e.action,args:t};return Object.keys(n).length>0?{...a,modifiers:n}:a}roleToModifierKey(e){return{destination:"on",duration:"for",source:"from",condition:"if",method:"via",style:"with"}[e]??e}buildEventHandler(e){const t=e.roles.get("event");let n,r;if("literal"===t?.type){const e=String(t.value);e.includes("|")||e.includes(" or ")?(r=e.split(/\s+or\s+|\|/).map(e=>e.trim()),n=r[0]):n=e}else n="reference"===t?.type?t.value:"click";const i=e.body.map(e=>this.build(e)),a=e.roles.get("source");let o,s;"selector"===a?.type?(o=a.value,s=a.value):"reference"===a?.type?s=a.value:"literal"===a?.type&&(s=String(a.value));const l=e.roles.get("condition"),c=l?Ag(l):void 0,u=e.roles.get("destination"),p=u?Ag(u):void 0,m=e.eventModifiers;let d=o;if(m?.from){const e=m.from;"selector"!==e.type||o||(d=e.value)}const h=e.parameterNames?[...e.parameterNames]:void 0;return{type:"eventHandler",event:n,commands:i,...r&&r.length>1?{events:r}:{},...d?{selector:d}:{},...s?{target:s}:{},...c?{condition:c}:{},...p?{watchTarget:p}:{},...h&&h.length>0?{args:h,params:h}:{}}}buildConditional(e){const t=e.roles.get("condition");if(!t)throw new Error("Conditional node missing condition");const n=Ag(t),r=e.thenBranch.map(e=>this.build(e)),i=e.elseBranch?.map(e=>this.build(e)),a=[n,{type:"block",commands:r}];return i&&i.length>0&&a.push({type:"block",commands:i}),{type:"command",name:"if",args:a}}buildCompound(e){const t=e.statements.map(e=>this.build(e));if(1===t.length)return t[0];if(0===t.length)return{type:"block",commands:[]};return{type:"CommandSequence",commands:t}}buildLoop(e){const t=e.body.map(e=>this.build(e)),n=[{type:"identifier",name:e.loopVariant}];switch(e.loopVariant){case"times":{const t=e.roles.get("quantity");t&&n.push(Ag(t));break}case"for":{e.loopVariable&&n.push({type:"string",value:e.loopVariable});const t=e.roles.get("source");t&&n.push(Ag(t));break}case"while":case"until":{const t=e.roles.get("condition");t&&n.push(Ag(t));break}}return n.push({type:"block",commands:t}),{type:"command",name:"repeat",args:n}}buildBlock(e){return{type:"block",commands:e.map(e=>this.build(e))}}};Pl();var Pb={en:async()=>{const{englishTokenizer:e}=await Promise.resolve().then(()=>(au(),tu)),{englishProfile:t}=await Promise.resolve().then(()=>(eu(),Jc)),{buildEnglishPatterns:n}=await Promise.resolve().then(()=>(kp(),mp));return{tokenizer:e,profile:t,buildPatterns:n}},es:async()=>{const{spanishTokenizer:e}=await Promise.resolve().then(()=>(Rp(),Np)),{spanishProfile:t}=await Promise.resolve().then(()=>(Ip(),Ep));return{tokenizer:e,profile:t}},ja:async()=>{const{japaneseTokenizer:e}=await Promise.resolve().then(()=>(Sd(),wd)),{japaneseProfile:t}=await Promise.resolve().then(()=>(kd(),sd));return{tokenizer:e,profile:t}},ar:async()=>{const{arabicTokenizer:e}=await Promise.resolve().then(()=>(wc(),bc)),{arabicProfile:t}=await Promise.resolve().then(()=>(gc(),lc));return{tokenizer:e,profile:t}},ko:async()=>{const{koreanTokenizer:e}=await Promise.resolve().then(()=>(Fd(),Vd)),{koreanProfile:t}=await Promise.resolve().then(()=>(_d(),jd));return{tokenizer:e,profile:t}},zh:async()=>{const{chineseTokenizer:e}=await Promise.resolve().then(()=>(Wy(),Ry)),{chineseProfile:t}=await Promise.resolve().then(()=>(Oy(),Ty));return{tokenizer:e,profile:t}},tr:async()=>{const{turkishTokenizer:e}=await Promise.resolve().then(()=>(ey(),Zf)),{turkishProfile:t}=await Promise.resolve().then(()=>(Yf(),Vf));return{tokenizer:e,profile:t}},pt:async()=>{const{portugueseTokenizer:e}=await Promise.resolve().then(()=>(Nh(),Ph)),{portugueseProfile:t}=await Promise.resolve().then(()=>(wh(),hh));return{tokenizer:e,profile:t}},fr:async()=>{const{frenchTokenizer:e}=await Promise.resolve().then(()=>(cm(),Zp)),{frenchProfile:t}=await Promise.resolve().then(()=>(Vp(),Mp));return{tokenizer:e,profile:t}},de:async()=>{const{germanTokenizer:e}=await Promise.resolve().then(()=>(Qc(),Kc)),{germanProfile:t}=await Promise.resolve().then(()=>($c(),Ic));return{tokenizer:e,profile:t}},id:async()=>{const{indonesianTokenizer:e}=await Promise.resolve().then(()=>($m(),Pm)),{indonesianProfile:t}=await Promise.resolve().then(()=>(Lm(),xm));return{tokenizer:e,profile:t}},qu:async()=>{const{quechuaTokenizer:e}=await Promise.resolve().then(()=>(Bh(),_h)),{quechuaProfile:t}=await Promise.resolve().then(()=>(Dh(),Oh));return{tokenizer:e,profile:t}},sw:async()=>{const{swahiliTokenizer:e}=await Promise.resolve().then(()=>(vf(),ff)),{swahiliProfile:t}=await Promise.resolve().then(()=>(hf(),sf));return{tokenizer:e,profile:t}},bn:async()=>{const{bengaliTokenizer:e}=await Promise.resolve().then(()=>(Pc(),jc)),{bengaliProfile:t}=await Promise.resolve().then(()=>(Ac(),zc));return{tokenizer:e,profile:t}},hi:async()=>{const{hindiTokenizer:e}=await Promise.resolve().then(()=>(zm(),km)),{hindiProfile:t}=await Promise.resolve().then(()=>(bm(),mm));return{tokenizer:e,profile:t}},it:async()=>{const{italianTokenizer:e}=await Promise.resolve().then(()=>(td(),Ym)),{italianProfile:t}=await Promise.resolve().then(()=>(Jm(),_m));return{tokenizer:e,profile:t}},ms:async()=>{const{malayTokenizer:e}=await Promise.resolve().then(()=>(Xd(),Yd)),{malayProfile:t}=await Promise.resolve().then(()=>(Jd(),Ud));return{tokenizer:e,profile:t}},pl:async()=>{const{polishTokenizer:e}=await Promise.resolve().then(()=>(dh(),ph)),{polishProfile:t}=await Promise.resolve().then(()=>(ch(),eh));return{tokenizer:e,profile:t}},ru:async()=>{const{russianTokenizer:e}=await Promise.resolve().then(()=>(of(),rf)),{russianProfile:t}=await Promise.resolve().then(()=>(Gh(),Fh));return{tokenizer:e,profile:t}},th:async()=>{const{thaiTokenizer:e}=await Promise.resolve().then(()=>(Tf(),Ef)),{thaiProfile:t}=await Promise.resolve().then(()=>(xf(),gf));return{tokenizer:e,profile:t}},tl:async()=>{const{tagalogTokenizer:e}=await Promise.resolve().then(()=>(Rf(),If)),{tagalogProfile:t}=await Promise.resolve().then(()=>(Pf(),Cf));return{tokenizer:e,profile:t}},uk:async()=>{const{ukrainianTokenizer:e}=await Promise.resolve().then(()=>(hy(),my)),{ukrainianProfile:t}=await Promise.resolve().then(()=>(iy(),ty));return{tokenizer:e,profile:t}},vi:async()=>{const{vietnameseTokenizer:e}=await Promise.resolve().then(()=>(Sy(),xy)),{vietnameseProfile:t}=await Promise.resolve().then(()=>(zy(),fy));return{tokenizer:e,profile:t}}},Ib=Object.keys(Pb);async function Nb(e,t={}){const{url:n,module:r,skipIfRegistered:i=!0}=t;if(i&&Cl(e))return{code:e,loaded:!1};try{let t;if(r)t=r;else if(n)t=await async function(e,t){try{const e=await fetch(t);if(!e.ok)throw new Error(`Failed to fetch ${t}: ${e.status} ${e.statusText}`);const n=await e.text(),r=new Blob([n],{type:"application/javascript"}),i=URL.createObjectURL(r);try{const e=await import(i);if(!e.tokenizer||!e.profile)throw new Error("Invalid language module: missing tokenizer or profile");return e}finally{URL.revokeObjectURL(i)}}catch(n){throw new Error(`Failed to load language '${e}' from ${t}: ${n instanceof Error?n.message:String(n)}`)}}(e,n);else{const n=Pb[e];if(!n)throw new Error(`Unknown language: ${e}. Supported: ${Ib.join(", ")}`);t=await n()}return function(e,t){wl(e,t.tokenizer,t.profile),t.patterns?zl(e,t.patterns):t.buildPatterns&&zl(e,t.buildPatterns())}(e,t),{code:e,loaded:!0}}catch(t){return{code:e,loaded:!1,error:t instanceof Error?t.message:String(t)}}}function Ob(e,t){try{const n=Jy(e,t),r=jl(t);if(0===r.length)return{confidence:0,parseSuccess:!1,error:`No patterns available for language: ${t}`};const i=[...r].sort((e,t)=>t.priority-e.priority),a=i.filter(e=>"on"===e.command),o=rv.matchBest(n,a);if(o)return{confidence:o.confidence,parseSuccess:!0,patternId:o.pattern.id,action:o.pattern.command,tokensConsumed:o.consumedTokens};n.reset(n.mark());const s=i.filter(e=>"on"!==e.command),l=rv.matchBest(n,s);return l?{confidence:l.confidence,parseSuccess:!0,patternId:l.pattern.id,action:l.pattern.command,tokensConsumed:l.consumedTokens}:{confidence:0,parseSuccess:!1,error:`Could not match any patterns for: ${e}`}}catch(e){return{confidence:0,parseSuccess:!1,error:e instanceof Error?e.message:String(e)}}}function Rb(e,t){const n=Ob(e,t);if(!n.parseSuccess)return{node:null,confidence:0,error:n.error};try{const{parse:r}=(Ov(),vl(bv));return{node:r(e,t),confidence:n.confidence,error:void 0}}catch(e){return{node:null,confidence:n.confidence,error:e instanceof Error?e.message:String(e)}}}function Mb(e){const t={};return"number"==typeof e.start&&(t.start=e.start),"number"==typeof e.end&&(t.end=e.end),"number"==typeof e.line&&(t.line=e.line),"number"==typeof e.column&&(t.column=e.column),t}function Wb(e){if(!e)return{type:"literal",value:null};switch(e.type){case"eventHandler":return function(e){const t=e.event??"click",n=e.commands??e.body??[],r=n.map(e=>Wb(e)),i=function(e){const t=e.eventModifiers;return{...e.once||t?.once?{once:!0}:{},...e.debounce||t?.debounce?{debounce:e.debounce??t?.debounce}:{},...e.throttle||t?.throttle?{throttle:e.throttle??t?.throttle}:{},...e.prevent||t?.prevent?{prevent:!0}:{},...e.stop||t?.stop?{stop:!0}:{},...e.capture||t?.capture?{capture:!0}:{},...e.passive||t?.passive?{passive:!0}:{},...e.from||t?.from?{from:e.from??t?.from}:e.selector?{from:e.selector}:{}}}(e);return{type:"event",event:t,modifiers:i,body:r,...Mb(e)}}(e);case"command":return function(e){const t=e.name;if("if"===t||"unless"===t)return function(e){const t=e.args??[];let n=t[0]?Wb(t[0]):{type:"literal",value:!0};const r=$b(t[1]),i=t[2]?$b(t[2]):void 0;"unless"===e.name&&(n={type:"unary",operator:"not",operand:n});return{type:"if",condition:n,thenBranch:r,...i?{elseBranch:i}:{},...Mb(e)}}(e);if("repeat"===t)return function(e){const t=e.args??[];if(0===t.length)return{type:"repeat",body:[],...Mb(e)};const n=t[0],r=n?.name??n?.value??"forever",i=t[t.length-1];switch(r){case"times":return{type:"repeat",count:t[1]?Wb(t[1]):void 0,body:$b(i),...Mb(e)};case"for":return{type:"foreach",itemName:t[1]?.value??"item",collection:t[2]?Wb(t[2]):{type:"identifier",value:"[]"},body:$b(i),...Mb(e)};case"while":return{type:"while",condition:t[1]?Wb(t[1]):{type:"literal",value:!0},body:$b(i),...Mb(e)};case"until":return{type:"while",condition:{type:"unary",operator:"not",operand:t[1]?Wb(t[1]):{type:"literal",value:!1}},body:$b(i),...Mb(e)};default:return{type:"repeat",body:$b(i),...Mb(e)}}}(e);const n=(e.args??[]).map(e=>Wb(e)),r=e.target?Wb(e.target):void 0,i=e.modifiers?function(e){const t={};for(const[n,r]of Object.entries(e))t[n]=Wb(r);return t}(e.modifiers):void 0,a=e.semanticRoles,o=a?function(e){const t={};for(const[n,r]of Object.entries(e))t[n]=Wb(r);return t}(a):void 0;return{type:"command",name:t,args:n,...r?{target:r}:{},...i&&Object.keys(i).length>0?{modifiers:i}:{},...o&&Object.keys(o).length>0?{roles:o}:{},...Mb(e)}}(e);case"CommandSequence":return function(e){const t=e.commands??[];return 1===t.length?Wb(t[0]):{type:"event",event:"click",body:t.map(e=>Wb(e)),...Mb(e)}}(e);case"block":return function(e){const t=e.commands??[];return 1===t.length?Wb(t[0]):{type:"event",event:"click",body:t.map(e=>Wb(e)),...Mb(e)}}(e);case"if":return function(e){const t=e.condition?Wb(e.condition):{type:"literal",value:!0},n=(e.thenBranch??[]).map(e=>Wb(e)),r=e.elseBranch?e.elseBranch.map(e=>Wb(e)):void 0;return{type:"if",condition:t,thenBranch:n,...r?{elseBranch:r}:{},...Mb(e)}}(e);case"literal":case"string":case"timeExpression":return{type:"literal",value:e.value,...Mb(e)};case"selector":case"htmlSelector":return{type:"selector",value:e.value??e.selector??"",...Mb(e)};case"contextReference":return{type:"identifier",value:e.name??e.contextType??"",...Mb(e)};case"identifier":return{type:"identifier",value:e.name??e.value??"",name:e.name??"",...Mb(e)};case"propertyAccess":return function(e){const t=e.object?Wb(e.object):{type:"identifier",value:"me"};return{type:"possessive",object:t,property:e.property??"",...Mb(e)}}(e);case"possessiveExpression":return function(e){const t=e.object?Wb(e.object):{type:"identifier",value:"me"},n="string"==typeof e.property?e.property:e.property?.name??e.property?.value??"";return{type:"possessive",object:t,property:n,...Mb(e)}}(e);case"memberExpression":return function(e){const t=e.object?Wb(e.object):{type:"identifier",value:"me"},n="string"==typeof e.property?e.property:e.property?Wb(e.property):{type:"literal",value:""};return{type:"member",object:t,property:n,computed:e.computed??!1,...Mb(e)}}(e);case"binaryExpression":return function(e){return{type:"binary",operator:e.operator??"",left:Wb(e.left),right:Wb(e.right),...Mb(e)}}(e);case"callExpression":return function(e){const t="string"==typeof e.callee?{type:"identifier",value:e.callee,name:e.callee}:Wb(e.callee),n=(e.arguments??e.args??[]).map(e=>Wb(e));return{type:"call",callee:t,args:n,...Mb(e)}}(e);case"unaryExpression":return{type:"unary",operator:e.operator,operand:Wb(e.operand),...Mb(e)};case"templateLiteral":return{type:"literal",value:e.raw??"",...Mb(e)};case"variable":return{type:"variable",name:e.name??"",scope:e.scope??"local",...Mb(e)};case"positional":return{type:"positional",position:e.position,...e.target?{target:Wb(e.target)}:{},...Mb(e)};case"positionalExpression":return{type:"positional",position:e.operator,...e.argument?{target:Wb(e.argument)}:{},...Mb(e)};default:return{type:"literal",value:e.value??null,...Mb(e)}}}function $b(e){return e?"block"===e.type?(e.commands??[]).map(e=>Wb(e)):[Wb(e)]:[]}Zy(),Pl(),sv();var Hb=Object.freeze({__proto__:null,ASTBuilder:Lb,DEFAULT_CONFIDENCE_THRESHOLD:rg,HIGH_CONFIDENCE_THRESHOLD:.8,LAZY_LOAD_LANGUAGES:Ib,get PatternMatcher(){return nv},get SchemaErrorCodes(){return nu},SemanticAnalyzerImpl:tg,SemanticCache:Xv,get SemanticParserImpl(){return yv},get SemanticRendererImpl(){return av},get TokenStreamImpl(){return Ll},VERSION:"0.1.0",get addSchema(){return vu},analyze:kg,analyzeAll:function(e,t="en",n={}){const r=[],i=[];for(const a of e){const e=kg(a,t,n);r.push(...e.warnings),e.node&&i.push(e.node)}r.push(...bg(i,n));const a=r.some(e=>"error"===e.severity),o={...mg,...n},s=r.some(e=>"warning"===e.severity);return{valid:o.strict?!a&&!s:!a,warnings:r,node:i[0]??null}},analyzeMultiple:bg,get appendSchema(){return ju},get arabicProfile(){return oc},get arabicTokenizer(){return vc},buildAST:function(e){const t=new Lb;return{ast:t.build(e),warnings:t.warnings}},calculateTranslationConfidence:Ob,canLoadLanguage:function(e){return e in Pb},canParse:wv,checkAccessibility:fg,checkPerformance:yg,checkSchema:vg,get chineseProfile(){return Ey},get chineseTokenizer(){return Ny},get commandSchemas(){return Pu},convertExpression:Ng,convertLiteral:jg,convertPropertyPath:Ig,convertReference:Pg,convertSelector:Lg,convertValue:Ag,createCommandNode:Vy,createCompoundNode:Fy,createConditionalNode:function(e,t,n,r){const i=new Map;i.set("condition",e);const a={kind:"conditional",action:"if",roles:i,thenBranch:t};return void 0!==n&&(a.elseBranch=n),void 0!==r&&(a.metadata=r),a},createEventHandler:By,createLiteral:Hy,createLoopNode:function(e,t,n,r,i){const a={kind:"loop",action:e,loopVariant:t,roles:new Map(Object.entries(n)),body:r};return i?.loopVariable&&(a.loopVariable=i.loopVariable),i?.indexVariable&&(a.indexVariable=i.indexVariable),i?.metadata&&(a.metadata=i.metadata),a},createPropertyPath:_y,createReference:Dy,createSelector:$y,createSemanticAnalyzer:ng,createSemanticCache:function(e){return new Xv(e)},get decrementSchema(){return Au},devModeAnalyze:function(e,t,n){if(!wg)return;if(!n)return void console.warn(`[hyperfixi] Parse failed: ${e}`);const r=kg(e,t,zg);for(const e of r.warnings){const t="error"===e.severity?"❌":"warning"===e.severity?"⚠️":"ℹ️",n="error"===e.severity?"error":"warning"===e.severity?"warn":"info";console[n](`${t} [hyperfixi:${e.code}] ${e.message}`,e.suggestion?`\n 💡 ${e.suggestion}`:"",e.location?.input?`\n 📍 ${e.location.input}`:"")}},disableDevMode:function(){wg=!1},enableDevMode:function(e={}){wg=!0,zg=e},get englishProfile(){return Gc},get englishTokenizer(){return Xc},get eventNameTranslations(){return Uy},get fetchSchema(){return Tu},formatValidationResults:hu,get frenchProfile(){return Op},fromExplicit:Jv,fromSemanticAST:Wb,generateAllPatterns:function(e,t=Du){const n=[],r=e??Vu();for(const e of r){const r=Ku(e,t);n.push(...r)}return n},generatePattern:Bu,generatePatternVariants:Uu,generatePatternsForCommand:function(e,t,n=Du){const r=[],i=t??Vu();for(const t of i){if(!t.keywords[e.action])continue;const i=Uu(e,t,n);r.push(...i)}return r},generatePatternsForLanguage:Ku,generateSimplePattern:Fu,get germanProfile(){return Lc},getAllPatterns:function(){return null===Uv&&(Uv=Bv()),Uv},getAllTranslations:function(e,t,n=["en","ja","ar","es","ko","zh","tr","pt","fr","de","id","qu","sw"]){const r={},i=Yv(e,t);for(const e of n)r[e]=lv(i,e);return r.explicit=cv(i),r},getCommandMapper:jb,getCommandType:zv,getDefinedSchemas:Nu,getDevModeConfig:function(){return{...zg}},getEventHandlerPatternsForLanguage:$v,getGeneratorLanguages:function(){return Object.keys(ig)},getGeneratorSummary:function(){const e=Tl(),t=Nu().map(e=>e.action);let n=0;for(const t of e){const e=Sl(t);if(e)for(const t of Nu())e.keywords[t.action]&&(n+=2)}return{languages:e,commands:t,totalPatterns:n}},getLoadedLanguages:function(){return Ib.filter(Cl)},getPatternById:function(e){return Gv.find(t=>t.id===e)},getPatternStats:function(){const e={},t={};for(const n of Gv)e[n.language]=(e[n.language]||0)+1,t[n.command]=(t[n.command]||0)+1;return{totalPatterns:Gv.length,byLanguage:e,byCommand:t}},getPatternsForLanguage:Qv,getPatternsForLanguageAndCommand:function(e,t){return Qv(e).filter(e=>e.command===t).sort((e,t)=>t.priority-e.priority)},getProfile:function(e){return ig[e]},getPutPatternsForLanguage:Wv,getRegisteredLanguages:Tl,getRegisteredMappers:function(){return new Map(Ab)},getSchema:function(e){return Pu[e]},getSchemasByCategory:function(e){return Object.values(Pu).filter(t=>t.category===e)},getSupportedCommands:function(){const e=new Set(Gv.map(e=>e.command));return Array.from(e)},getSupportedLanguages:function(){return["en","ja","ar","es","ko","zh","tr","pt","fr","de","id","qu","sw"]},getSupportedPatternLanguages:function(){const e=new Set(Gv.map(e=>e.language));return Array.from(e)},getSupportedTokenizerLanguages:Yy,getTogglePatternsForLanguage:Mv,getTokenizer:Qy,getUnloadedLanguages:function(){return Ib.filter(e=>!Cl(e))},getValidationStats:fu,getValidatorSchema:og,get hideSchema(){return zu},get incrementSchema(){return Cu},get indonesianProfile(){return wm},isDevModeEnabled:function(){return wg},isExplicitSyntax:hv,isGeneratorLanguageSupported:function(e){return e in ig},isLanguageSupported:function(e){return Cl(e)},isUnifiedProfile:function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.code&&"string"==typeof t.name&&"string"==typeof t.wordOrder&&"string"==typeof t.markingStrategy&&"string"==typeof t.morphology&&"object"==typeof t.keywords&&Array.isArray(t.canonicalOrder)},get japaneseProfile(){return ad},get japaneseTokenizer(){return bd},get koreanProfile(){return Cd},get koreanTokenizer(){return Dd},languageProfiles:ig,loadLanguage:Nb,loadLanguages:async function(e,t={}){return Promise.all(e.map(e=>Nb(e,t)))},markingStrategyToAdpositionType:ug,matchBest:function(e,t){return rv.matchBest(e,t)},matchPattern:function(e,t){return rv.matchPattern(e,t)},normalizeEventName:function(e,t){const n=Uy[t];return n&&n[e]?n[e]:e.toLowerCase()},get onSchema(){return xu},parse:kv,parseAny:Yv,parseExplicit:pv,parseSemantic:function(e,t){return Rb(e,t)},parseWithConfidence:Rb,get patternMatcher(){return rv},get portugueseProfile(){return mh},get prependSchema(){return Lu},get putSchema(){return bu},get quechuaProfile(){return Ih},registerCommandMapper:function(e){Ab.set(e.action,e)},registerSchema:function(e,t){ag.set(e,t)},registerTokenizer:function(e){!function(e){ol.set(e.language,e)}(e)},get removeSchema(){return gu},render:lv,renderExplicit:cv,rolesToCommandArgs:function(e,t){const n=[],r={};for(const[i,a]of e)switch(i){case"patient":case"event":n.push(a);break;case"destination":"put"===t?r.into=a:r.on=a;break;case"source":r.from=a;break;case"quantity":r.by=a;break;case"duration":r.over=a;break;case"method":r.as=a;break;case"style":r.with=a;break;case"condition":r.if=a;break;case"agent":r.agent=a;break;default:r[i]=a}return{args:n,modifiers:r}},roundTrip:function(e,t,n){const r=Yv(e,t),i=n??t,a=hv(e)?cv(r):lv(r,i);if(void 0!==n)return a;const o=e.trim().toLowerCase(),s=a.trim().toLowerCase();return{original:e,semantic:r,rendered:a,matches:o===s}},schemaRegistry:ag,semanticCache:eg,get semanticParser(){return vv},get semanticRenderer(){return ov},get setSchema(){return ku},shouldUseSemanticResult:function(e,t=.5){return e.confidence>=t&&void 0!==e.command},get showSchema(){return wu},get spanishProfile(){return zp},get spanishTokenizer(){return Pp},get swahiliProfile(){return af},toExplicit:function(e,t){return hv(e)?e:cv(kv(e,t))},toGrammaticalMarker:pg,toI18nProfile:function(e){const t=[];for(const[n,r]of Object.entries(e.roleMarkers))r&&t.push(pg(n,r,e.markingStrategy));return{code:e.code,name:e.nativeName,wordOrder:e.wordOrder,adpositionType:ug(e.markingStrategy),morphology:e.morphology,direction:e.direction,markers:t,canonicalOrder:e.canonicalOrder}},get toggleSchema(){return yu},tokenize:Jy,translate:function(e,t,n){return hv(e)?Jv(e,n):lv(kv(e,t),n)},get triggerSchema(){return Eu},tryGetProfile:Sl,get turkishProfile(){return Df},get turkishTokenizer(){return Jf},validateAllSchemas:du,validateAndAdjustConfidence:function(e){const t=cg(e);return{...e,confidence:Math.max(0,Math.min(1,e.confidence+t.confidenceAdjustment)),validation:t}},validateCommandSchema:mu,validateLanguageKeywords:function(e,t=Nu()){const n=[],r=[];for(const i of t)e.keywords[i.action]?r.push(i.action):n.push(i.action);return{missing:n,available:r}},validateSemanticResult:cg,validateTranslation:function(e,t,n,r){try{const i=Yv(e,n),a=Yv(t,r);if(i.action!==a.action)return!1;for(const[e,t]of i.roles){const n=a.roles.get(e);if(!n)return!1;if(!Zv(t,n))return!1}return!0}catch{return!1}},get waitSchema(){return Su},withCache:function(e,t=eg){return(n,r)=>{const i=t.get(n,r);if(i)return i;const a=e(n,r);return t.set(n,r,a),a}}});function qb(e){const{target:t,strategy:n="morph",useViewTransition:r=!1,fetchOptions:i={},transformUrl:a,onBeforeFetch:o,onAfterSwap:s,onError:l}=e,c=async e=>{const c=(()=>{if("string"==typeof t){const e=document.querySelector(t);return Ci(e)?e:null}return Ci(t)?t:null})();if(!c)return void console.warn(`HistorySwap: target "${t}" not found`);let u=window.location.href;a&&(u=a(u));try{o&&await o(u),c.classList.add("hx-swapping");const e=await fetch(u,{method:"GET",headers:{Accept:"text/html","HX-Request":"true","HX-History-Restore-Request":"true"},...i});if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);const a=await e.text(),l=()=>{$o(c,a,n)};r&&oo()?await po(l):l(),c.classList.remove("hx-swapping"),s&&await s(u,a),Qo(window,"historyswap",{url:u,strategy:n,target:t})}catch(e){c.classList.remove("hx-swapping"),l?l(e,u):console.error("HistorySwap fetch failed:",e)}};return window.addEventListener("popstate",c),{destroy:()=>{window.removeEventListener("popstate",c)},config:e}}const Db={name:"HistorySwap",init:(e,t={})=>qb({target:t.target||e,strategy:t.strategy||"morph",useViewTransition:Boolean(t.useViewTransition)}),destroy(e){e.destroy()}};function _b(e){return!function(e){try{return new URL(e,window.location.origin).origin!==window.location.origin}catch{return!1}}(e.href)&&((!e.target||"_self"===e.target)&&(!e.hasAttribute("download")&&(!e.hasAttribute("data-no-boost")&&!e.hasAttribute("hx-boost-off")&&("javascript:"!==e.protocol&&"mailto:"!==e.protocol))))}function Vb(e){const{container:t,target:n,linkSelector:r="a[href]",formSelector:i="form",boostForms:a=!1,strategy:o="morph",pushUrl:s=!0,useViewTransition:l=!1,fetchOptions:c={},onBeforeFetch:u,onAfterSwap:p,onError:m}=e,d=async(e,r="GET",i=null)=>{const a=(()=>{if(!n)return document.body;if("string"==typeof n){const e=document.querySelector(n);return Ci(e)?e:null}return Ci(n)?n:null})();if(a)try{if(u){if(!1===await u(e,r))return}a.classList.add("hx-swapping"),t.classList.add("hx-boosting");const m={method:r,headers:{Accept:"text/html","HX-Request":"true","HX-Boosted":"true"},...c};i&&"GET"!==r&&(m.body=i);const d=await fetch(e,m);if(!d.ok)throw new Error(`HTTP ${d.status}: ${d.statusText}`);const h=await d.text(),f=()=>{$o(a,h,o)};l&&oo()?await po(f):f(),a.classList.remove("hx-swapping"),t.classList.remove("hx-boosting"),s&&"GET"===r&&window.history.pushState(null,"",e),p&&await p(e,h),Qo(window,"boosted",{url:e,method:r,strategy:o,target:n})}catch(n){a.classList.remove("hx-swapping"),t.classList.remove("hx-boosting"),m?m(n,e):(console.error("Boosted fetch failed:",n),window.location.href=e)}else console.warn(`Boosted: target "${n}" not found`)},h=async e=>{const t=e.target.closest(r);t&&function(e){return!(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)&&0===e.button}(e)&&_b(t)&&(e.preventDefault(),e.stopPropagation(),await d(t.href))},f=async e=>{if(!a)return;const t=e.target.closest(i);if(!t)return;if(t.hasAttribute("data-no-boost")||t.hasAttribute("hx-boost-off"))return;if(t.target&&"_self"!==t.target)return;e.preventDefault(),e.stopPropagation();const n=(t.method||"GET").toUpperCase(),r=new FormData(t);let o,s=null;if("GET"===n){const e=new URLSearchParams;r.forEach((t,n)=>{e.append(n,String(t))}),o=`${t.action||window.location.pathname}?${e.toString()}`}else o=t.action||window.location.pathname,s=r;await d(o,n,s)};return t.addEventListener("click",h),a&&t.addEventListener("submit",f),{destroy:()=>{t.removeEventListener("click",h),t.removeEventListener("submit",f)},config:e,boost:d}}const Bb={name:"Boosted",init:(e,t={})=>Vb({container:e,target:t.target,linkSelector:t.linkSelector||"a[href]",formSelector:t.formSelector||"form",boostForms:Boolean(t.boostForms),strategy:t.strategy||"morph",pushUrl:!1!==t.pushUrl,useViewTransition:Boolean(t.useViewTransition)}),destroy(e){e.destroy()}};const Fb="click";let Ub,Kb,Gb;function Qb(e,t,n){console.error("Failed to compile hyperscript on element:",e),console.error(`Code: "${t}"`),n.errors?.length&&n.errors.forEach((e,t)=>{console.error(`Error ${t+1}: ${e.message} (line ${e.line}, col ${e.column})`)}),xe("Compilation failed - error details:",{code:t,errors:n.errors,codeLines:t.split("\n"),element:e.tagName})}async function Jb(e,t){try{return await Gb().execute(e,t)}catch(e){throw console.error("Error executing hyperscript AST:",e),e}}function Yb(e,t,n){try{const r=function(e){try{if(function(e){return"eventHandler"===e.type}(e)){const t=e.event||Fb,n=e.commands,r={type:"CommandSequence",commands:n||[],start:e.start||0,end:e.end||0,line:e.line||1,column:e.column||1};return ze("Extracted event info:",{type:e.type,eventType:t,commandCount:n?.length||0}),{eventType:t,body:r}}if(function(e){return"FeatureNode"===e.type}(e)&&"on"===e.name){const t=e.args?.[0]?.value||Fb,n=e.body||e;return ze("Extracted event info:",{type:e.type,eventType:t}),{eventType:t,body:n}}return"CommandSequence"===e.type||"Block"===e.type?(ze("Extracted event info:",{type:e.type,eventType:Fb}),{eventType:Fb,body:e}):(console.warn("⚠️ Unknown AST structure for event extraction:",e.type),null)}catch(e){return console.error("❌ Error extracting event info:",e),null}}(t);if(!r)return void console.error("❌ Could not extract event information from AST:",t);ze("Setting up event handler:",{element:e.tagName,eventType:r.eventType});const i=async e=>{try{n.locals.set("event",e),n.locals.set("target",e.target),await Jb(r.body,n)}catch(e){console.error("❌ Error executing hyperscript event handler:",e),console.error("❌ Error stack:",e instanceof Error?e.stack:"No stack trace"),console.error("❌ Event info body:",r.body),console.error("❌ Context:",n)}};e.addEventListener(r.eventType,i),ze("Event handler attached:",r.eventType)}catch(e){console.error("Error setting up event handler:",e)}}function Zb(e){return Dt(e)}function Xb(e,t){const n=function(e){const t=e.getAttribute("data-lang");if(t)return t;const n=e.closest("[lang]")?.getAttribute("lang");if(n)return n.split("-")[0];if("undefined"!=typeof document){const e=document.documentElement?.lang;if(e)return e.split("-")[0]}return"en"}(e);"en"===n?function(e,t){try{Se("Processing hyperscript:",t);const n=Ub(t);if(!n.ok)return void Qb(e,t,n);if(!n.ast)return void console.warn("⚠️ No AST generated for hyperscript:",t);Se("Successfully compiled hyperscript:",t),Se("Generated AST:",n.ast);const r=Zb(e);if(t.trim().startsWith("on ")){ze("Setting up event handler for:",t),ze("Element for event handler:",e),ze("AST for event handler:",n.ast);try{ze("About to call setupEventHandler..."),Yb(e,n.ast,r),ze("setupEventHandler completed successfully")}catch(e){throw console.error("❌ Error in setupEventHandler:",e),console.error("❌ setupError stack:",e instanceof Error?e.stack:"No stack trace"),e}}else Se("Executing immediate hyperscript:",t),Jb(n.ast,r)}catch(t){console.error("❌ Error processing hyperscript attribute:",t,"on element:",e)}}(e,t):async function(e,t,n){try{Se("Processing multilingual hyperscript:",{code:t,lang:n});const r=await Kb(t,{language:n});if(!r.ok)return void Qb(e,t,r);if(!r.ast)return void console.warn("⚠️ No AST generated for hyperscript:",t);Se("Successfully compiled multilingual hyperscript:",{code:t,lang:n,directPath:r.meta.directPath,confidence:r.meta.confidence});const i=Zb(e);t.trim().startsWith("on ")||"eventHandler"===r.ast.type?(ze("Setting up multilingual event handler:",{code:t,lang:n}),Yb(e,r.ast,i)):(Se("Executing immediate multilingual hyperscript:",t),Jb(r.ast,i))}catch(t){console.error("❌ Error processing multilingual hyperscript:",t,"on element:",e)}}(e,t,n)}const ek="en";const tk=new class{constructor(e=500){this.cache=new Map,this.hits=0,this.misses=0,this.maxSize=e}makeKey(e,t){return`${t?.language||ek}\0${t?.traditional?"1":"0"}\0${e}`}get(e,t){const n=this.makeKey(e,t),r=this.cache.get(n);if(r)return this.hits++,this.cache.delete(n),this.cache.set(n,r),r.result;this.misses++}set(e,t,n){if(!n.ok)return;const r=this.makeKey(e,t);if(this.cache.size>=this.maxSize&&!this.cache.has(r)){const e=this.cache.keys().next().value;void 0!==e&&this.cache.delete(e)}this.cache.set(r,{result:n})}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){const e=this.hits+this.misses;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0}}}(500);let nk=null,rk=null;const ik={semantic:!0,language:"en",confidenceThreshold:rg};async function ak(){if(!rk){const{SemanticGrammarBridge:e}=await Promise.resolve().then(function(){return iw});rk=new e,await rk.initialize()}return rk}let ok=null;function sk(){if(!ok&&(ok=new al({lazyLoad:!1}),(e=ok.behaviorRegistry)instanceof Map||e&&"function"==typeof e.set?e.set("HistorySwap",Db):e&&"object"==typeof e&&(e.HistorySwap=Db),function(e){e instanceof Map||e&&"function"==typeof e.set?e.set("Boosted",Bb):e&&"object"==typeof e&&(e.Boosted=Bb)}(ok.behaviorRegistry),"undefined"!=typeof globalThis)){const e=globalThis;e._hyperscript=e._hyperscript||{},e._hyperscript.runtime=ok,e._hyperscript.behaviors=ok.behaviorAPI}var e;return ok}async function lk(e,t){if(!e)throw new Error("AST is required for execution");const n=t||Dt();return await sk().execute(e,n)}function ck(e,t){if("string"!=typeof e)throw new TypeError("Code must be a string");const n=tk.get(e,t);if(n)return n;const r=performance.now(),i=t?.language||ek;try{const n=t?.traditional??!1,o=n?{}:ik.semantic?{semanticAnalyzer:(nk||(nk=ng()),nk),language:ik.language,semanticConfidenceThreshold:ik.confidenceThreshold}:{},s=!n,l=Nt(e,o),c=performance.now()-r;if(l.success&&l.node){const n={ok:!0,ast:l.node,meta:{parser:s?"semantic":"traditional",language:i,timeMs:c}};return tk.set(e,t,n),n}return{ok:!1,errors:l.error?[(a=l.error,{message:a.message,line:a.line??1,column:a.column??1})]:[],meta:{parser:s?"semantic":"traditional",language:i,timeMs:c}}}catch(a){const e=performance.now()-r;return{ok:!1,errors:[{message:a instanceof Error?a.message:"Unknown compilation error",line:1,column:1}],meta:{parser:"traditional",language:i,timeMs:e}}}var a}async function uk(e,t){if("string"!=typeof e)throw new TypeError("Code must be a string");const n=t?.language||ek;if(n===ek||t?.traditional)return ck(e,t);const r=tk.get(e,t);if(r)return r;const i=performance.now();try{const r=await ak(),a=await r.parseToASTWithDetails(e,n);if(a.usedDirectPath&&a.ast){const r=performance.now()-i,o={ok:!0,ast:a.ast,meta:{parser:"semantic",confidence:a.confidence,language:n,timeMs:r,directPath:!0}};return tk.set(e,t,o),o}const o=ck(a.fallbackText||e,{...t,language:ek}),s={...o,meta:{...o.meta,language:n,confidence:a.confidence,directPath:!1}};return tk.set(e,t,s),s}catch{return ck(e,{...t,language:"en"})}}!function(e,t,n){Ub=e,Kb=t,Gb=n}(ck,uk,sk);const pk={compile:uk,compileSync:ck,execute:lk,eval:async function(e,t,n){if("string"!=typeof e||0===e.trim().length)throw new Error("Code must be a non-empty string");let r;if(t)if(t instanceof Element)r=Dt(t);else if("object"==typeof(i=t)&&null!==i&&"locals"in i&&i.locals instanceof Map)r=t;else{const e=t;r=function(e){return"object"==typeof e&&null!==e&&"me"in e}(e)?Dt(e.me):Dt()}else r=Dt();var i;const a=await uk(e.trim(),n);if(!a.ok){const e=a.errors?.[0]?.message||"Unknown compilation error";throw new Error(`Compilation failed: ${e}`)}return lk(a.ast,r)},validate:async function(e,t){const n=await uk(e,t);return{valid:n.ok,errors:n.errors}},process:function(e){try{const t=e.getAttribute("_");t&&Xb(e,t);e.querySelectorAll("[_]").forEach(e=>{const t=e.getAttribute("_");t&&Xb(e,t)})}catch(e){console.error("Error processing hyperscript node:",e)}},createContext:function(e,t){return t?_t(t,e):Dt(e)},config:ik,version:"2.0.0",createRuntime:function(e){return new al(e)},registerHooks:(e,t)=>{sk().registerHooks(e,t)},unregisterHooks:e=>sk().unregisterHooks(e),getRegisteredHooks:()=>sk().getRegisteredHooks(),clearCache:()=>tk.clear(),getCacheStats:()=>tk.getStats()},mk=pk,dk={"+":"PLUS","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",".":"PERIOD","..":"ELLIPSIS","\\":"BACKSLASH",":":"COLON","%":"PERCENT","|":"PIPE","!":"EXCLAMATION","?":"QUESTION","#":"POUND","&":"AMPERSAND",$:"DOLLAR",";":"SEMI",",":"COMMA","(":"L_PAREN",")":"R_PAREN","<":"L_ANG",">":"R_ANG","<=":"LTE_ANG",">=":"GTE_ANG","==":"EQ","===":"EQQ","!=":"NEQ","!==":"NEQQ","{":"L_BRACE","}":"R_BRACE","[":"L_BRACKET","]":"R_BRACKET","=":"EQUALS","~":"TILDE","'":"APOSTROPHE"};class hk{static isAlpha(e){return void 0!==e&&/[a-zA-Z]/.test(e)}static isNumeric(e){return void 0!==e&&/[0-9]/.test(e)}static isWhitespace(e){return void 0!==e&&/\s/.test(e)}static isNewline(e){return"\r"===e||"\n"===e}static isIdentifierChar(e){return"_"===e||"$"===e}static isReservedChar(e){return"`"===e||"^"===e}static isValidCSSClassChar(e){return void 0!==e&&/[a-zA-Z0-9_-]/.test(e)}static isValidCSSIDChar(e){return void 0!==e&&/[a-zA-Z0-9_-]/.test(e)}static isValidSingleQuoteStringStart(e){if(e.length>0){const t=e[e.length-1];if("IDENTIFIER"===t.type||"CLASS_REF"===t.type||"ID_REF"===t.type)return!1;if(t.op&&(">"===t.value||")"===t.value))return!1}return!0}static tokenize(e,t=!1){const n=[];let r=0,i=1,a=1,o=0;const s=()=>e[r],l=(t=1)=>e[r+t],c=()=>{const e=s();return r++,hk.isNewline(e)?(i++,a=1):a++,e},u=(e,n,o)=>({type:e,value:n,start:o,end:r,column:a-n.length,line:i,op:void 0!==dk[n],template:t});for(;r<e.length;){const i=r,a=s();if("/"===a&&"/"===l()){for(;r<e.length&&!hk.isNewline(s());)c();continue}if("/"===a&&"*"===l()){for(c(),c();r<e.length-1;){if("*"===s()&&"/"===l()){c(),c();break}c()}continue}if("-"===a&&"-"===l()){for(;r<e.length&&!hk.isNewline(s());)c();continue}if(hk.isWhitespace(a)){let t="";for(;r<e.length&&hk.isWhitespace(s());)t+=c();n.push(u("WHITESPACE",t,i));continue}if(hk.isNumeric(a)){let t="";for(;r<e.length&&(hk.isNumeric(s())||"."===s());)t+=c();if("e"===s()||"E"===s())for(t+=c(),"+"!==s()&&"-"!==s()||(t+=c());r<e.length&&hk.isNumeric(s());)t+=c();n.push(u("NUMBER",t,i));continue}if('"'===a||"`"===a||"'"===a&&hk.isValidSingleQuoteStringStart(n)){const p=a;let m=c();if("`"===p&&t)for(;r<e.length;){const t=s();if("`"===t){m+=c();break}"$"===t&&"{"===l()?(m+=c(),m+=c(),o++):"}"===t&&o>0?(m+=c(),o--):"\\"===t?(m+=c(),r<e.length&&(m+=c())):m+=c()}else for(;r<e.length;){const t=s();if(t===p){m+=c();break}"\\"===t?(m+=c(),r<e.length&&(m+=c())):m+=c()}n.push(u("STRING",m,i));continue}if("["===a&&"@"===l()){let t=c();for(t+=c();r<e.length&&"]"!==s();)t+=c();"]"===s()&&(t+=c()),n.push(u("ATTRIBUTE_REF",t,i));continue}if("@"===a){let t=c();for(;r<e.length&&(hk.isAlpha(s())||hk.isNumeric(s())||"-"===s());)t+=c();n.push(u("ATTRIBUTE_REF",t,i));continue}if("."===a&&hk.isAlpha(l())){let t=c();for(;r<e.length&&hk.isValidCSSClassChar(s());)t+=c();n.push({...u("CLASS_REF",t,i),template:!0});continue}if("#"===a&&hk.isAlpha(l())){let t=c();for(;r<e.length&&hk.isValidCSSIDChar(s());)t+=c();n.push({...u("ID_REF",t,i),template:!0});continue}if("*"===a&&hk.isAlpha(l())){let t=c();for(;r<e.length&&(hk.isAlpha(s())||hk.isNumeric(s())||"-"===s());)t+=c();n.push(u("STYLE_REF",t,i));continue}if(hk.isReservedChar(a)){n.push(u("RESERVED",c(),i));continue}const p=a+l(),m=p+e[r+2];if(dk[m])c(),c(),n.push(u(dk[m],m,i));else if(dk[p])c(),n.push(u(dk[p],p,i));else if(dk[a])n.push(u(dk[a],c(),i));else{if(hk.isAlpha(a)||hk.isIdentifierChar(a)){let t="";for(;r<e.length&&(hk.isAlpha(s())||hk.isNumeric(s())||hk.isIdentifierChar(s()));)t+=c();n.push(u("IDENTIFIER",t,i));continue}n.push(u("UNKNOWN",c(),i))}}return n.push({type:"EOF",value:"<<<EOF>>>",start:r,end:r,column:a,line:i}),new fk(n,0,e)}}class fk{constructor(e,t,n){this.tokens=e,this.consumed=t,this.source=n}hasMore(){return this.consumed<this.tokens.length}token(e=0,t=!1){let n=this.consumed,r=0;for(;n<this.tokens.length&&r<=e;){if(t||"WHITESPACE"!==this.tokens[n].type){if(r===e)break;r++}n++}return n>=this.tokens.length?{type:"EOF",value:"<<<EOF>>>",start:this.source.length,end:this.source.length,column:0,line:0}:this.tokens[n]}currentToken(){return this.token(0)}consumeToken(){const e=this.currentToken();for(;this.consumed<this.tokens.length&&"WHITESPACE"===this.tokens[this.consumed].type;)this.consumed++;return this.consumed<this.tokens.length&&(this.lastConsumed=this.tokens[this.consumed],this.consumed++),e}consumeWhitespace(){for(;this.consumed<this.tokens.length&&"WHITESPACE"===this.tokens[this.consumed].type;)this.consumed++}lastMatch(){return this.lastConsumed}matchToken(e,t){const n=this.currentToken();return n.value!==e||t&&n.type!==t?null:this.consumeToken()}matchTokenType(...e){const t=this.currentToken();return e.includes(t.type)?this.consumeToken():null}matchOpToken(e){const t=this.currentToken();return t.op&&t.value===e?this.consumeToken():null}requireToken(e,t){const n=this.matchToken(e,t);return n||this.raiseError(`Expected '${e}'${t?` (${t})`:""} but found '${this.currentToken().value}'`),n}requireTokenType(e){const t=this.matchTokenType(e);return t||this.raiseError(`Expected ${e} but found '${this.currentToken().value}'`),t}requireOpToken(e){const t=this.matchOpToken(e);return t||this.raiseError(`Expected operator '${e}' but found '${this.currentToken().value}'`),t}consumeUntil(e,t){const n=[];for(;this.hasMore();){const r=this.currentToken();if("EOF"===r.type)break;if(e&&r.value===e)break;if(t&&r.type===t)break;n.push(this.consumeToken())}return n}consumeUntilWhitespace(){const e=[];for(;this.hasMore();){const t=this.currentToken();if("WHITESPACE"===t.type||"EOF"===t.type)break;e.push(this.consumeToken())}return e}lastWhitespace(){return this.consumed>0&&"WHITESPACE"===this.tokens[this.consumed-1].type?this.tokens[this.consumed-1].value:""}raiseError(e){const t=this.currentToken();throw new Error(`Parse error at line ${t.line}, column ${t.column}: ${e}`)}static sourceFor(e){return 0===e.length?"":e.map(e=>e.value).join("")}static lineFor(e){return`Line ${e.line}`}static positionString(e){return`line ${e.line}, column ${e.column}`}}const yk=Cn.object({property:Cn.string().describe("Property name to access")}).strict(),vk=Cn.object({target:Cn.unknown().describe("Target object to access property from"),property:Cn.string().describe("Property name to access")}).strict(),gk=Cn.object({element:Cn.unknown().describe("DOM element to access attribute from"),attribute:Cn.string().describe("Attribute name to access")}).strict();function bk(e,t){if(null==e)return;if(!t.includes("."))return Zt(e)?nn(e,t):e[t];const n=t.split(".");let r=e;for(const e of n){if(null==r)return;r=Zt(r)?nn(r,e):r[e]}return r}class kk extends jn{constructor(){super(...arguments),this.name="my",this.category="Property",this.syntax="my property",this.description="Accesses properties of the current context element (me) with validation",this.inputSchema=yk,this.outputType="Any",this.metadata={category:"Property",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};if(!e.me)return{success:!1,error:{type:"context-error",message:"No current element (me) available in context for property access",suggestions:["Ensure this expression is used within an element context","Check that the element reference is properly set"]}};const i=bk(e.me,t.property);this.trackSimple(e,n,!0,i);return{success:!0,value:i,type:void 0===i?"unknown":this.inferType(i)}}catch(t){return this.trackSimple(e,n,!1),{success:!1,error:{type:"runtime-error",message:`Property access failed: ${t instanceof Error?t.message:String(t)}`,suggestions:["Check that the property name is valid","Ensure the current element supports the requested property"]}}}}validate(e){try{const t=this.inputSchema.safeParse(e);if(!t.success)return this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid property access input",["Provide a valid property name as a string","Ensure the property name is not empty"]);const{property:n}=t.data;return""===n.trim()?this.validationFailure("validation-error","Property name cannot be empty",["Provide a non-empty property name"]):this.validationSuccess()}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class wk extends jn{constructor(){super(...arguments),this.name="its",this.category="Property",this.syntax="target its property",this.description="Generic possessive property access with comprehensive validation",this.inputSchema=vk,this.outputType="Any",this.metadata={category:"Property",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=bk(t.target,t.property);this.trackSimple(e,n,!0,i);return{success:!0,value:i,type:void 0===i?"unknown":this.inferType(i)}}catch(t){return this.trackSimple(e,n,!1),{success:!1,error:{type:"runtime-error",message:`Property access failed: ${t instanceof Error?t.message:String(t)}`,suggestions:["Check that the target object is not null or undefined","Ensure the property name is valid"]}}}}validate(e){try{const t=this.inputSchema.safeParse(e);if(!t.success)return this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid possessive access input",["Provide both target and property parameters","Ensure property name is a string"]);const{property:n}=t.data;return""===n.trim()?this.validationFailure("validation-error","Property name cannot be empty",["Provide a non-empty property name"]):this.validationSuccess()}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class zk extends jn{constructor(){super(...arguments),this.name="attribute",this.category="Property",this.syntax="@attribute or element@attribute",this.description="Accesses HTML attributes with comprehensive DOM validation",this.inputSchema=gk,this.outputType="String",this.metadata={category:"Property",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};if(!this.isElement(t.element))return{success:!1,error:{type:"type-mismatch",message:"Target must be a DOM element for attribute access",suggestions:["Ensure the target is a valid DOM element","Check that the element reference is correct"]}};const i=t.element.getAttribute(t.attribute);return this.trackSimple(e,n,!0,i),{success:!0,value:i,type:null===i?"null":"string"}}catch(t){return this.trackSimple(e,n,!1),{success:!1,error:{type:"runtime-error",message:`Attribute access failed: ${t instanceof Error?t.message:String(t)}`,suggestions:["Check that the element supports getAttribute","Ensure the attribute name is valid"]}}}}validate(e){try{const t=this.inputSchema.safeParse(e);if(!t.success)return this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid attribute access input",["Provide both element and attribute parameters","Ensure attribute name is a string"]);const{attribute:n}=t.data;return""===n.trim()?this.validationFailure("validation-error","Attribute name cannot be empty",["Provide a non-empty attribute name"]):this.validationSuccess()}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}new kk,new wk,new zk;function xk(e,t,n=1e3){e.push(t),e.length>n&&e.shift()}const Ek=Cn.object({definition:An.object({name:Cn.string().min(1),namespace:Cn.string().optional(),parameters:Cn.array(Cn.string()).default([]),body:Cn.array(Cn.any()),catchBlock:An.object({parameter:Cn.string(),body:Cn.array(Cn.any())}).optional(),finallyBlock:Cn.array(Cn.any()).optional(),isAsync:Cn.boolean().default(!1),returnType:Cn.string().optional()}),context:Cn.object({variables:An.record(Cn.string(),Cn.any()).default({}),me:Cn.any().optional(),it:Cn.any().optional(),target:Cn.any().optional()}).default({}),options:Cn.object({enableClosures:Cn.boolean().default(!0),enableTypeChecking:Cn.boolean().default(!0),maxParameterCount:Cn.number().default(20),allowDynamicParameters:Cn.boolean().default(!1)}).default({}),environment:An.enum(["frontend","backend","universal"]).default("universal"),debug:Cn.boolean().default(!1)});Cn.object({contextId:Cn.string(),timestamp:Cn.number(),category:Cn.literal("Universal"),capabilities:Cn.array(Cn.string()),state:An.enum(["ready","defining","executing","error"]),functions:An.object({define:An.function(),call:An.function(),exists:An.function(),remove:An.function(),list:An.function(),getMetadata:An.function()}),parameters:Cn.object({validate:An.function(),bind:An.function(),getSignature:An.function()}),execution:Cn.object({invoke:An.function(),invokeAsync:An.function(),createClosure:An.function(),getCallStack:An.function()}),types:Cn.object({check:An.function(),infer:An.function(),validate:An.function(),annotate:An.function()}),errors:Cn.object({handle:An.function(),getCatchBlock:An.function(),getFinallyBlock:An.function()})});class Sk{constructor(){this.name="defFeature",this.category="Universal",this.description="Type-safe function definition feature with parameter validation, closure support, and async execution",this.inputSchema=Ek,this.outputType="Context",this.evaluationHistory=[],this.functions=new Map,this.callHistory=[],this.namespaces=new Set,this.metadata={category:"Universal",complexity:"complex",sideEffects:["function-registration","context-modification","closure-creation"],dependencies:["execution-context","command-executor","type-system"],returnTypes:["Context"],examples:[{input:'{ definition: { name: "add", parameters: ["a", "b"], body: ["return a + b"] } }',description:"Define a simple addition function with parameters",expectedOutput:"TypedDefContext with function registration and type validation"},{input:'{ definition: { name: "asyncProcess", isAsync: true, body: ["wait 100ms", "return success"] } }',description:"Define an async function with delay and return",expectedOutput:"Async function with proper promise handling and execution"},{input:'{ definition: { name: "safeDivide", catchBlock: { parameter: "err", body: ["return 0"] } } }',description:"Define function with error handling and fallback",expectedOutput:"Function with try-catch pattern and error recovery"}],relatedExpressions:[],relatedContexts:["onFeature","behaviorFeature","executionContext"],frameworkDependencies:["hyperscript-runtime","command-system"],environmentRequirements:{browser:!0,server:!0,nodejs:!0},performance:{averageTime:12.8,complexity:"O(n)"}},this.documentation={summary:"Creates type-safe function definitions for hyperscript with parameter validation, closure support, and comprehensive error handling",parameters:[{name:"defConfig",type:"DefInput",description:"Function definition configuration including name, parameters, body, and execution options",optional:!1,examples:['{ definition: { name: "myFunc", parameters: ["x"], body: ["return x * 2"] } }','{ definition: { name: "validator", body: ["if x > 0", "return true", "else", "return false"] } }','{ definition: { isAsync: true, catchBlock: { parameter: "e", body: ["log e"] } } }']}],returns:{type:"DefContext",description:"Function management context with registration, execution, and type validation capabilities",examples:["context.functions.define(functionDef) → registered function",'context.functions.call("myFunc", [args]) → function result','context.execution.invoke("asyncFunc") → Promise<result>',"context.types.validate(params, signature) → validation result"]},examples:[{title:"Define simple function",code:'const defContext = await createDefFeature({ definition: { name: "double", parameters: ["x"], body: ["return x * 2"] } })',explanation:"Create a simple function that doubles its input with type validation",output:"Function context with type-safe parameter handling"},{title:"Define async function with error handling",code:'await defContext.functions.define({ name: "fetchData", isAsync: true, catchBlock: { parameter: "error", body: ["return null"] } })',explanation:"Create async function with built-in error handling and fallback",output:"Async function with promise-based execution and error recovery"},{title:"Call function with validation",code:'const result = await defContext.functions.call("double", [5])',explanation:"Execute function with automatic parameter validation",output:"Type-validated function execution with result: 10"}],seeAlso:["onFeature","behaviorFeature","executionContext","typeValidation"],tags:["functions","definitions","parameters","async","closures","type-safe","enhanced-pattern"]}}async initialize(e){const t=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:{name:"ValidationError",type:"validation-error",message:n.errors.map(e=>e.message).join(", "),code:"VALIDATION_FAILED",suggestions:n.suggestions}};const r=await this.initializeConfig(e),i={contextId:`def-${Date.now()}`,timestamp:t,category:"Universal",capabilities:["function-definition","parameter-validation","closure-support","async-execution","type-checking","error-handling"],state:"ready",functions:{define:this.createFunctionDefiner(r),call:this.createFunctionCaller(r),exists:this.createFunctionChecker(),remove:this.createFunctionRemover(),list:this.createFunctionLister(),getMetadata:this.createMetadataGetter()},parameters:{validate:this.createParameterValidator(),bind:this.createParameterBinder(),getSignature:this.createSignatureGetter()},execution:{invoke:this.createFunctionInvoker(r),invokeAsync:this.createAsyncInvoker(r),createClosure:this.createClosureCreator(r),getCallStack:this.createCallStackGetter()},types:{check:this.createTypeChecker(),infer:this.createTypeInferrer(),validate:this.createTypeValidator(),annotate:this.createTypeAnnotator()},errors:{handle:this.createErrorHandler(),getCatchBlock:this.createCatchBlockGetter(),getFinallyBlock:this.createFinallyBlockGetter()}};return e.definition&&await this.registerFunction(e.definition,e.context),this.trackPerformance(t,!0,i),{success:!0,value:i,type:"object"}}catch(e){return this.trackPerformance(t,!1),{success:!1,error:{type:"runtime-error",message:`Def feature initialization failed: ${e instanceof Error?e.message:String(e)}`,suggestions:[]}}}}validate(e){try{if(!e||"object"!=typeof e)return{isValid:!1,error:{type:"invalid-input",message:"Input must be an object",suggestions:[]},suggestions:["Provide a valid function definition configuration object"],errors:[]};const t=this.inputSchema.parse(e),n=[],r=[],i=t;if(i.definition&&!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(i.definition.name)&&(n.push({type:"validation-error",message:"Function name must be a valid JavaScript identifier",path:"definition.name",suggestions:[]}),r.push("Use valid JavaScript identifier for function name")),i.definition?.parameters){i.definition.parameters.forEach((e,t)=>{/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)||(n.push({type:"validation-error",message:`Parameter "${e}" must be a valid JavaScript identifier`,path:`definition.parameters[${t}]`,suggestions:[]}),r.push("Use valid JavaScript identifiers for parameter names"))});new Set(i.definition.parameters).size!==i.definition.parameters.length&&(n.push({type:"validation-error",message:"Function parameters must be unique",path:"definition.parameters",suggestions:[]}),r.push("Remove duplicate parameter names")),i.definition.parameters.length>(i.options?.maxParameterCount||20)&&(n.push({type:"validation-error",message:`Function has too many parameters (max: ${i.options?.maxParameterCount||20})`,path:"definition.parameters",suggestions:[]}),r.push("Reduce number of parameters or increase maxParameterCount limit"))}return i.definition?.body&&0===i.definition.body.length&&(n.push({type:"validation-error",message:"Function body cannot be empty",path:"definition.body",suggestions:[]}),r.push("Add at least one command to the function body")),i.definition?.catchBlock&&!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(i.definition.catchBlock.parameter)&&(n.push({type:"validation-error",message:"Catch block parameter must be a valid JavaScript identifier",path:"definition.catchBlock.parameter",suggestions:[]}),r.push("Use valid JavaScript identifier for catch parameter")),i.definition?.namespace&&!/^[a-zA-Z_$][a-zA-Z0-9_$.]*$/.test(i.definition.namespace)&&(n.push({type:"validation-error",message:"Namespace must be a valid JavaScript identifier or dot-separated path",path:"definition.namespace",suggestions:[]}),r.push('Use valid namespace format (e.g., "myNamespace" or "my.nested.namespace")')),{isValid:0===n.length,errors:n,suggestions:r}}catch(e){return{isValid:!1,error:{type:"schema-validation",message:e instanceof Error?e.message:"Invalid input format",suggestions:[]},suggestions:["Ensure input matches DefInput schema","Check function definition structure","Verify parameter and body configurations are valid"],errors:[]}}}async initializeConfig(e){return{...e.options,environment:e.environment,debug:e.debug,initialized:Date.now()}}async registerFunction(e,t){const n={variables:t?.variables||{},me:t?.me||null,it:t?.it||null,target:t?.target||null,...t},r={name:e.name,namespace:e.namespace,parameters:e.parameters||[],body:e.body||[],catchBlock:e.catchBlock,finallyBlock:e.finallyBlock,isAsync:e.isAsync||!1,returnType:e.returnType,context:n,metadata:{name:e.name,namespace:e.namespace,parameters:e.parameters||[],isAsync:e.isAsync||!1,returnType:e.returnType,complexity:this.calculateComplexity(e.body||[]),createdAt:Date.now(),callCount:0,averageExecutionTime:0}},i=e.namespace?`${e.namespace}.${e.name}`:e.name;return this.functions.set(i,r),e.namespace&&this.namespaces.add(e.namespace),r}createFunctionDefiner(e){return async e=>await this.registerFunction(e,{})}createFunctionCaller(e){return async(e,t=[])=>{const n=this.functions.get(e);if(!n)throw new Error(`Function "${e}" not found`);const r=Date.now();try{if(t.length!==n.parameters.length)throw new Error(`Function "${e}" expects ${n.parameters.length} parameters, got ${t.length}`);const i={...n.context,variables:{...n.context.variables,...Object.fromEntries(n.parameters.map((e,n)=>[e,t[n]]))}};let a;a=n.isAsync?await this.executeAsyncFunction(n,i):await this.executeFunction(n,i);const o={functionName:e,parameters:t,context:i,timestamp:r,result:a,executionTime:Date.now()-r};return xk(this.callHistory,o),n.metadata.callCount++,n.metadata.averageExecutionTime=(n.metadata.averageExecutionTime*(n.metadata.callCount-1)+o.executionTime)/n.metadata.callCount,a}catch(i){const a={functionName:e,parameters:t,context:n.context,timestamp:r,error:i,executionTime:Date.now()-r};if(xk(this.callHistory,a),n.catchBlock)return await this.executeCatchBlock(n,i);throw i}}}createFunctionChecker(){return e=>this.functions.has(e)}createFunctionRemover(){return e=>this.functions.delete(e)}createFunctionLister(){return e=>e?Array.from(this.functions.keys()).filter(t=>t.startsWith(`${e}.`)):Array.from(this.functions.keys())}createMetadataGetter(){return e=>{const t=this.functions.get(e);return t?.metadata||null}}createParameterValidator(){return(e,t)=>{const n=this.functions.get(e);return n?t.length!==n.parameters.length?{isValid:!1,error:`Expected ${n.parameters.length} parameters, got ${t.length}`}:{isValid:!0}:{isValid:!1,error:"Function not found"}}}createParameterBinder(){return(e,t)=>{const n=this.functions.get(e);return n?Object.fromEntries(n.parameters.map((e,n)=>[e,t[n]])):{}}}createSignatureGetter(){return e=>{const t=this.functions.get(e);return t?{name:t.name,parameters:t.parameters,isAsync:t.isAsync,returnType:t.returnType}:null}}createFunctionInvoker(e){return async(t,...n)=>await this.createFunctionCaller(e)(t,n)}createAsyncInvoker(e){return async(t,...n)=>{const r=this.functions.get(t);if(!r)throw new Error(`Function "${t}" not found`);if(!r.isAsync)throw new Error(`Function "${t}" is not async`);return await this.createFunctionCaller(e)(t,n)}}createClosureCreator(e){return(t,n)=>{const r=this.functions.get(t);if(!r)throw new Error(`Function "${t}" not found`);return{call:async(...i)=>{const a={...r.context,variables:{...r.context.variables,...n}},o=r.context;r.context=a;try{return await this.createFunctionCaller(e)(t,i)}finally{r.context=o}}}}}createCallStackGetter(){return()=>this.callHistory.slice(-10)}createTypeChecker(){return(e,t)=>{switch(t.toLowerCase()){case"string":return"string"==typeof e;case"number":return"number"==typeof e;case"boolean":return"boolean"==typeof e;case"object":return"object"==typeof e&&null!==e;case"array":return Array.isArray(e);case"function":return"function"==typeof e;default:return!0}}}createTypeInferrer(){return e=>null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}createTypeValidator(){return(e,t)=>({isValid:!0,errors:[]})}createTypeAnnotator(){return(e,t,n)=>{const r=this.functions.get(e);return r&&(r.returnType=n),!0}}createErrorHandler(){return async(e,t)=>{const n=this.functions.get(t);if(n?.catchBlock)return await this.executeCatchBlock(n,e);throw e}}createCatchBlockGetter(){return e=>{const t=this.functions.get(e);return t?.catchBlock||null}}createFinallyBlockGetter(){return e=>{const t=this.functions.get(e);return t?.finallyBlock||null}}async executeFunction(e,t){let n;try{for(const t of e.body)if("string"==typeof t&&t.startsWith("return ")){const e=t.substring(7);n="true"===e||"false"!==e&&(isNaN(Number(e))?e:Number(e));break}}finally{e.finallyBlock&&await this.executeFinallyBlock(e)}return n}async executeAsyncFunction(e,t){return await new Promise(e=>setTimeout(e,1)),await this.executeFunction(e,t)}async executeCatchBlock(e,t){if(e.catchBlock)return e.context,e.context.variables,e.catchBlock.parameter,"handled"}async executeFinallyBlock(e){e.finallyBlock}calculateComplexity(e){return e.length}dispose(){this.functions.clear(),this.namespaces.clear(),this.callHistory=[],this.evaluationHistory=[]}trackPerformance(e,t,n){const r=Date.now()-e;xk(this.evaluationHistory,{input:{},output:n,success:t,duration:r,timestamp:e})}getPerformanceMetrics(){return{totalInitializations:this.evaluationHistory.length,successRate:this.evaluationHistory.filter(e=>e.success).length/Math.max(this.evaluationHistory.length,1),averageDuration:this.evaluationHistory.reduce((e,t)=>e+t.duration,0)/Math.max(this.evaluationHistory.length,1),lastEvaluationTime:this.evaluationHistory[this.evaluationHistory.length-1]?.timestamp||0,evaluationHistory:this.evaluationHistory.slice(-10),totalFunctions:this.functions.size,totalNamespaces:this.namespaces.size,totalCalls:this.callHistory.length,averageCallTime:this.callHistory.reduce((e,t)=>e+t.executionTime,0)/Math.max(this.callHistory.length,1)}}}const Tk=new Sk;function Ck(e,t,n=1e3){e.push(t),e.length>n&&e.shift()}const Ak=Cn.object({event:An.object({type:Cn.string().min(1),target:Cn.string().optional(),delegated:Cn.boolean().default(!1),once:Cn.boolean().default(!1),passive:Cn.boolean().default(!1),capture:Cn.boolean().default(!1),preventDefault:Cn.boolean().default(!1),stopPropagation:Cn.boolean().default(!1),filter:Cn.string().optional(),inSelector:Cn.string().optional(),every:Cn.boolean().default(!1),throttle:Cn.number().optional(),debounce:Cn.number().optional()}),commands:Cn.array(Cn.any()),context:Cn.object({variables:An.record(Cn.string(),Cn.any()).default({}),me:Cn.any().optional(),it:Cn.any().optional(),target:Cn.any().optional()}).default({}),options:Cn.object({enableErrorHandling:Cn.boolean().default(!0),enableEventCapture:Cn.boolean().default(!0),enableAsyncExecution:Cn.boolean().default(!0),maxCommandCount:Cn.number().default(100)}).default({}),environment:An.enum(["frontend","backend","universal"]).default("frontend"),debug:Cn.boolean().default(!1)});Cn.object({contextId:Cn.string(),timestamp:Cn.number(),category:Cn.literal("Frontend"),capabilities:Cn.array(Cn.string()),state:An.enum(["ready","listening","executing","error"]),events:An.object({listen:An.function(),unlisten:An.function(),trigger:An.function(),getListeners:An.function(),pauseListener:An.function(),resumeListener:An.function()}),execution:Cn.object({execute:An.function(),executeAsync:An.function(),getExecutionHistory:An.function(),clearHistory:An.function()}),filtering:Cn.object({addFilter:An.function(),removeFilter:An.function(),testFilter:An.function(),getFilters:An.function()}),performance:Cn.object({throttle:An.function(),debounce:An.function(),setThrottleDelay:An.function(),setDebounceDelay:An.function()}),errors:Cn.object({handle:An.function(),getErrorHistory:An.function(),clearErrors:An.function(),setErrorHandler:An.function()})});class jk{constructor(){this.name="onFeature",this.category="Frontend",this.description="Type-safe event handling feature with advanced filtering, throttling, and execution control",this.inputSchema=Ak,this.outputType="Context",this.evaluationHistory=[],this.listeners=new Map,this.executionHistory=[],this.filters=new Map,this.errorHistory=[],this.throttleTimers=new Map,this.debounceTimers=new Map,this.filterCache=new Map,this.metadata={category:"Frontend",complexity:"complex",sideEffects:["event-listening","dom-modification","command-execution"],dependencies:["dom-api","event-system","command-executor"],returnTypes:["Context"],examples:[{input:'{ event: { type: "click", target: "button" }, commands: [{ type: "command", name: "hide", args: [] }] }',description:"Listen for click events on buttons and hide the element",expectedOutput:"TypedOnContext with event listener registration and command execution"},{input:'{ event: { type: "submit", preventDefault: true, throttle: 1000 }, commands: [{ type: "command", name: "log", args: ["Form submitted"] }] }',description:"Handle form submission with preventDefault and throttling",expectedOutput:"Event handler with form processing and rate limiting"},{input:'{ event: { type: "scroll", target: "window", debounce: 500 }, commands: [{ type: "command", name: "updateScrollPosition" }] }',description:"Handle window scroll events with debouncing for performance",expectedOutput:"Optimized scroll handler with debounce control"}],relatedExpressions:["onCommand","eventTrigger","listenerManagement"],relatedContexts:["defFeature","behaviorFeature","executionContext"],frameworkDependencies:["hyperscript-runtime","event-system"],environmentRequirements:{browser:!0,server:!1,nodejs:!1},performance:{averageTime:8.5,complexity:"O(n)"}},this.documentation={summary:"Creates type-safe event listeners for hyperscript with advanced filtering, performance optimization, and comprehensive error handling",parameters:[{name:"onConfig",type:"EnhancedOnInput",description:"Event handling configuration including event type, target, commands, and performance options",optional:!1,examples:['{ event: { type: "click", target: ".button" }, commands: [{ name: "toggle", args: [] }] }','{ event: { type: "input", debounce: 300 }, commands: [{ name: "validateForm" }] }','{ event: { type: "keydown", filter: "event.key === \\"Enter\\"" }, commands: [{ name: "submit" }] }']}],returns:{type:"EnhancedOnContext",description:"Event handling context with listener management, execution control, and performance optimization capabilities",examples:["context.events.listen(eventConfig) → event listener ID",'context.events.trigger("customEvent", data) → trigger custom event',"context.performance.throttle(listenerConfig, 1000) → throttled listener",'context.filtering.addFilter("clickFilter", expression) → event filter']},examples:[{title:"Simple click handler",code:'const onContext = await createOnFeature({ event: { type: "click", target: "button" }, commands: [{ name: "alert", args: ["Clicked!"] }] })',explanation:"Create a click event listener that shows an alert when buttons are clicked",output:"Event context with click handler registration"},{title:"Throttled scroll handler",code:'await onContext.events.listen({ type: "scroll", target: "window", throttle: 100 })',explanation:"Create scroll event listener with 100ms throttling for performance",output:"Optimized scroll handler with rate limiting"},{title:"Filtered keyboard handler",code:'await onContext.filtering.addFilter("enterKey", "event.key === \\"Enter\\" && !event.shiftKey")',explanation:"Add event filter to only handle Enter key presses without Shift",output:"Conditional event handling with custom filtering logic"}],seeAlso:["defFeature","behaviorFeature","eventSystem","commandExecution"],tags:["events","listeners","filtering","throttling","debouncing","type-safe","enhanced-pattern"]}}async initialize(e){const t=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:{name:"ValidationError",type:"validation-error",message:n.errors.map(e=>e.message).join(", "),code:"VALIDATION_FAILED",suggestions:n.suggestions}};const r=await this.initializeConfig(e),i={contextId:`on-${Date.now()}`,timestamp:t,category:"Frontend",capabilities:["event-listening","command-execution","event-filtering","performance-optimization","error-handling"],state:"ready",events:{listen:this.createEventListener(r),unlisten:this.createEventUnlistener(),trigger:this.createEventTrigger(),getListeners:this.createListenerGetter(),pauseListener:this.createListenerPauser(),resumeListener:this.createListenerResumer()},execution:{execute:this.createCommandExecutor(r),executeAsync:this.createAsyncExecutor(r),getExecutionHistory:this.createExecutionHistoryGetter(),clearHistory:this.createHistoryClearer()},filtering:{addFilter:this.createFilterAdder(),removeFilter:this.createFilterRemover(),testFilter:this.createFilterTester(),getFilters:this.createFilterGetter()},performance:{throttle:this.createThrottleController(),debounce:this.createDebounceController(),setThrottleDelay:this.createThrottleDelaySetter(),setDebounceDelay:this.createDebounceDelaySetter()},errors:{handle:this.createErrorHandler(),getErrorHistory:this.createErrorHistoryGetter(),clearErrors:this.createErrorClearer(),setErrorHandler:this.createErrorHandlerSetter()}};return e.event&&e.commands&&await this.registerEventListener(e.event,e.commands,e.context),this.trackPerformance(t,!0,i),{success:!0,value:i,type:"object"}}catch(e){return this.trackPerformance(t,!1),{success:!1,error:{type:"runtime-error",message:`On feature initialization failed: ${e instanceof Error?e.message:String(e)}`,suggestions:[]}}}}validate(e){try{if(!e||"object"!=typeof e)return{isValid:!1,error:{type:"invalid-input",message:"Input must be an object",suggestions:[]},suggestions:["Provide a valid event handling configuration object"],errors:[]};const t=this.inputSchema.parse(e),n=[],r=[],i=t;if(i.event&&!this.isValidEventType(i.event.type)&&(n.push({type:"validation-error",message:`"${i.event.type}" is not a valid DOM event type`,path:"event.type",suggestions:[]}),r.push('Use standard DOM event types like "click", "input", "submit", "keydown", etc.')),i.event?.target&&"me"!==i.event.target){let e=!1;try{"undefined"!=typeof document&&document.querySelector(i.event.target)}catch{e=!0}!e&&/[<]/.test(i.event.target)&&(e=!0),e&&(n.push({type:"syntax-error",message:`Invalid CSS selector: "${i.event.target}"`,path:"event.target",suggestions:[]}),r.push("Use valid CSS selector syntax for target element"))}if(i.event?.throttle&&i.event?.debounce&&(n.push({type:"validation-error",message:"Cannot use both throttle and debounce simultaneously",path:"event",suggestions:[]}),r.push("Choose either throttle OR debounce, not both")),i.event?.throttle&&i.event.throttle<0&&(n.push({type:"invalid-input",message:"Throttle delay must be a positive number",path:"event.throttle",suggestions:[]}),r.push("Set throttle delay to a positive number in milliseconds")),i.event?.debounce&&i.event.debounce<0&&(n.push({type:"invalid-input",message:"Debounce delay must be a positive number",path:"event.debounce",suggestions:[]}),r.push("Set debounce delay to a positive number in milliseconds")),i.commands&&0===i.commands.length&&(n.push({type:"empty-config",message:"Commands array cannot be empty",path:"commands",suggestions:[]}),r.push("Add at least one command to execute when event occurs")),i.commands&&i.commands.length>(i.options?.maxCommandCount||100)&&(n.push({type:"validation-error",message:`Too many commands (max: ${i.options?.maxCommandCount||100})`,path:"commands",suggestions:[]}),r.push("Reduce number of commands or increase maxCommandCount limit")),i.event?.filter)try{new Function("event",`return ${i.event.filter}`)}catch(e){n.push({type:"syntax-error",message:`Invalid filter expression: ${i.event.filter}`,path:"event.filter",suggestions:[]}),r.push("Use valid JavaScript expression for event filtering")}return{isValid:0===n.length,errors:n,suggestions:r}}catch(e){return{isValid:!1,error:{type:"schema-validation",message:e instanceof Error?e.message:"Invalid input format",suggestions:[]},suggestions:["Ensure input matches EnhancedOnInput schema","Check event configuration structure","Verify commands array contains valid command objects"],errors:[]}}}async initializeConfig(e){return{...e.options,environment:e.environment,debug:e.debug,initialized:Date.now()}}async registerEventListener(e,t,n){const r=`listener-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,i={id:r,eventType:e.type,target:e.target||"me",commands:t,context:{variables:n?.variables||{},me:n?.me||null,it:n?.it||null,target:n?.target||null,...n},options:{once:e.once||!1,passive:e.passive||!1,capture:e.capture||!1,delegated:e.delegated||!1,filter:e.filter,inSelector:e.inSelector,every:e.every||!1,throttle:e.throttle,debounce:e.debounce},isActive:!0,isPaused:!1,executionCount:0,lastExecutionTime:0,averageExecutionTime:0};return this.listeners.set(r,i),"undefined"!=typeof document&&this.attachDOMListener(i),i}attachDOMListener(e){const t=this.createDOMEventHandler(e);let n=null;n="string"==typeof e.target?"me"===e.target?e.context.me:"window"===e.target?window:"document"===e.target?document:document.querySelector(e.target):e.target,n&&n.addEventListener(e.eventType,t,e.options)}createDOMEventHandler(e){return t=>{(async()=>{e.isActive&&!e.isPaused&&(e.options.inSelector&&!this.testInSelectorFilter(t,e.options.inSelector)||e.options.filter&&!this.testEventFilter(t,e.options.filter)||e.options.throttle&&this.isThrottled(e.id,e.options.throttle)||(e.options.debounce?this.applyDebounce(e.id,e.options.debounce,()=>{this.executeEventHandler(t,e)}):await this.executeEventHandler(t,e)))})()}}async executeEventHandler(e,t){const n=Date.now();try{const r={...t.context,event:e,target:e.target,currentTarget:e.currentTarget,it:e.target},i=await this.executeCommands(t.commands,r),a={listenerId:t.id,eventType:t.eventType,timestamp:n,event:e,commands:t.commands,result:i,executionTime:Date.now()-n,preventDefault:!1,stopPropagation:!1};Ck(this.executionHistory,a),t.executionCount++,t.lastExecutionTime=Date.now(),t.averageExecutionTime=(t.averageExecutionTime*(t.executionCount-1)+a.executionTime)/t.executionCount}catch(r){const i={listenerId:t.id,eventType:t.eventType,timestamp:n,event:e,commands:t.commands,error:r,executionTime:Date.now()-n,preventDefault:!1,stopPropagation:!1};Ck(this.executionHistory,i),Ck(this.errorHistory,{error:r,timestamp:Date.now(),context:{listener:t,event:e}})}}async executeCommands(e,t){const n={success:!0,executed:e.length};for(const n of e)"object"==typeof n&&n.name&&await this.executeBasicCommand(n,t);return n}async executeBasicCommand(e,t){switch(e.name){case"log":console.log(e.args?.[0]||"Event triggered");break;case"alert":"undefined"!=typeof window&&window.alert(e.args?.[0]||"Event triggered");break;case"hide":t.me&&t.me.style&&(t.me.style.display="none");break;case"show":t.me&&t.me.style&&(t.me.style.display="")}}isValidEventType(e){return["click","dblclick","mousedown","mouseup","mouseover","mouseout","mousemove","keydown","keyup","keypress","focus","blur","focusin","focusout","input","change","submit","reset","load","unload","beforeunload","resize","scroll","dragstart","drag","dragenter","dragover","dragleave","drop","dragend","touchstart","touchmove","touchend","touchcancel","animationstart","animationend","animationiteration","transitionstart","transitionend","error","unhandledrejection"].includes(e)||e.startsWith("custom:")||/^test/.test(e)}testEventFilter(e,t){try{let n=this.filterCache.get(t);return n||(n=new Function("event",`return ${t}`),this.filterCache.set(t,n)),Boolean(n(e))}catch{return!0}}testInSelectorFilter(e,t){try{const n=e.target;if(!n||!n.matches)return!1;if(n.matches(t))return!0;return null!==n.closest(t)}catch(e){return console.warn(`Invalid 'in' selector: "${t}"`,e),!0}}isThrottled(e,t){const n=this.throttleTimers.get(e)||0,r=Date.now();return!(r-n>=t)||(this.throttleTimers.set(e,r),!1)}applyDebounce(e,t,n){const r=this.debounceTimers.get(e);r&&clearTimeout(r);const i=setTimeout(n,t);this.debounceTimers.set(e,i)}createEventListener(e){return async e=>await this.registerEventListener(e,e.commands||[],e.context||{})}createEventUnlistener(){return e=>this.listeners.delete(e)}createEventTrigger(){return(e,t)=>{if("undefined"!=typeof document){const n=new CustomEvent(e,{detail:t});document.dispatchEvent(n)}}}createListenerGetter(){return e=>e?Array.from(this.listeners.values()).filter(t=>t.eventType===e):Array.from(this.listeners.values())}createListenerPauser(){return e=>{const t=this.listeners.get(e);return!!t&&(t.isPaused=!0,!0)}}createListenerResumer(){return e=>{const t=this.listeners.get(e);return!!t&&(t.isPaused=!1,!0)}}createCommandExecutor(e){return async(e,t)=>await this.executeCommands(e,t)}createAsyncExecutor(e){return async(e,t)=>await this.executeCommands(e,t)}createExecutionHistoryGetter(){return e=>e?this.executionHistory.slice(-e):this.executionHistory.slice()}createHistoryClearer(){return()=>(this.executionHistory=[],!0)}createFilterAdder(){return(e,t)=>{try{const n={id:e,expression:t,compiled:new Function("event",`return ${t}`),isActive:!0};return this.filters.set(e,n),!0}catch{return!1}}}createFilterRemover(){return e=>this.filters.delete(e)}createFilterTester(){return(e,t)=>{const n=this.filters.get(e);if(!n||!n.isActive)return!1;try{return Boolean(n.compiled(t))}catch{return!1}}}createFilterGetter(){return()=>Array.from(this.filters.values())}createThrottleController(){return(e,t)=>!0}createDebounceController(){return(e,t)=>!0}createThrottleDelaySetter(){return(e,t)=>{const n=this.listeners.get(e);return!(!n||!n.options)&&(n.options.throttle=t,!0)}}createDebounceDelaySetter(){return(e,t)=>{const n=this.listeners.get(e);return!(!n||!n.options)&&(n.options.debounce=t,!0)}}createErrorHandler(){return async(e,t)=>(Ck(this.errorHistory,{error:e,timestamp:Date.now(),context:t}),!0)}createErrorHistoryGetter(){return e=>e?this.errorHistory.slice(-e):this.errorHistory.slice()}createErrorClearer(){return()=>(this.errorHistory=[],!0)}createErrorHandlerSetter(){return e=>!0}dispose(){for(const e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(const e of this.throttleTimers.values())clearTimeout(e);this.throttleTimers.clear(),this.listeners.clear(),this.filters.clear(),this.filterCache.clear(),this.executionHistory=[],this.errorHistory=[],this.evaluationHistory=[]}trackPerformance(e,t,n){const r=Date.now()-e;Ck(this.evaluationHistory,{input:{},output:n,success:t,duration:r,timestamp:e})}getPerformanceMetrics(){return{totalInitializations:this.evaluationHistory.length,successRate:this.evaluationHistory.filter(e=>e.success).length/Math.max(this.evaluationHistory.length,1),averageDuration:this.evaluationHistory.reduce((e,t)=>e+t.duration,0)/Math.max(this.evaluationHistory.length,1),lastEvaluationTime:this.evaluationHistory[this.evaluationHistory.length-1]?.timestamp||0,evaluationHistory:this.evaluationHistory.slice(-10),totalListeners:this.listeners.size,totalExecutions:this.executionHistory.length,totalErrors:this.errorHistory.length,averageExecutionTime:this.executionHistory.reduce((e,t)=>e+t.executionTime,0)/Math.max(this.executionHistory.length,1)}}}const Lk=new jk;function Pk(e,t,n=1e3){e.push(t),e.length>n&&e.shift()}const Ik=Cn.object({behavior:An.object({name:Cn.string().min(1),namespace:Cn.string().optional(),parameters:Cn.array(Cn.string()).default([]),initBlock:An.object({commands:Cn.array(Cn.any())}).optional(),eventHandlers:Cn.array(Cn.object({event:Cn.string(),eventSource:Cn.string().optional(),filter:Cn.string().optional(),commands:Cn.array(Cn.any()),options:An.object({once:Cn.boolean().default(!1),passive:Cn.boolean().default(!1),capture:Cn.boolean().default(!1),throttle:Cn.number().optional(),debounce:Cn.number().optional()}).default({})})).default([]),lifecycle:Cn.object({onCreate:Cn.array(Cn.any()).optional(),onMount:Cn.array(Cn.any()).optional(),onUnmount:Cn.array(Cn.any()).optional(),onDestroy:Cn.array(Cn.any()).optional()}).optional()}),installation:Cn.object({target:Cn.string().optional(),parameters:An.record(Cn.string(),Cn.any()).default({}),autoInstall:Cn.boolean().default(!1),scope:An.enum(["element","document","global"]).default("element")}).default({}),context:Cn.object({variables:An.record(Cn.string(),Cn.any()).default({}),me:Cn.any().optional(),it:Cn.any().optional(),target:Cn.any().optional()}).default({}),options:Cn.object({enableLifecycleEvents:Cn.boolean().default(!0),enableEventDelegation:Cn.boolean().default(!0),enableParameterValidation:Cn.boolean().default(!0),maxEventHandlers:Cn.number().default(50),enableInheritance:Cn.boolean().default(!1)}).default({}),environment:An.enum(["frontend","backend","universal"]).default("frontend"),debug:Cn.boolean().default(!1)});Cn.object({contextId:Cn.string(),timestamp:Cn.number(),category:Cn.literal("Frontend"),capabilities:Cn.array(Cn.string()),state:An.enum(["ready","defining","installing","installed","error"]),behaviors:An.object({define:Cn.any(),install:Cn.any(),uninstall:Cn.any(),exists:Cn.any(),list:Cn.any(),getDefinition:Cn.any()}),instances:Cn.object({create:Cn.any(),destroy:Cn.any(),getInstances:Cn.any(),getInstancesForElement:Cn.any(),updateParameters:Cn.any()}),events:Cn.object({addHandler:Cn.any(),removeHandler:Cn.any(),triggerLifecycle:Cn.any(),getHandlers:Cn.any()}),parameters:Cn.object({validate:Cn.any(),bind:Cn.any(),getDefaults:Cn.any(),setDefaults:Cn.any()}),lifecycle:Cn.object({onCreate:Cn.any(),onMount:Cn.any(),onUnmount:Cn.any(),onDestroy:Cn.any(),trigger:Cn.any()})});class Nk{constructor(){this.name="behaviorsFeature",this.category="Frontend",this.description="Type-safe behavior definition and installation feature with lifecycle management, event handling, and parameter validation",this.inputSchema=Ik,this.outputType="Context",this.evaluationHistory=[],this.behaviorDefinitions=new Map,this.behaviorInstances=new Map,this.elementBehaviors=new Map,this.lifecycleHistory=[],this.namespaces=new Set,this.filterCache=new Map,this.metadata={category:"Frontend",complexity:"complex",sideEffects:["behavior-registration","element-modification","event-binding","lifecycle-management"],dependencies:["dom-api","event-system","command-executor","lifecycle-manager"],returnTypes:["Context"],examples:[{input:'{ behavior: { name: "draggable", eventHandlers: [{ event: "mousedown", commands: [{ name: "startDrag" }] }] } }',description:"Define a draggable behavior with mouse event handling",expectedOutput:"TypedBehaviorsContext with behavior registration and event management"},{input:'{ behavior: { name: "tooltip", parameters: ["text", "position"], lifecycle: { onMount: [{ name: "showTooltip" }] } } }',description:"Define tooltip behavior with parameters and lifecycle hooks",expectedOutput:"Parameterized behavior with lifecycle event handling"},{input:'{ behavior: { name: "validator", eventHandlers: [{ event: "input", filter: "event.target.value.length > 0" }] } }',description:"Define form validator with filtered event handling",expectedOutput:"Conditional behavior with input validation logic"}],relatedContexts:["defFeature","onFeature","executionContext"],frameworkDependencies:["hyperscript-runtime","behavior-system"],environmentRequirements:{browser:!0,server:!1,nodejs:!1},performance:{averageTime:15.2,complexity:"O(n)"},relatedExpressions:[]},this.documentation={summary:"Creates type-safe behavior definitions for hyperscript with parameter validation, lifecycle management, and comprehensive event handling",parameters:[{name:"behaviorsConfig",type:"BehaviorsInput",description:"Behavior definition configuration including name, parameters, event handlers, and lifecycle hooks",optional:!1,examples:['{ behavior: { name: "modal", eventHandlers: [{ event: "click", eventSource: ".close", commands: [{ name: "hide" }] }] } }','{ behavior: { name: "counter", parameters: ["initial"], lifecycle: { onCreate: [{ name: "initCounter" }] } } }','{ behavior: { name: "tabs", eventHandlers: [{ event: "click", filter: "event.target.matches(".tab")" }] } }']}],returns:{type:"BehaviorsContext",description:"Behavior management context with definition, installation, and lifecycle management capabilities",examples:["context.behaviors.define(behaviorDef) → behavior registration",'context.behaviors.install("tooltip", element, params) → behavior instance','context.lifecycle.trigger("mount", instanceId) → lifecycle event',"context.instances.getInstancesForElement(element) → behavior instances"]},examples:[{title:"Define simple behavior",code:'const behaviorsContext = await createBehaviorsFeature({ behavior: { name: "highlight", eventHandlers: [{ event: "hover", commands: [{ name: "addClass", args: ["highlight"] }] }] } })',explanation:"Create a simple hover highlight behavior with CSS class management",output:"Behavior context with hover event handling and class manipulation"},{title:"Parameterized behavior with lifecycle",code:'await behaviorsContext.behaviors.define({ name: "slideshow", parameters: ["duration", "autoplay"], lifecycle: { onMount: [{ name: "startSlideshow" }], onUnmount: [{ name: "stopSlideshow" }] } })',explanation:"Create slideshow behavior with configurable parameters and lifecycle management",output:"Complex behavior with parameter validation and lifecycle hooks"},{title:"Install behavior on element",code:'const instance = await behaviorsContext.behaviors.install("tooltip", element, { text: "Help text", position: "top" })',explanation:"Install tooltip behavior on element with runtime parameters",output:"Behavior instance with parameter binding and event listener registration"}],seeAlso:["defFeature","onFeature","eventSystem","lifecycleManagement"],tags:["behaviors","components","lifecycle","parameters","events","type-safe","enhanced-pattern"]}}async initialize(e){const t=Date.now();try{const n=await this.initializeConfig(e);if(e.enableStrictValidation){const t=this.validate(e);if(!t.isValid)return e.debug&&console.log("Behaviors validation failed:",t.errors),{success:!1,error:t.errors[0]}}const r={contextId:`behaviors-${Date.now()}`,timestamp:t,category:"Frontend",capabilities:["behavior-definition","behavior-installation","lifecycle-management","event-handling","parameter-validation","instance-management"],state:"ready",behaviors:{define:this.createBehaviorDefiner(n),install:this.createBehaviorInstaller(n),uninstall:this.createBehaviorUninstaller(),exists:this.createBehaviorChecker(),list:this.createBehaviorLister(),getDefinition:this.createDefinitionGetter()},instances:{create:this.createInstanceCreator(n),destroy:this.createInstanceDestroyer(),getInstances:this.createInstanceGetter(),getInstancesForElement:this.createElementInstanceGetter(),updateParameters:this.createParameterUpdater()},events:{addHandler:this.createEventHandlerAdder(),removeHandler:this.createEventHandlerRemover(),triggerLifecycle:this.createLifecycleTrigger(),getHandlers:this.createHandlerGetter()},parameters:{validate:this.createParameterValidator(),bind:this.createParameterBinder(),getDefaults:this.createDefaultsGetter(),setDefaults:this.createDefaultsSetter()},lifecycle:{onCreate:this.createLifecycleHandler("create"),onMount:this.createLifecycleHandler("mount"),onUnmount:this.createLifecycleHandler("unmount"),onDestroy:this.createLifecycleHandler("destroy"),trigger:this.createLifecycleEventTrigger()}};return e.behavior&&(await this.registerBehavior(e.behavior,e.context),e.installation?.autoInstall&&e.installation?.target&&await this.installBehaviorOnTarget(e.behavior.name,e.installation.target,e.installation.parameters,e.context)),this.trackPerformance(t,!0,r),{success:!0,value:r,type:"object"}}catch(e){return this.trackPerformance(t,!1),{success:!1,error:{type:"runtime-error",message:`Behaviors feature initialization failed: ${e instanceof Error?e.message:String(e)}`,suggestions:["Verify behavior definition syntax is correct","Check event handler configurations are valid","Ensure parameter names are valid identifiers","Validate lifecycle hooks contain valid commands"]}}}}validate(e,t){try{if(!e||"object"!=typeof e)return{isValid:!1,errors:[],suggestions:["Provide a valid behavior definition configuration object"]};const n=this.inputSchema.parse(e),r=[],i=[],a=n;if(a.behavior&&!/^[a-zA-Z_$][a-zA-Z0-9_$-]*$/.test(a.behavior.name)&&(r.push({type:"validation-error",code:"invalid-behavior-name",message:"Behavior name must be a valid identifier (letters, numbers, underscore, hyphen)",path:"behavior.name",suggestions:[]}),i.push('Use valid identifier for behavior name (e.g., "my-behavior", "tooltip", "draggable_item")')),a.behavior?.parameters){a.behavior.parameters.forEach((e,t)=>{/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)||(r.push({type:"validation-error",code:"invalid-parameter-name",message:`Parameter "${e}" must be a valid JavaScript identifier`,path:`behavior.parameters[${t}]`,suggestions:[]}),i.push("Use valid JavaScript identifiers for parameter names"))});new Set(a.behavior.parameters).size!==a.behavior.parameters.length&&(r.push({type:"schema-validation",code:"duplicate-parameters",message:"Behavior parameters must be unique",path:"behavior.parameters",suggestions:[]}),i.push("Remove duplicate parameter names"))}if(a.behavior?.eventHandlers&&(a.behavior.eventHandlers.forEach((e,n)=>{if(t?.skipEventTypeValidation||this.isValidEventType(e.event)||(r.push({type:"validation-error",code:"invalid-event-type",message:`"${e.event}" is not a valid DOM event type`,path:`behavior.eventHandlers[${n}].event`,suggestions:[]}),i.push('Use standard DOM event types like "click", "input", "submit", etc.')),e.eventSource&&"me"!==e.eventSource&&"document"!==e.eventSource&&"window"!==e.eventSource){let t=!1;try{"undefined"!=typeof document&&document.querySelector(e.eventSource)}catch{t=!0}!t&&/[<]/.test(e.eventSource)&&(t=!0),t&&(r.push({type:"validation-error",code:"invalid-event-source-selector",message:`Invalid CSS selector: "${e.eventSource}"`,path:`behavior.eventHandlers[${n}].eventSource`,suggestions:[]}),i.push("Use valid CSS selector syntax for event source"))}if(e.filter)try{new Function("event",`return ${e.filter}`)}catch(t){r.push({type:"invalid-input",code:"invalid-filter-expression",message:`Invalid filter expression: ${e.filter}`,path:`behavior.eventHandlers[${n}].filter`,suggestions:[]}),i.push("Use valid JavaScript expression for event filtering")}e.options?.throttle&&e.options?.debounce&&(r.push({type:"schema-validation",code:"conflicting-performance-options",message:"Cannot use both throttle and debounce on the same event handler",path:`behavior.eventHandlers[${n}].options`,suggestions:[]}),i.push("Choose either throttle OR debounce, not both")),e.commands&&0!==e.commands.length||(r.push({type:"empty-config",code:"empty-commands-array",message:"Event handler must have at least one command",path:`behavior.eventHandlers[${n}].commands`,suggestions:[]}),i.push("Add at least one command to the event handler"))}),a.behavior.eventHandlers.length>(a.options?.maxEventHandlers||50)&&(r.push({type:"security-warning",code:"too-many-event-handlers",message:`Too many event handlers (max: ${a.options?.maxEventHandlers||50})`,path:"behavior.eventHandlers",suggestions:[]}),i.push("Reduce number of event handlers or increase maxEventHandlers limit"))),a.behavior?.namespace&&!/^[a-zA-Z_$][a-zA-Z0-9_$.]*$/.test(a.behavior.namespace)&&(r.push({type:"validation-error",code:"invalid-namespace",message:"Namespace must be a valid JavaScript identifier or dot-separated path",path:"behavior.namespace",suggestions:[]}),i.push('Use valid namespace format (e.g., "myNamespace" or "my.nested.namespace")')),a.installation?.target&&"me"!==a.installation.target)try{"undefined"!=typeof document&&document.querySelector(a.installation.target)}catch(e){r.push({type:"validation-error",message:`Invalid CSS selector for installation target: "${a.installation.target}"`,path:"installation.target",suggestions:[]}),i.push("Use valid CSS selector syntax for installation target")}return{isValid:0===r.length,errors:r,suggestions:i}}catch(e){return{isValid:!1,errors:[{type:"schema-validation",message:e instanceof Error?e.message:"Invalid input format",suggestions:[]}],suggestions:["Ensure input matches BehaviorsInput schema","Check behavior definition structure","Verify event handler and parameter configurations are valid"]}}}async initializeConfig(e){return{...e.options,environment:e.environment,debug:e.debug,initialized:Date.now()}}async registerBehavior(e,t){const n={name:e.name,namespace:e.namespace,parameters:e.parameters||[],initBlock:e.initBlock,eventHandlers:e.eventHandlers?.map((e,t)=>({id:`handler-${Date.now()}-${t}`,event:e.event,eventSource:e.eventSource,filter:e.filter,commands:e.commands||[],options:e.options||{}}))||[],lifecycle:e.lifecycle,metadata:{name:e.name,namespace:e.namespace,parameters:e.parameters||[],eventHandlerCount:e.eventHandlers?.length||0,hasLifecycleHooks:Boolean(e.lifecycle),complexity:this.calculateBehaviorComplexity(e),createdAt:Date.now(),installCount:0,averageInstallTime:0}},r=e.namespace?`${e.namespace}.${e.name}`:e.name;return this.behaviorDefinitions.set(r,n),e.namespace&&this.namespaces.add(e.namespace),n}async installBehaviorOnTarget(e,t,n,r){const i="undefined"!=typeof document?"me"===t?[r.me]:Array.from(document.querySelectorAll(t)):[];for(const t of i)t instanceof HTMLElement&&await this.createBehaviorInstance(e,t,n)}async createBehaviorInstance(e,t,n={}){const r=this.behaviorDefinitions.get(e);if(!r)throw new Error(`Behavior "${e}" not found`);const i=`instance-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,a={id:i,behaviorName:e,element:t,parameters:n,eventListeners:new Map,isInstalled:!1,isActive:!1,createdAt:Date.now(),lastActivated:0,installationCount:0};return this.behaviorInstances.set(i,a),this.elementBehaviors.has(t)||this.elementBehaviors.set(t,new Set),this.elementBehaviors.get(t).add(i),await this.installEventHandlers(a,r),await this.executeLifecycleHook(a,"create"),a.isInstalled=!0,a.isActive=!0,a.lastActivated=Date.now(),a.installationCount++,r.metadata.installCount++,a}async installEventHandlers(e,t){for(const n of t.eventHandlers)await this.installEventHandler(e,n)}async installEventHandler(e,t){const n=this.createBehaviorEventHandler(e,t);let r=null;if(r=t.eventSource?"me"===t.eventSource?e.element:"document"===t.eventSource?document:"window"===t.eventSource?window:document.querySelector(t.eventSource):e.element,r){const{once:i,passive:a,capture:o}=t.options;r.addEventListener(t.event,n,{once:i,passive:a,capture:o}),e.eventListeners.set(t.id,n)}}createBehaviorEventHandler(e,t){return async n=>{e.isActive&&(t.filter&&!this.testEventFilter(n,t.filter)||await this.executeCommands(t.commands,{variables:e.parameters,me:e.element,it:n.target,target:n.target,event:n}))}}async executeCommands(e,t){const n={success:!0,executed:e.length};for(const n of e)"object"==typeof n&&n.name&&await this.executeBasicCommand(n,t);return n}async executeBasicCommand(e,t){switch(e.name){case"log":console.log(e.args?.[0]||"Behavior event triggered");break;case"addClass":t.me&&t.me.classList&&e.args?.[0]&&t.me.classList.add(e.args[0]);break;case"removeClass":t.me&&t.me.classList&&e.args?.[0]&&t.me.classList.remove(e.args[0]);break;case"toggleClass":t.me&&t.me.classList&&e.args?.[0]&&t.me.classList.toggle(e.args[0]);break;case"hide":t.me&&t.me.style&&(t.me.style.display="none");break;case"show":t.me&&t.me.style&&(t.me.style.display="")}}async executeLifecycleHook(e,t){const n=this.behaviorDefinitions.get(e.behaviorName);if(!n?.lifecycle)return;const r={phase:t,behaviorName:e.behaviorName,instanceId:e.id,element:e.element,timestamp:Date.now()};Pk(this.lifecycleHistory,r);const i=n.lifecycle[`on${t.charAt(0).toUpperCase()+t.slice(1)}`];i&&await this.executeCommands(i,{variables:e.parameters,me:e.element,it:e.element,target:e.element})}isValidEventType(e){return["click","dblclick","mousedown","mouseup","mouseover","mouseout","mousemove","mouseenter","mouseleave","keydown","keyup","keypress","focus","blur","focusin","focusout","input","change","submit","reset","load","unload","beforeunload","resize","scroll","dragstart","drag","dragenter","dragover","dragleave","drop","dragend","touchstart","touchmove","touchend","touchcancel","animationstart","animationend","animationiteration","transitionstart","transitionend"].includes(e)||e.startsWith("custom:")||/^behavior:/.test(e)}testEventFilter(e,t){try{let n=this.filterCache.get(t);return n||(n=new Function("event",`return ${t}`),this.filterCache.set(t,n)),Boolean(n(e))}catch{return!0}}calculateBehaviorComplexity(e){let t=0;if(t+=1,t+=.5*(e.parameters?.length||0),t+=2*(e.eventHandlers?.length||0),e.lifecycle){t+=1.5*Object.keys(e.lifecycle).length}return e.initBlock?.commands?.length&&(t+=.3*e.initBlock.commands.length),Math.round(t)}createBehaviorDefiner(e){return async e=>await this.registerBehavior(e,{})}createBehaviorInstaller(e){return async(e,t,n={})=>await this.createBehaviorInstance(e,t,n)}createBehaviorUninstaller(){return(e,t)=>{const n=this.elementBehaviors.get(t);if(!n)return!1;let r=0;for(const t of n){const n=this.behaviorInstances.get(t);n&&n.behaviorName===e&&(this.destroyBehaviorInstance(n),r++)}return r>0}}createBehaviorChecker(){return e=>this.behaviorDefinitions.has(e)}createBehaviorLister(){return e=>e?Array.from(this.behaviorDefinitions.keys()).filter(t=>t.startsWith(`${e}.`)):Array.from(this.behaviorDefinitions.keys())}createDefinitionGetter(){return e=>this.behaviorDefinitions.get(e)||null}createInstanceCreator(e){return async(e,t,n={})=>await this.createBehaviorInstance(e,t,n)}createInstanceDestroyer(){return e=>{const t=this.behaviorInstances.get(e);return!!t&&(this.destroyBehaviorInstance(t),!0)}}createInstanceGetter(){return e=>e?Array.from(this.behaviorInstances.values()).filter(t=>t.behaviorName===e):Array.from(this.behaviorInstances.values())}createElementInstanceGetter(){return e=>{const t=this.elementBehaviors.get(e);return t?Array.from(t).map(e=>this.behaviorInstances.get(e)).filter(e=>void 0!==e):[]}}createParameterUpdater(){return(e,t)=>{const n=this.behaviorInstances.get(e);return!!n&&(n.parameters={...n.parameters,...t},!0)}}createEventHandlerAdder(){return(e,t)=>{const n=this.behaviorInstances.get(e);return!!n&&(this.installEventHandler(n,t),!0)}}createEventHandlerRemover(){return(e,t)=>{const n=this.behaviorInstances.get(e);return!(!n||!n.eventListeners.has(t))&&(n.eventListeners.delete(t),!0)}}createLifecycleTrigger(){return async(e,t)=>{const n=this.behaviorInstances.get(e);return!!n&&(await this.executeLifecycleHook(n,t),!0)}}createHandlerGetter(){return e=>{const t=this.behaviorInstances.get(e);return t?Array.from(t.eventListeners.keys()):[]}}createParameterValidator(){return(e,t)=>{const n=this.behaviorDefinitions.get(e);if(!n)return{isValid:!1,error:"Behavior not found"};const r=n.parameters.filter(e=>!(e in t));return r.length>0?{isValid:!1,error:`Missing required parameters: ${r.join(", ")}`}:{isValid:!0}}}createParameterBinder(){return(e,t)=>{const n=this.behaviorDefinitions.get(e);return n?Object.fromEntries(n.parameters.map(e=>[e,t[e]||void 0])):{}}}createDefaultsGetter(){return e=>{const t=this.behaviorDefinitions.get(e);return t?Object.fromEntries(t.parameters.map(e=>[e,void 0])):{}}}createDefaultsSetter(){return(e,t)=>!!this.behaviorDefinitions.get(e)}createLifecycleHandler(e){return async(t,n)=>{const r=this.behaviorInstances.get(t);return!!r&&(await this.executeLifecycleHook(r,e),!0)}}createLifecycleEventTrigger(){return async(e,t,n)=>await this.createLifecycleHandler(e)(t,n)}destroyBehaviorInstance(e){this.executeLifecycleHook(e,"destroy");for(const[t,n]of e.eventListeners);e.eventListeners.clear(),this.behaviorInstances.delete(e.id);const t=this.elementBehaviors.get(e.element);t&&(t.delete(e.id),0===t.size&&this.elementBehaviors.delete(e.element)),e.isInstalled=!1,e.isActive=!1}dispose(){for(const e of this.behaviorInstances.values())this.destroyBehaviorInstance(e);this.behaviorInstances.clear(),this.behaviorDefinitions.clear(),this.elementBehaviors.clear(),this.namespaces.clear(),this.filterCache.clear(),this.lifecycleHistory=[],this.evaluationHistory=[]}trackPerformance(e,t,n){const r=Date.now()-e;Pk(this.evaluationHistory,{input:{},output:n,success:t,duration:r,timestamp:e})}getPerformanceMetrics(){return{totalInitializations:this.evaluationHistory.length,successRate:this.evaluationHistory.filter(e=>e.success).length/Math.max(this.evaluationHistory.length,1),averageDuration:this.evaluationHistory.reduce((e,t)=>e+t.duration,0)/Math.max(this.evaluationHistory.length,1),lastEvaluationTime:this.evaluationHistory[this.evaluationHistory.length-1]?.timestamp||0,evaluationHistory:this.evaluationHistory.slice(-10),totalBehaviors:this.behaviorDefinitions.size,totalInstances:this.behaviorInstances.size,totalNamespaces:this.namespaces.size,lifecycleEvents:this.lifecycleHistory.length,averageComplexity:Array.from(this.behaviorDefinitions.values()).reduce((e,t)=>e+t.metadata.complexity,0)/Math.max(this.behaviorDefinitions.size,1)}}}const Ok=new Nk;function Rk(e,t,n=1e3){e.push(t),e.length>n&&e.shift()}const Mk=Cn.object({socket:An.object({url:Cn.string().url(),protocols:Cn.array(Cn.string()).default([]),reconnect:An.object({enabled:Cn.boolean().default(!0),maxAttempts:Cn.number().default(5),delay:Cn.number().default(1e3),backoff:An.enum(["linear","exponential"]).default("exponential"),maxDelay:Cn.number().default(3e4)}).default({}),heartbeat:Cn.object({enabled:Cn.boolean().default(!1),interval:Cn.number().default(3e4),message:Cn.string().default("ping"),timeout:Cn.number().default(5e3)}).default({}),compression:Cn.boolean().default(!1),binaryType:An.enum(["blob","arraybuffer"]).default("blob")}),eventHandlers:Cn.array(Cn.object({event:An.enum(["open","close","error","message"]),filter:Cn.string().optional(),commands:Cn.array(Cn.any()),options:An.object({once:Cn.boolean().default(!1),debounce:Cn.number().optional(),throttle:Cn.number().optional()}).default({})})).default([]),messageHandling:Cn.object({format:An.enum(["json","text","binary"]).default("json"),validation:An.object({enabled:Cn.boolean().default(!0),schema:Cn.any().optional()}).default({}),queue:Cn.object({enabled:Cn.boolean().default(!0),maxSize:Cn.number().default(100),persistence:Cn.boolean().default(!1)}).default({})}).default({}),context:Cn.object({variables:An.record(Cn.string(),Cn.any()).default({}),me:Cn.any().optional(),it:Cn.any().optional(),target:Cn.any().optional()}).default({}),options:Cn.object({enableAutoConnect:Cn.boolean().default(!0),enableMessageQueue:Cn.boolean().default(!0),enableErrorHandling:Cn.boolean().default(!0),maxConnections:Cn.number().default(5),connectionTimeout:Cn.number().default(1e4)}).default({}),environment:An.enum(["frontend","backend","universal"]).default("frontend"),debug:Cn.boolean().default(!1)});Cn.object({contextId:Cn.string(),timestamp:Cn.number(),category:Cn.literal("Frontend"),capabilities:Cn.array(Cn.string()),state:An.enum(["ready","connecting","connected","disconnecting","disconnected","error"]),connection:An.object({connect:Cn.any(),disconnect:Cn.any(),reconnect:Cn.any(),isConnected:Cn.any(),getState:Cn.any(),getConnectionInfo:Cn.any()}),messaging:Cn.object({send:Cn.any(),sendJSON:Cn.any(),sendBinary:Cn.any(),subscribe:Cn.any(),unsubscribe:Cn.any(),getMessageHistory:Cn.any()}),events:Cn.object({addHandler:Cn.any(),removeHandler:Cn.any(),emit:Cn.any(),getHandlers:Cn.any()}),queue:Cn.object({add:Cn.any(),process:Cn.any(),clear:Cn.any(),getSize:Cn.any(),getPending:Cn.any()}),errors:Cn.object({handle:Cn.any(),getErrorHistory:Cn.any(),clearErrors:Cn.any(),setErrorHandler:Cn.any()})});class Wk{constructor(){this.name="socketsFeature",this.category="Frontend",this.description="Type-safe WebSocket management feature with reconnection, message queuing, and comprehensive error handling",this.inputSchema=Mk,this.outputType="Context",this.evaluationHistory=[],this.connections=new Map,this.eventHandlers=new Map,this.messageQueue=new Map,this.messageHistory=[],this.errorHistory=[],this.throttleTimers=new Map,this.debounceTimers=new Map,this.filterCache=new Map,this.metadata={category:"Frontend",complexity:"complex",sideEffects:["network-connection","websocket-management","message-transmission","reconnection-logic"],dependencies:["websocket-api","network-connection","message-serialization","event-system"],returnTypes:["Context"],examples:[{input:'{ socket: { url: "wss://api.example.com/ws" }, eventHandlers: [{ event: "message", commands: [{ name: "processMessage" }] }] }',description:"Connect to WebSocket server and handle incoming messages",expectedOutput:"TypedSocketsContext with connection management and message handling"},{input:'{ socket: { url: "wss://chat.example.com", reconnect: { enabled: true, maxAttempts: 10 } }, messageHandling: { format: "json" } }',description:"Chat WebSocket with auto-reconnection and JSON message handling",expectedOutput:"Resilient WebSocket connection with automatic recovery"},{input:'{ socket: { url: "wss://data.example.com", heartbeat: { enabled: true, interval: 30000 } }, messageHandling: { queue: { enabled: true } } }',description:"Data WebSocket with heartbeat monitoring and message queuing",expectedOutput:"Monitored connection with reliable message delivery"}],relatedContexts:["onFeature","behaviorFeature","eventSourceFeature"],relatedExpressions:[],frameworkDependencies:["websocket-api","network-stack"],environmentRequirements:{browser:!0,server:!0,nodejs:!0},performance:{averageTime:25.4,complexity:"O(n)"}},this.documentation={summary:"Creates type-safe WebSocket connections for hyperscript with automatic reconnection, message queuing, and comprehensive error handling",parameters:[{name:"socketsConfig",type:"SocketsInput",description:"WebSocket configuration including URL, protocols, reconnection settings, and event handlers",optional:!1,examples:['{ socket: { url: "wss://api.example.com/ws" }, eventHandlers: [{ event: "message", commands: [{ name: "handleMessage" }] }] }','{ socket: { url: "wss://chat.com", reconnect: { maxAttempts: 5 } }, messageHandling: { format: "json" } }','{ socket: { url: "wss://realtime.com", heartbeat: { enabled: true } }, options: { enableAutoConnect: true } }']}],returns:{type:"SocketsContext",description:"WebSocket management context with connection control, messaging, and event handling capabilities",examples:["context.connection.connect() → establish WebSocket connection",'context.messaging.sendJSON({data: "value"}) → send JSON message','context.events.addHandler("message", handler) → add message handler',"context.queue.add(message) → queue message for delivery"]},examples:[{title:"Basic WebSocket connection",code:'const socketsContext = await createSocketsFeature({ socket: { url: "wss://api.example.com/ws" }, eventHandlers: [{ event: "message", commands: [{ name: "processData" }] }] })',explanation:"Create WebSocket connection with message processing",output:"Connected WebSocket with automatic message handling"},{title:"Resilient chat connection",code:"await socketsContext.connection.connect({ reconnect: { enabled: true, maxAttempts: 10 }, heartbeat: { enabled: true } })",explanation:"Establish chat connection with reconnection and heartbeat monitoring",output:"Robust WebSocket suitable for real-time chat applications"},{title:"Send structured data",code:'await socketsContext.messaging.sendJSON({ type: "chat", message: "Hello", userId: 123 })',explanation:"Send JSON-formatted message through WebSocket",output:"Structured message transmitted with automatic serialization"}],seeAlso:["onFeature","eventSourceFeature","networkManagement","realTimeData"],tags:["websockets","realtime","networking","messaging","reconnection","type-safe","enhanced-pattern"]}}async initialize(e){const t=Date.now();try{const n=await this.initializeConfig(e),r=this.validate(e);if(!r.isValid)return e.debug&&console.log("Sockets validation failed:",r.errors),{success:!1,error:r.errors[0]};const i={contextId:`sockets-${Date.now()}`,timestamp:t,category:"Frontend",capabilities:["websocket-connection","message-handling","reconnection-management","queue-management","event-handling","error-recovery"],state:"ready",connection:{connect:this.createConnectionEstablisher(n),disconnect:this.createConnectionTerminator(),reconnect:this.createReconnector(),isConnected:this.createConnectionChecker(),getState:this.createStateGetter(),getConnectionInfo:this.createConnectionInfoGetter()},messaging:{send:this.createMessageSender(),sendJSON:this.createJSONSender(),sendBinary:this.createBinarySender(),subscribe:this.createMessageSubscriber(),unsubscribe:this.createMessageUnsubscriber(),getMessageHistory:this.createMessageHistoryGetter()},events:{addHandler:this.createEventHandlerAdder(),removeHandler:this.createEventHandlerRemover(),emit:this.createEventEmitter(),getHandlers:this.createHandlerGetter()},queue:{add:this.createQueueAdder(),process:this.createQueueProcessor(),clear:this.createQueueClearer(),getSize:this.createQueueSizeGetter(),getPending:this.createPendingGetter()},errors:{handle:this.createErrorHandler(),getErrorHistory:this.createErrorHistoryGetter(),clearErrors:this.createErrorClearer(),setErrorHandler:this.createErrorHandlerSetter()}};return e.options?.enableAutoConnect&&e.socket&&await this.createSocketConnection(e.socket,e.eventHandlers,e.context),this.trackPerformance(t,!0,i),{success:!0,value:i,type:"object"}}catch(e){return this.trackPerformance(t,!1),{success:!1,error:{type:"runtime-error",message:`Sockets feature initialization failed: ${e instanceof Error?e.message:String(e)}`,suggestions:["Verify WebSocket URL is valid and accessible","Check network connectivity and firewall settings","Ensure WebSocket server supports specified protocols","Validate event handler configurations are correct"]}}}}validate(e){try{if(!e||"object"!=typeof e)return{isValid:!1,errors:[{type:"invalid-input",message:"Input must be an object",suggestions:[]}],suggestions:["Provide a valid WebSocket configuration object"]};const t=this.inputSchema.parse(e),n=[],r=[],i=t;if(i.socket?.url)try{const e=new URL(i.socket.url);["ws:","wss:"].includes(e.protocol)||(n.push({type:"invalid-input",code:"invalid-websocket-protocol",message:"WebSocket URL must use ws:// or wss:// protocol",path:"socket.url",suggestions:[]}),r.push("Use ws:// for local development or wss:// for secure connections"))}catch(e){n.push({type:"invalid-input",code:"invalid-websocket-url",message:`Invalid WebSocket URL: ${i.socket.url}`,path:"socket.url",suggestions:[]}),r.push('Provide a valid WebSocket URL (e.g., "wss://api.example.com/ws")')}return i.socket?.reconnect&&(i.socket.reconnect.maxAttempts<0&&(n.push({type:"invalid-input",code:"invalid-reconnect-attempts",message:"Max reconnection attempts must be non-negative",path:"socket.reconnect.maxAttempts",suggestions:[]}),r.push("Set maxAttempts to 0 or positive number (0 = no reconnection)")),i.socket.reconnect.delay<0&&(n.push({type:"invalid-input",code:"invalid-reconnect-delay",message:"Reconnection delay must be non-negative",path:"socket.reconnect.delay",suggestions:[]}),r.push("Set delay to positive number in milliseconds")),i.socket.reconnect.maxDelay<i.socket.reconnect.delay&&(n.push({type:"validation-error",message:"Max delay must be greater than or equal to initial delay",path:"socket.reconnect.maxDelay",suggestions:[]}),r.push("Ensure maxDelay >= delay for proper backoff behavior"))),i.socket?.heartbeat?.enabled&&(i.socket.heartbeat.interval<=0&&(n.push({type:"invalid-input",code:"invalid-heartbeat-interval",message:"Heartbeat interval must be positive",path:"socket.heartbeat.interval",suggestions:[]}),r.push("Set heartbeat interval to positive number in milliseconds")),i.socket.heartbeat.timeout<=0&&(n.push({type:"invalid-input",code:"invalid-heartbeat-timeout",message:"Heartbeat timeout must be positive",path:"socket.heartbeat.timeout",suggestions:[]}),r.push("Set heartbeat timeout to positive number in milliseconds")),i.socket.heartbeat.timeout>=i.socket.heartbeat.interval&&(n.push({type:"validation-error",message:"Heartbeat timeout must be less than interval",path:"socket.heartbeat",suggestions:[]}),r.push("Ensure timeout < interval for proper heartbeat detection"))),i.eventHandlers&&i.eventHandlers.forEach((e,t)=>{if(e.filter)try{new Function("message","event",`return ${e.filter}`)}catch(i){n.push({type:"invalid-input",code:"invalid-filter-expression",message:`Invalid filter expression: ${e.filter}`,path:`eventHandlers[${t}].filter`,suggestions:[]}),r.push("Use valid JavaScript expression for message filtering")}e.options?.throttle&&e.options?.debounce&&(n.push({type:"schema-validation",code:"conflicting-performance-options",message:"Cannot use both throttle and debounce on the same event handler",path:`eventHandlers[${t}].options`,suggestions:[]}),r.push("Choose either throttle OR debounce, not both")),e.commands&&0!==e.commands.length||(n.push({type:"empty-config",code:"empty-commands-array",message:"Event handler must have at least one command",path:`eventHandlers[${t}].commands`,suggestions:[]}),r.push("Add at least one command to execute when event occurs"))}),i.messageHandling?.queue&&i.messageHandling.queue.maxSize<0&&(n.push({type:"invalid-input",code:"invalid-queue-size",message:"Queue max size must be non-negative (0 = unlimited)",path:"messageHandling.queue.maxSize",suggestions:[]}),r.push("Set queue maxSize to non-negative number (0 for unlimited)")),i.options?.maxConnections<=0&&(n.push({type:"invalid-input",code:"invalid-max-connections",message:"Max connections must be positive",path:"options.maxConnections",suggestions:[]}),r.push("Set maxConnections to positive number")),i.options?.connectionTimeout<=0&&(n.push({type:"invalid-input",code:"invalid-connection-timeout",message:"Connection timeout must be positive",path:"options.connectionTimeout",suggestions:[]}),r.push("Set connectionTimeout to positive number in milliseconds")),{isValid:0===n.length,errors:n,suggestions:r}}catch(e){return{isValid:!1,errors:[{type:"schema-validation",suggestions:[],message:e instanceof Error?e.message:"Invalid input format"}],suggestions:["Ensure input matches SocketsInput schema","Check WebSocket configuration structure","Verify event handler and message handling configurations are valid"]}}}async initializeConfig(e){return{...e.options,environment:e.environment,debug:e.debug,initialized:Date.now()}}async createSocketConnection(e,t,n){const r=`socket-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,i={id:r,url:e.url,protocols:e.protocols||[],websocket:null,state:"disconnected",reconnectAttempts:0,totalReconnects:0,messagesSent:0,messagesReceived:0};this.connections.set(r,i),this.messageQueue.set(r,[]);for(const e of t)await this.registerEventHandler(r,e);return i}async registerEventHandler(e,t){const n=`handler-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,r={id:n,event:t.event,filter:t.filter,commands:t.commands||[],options:t.options||{},isActive:!0,executionCount:0,lastExecutionTime:0};return this.eventHandlers.set(n,r),r}async connectWebSocket(e){const t=this.connections.get(e);if(!t)return!1;try{return t.state="connecting","undefined"!=typeof WebSocket?(t.websocket=new WebSocket(t.url,t.protocols),t.websocket.onopen=()=>this.handleWebSocketOpen(e),t.websocket.onclose=t=>this.handleWebSocketClose(e,t),t.websocket.onerror=t=>this.handleWebSocketError(e,t),t.websocket.onmessage=t=>this.handleWebSocketMessage(e,t)):(t.state="connected",t.connectedAt=Date.now(),await this.executeEventHandlers(e,"open",null)),!0}catch(n){return t.state="error",t.lastError=n,await this.executeEventHandlers(e,"error",n),!1}}async handleWebSocketOpen(e){const t=this.connections.get(e);t&&(t.state="connected",t.connectedAt=Date.now(),t.reconnectAttempts=0,await this.executeEventHandlers(e,"open",null),await this.processQueuedMessages(e))}async handleWebSocketClose(e,t){const n=this.connections.get(e);n&&(n.state="disconnected",n.disconnectedAt=Date.now(),await this.executeEventHandlers(e,"close",t))}async handleWebSocketError(e,t){const n=this.connections.get(e);n&&(n.state="error",n.lastError=new Error("WebSocket error occurred"),await this.executeEventHandlers(e,"error",t))}async handleWebSocketMessage(e,t){const n=this.connections.get(e);if(!n)return;n.messagesReceived++;const r={id:`msg-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,connectionId:e,type:"incoming",data:t.data,format:this.detectMessageFormat(t.data),timestamp:Date.now(),size:this.calculateMessageSize(t.data),validated:!0};Rk(this.messageHistory,r),await this.executeEventHandlers(e,"message",t)}async executeEventHandlers(e,t,n){const r=Array.from(this.eventHandlers.values()).filter(e=>e.event===t&&e.isActive);for(const e of r)try{if(e.filter&&!this.testMessageFilter(n,e.filter))continue;if(e.options.throttle&&this.isThrottled(e.id,e.options.throttle))continue;if(e.options.debounce){this.applyDebounce(e.id,e.options.debounce,()=>{this.executeHandlerCommands(e,n)});continue}await this.executeHandlerCommands(e,n),e.executionCount++,e.lastExecutionTime=Date.now(),e.options.once&&(e.isActive=!1)}catch(t){Rk(this.errorHistory,{error:t,timestamp:Date.now(),context:{handler:e,eventData:n}})}}async executeHandlerCommands(e,t){const n={success:!0,executed:e.commands.length};for(const n of e.commands)"object"==typeof n&&n.name&&await this.executeBasicCommand(n,{eventData:t});return n}async executeBasicCommand(e,t){if("log"===e.name)console.log(e.args?.[0]||"WebSocket event triggered",t.eventData)}detectMessageFormat(e){if(e instanceof ArrayBuffer||e instanceof Blob)return"binary";if("string"==typeof e)try{return JSON.parse(e),"json"}catch{return"text"}return"text"}calculateMessageSize(e){return e instanceof ArrayBuffer?e.byteLength:e instanceof Blob?e.size:"string"==typeof e?new Blob([e]).size:0}testMessageFilter(e,t){try{let n=this.filterCache.get(t);return n||(n=new Function("message","event",`return ${t}`),this.filterCache.set(t,n)),Boolean(n(e?.data,e))}catch{return!0}}isThrottled(e,t){const n=this.throttleTimers.get(e)||0,r=Date.now();return!(r-n>=t)||(this.throttleTimers.set(e,r),!1)}applyDebounce(e,t,n){const r=this.debounceTimers.get(e);r&&clearTimeout(r);const i=setTimeout(n,t);this.debounceTimers.set(e,i)}async processQueuedMessages(e){const t=this.messageQueue.get(e);if(!t||0===t.length)return;const n=this.connections.get(e);if(!n||"connected"!==n.state)return;const r=[];for(const n of t)try{await this.sendMessage(e,n.data,n.format)}catch(e){n.attempts++,n.lastAttempt=Date.now(),n.error=e,n.attempts<n.maxAttempts?r.push(n):Rk(this.errorHistory,{error:new Error(`Message ${n.id} dropped after ${n.maxAttempts} failed attempts`),timestamp:Date.now(),context:{messageId:n.id,data:n.data,format:n.format}})}t.length=0,t.push(...r)}async sendMessage(e,t,n){const r=this.connections.get(e);if(!r||!r.websocket||"connected"!==r.state)return await this.queueMessage(e,t,n),!1;try{let i;switch(n){case"json":i=JSON.stringify(t);break;case"binary":i=t instanceof ArrayBuffer?t:new ArrayBuffer(0);break;default:i=String(t)}if(r.websocket.readyState===WebSocket.OPEN){r.websocket.send(i),r.messagesSent++;const a={id:`msg-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,connectionId:e,type:"outgoing",data:t,format:n,timestamp:Date.now(),size:this.calculateMessageSize(i),validated:!0};return Rk(this.messageHistory,a),!0}return!1}catch(r){return await this.queueMessage(e,t,n),!1}}async queueMessage(e,t,n){const r=this.messageQueue.get(e);if(!r)return;const i={id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,data:t,format:n,timestamp:Date.now(),attempts:0,maxAttempts:3};r.push(i);r.length>100&&r.shift()}createConnectionEstablisher(e){return async e=>{if("string"==typeof e)return await this.connectWebSocket(e);{const t=e||{url:"wss://localhost:8080",protocols:[],reconnect:{enabled:!0},heartbeat:{enabled:!1},compression:!1,binaryType:"blob"},n=await this.createSocketConnection(t,[],{});return await this.connectWebSocket(n.id)}}}createConnectionTerminator(){return async e=>{const t=this.connections.get(e);return!!t&&(t.state="disconnecting",t.websocket&&t.websocket.close(),t.state="disconnected",t.disconnectedAt=Date.now(),await this.executeEventHandlers(e,"close",null),!0)}}createReconnector(){return async e=>{const t=this.connections.get(e);return!!t&&(t.websocket&&t.websocket.close(),t.reconnectAttempts++,t.totalReconnects++,await this.connectWebSocket(e))}}createConnectionChecker(){return e=>{const t=this.connections.get(e);return"connected"===t?.state||!1}}createStateGetter(){return e=>{const t=this.connections.get(e);return t?.state||"disconnected"}}createConnectionInfoGetter(){return e=>{const t=this.connections.get(e);if(!t)return null;return{connectionId:t.id,...void 0!==t.connectedAt&&{connectedAt:t.connectedAt},totalReconnects:t.totalReconnects,messagesSent:t.messagesSent,messagesReceived:t.messagesReceived,bytesTransmitted:0,bytesReceived:0,averageLatency:0,errorCount:this.errorHistory.filter(t=>t.context?.connectionId===e).length,uptime:t.connectedAt?Date.now()-t.connectedAt:0}}}createMessageSender(){return async(e,t,n="text")=>await this.sendMessage(e,t,n)}createJSONSender(){return async(e,t)=>await this.sendMessage(e,t,"json")}createBinarySender(){return async(e,t)=>await this.sendMessage(e,t,"binary")}createMessageSubscriber(){return(e,t)=>this.registerEventHandler("*",{event:e,commands:[t]})}createMessageUnsubscriber(){return e=>this.eventHandlers.delete(e)}createMessageHistoryGetter(){return(e,t)=>{let n=this.messageHistory;return e&&(n=n.filter(t=>t.connectionId===e)),t&&(n=n.slice(-t)),n}}createEventHandlerAdder(){return async(e,t,n)=>await this.registerEventHandler(e,{event:t,commands:[n],options:{}})}createEventHandlerRemover(){return e=>this.eventHandlers.delete(e)}createEventEmitter(){return async(e,t,n)=>(await this.executeEventHandlers(e,t,n),!0)}createHandlerGetter(){return e=>e?Array.from(this.eventHandlers.values()).filter(t=>t.id.includes(e)):Array.from(this.eventHandlers.values())}createQueueAdder(){return async(e,t,n="json")=>(await this.queueMessage(e,t,n),!0)}createQueueProcessor(){return async e=>(await this.processQueuedMessages(e),!0)}createQueueClearer(){return e=>{const t=this.messageQueue.get(e);return!!t&&(t.length=0,!0)}}createQueueSizeGetter(){return e=>{const t=this.messageQueue.get(e);return t?t.length:0}}createPendingGetter(){return e=>{const t=this.messageQueue.get(e);return t?t.slice():[]}}createErrorHandler(){return async(e,t)=>(Rk(this.errorHistory,{error:e,timestamp:Date.now(),context:{connectionId:t}}),!0)}createErrorHistoryGetter(){return e=>e?this.errorHistory.slice(-e):this.errorHistory.slice()}createErrorClearer(){return()=>(this.errorHistory=[],!0)}createErrorHandlerSetter(){return e=>!0}dispose(){for(const e of this.connections.values())e.websocket&&e.websocket.close();this.connections.clear();for(const e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(const e of this.throttleTimers.values())clearTimeout(e);this.throttleTimers.clear(),this.eventHandlers.clear(),this.messageQueue.clear(),this.filterCache.clear(),this.messageHistory=[],this.errorHistory=[],this.evaluationHistory=[]}trackPerformance(e,t,n){const r=Date.now()-e;Rk(this.evaluationHistory,{input:{},output:n,success:t,duration:r,timestamp:e})}getPerformanceMetrics(){return{totalInitializations:this.evaluationHistory.length,successRate:this.evaluationHistory.filter(e=>e.success).length/Math.max(this.evaluationHistory.length,1),averageDuration:this.evaluationHistory.reduce((e,t)=>e+t.duration,0)/Math.max(this.evaluationHistory.length,1),lastEvaluationTime:this.evaluationHistory[this.evaluationHistory.length-1]?.timestamp||0,evaluationHistory:this.evaluationHistory.slice(-10),totalConnections:this.connections.size,totalHandlers:this.eventHandlers.size,totalMessages:this.messageHistory.length,totalErrors:this.errorHistory.length,queuedMessages:Array.from(this.messageQueue.values()).reduce((e,t)=>e+t.length,0)}}}const $k=new Wk;function Hk(e,t,n=1e3){e.push(t),e.length>n&&e.shift()}const qk=Cn.object({worker:An.object({script:Cn.string().min(1),type:An.enum(["module","classic"]).default("classic"),name:Cn.string().optional(),credentials:An.enum(["omit","same-origin","include"]).default("same-origin"),inline:Cn.boolean().default(!1)}),messaging:Cn.object({format:An.enum(["json","text","binary"]).default("json"),serialization:An.enum(["structured-clone","json"]).default("structured-clone"),transferables:Cn.array(Cn.string()).default([]),validation:An.object({enabled:Cn.boolean().default(!0),schema:Cn.any().optional()}).default({}),queue:Cn.object({enabled:Cn.boolean().default(!0),maxSize:Cn.number().min(0).default(100),persistence:Cn.boolean().default(!1)}).default({})}).default({}),eventHandlers:Cn.array(Cn.object({event:An.enum(["message","error","messageerror"]),commands:Cn.array(Cn.any()).min(1),filter:Cn.string().optional(),options:An.object({throttle:Cn.number().optional(),debounce:Cn.number().optional()}).optional()})).default([]),context:Cn.object({variables:An.record(Cn.string(),Cn.any()).default({}),me:Cn.any().optional(),it:Cn.any().optional(),target:Cn.any().optional()}).default({}),options:Cn.object({enableAutoStart:Cn.boolean().default(!0),enableMessageQueue:Cn.boolean().default(!0),enableErrorHandling:Cn.boolean().default(!0),maxWorkers:Cn.number().default(4),workerTimeout:Cn.number().default(3e4),terminationTimeout:Cn.number().default(5e3)}).default({}),environment:An.enum(["frontend","backend","universal"]).default("frontend"),debug:Cn.boolean().default(!1)});Cn.object({contextId:Cn.string(),timestamp:Cn.number(),category:Cn.literal("Frontend"),capabilities:Cn.array(Cn.string()),state:An.enum(["ready","starting","running","terminating","terminated","error"]),workers:An.object({create:Cn.any(),terminate:Cn.any(),restart:Cn.any(),getWorker:Cn.any(),listWorkers:Cn.any(),getWorkerInfo:Cn.any()}),messaging:Cn.object({send:Cn.any(),sendJSON:Cn.any(),sendBinary:Cn.any(),broadcast:Cn.any(),getMessageHistory:Cn.any(),subscribe:Cn.any(),unsubscribe:Cn.any()}),events:Cn.object({addHandler:Cn.any(),removeHandler:Cn.any(),getHandlers:Cn.any(),emit:Cn.any()}),queue:Cn.object({add:Cn.any(),process:Cn.any(),getSize:Cn.any(),getPending:Cn.any(),clear:Cn.any()}),errors:Cn.object({handle:Cn.any(),getErrorHistory:Cn.any(),clearErrors:Cn.any(),setErrorHandler:Cn.any()})});class Dk{constructor(){this.name="webworkerFeature",this.category="Frontend",this.description="Type-safe Web Worker management feature with message handling, event processing, and comprehensive error management",this.inputSchema=qk,this.outputType="Context",this.evaluationHistory=[],this.workers=new Map,this.messageHistory=[],this.eventHandlers=new Map,this.messageQueue=new Map,this.errorHistory=[],this.throttleTimers=new Map,this.debounceTimers=new Map,this.filterCache=new Map,this.metadata={category:"Frontend",complexity:"complex",sideEffects:["worker-creation","message-passing","background-execution"],dependencies:["web-worker-api","message-channel","transferable-objects"],returnTypes:["Context"],examples:[{input:'{ worker: { script: "./worker.js" }, messaging: { format: "json" } }',description:"Create a Web Worker for background JavaScript execution",expectedOutput:"TypedWebWorkerContext with worker management and message handling"},{input:'{ worker: { script: "self.onmessage = e => self.postMessage(e.data * 2)", inline: true } }',description:"Create inline worker for simple calculations",expectedOutput:"Worker context with inline script execution"},{input:'{ worker: { script: "./data-processor.js", type: "module" }, messaging: { transferables: ["ArrayBuffer"] } }',description:"Module worker with transferable object support for large data processing",expectedOutput:"High-performance worker context with zero-copy data transfer"}],relatedExpressions:[],relatedContexts:["socketsFeature","onFeature","executionContext"],frameworkDependencies:["web-worker-api","hyperscript-runtime"],environmentRequirements:{browser:!0,server:!1,nodejs:!1},performance:{averageTime:25,complexity:"O(n)"}},this.documentation={summary:"Creates and manages Web Workers for background JavaScript execution with type-safe message handling, event processing, and comprehensive error recovery",parameters:[{name:"workerConfig",type:"WebWorkerInput",description:"Web Worker configuration including script source, messaging format, event handlers, and performance options",optional:!1,examples:['{ worker: { script: "./worker.js" }, messaging: { format: "json" } }','{ worker: { script: "worker-code", inline: true }, options: { maxWorkers: 2 } }','{ worker: { script: "./module-worker.js", type: "module" }, messaging: { transferables: ["ArrayBuffer"] } }']}],returns:{type:"WebWorkerContext",description:"Web Worker management context with worker lifecycle, message handling, queue management, and error recovery capabilities",examples:["context.workers.create(config) → worker instance ID","context.messaging.sendJSON(workerId, data) → send JSON message to worker","context.queue.add(workerId, message) → queue message for worker","context.workers.terminate(workerId) → gracefully terminate worker"]},examples:[{title:"Basic worker creation",code:'const workerContext = await createWebWorkerFeature({ worker: { script: "./calc-worker.js" } })',explanation:"Create a Web Worker for background calculations",output:"Worker context with calculation worker ready"},{title:"Message passing with transferables",code:'await workerContext.messaging.sendBinary(workerId, arrayBuffer, ["ArrayBuffer"])',explanation:"Send large binary data to worker using transferable objects for zero-copy transfer",output:"High-performance message transfer without copying data"},{title:"Worker event handling",code:'await workerContext.events.addHandler(workerId, "message", { name: "processResult", args: [] })',explanation:"Add event handler for worker messages with command execution",output:"Event-driven worker communication with hyperscript integration"}],seeAlso:["socketsFeature","onFeature","messagingSystem","backgroundExecution"],tags:["webworkers","background-execution","message-passing","transferables","type-safe","enhanced-pattern"]}}async initialize(e){const t=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:n.errors[0]};const r=await this.initializeConfig(e),i={contextId:`webworker-${Date.now()}`,timestamp:t,category:"Frontend",capabilities:["worker-management","message-handling","background-execution","transferable-objects","error-recovery"],state:"ready",workers:{create:this.createWorkerCreator(r),terminate:this.createWorkerTerminator(),restart:this.createWorkerRestarter(),getWorker:this.createWorkerGetter(),listWorkers:this.createWorkerLister(),getWorkerInfo:this.createWorkerInfoGetter()},messaging:{send:this.createMessageSender(),sendJSON:this.createJSONSender(),sendBinary:this.createBinarySender(),broadcast:this.createBroadcaster(),getMessageHistory:this.createMessageHistoryGetter(),subscribe:this.createMessageSubscriber(),unsubscribe:this.createMessageUnsubscriber()},events:{addHandler:this.createEventHandlerAdder(),removeHandler:this.createEventHandlerRemover(),getHandlers:this.createEventHandlerGetter(),emit:this.createEventEmitter()},queue:{add:this.createQueueAdder(),process:this.createQueueProcessor(),getSize:this.createQueueSizeGetter(),getPending:this.createPendingGetter(),clear:this.createQueueClearer()},errors:{handle:this.createErrorHandler(),getErrorHistory:this.createErrorHistoryGetter(),clearErrors:this.createErrorClearer(),setErrorHandler:this.createErrorHandlerSetter()}};return e.worker.script&&!1!==e.options?.enableAutoStart&&await this.createWorker(e.worker,e.context||{}),this.trackPerformance(t,!0,i),{success:!0,value:i,type:"object"}}catch(e){return this.trackPerformance(t,!1),{success:!1,error:{type:"runtime-error",message:`WebWorker feature initialization failed: ${e instanceof Error?e.message:String(e)}`,suggestions:["Verify worker script URL is accessible","Check browser supports Web Workers","Ensure script has valid JavaScript syntax","Validate worker configuration parameters"]}}}}validate(e){try{if(!e||"object"!=typeof e)return{isValid:!1,errors:[{type:"invalid-input",message:"Input must be an object",suggestions:[]}],suggestions:["Provide a valid Web Worker configuration object"]};const t=e,n=[],r=[];if(void 0!==t.messaging?.queue?.maxSize&&t.messaging.queue.maxSize<0&&(n.push({type:"invalid-input",code:"invalid-queue-size",message:"Queue size must be non-negative (0 = unlimited)",path:"messaging.queue.maxSize",suggestions:[]}),r.push("Set queue maxSize to 0 for unlimited or positive number for limit")),t.eventHandlers&&Array.isArray(t.eventHandlers))for(const e of t.eventHandlers)e.commands&&Array.isArray(e.commands)&&0===e.commands.length&&(n.push({type:"empty-config",code:"empty-commands-array",message:"Event handler commands array cannot be empty",path:"eventHandlers.commands",suggestions:[]}),r.push("Add at least one command to execute for event handler"));if(n.length>0)return{isValid:!1,errors:n,suggestions:r};const i=this.inputSchema.parse(e);if(i.worker&&(i.worker.inline||this.isValidWorkerScript(i.worker.script)||(n.push({type:"invalid-input",code:"invalid-worker-script",message:`Invalid worker script: "${i.worker.script}"`,path:"worker.script",suggestions:[]}),r.push("Provide valid JavaScript file URL or inline script code")),i.worker.inline))try{"module"===i.worker.type&&i.worker.script.includes("import")||new Function(i.worker.script)}catch(e){n.push({type:"syntax-error",code:"invalid-inline-script",message:`Invalid inline script syntax: ${i.worker.script}`,path:"worker.script",suggestions:[]}),r.push("Ensure inline script has valid JavaScript syntax")}if(i.options&&(i.options.maxWorkers<1&&(n.push({type:"invalid-input",code:"invalid-max-workers",message:"maxWorkers must be at least 1",path:"options.maxWorkers",suggestions:[]}),r.push("Set maxWorkers to at least 1")),i.options.workerTimeout<1e3&&(n.push({type:"invalid-input",code:"invalid-worker-timeout",message:"Worker timeout must be at least 1000ms",path:"options.workerTimeout",suggestions:[]}),r.push("Set worker timeout to at least 1000ms for proper operation")),i.options.terminationTimeout<1e3&&(n.push({type:"invalid-input",code:"invalid-termination-timeout",message:"Termination timeout must be at least 1000ms",path:"options.terminationTimeout",suggestions:[]}),r.push("Set termination timeout to at least 1000ms for graceful shutdown"))),i.eventHandlers&&i.eventHandlers.length>0)for(const e of i.eventHandlers)if(e.options?.throttle&&e.options?.debounce&&(n.push({type:"schema-validation",code:"conflicting-performance-options",message:"Cannot use both throttle and debounce simultaneously",path:"eventHandlers.options",suggestions:[]}),r.push("Choose either throttle OR debounce, not both")),e.filter)try{new Function("message",`return ${e.filter}`)}catch(t){n.push({type:"invalid-input",code:"invalid-filter-expression",message:`Invalid filter expression: ${e.filter}`,path:"eventHandlers.filter",suggestions:[]}),r.push("Use valid JavaScript expression for message filtering")}return"undefined"==typeof Worker&&(n.push({type:"runtime-error",message:"Web Workers are not supported in this environment",suggestions:[]}),r.push("Web Workers require a browser environment")),{isValid:0===n.length,errors:n,suggestions:r}}catch(e){return{isValid:!1,errors:[{type:"schema-validation",suggestions:[],message:e instanceof Error?e.message:"Invalid input format"}],suggestions:["Ensure input matches WebWorkerInput schema","Check worker configuration structure","Verify messaging and event handler configurations"]}}}async initializeConfig(e){return{...e.options,environment:e.environment,debug:e.debug,initialized:Date.now()}}async createWorker(e,t){const n=`worker-${Date.now()}-${Math.random().toString(36).substring(2,11)}`;let r;if(e.inline){const t=new Blob([e.script],{type:"application/javascript"}),i=URL.createObjectURL(t);r=new Worker(i,{type:e.type||"classic",name:e.name||n}),setTimeout(()=>URL.revokeObjectURL(i),0)}else r=new Worker(e.script,{type:e.type||"classic",name:e.name||n});const i={id:n,name:e.name,worker:r,script:e.script,type:e.type||"classic",state:"starting",createdAt:Date.now(),lastMessageTime:0,messageCount:0,errorCount:0,isTerminating:!1};return r.onmessage=e=>{i.messageCount++,i.lastMessageTime=Date.now(),this.handleWorkerMessage(i,e)},r.onerror=e=>{i.errorCount++,i.state="error",this.handleWorkerError(i,e)},r.onmessageerror=e=>{i.errorCount++,this.handleWorkerMessageError(i,e)},this.workers.set(n,i),i.state="running",i}handleWorkerMessage(e,t){const n={id:`msg-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,workerId:e.id,type:"incoming",data:t.data,timestamp:Date.now(),format:this.detectMessageFormat(t.data)};Hk(this.messageHistory,n),this.processEventHandlers(e.id,"message",t)}handleWorkerError(e,t){const n=new Error(`Worker error: ${t.message}`);Hk(this.errorHistory,{error:n,timestamp:Date.now(),context:{worker:e,event:t}}),this.processEventHandlers(e.id,"error",t)}handleWorkerMessageError(e,t){const n=new Error("Worker message error: Failed to deserialize message");Hk(this.errorHistory,{error:n,timestamp:Date.now(),context:{worker:e,event:t}}),this.processEventHandlers(e.id,"messageerror",t)}processEventHandlers(e,t,n){const r=Array.from(this.eventHandlers.values()).filter(n=>n.workerId===e&&n.eventType===t&&n.isActive);for(const e of r)this.executeEventHandler(e,n)}async executeEventHandler(e,t){try{if(e.filter&&!this.testMessageFilter(t,e.filter))return;if(e.options?.throttle&&this.isThrottled(e.id,e.options.throttle))return;if(e.options?.debounce)return void this.applyDebounce(e.id,e.options.debounce,()=>{this.executeCommands(e.commands,{event:t})});await this.executeCommands(e.commands,{event:t}),e.executionCount++,e.lastExecutionTime=Date.now()}catch(n){Hk(this.errorHistory,{error:n,timestamp:Date.now(),context:{handler:e,event:t}})}}async executeCommands(e,t){const n={success:!0,executed:e.length};for(const n of e)"object"==typeof n&&n.name&&await this.executeBasicCommand(n,t);return n}async executeBasicCommand(e,t){if("log"===e.name)console.log(e.args?.[0]||"Worker message received",t.event?.data)}isValidWorkerScript(e){return!(!e.startsWith("http://")&&!e.startsWith("https://"))||!!(e.startsWith("./")||e.startsWith("../")||e.startsWith("/"))}detectMessageFormat(e){return e instanceof ArrayBuffer||e instanceof Uint8Array?"binary":"string"==typeof e?"text":"json"}testMessageFilter(e,t){try{let n=this.filterCache.get(t);return n||(n=new Function("message",`return ${t}`),this.filterCache.set(t,n)),Boolean(n(e))}catch{return!0}}isThrottled(e,t){const n=this.throttleTimers.get(e)||0,r=Date.now();return!(r-n>=t)||(this.throttleTimers.set(e,r),!1)}applyDebounce(e,t,n){const r=this.debounceTimers.get(e);r&&clearTimeout(r);const i=setTimeout(n,t);this.debounceTimers.set(e,i)}createWorkerCreator(e){return async t=>{if(this.workers.size>=(e.maxWorkers||4))throw new Error("Maximum number of workers reached");return await this.createWorker(t,{})}}createWorkerTerminator(){return async(e,t)=>{const n=this.workers.get(e);if(!n)return!1;n.isTerminating=!0,n.state="terminating";return setTimeout(()=>{"terminating"===n.state&&(n.worker.terminate(),n.state="terminated",this.workers.delete(e))},t||5e3),!0}}createWorkerRestarter(){return async e=>{const t=this.workers.get(e);if(!t)return!1;t.worker.terminate(),this.workers.delete(e);return(await this.createWorker({script:t.script,type:t.type,name:t.name,inline:!1},{})).id}}createWorkerGetter(){return e=>this.workers.get(e)||null}createWorkerLister(){return()=>Array.from(this.workers.keys())}createWorkerInfoGetter(){return e=>{const t=this.workers.get(e);return t?{id:t.id,name:t.name,state:t.state,createdAt:t.createdAt,messageCount:t.messageCount,errorCount:t.errorCount,lastMessageTime:t.lastMessageTime}:null}}createMessageSender(){return async(e,t,n)=>{const r=this.workers.get(e);if(!r||"running"!==r.state)return!1;try{r.worker.postMessage(t,n||[]);const i={id:`msg-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,workerId:e,type:"outgoing",data:t,...n&&{transferables:n},timestamp:Date.now(),format:this.detectMessageFormat(t)};return Hk(this.messageHistory,i),!0}catch(n){return Hk(this.errorHistory,{error:n,timestamp:Date.now(),context:{workerId:e,data:t}}),!1}}}createJSONSender(){return async(e,t)=>await this.createMessageSender()(e,t)}createBinarySender(){return async(e,t)=>{const n=t instanceof ArrayBuffer?[t]:[];return await this.createMessageSender()(e,t,n)}}createBroadcaster(){return async(e,t)=>{const n=[];for(const r of this.workers.keys()){const i=await this.createMessageSender()(r,e,t);n.push(i)}return n.every(e=>e)}}createMessageHistoryGetter(){return(e,t)=>{let n=this.messageHistory;return e&&(n=n.filter(t=>t.workerId===e)),t&&(n=n.slice(-t)),n}}createMessageSubscriber(){return async(e,t)=>{const n=`handler-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,r={id:n,workerId:"",eventType:e,commands:[t],isActive:!0,executionCount:0,lastExecutionTime:0};return this.eventHandlers.set(n,r),n}}createMessageUnsubscriber(){return e=>this.eventHandlers.delete(e)}createEventHandlerAdder(){return async(e,t,n)=>{const r=`handler-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,i={id:r,workerId:e,eventType:t,commands:[n],isActive:!0,executionCount:0,lastExecutionTime:0};return this.eventHandlers.set(r,i),r}}createEventHandlerRemover(){return e=>this.eventHandlers.delete(e)}createEventHandlerGetter(){return e=>e?Array.from(this.eventHandlers.values()).filter(t=>t.workerId===e):Array.from(this.eventHandlers.values())}createEventEmitter(){return async(e,t,n)=>!0}createQueueAdder(){return async(e,t)=>{this.messageQueue.has(e)||this.messageQueue.set(e,[]);return this.messageQueue.get(e).push({id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,workerId:e,type:"outgoing",data:t,timestamp:Date.now(),format:this.detectMessageFormat(t)}),!0}}createQueueProcessor(){return async e=>{const t=this.messageQueue.get(e);if(!t||0===t.length)return!0;const n=this.workers.get(e);if(!n||"running"!==n.state)return!1;try{for(const e of t)n.worker.postMessage(e.data),Hk(this.messageHistory,e);return t.length=0,!0}catch(n){return Hk(this.errorHistory,{error:n,timestamp:Date.now(),context:{workerId:e,queueSize:t.length}}),!1}}}createQueueSizeGetter(){return e=>{const t=this.messageQueue.get(e);return t?t.length:0}}createPendingGetter(){return e=>{const t=this.messageQueue.get(e);return t?t.slice():[]}}createQueueClearer(){return e=>{const t=this.messageQueue.get(e);return!!t&&(t.length=0,!0)}}createErrorHandler(){return async(e,t)=>(Hk(this.errorHistory,{error:e,timestamp:Date.now(),context:t}),!0)}createErrorHistoryGetter(){return e=>e?this.errorHistory.slice(-e):this.errorHistory.slice()}createErrorClearer(){return()=>(this.errorHistory=[],!0)}createErrorHandlerSetter(){return e=>!0}dispose(){for(const e of this.workers.values())e.worker.terminate();this.workers.clear();for(const e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(const e of this.throttleTimers.values())clearTimeout(e);this.throttleTimers.clear(),this.eventHandlers.clear(),this.messageQueue.clear(),this.filterCache.clear(),this.messageHistory=[],this.errorHistory=[],this.evaluationHistory=[]}trackPerformance(e,t,n){const r=Date.now()-e;Hk(this.evaluationHistory,{input:{},output:n,success:t,duration:r,timestamp:e})}getPerformanceMetrics(){return{totalInitializations:this.evaluationHistory.length,successRate:this.evaluationHistory.filter(e=>e.success).length/Math.max(this.evaluationHistory.length,1),averageDuration:this.evaluationHistory.reduce((e,t)=>e+t.duration,0)/Math.max(this.evaluationHistory.length,1),lastEvaluationTime:this.evaluationHistory[this.evaluationHistory.length-1]?.timestamp||0,evaluationHistory:this.evaluationHistory.slice(-10),totalWorkers:this.workers.size,totalMessages:this.messageHistory.length,totalErrors:this.errorHistory.length,totalEventHandlers:this.eventHandlers.size,queuedMessages:Array.from(this.messageQueue.values()).reduce((e,t)=>e+t.length,0)}}}const _k=new Dk;function Vk(e,t,n=1e3){e.push(t),e.length>n&&e.shift()}const Bk=Cn.object({source:An.object({url:Cn.string().min(1),withCredentials:Cn.boolean().default(!1),headers:An.record(Cn.string(),Cn.string()).default({}),retry:Cn.object({enabled:Cn.boolean().default(!0),maxAttempts:Cn.number().default(5),delay:Cn.number().default(3e3),backoff:An.enum(["linear","exponential"]).default("exponential"),maxDelay:Cn.number().default(3e4)}).default({}),timeout:Cn.object({enabled:Cn.boolean().default(!0),duration:Cn.number().default(6e4)}).default({})}),eventHandlers:Cn.array(Cn.object({event:Cn.string().min(1),commands:Cn.array(Cn.any()).min(1),filter:Cn.string().optional(),options:An.object({throttle:Cn.number().optional(),debounce:Cn.number().optional()}).optional()})).default([]),messageProcessing:Cn.object({format:An.enum(["text","json","raw"]).default("text"),validation:An.object({enabled:Cn.boolean().default(!0),schema:Cn.any().optional()}).default({}),buffer:Cn.object({enabled:Cn.boolean().default(!0),maxSize:Cn.number().min(0).default(100),flushInterval:Cn.number().default(1e3)}).default({})}).default({}),context:Cn.object({variables:An.record(Cn.string(),Cn.any()).default({}),me:Cn.any().optional(),it:Cn.any().optional(),target:Cn.any().optional()}).default({}),options:Cn.object({enableAutoConnect:Cn.boolean().default(!0),enableMessageBuffer:Cn.boolean().default(!0),enableErrorHandling:Cn.boolean().default(!0),maxConnections:Cn.number().default(1),connectionTimeout:Cn.number().default(3e4)}).default({}),environment:An.enum(["frontend","backend","universal"]).default("frontend"),debug:Cn.boolean().default(!1)});Cn.object({contextId:Cn.string(),timestamp:Cn.number(),category:Cn.literal("Frontend"),capabilities:Cn.array(Cn.string()),state:An.enum(["ready","connecting","connected","disconnecting","disconnected","error"]),connection:An.object({connect:Cn.any(),disconnect:Cn.any(),reconnect:Cn.any(),getState:Cn.any(),getConnectionInfo:Cn.any(),isConnected:Cn.any()}),events:Cn.object({addHandler:Cn.any(),removeHandler:Cn.any(),getHandlers:Cn.any(),emit:Cn.any()}),messages:Cn.object({getHistory:Cn.any(),getBuffer:Cn.any(),flushBuffer:Cn.any(),clearHistory:Cn.any(),subscribe:Cn.any(),unsubscribe:Cn.any()}),errors:Cn.object({handle:Cn.any(),getErrorHistory:Cn.any(),clearErrors:Cn.any(),setErrorHandler:Cn.any()})});class Fk{constructor(){this.name="eventsourceFeature",this.category="Frontend",this.description="Type-safe Server-Sent Events management feature with connection handling, message processing, and comprehensive error recovery",this.inputSchema=Bk,this.outputType="Context",this.evaluationHistory=[],this.connections=new Map,this.messageHistory=[],this.eventHandlers=new Map,this.messageBuffers=new Map,this.errorHistory=[],this.throttleTimers=new Map,this.debounceTimers=new Map,this.filterCache=new Map,this.metadata={category:"Frontend",complexity:"complex",sideEffects:["sse-connection","event-listening","background-processing"],dependencies:["eventsource-api","stream-processing","connection-management"],returnTypes:["Context"],examples:[{input:'{ source: { url: "/api/events" }, eventHandlers: [{ event: "message", commands: [{ name: "processUpdate" }] }] }',description:"Create Server-Sent Events connection for real-time updates",expectedOutput:"TypedEventSourceContext with SSE connection and message handling"},{input:'{ source: { url: "/api/notifications", retry: { maxAttempts: 10 } }, messageProcessing: { format: "json" } }',description:"SSE connection with automatic retry and JSON message processing",expectedOutput:"Event source context with robust reconnection and data parsing"},{input:'{ source: { url: "/api/metrics" }, messageProcessing: { buffer: { enabled: true, maxSize: 500 } } }',description:"High-volume SSE with message buffering for performance",expectedOutput:"Buffered event source for handling high-frequency updates"}],relatedExpressions:[],relatedContexts:["socketsFeature","onFeature","executionContext"],frameworkDependencies:["eventsource-api","hyperscript-runtime"],environmentRequirements:{browser:!0,server:!1,nodejs:!1},performance:{averageTime:15,complexity:"O(n)"}},this.documentation={summary:"Creates and manages Server-Sent Events connections for real-time data streaming with type-safe message handling, automatic reconnection, and comprehensive error recovery",parameters:[{name:"sourceConfig",type:"EventSourceInput",description:"SSE configuration including server URL, event handlers, message processing options, and connection settings",optional:!1,examples:['{ source: { url: "/api/events" }, eventHandlers: [{ event: "message", commands: [{ name: "update" }] }] }','{ source: { url: "/api/stream", withCredentials: true }, messageProcessing: { format: "json" } }','{ source: { url: "/api/feed" }, messageProcessing: { buffer: { enabled: true, maxSize: 100 } } }']}],returns:{type:"EventSourceContext",description:"Server-Sent Events management context with connection lifecycle, message processing, buffer management, and error recovery capabilities",examples:["context.connection.connect() → establish SSE connection","context.messages.getHistory(50) → get last 50 messages","context.connection.reconnect() → reconnect after failure","context.messages.flushBuffer() → process buffered messages"]},examples:[{title:"Basic SSE connection",code:'const sseContext = await createEventSourceFeature({ source: { url: "/api/updates" } })',explanation:"Create Server-Sent Events connection for real-time updates",output:"SSE context ready for receiving server events"},{title:"JSON message processing",code:'await sseContext.events.addHandler("user-update", { name: "updateUserInterface", args: [] })',explanation:"Add handler for specific event types with JSON parsing",output:"Event-driven SSE with structured data processing"},{title:"Buffered high-frequency events",code:"await sseContext.messages.flushBuffer() // Process accumulated messages",explanation:"Batch process high-frequency events for performance",output:"Efficient handling of rapid event streams"}],seeAlso:["socketsFeature","onFeature","streamProcessing","realTimeUpdates"],tags:["server-sent-events","real-time","streaming","events","connection-management","type-safe","enhanced-pattern"]}}async initialize(e){const t=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:n.errors[0]};const r=await this.initializeConfig(e),i={contextId:`eventsource-${Date.now()}`,timestamp:t,category:"Frontend",capabilities:["sse-connection","message-processing","event-handling","automatic-reconnection","error-recovery"],state:"ready",connection:{connect:this.createConnectionEstablisher(r),disconnect:this.createConnectionDisconnector(),reconnect:this.createConnectionReconnector(),getState:this.createStateGetter(),getConnectionInfo:this.createConnectionInfoGetter(),isConnected:this.createConnectionChecker()},events:{addHandler:this.createEventHandlerAdder(),removeHandler:this.createEventHandlerRemover(),getHandlers:this.createEventHandlerGetter(),emit:this.createEventEmitter()},messages:{getHistory:this.createMessageHistoryGetter(),getBuffer:this.createBufferGetter(),flushBuffer:this.createBufferFlusher(),clearHistory:this.createHistoryClearer(),subscribe:this.createMessageSubscriber(),unsubscribe:this.createMessageUnsubscriber()},errors:{handle:this.createErrorHandler(),getErrorHistory:this.createErrorHistoryGetter(),clearErrors:this.createErrorClearer(),setErrorHandler:this.createErrorHandlerSetter()}};return!1!==e.options?.enableAutoConnect&&await this.createConnection(e.source,e.context||{}),this.trackPerformance(t,!0,i),{success:!0,value:i,type:"object"}}catch(e){return this.trackPerformance(t,!1),{success:!1,error:{type:"runtime-error",message:`EventSource feature initialization failed: ${e instanceof Error?e.message:String(e)}`,suggestions:["Verify EventSource URL is accessible","Check browser supports Server-Sent Events","Ensure server supports SSE with proper headers","Validate event configuration parameters"]}}}}validate(e){try{if(!e||"object"!=typeof e)return{isValid:!1,errors:[{type:"invalid-input",message:"Input must be an object",suggestions:[]}],suggestions:["Provide a valid EventSource configuration object"]};const t=e,n=[],r=[];if(void 0!==t.messageProcessing?.buffer?.maxSize&&t.messageProcessing.buffer.maxSize<0&&(n.push({type:"invalid-input",code:"invalid-buffer-size",message:"Buffer size must be non-negative (0 = unlimited)",path:"messageProcessing.buffer.maxSize",suggestions:[]}),r.push("Set buffer maxSize to 0 for unlimited or positive number for limit")),t.eventHandlers&&Array.isArray(t.eventHandlers))for(const e of t.eventHandlers)e.commands&&Array.isArray(e.commands)&&0===e.commands.length&&(n.push({type:"empty-config",code:"empty-commands-array",message:"Event handler commands array cannot be empty",path:"eventHandlers.commands",suggestions:[]}),r.push("Add at least one command to execute for event handler"));if(n.length>0)return{isValid:!1,errors:n,suggestions:r};const i=this.inputSchema.parse(e);if(i.source&&(this.isValidEventSourceURL(i.source.url)||(n.push({type:"invalid-input",code:"invalid-eventsource-url",message:`Invalid EventSource URL: "${i.source.url}"`,path:"source.url",suggestions:[]}),r.push("Use valid HTTP/HTTPS URL for EventSource connection")),i.source.retry&&(i.source.retry.maxAttempts<0&&(n.push({type:"invalid-input",code:"invalid-retry-attempts",message:"Retry max attempts must be non-negative",path:"source.retry.maxAttempts",suggestions:[]}),r.push("Set maxAttempts to 0 for no retry or positive number for retry limit")),i.source.retry.delay<0&&(n.push({type:"invalid-input",code:"invalid-retry-delay",message:"Retry delay must be non-negative",path:"source.retry.delay",suggestions:[]}),r.push("Set retry delay to positive number in milliseconds")),i.source.retry.maxDelay<i.source.retry.delay&&(n.push({type:"validation-error",message:"Max delay must be greater than or equal to delay",path:"source.retry.maxDelay",suggestions:[]}),r.push("Set maxDelay to be greater than or equal to delay"))),i.source.timeout&&i.source.timeout.duration<1e3&&(n.push({type:"invalid-input",code:"invalid-timeout-duration",message:"Timeout duration must be at least 1000ms",path:"source.timeout.duration",suggestions:[]}),r.push("Set timeout duration to at least 1000ms for proper operation"))),i.options&&(i.options.maxConnections<1&&(n.push({type:"invalid-input",code:"invalid-max-connections",message:"maxConnections must be at least 1",path:"options.maxConnections",suggestions:[]}),r.push("Set maxConnections to at least 1")),i.options.connectionTimeout<1e3&&(n.push({type:"invalid-input",code:"invalid-connection-timeout",message:"Connection timeout must be at least 1000ms",path:"options.connectionTimeout",suggestions:[]}),r.push("Set connection timeout to at least 1000ms for proper operation"))),i.eventHandlers&&i.eventHandlers.length>0)for(const e of i.eventHandlers)if(e.options?.throttle&&e.options?.debounce&&(n.push({type:"schema-validation",code:"conflicting-performance-options",message:"Cannot use both throttle and debounce simultaneously",path:"eventHandlers.options",suggestions:[]}),r.push("Choose either throttle OR debounce, not both")),e.filter)try{new Function("event",`return ${e.filter}`)}catch(t){n.push({type:"invalid-input",code:"invalid-filter-expression",message:`Invalid filter expression: ${e.filter}`,path:"eventHandlers.filter",suggestions:[]}),r.push("Use valid JavaScript expression for event filtering")}return"undefined"==typeof EventSource&&(n.push({type:"runtime-error",message:"Server-Sent Events are not supported in this environment",suggestions:[]}),r.push("EventSource requires a browser environment")),{isValid:0===n.length,errors:n,suggestions:r}}catch(e){return{isValid:!1,errors:[{type:"schema-validation",suggestions:[],message:e instanceof Error?e.message:"Invalid input format"}],suggestions:["Ensure input matches EventSourceInput schema","Check source configuration structure","Verify event handlers and message processing configurations"]}}}async initializeConfig(e){return{...e.options,environment:e.environment,debug:e.debug,initialized:Date.now()}}async createConnection(e,t){const n=`connection-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,r={id:n,url:e.url,eventSource:null,state:"connecting",createdAt:Date.now(),lastMessageTime:0,messageCount:0,errorCount:0,retryAttempts:0,maxRetryAttempts:e.retry?.maxAttempts||5};try{const t={withCredentials:e.withCredentials||!1};return r.eventSource=new EventSource(e.url,t),r.eventSource.onopen=e=>{r.state="connected",r.connectedAt=Date.now(),r.retryAttempts=0,this.handleConnectionOpen(r,e)},r.eventSource.onmessage=e=>{r.messageCount++,r.lastMessageTime=Date.now(),this.handleMessage(r,e)},r.eventSource.onerror=e=>{r.errorCount++,r.state="error",this.handleConnectionError(r,e)},this.connections.set(n,r),r}catch(t){throw r.state="error",r.errorCount++,Vk(this.errorHistory,{error:t,timestamp:Date.now(),context:{connection:r,sourceConfig:e}}),t}}handleConnectionOpen(e,t){this.processEventHandlers(e.id,"open",t)}handleMessage(e,t){const n={id:`msg-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,connectionId:e.id,event:t.type,data:t.data,timestamp:Date.now(),format:this.detectMessageFormat(t.data),...t.lastEventId&&{lastEventId:t.lastEventId},...t.origin&&{origin:t.origin}};Vk(this.messageHistory,n);const r=this.messageBuffers.get(e.id);r&&(r.messages.push(n),r.maxSize>0&&r.messages.length>r.maxSize&&r.messages.shift()),this.processEventHandlers(e.id,"message",t)}handleConnectionError(e,t){Vk(this.errorHistory,{error:new Error("EventSource connection error"),timestamp:Date.now(),context:{connection:e,event:t}}),this.processEventHandlers(e.id,"error",t),e.retryAttempts<e.maxRetryAttempts&&this.scheduleReconnection(e)}scheduleReconnection(e){e.retryAttempts++;const t=3e3*e.retryAttempts;setTimeout(()=>{this.attemptReconnection(e)},t)}async attemptReconnection(e){try{e.eventSource&&e.eventSource.close(),e.state="connecting",e.eventSource=new EventSource(e.url),e.eventSource.onopen=t=>{e.state="connected",e.connectedAt=Date.now(),e.retryAttempts=0,this.handleConnectionOpen(e,t)},e.eventSource.onmessage=t=>{e.messageCount++,e.lastMessageTime=Date.now(),this.handleMessage(e,t)},e.eventSource.onerror=t=>{e.errorCount++,e.state="error",this.handleConnectionError(e,t)}}catch(t){Vk(this.errorHistory,{error:t,timestamp:Date.now(),context:{connection:e,reconnectAttempt:e.retryAttempts}})}}processEventHandlers(e,t,n){const r=Array.from(this.eventHandlers.values()).filter(n=>n.connectionId===e&&n.eventType===t&&n.isActive);for(const e of r)this.executeEventHandler(e,n)}async executeEventHandler(e,t){try{if(e.filter&&!this.testEventFilter(t,e.filter))return;if(e.options?.throttle&&this.isThrottled(e.id,e.options.throttle))return;if(e.options?.debounce)return void this.applyDebounce(e.id,e.options.debounce,()=>{this.executeCommands(e.commands,{event:t})});await this.executeCommands(e.commands,{event:t}),e.executionCount++,e.lastExecutionTime=Date.now()}catch(n){Vk(this.errorHistory,{error:n,timestamp:Date.now(),context:{handler:e,event:t}})}}async executeCommands(e,t){const n={success:!0,executed:e.length};for(const n of e)"object"==typeof n&&n.name&&await this.executeBasicCommand(n,t);return n}async executeBasicCommand(e,t){if("log"===e.name)console.log(e.args?.[0]||"SSE event received",t.event?.data)}isValidEventSourceURL(e){try{const t=new URL(e,window?.location?.href);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}detectMessageFormat(e){if("string"==typeof e)try{return JSON.parse(e),"json"}catch{return"text"}return"raw"}testEventFilter(e,t){try{let n=this.filterCache.get(t);return n||(n=new Function("event",`return ${t}`),this.filterCache.set(t,n)),Boolean(n(e))}catch{return!0}}isThrottled(e,t){const n=this.throttleTimers.get(e)||0,r=Date.now();return!(r-n>=t)||(this.throttleTimers.set(e,r),!1)}applyDebounce(e,t,n){const r=this.debounceTimers.get(e);r&&clearTimeout(r);const i=setTimeout(n,t);this.debounceTimers.set(e,i)}createConnectionEstablisher(e){return async t=>{const n=t||e;return await this.createConnection(n,{})}}createConnectionDisconnector(){return async e=>{const t=this.connections.get(e);return!!t&&(t.state="disconnecting",t.eventSource&&(t.eventSource.close(),t.eventSource=null),t.state="disconnected",t.disconnectedAt=Date.now(),!0)}}createConnectionReconnector(){return async e=>{const t=this.connections.get(e);return!!t&&(await this.attemptReconnection(t),!0)}}createStateGetter(){return e=>{const t=this.connections.get(e);return t?t.state:"disconnected"}}createConnectionInfoGetter(){return e=>{const t=this.connections.get(e);return t?{id:t.id,url:t.url,state:t.state,createdAt:t.createdAt,connectedAt:t.connectedAt,messageCount:t.messageCount,errorCount:t.errorCount,retryAttempts:t.retryAttempts}:null}}createConnectionChecker(){return e=>{const t=this.connections.get(e);return!!t&&"connected"===t.state}}createEventHandlerAdder(){return async(e,t,n)=>{const r=`handler-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,i={id:r,connectionId:e,eventType:t,commands:[n],isActive:!0,executionCount:0,lastExecutionTime:0};return this.eventHandlers.set(r,i),r}}createEventHandlerRemover(){return e=>this.eventHandlers.delete(e)}createEventHandlerGetter(){return e=>e?Array.from(this.eventHandlers.values()).filter(t=>t.connectionId===e):Array.from(this.eventHandlers.values())}createEventEmitter(){return async(e,t,n)=>!0}createMessageHistoryGetter(){return(e,t)=>{let n=this.messageHistory;return e&&(n=n.filter(t=>t.connectionId===e)),t&&(n=n.slice(-t)),n}}createBufferGetter(){return e=>{const t=this.messageBuffers.get(e);return t?t.messages.slice():[]}}createBufferFlusher(){return async e=>{const t=this.messageBuffers.get(e);if(!t||0===t.messages.length)return[];const n=t.messages.slice();return t.messages.length=0,t.lastFlushTime=Date.now(),n}}createHistoryClearer(){return e=>(this.messageHistory=e?this.messageHistory.filter(t=>t.connectionId!==e):[],!0)}createMessageSubscriber(){return async(e,t)=>{const n=`handler-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,r={id:n,connectionId:"",eventType:e,commands:[t],isActive:!0,executionCount:0,lastExecutionTime:0};return this.eventHandlers.set(n,r),n}}createMessageUnsubscriber(){return e=>this.eventHandlers.delete(e)}createErrorHandler(){return async(e,t)=>(Vk(this.errorHistory,{error:e,timestamp:Date.now(),context:t}),!0)}createErrorHistoryGetter(){return e=>e?this.errorHistory.slice(-e):this.errorHistory.slice()}createErrorClearer(){return()=>(this.errorHistory=[],!0)}createErrorHandlerSetter(){return e=>!0}dispose(){for(const e of this.connections.values())e.eventSource&&(e.eventSource.close(),e.eventSource=null);this.connections.clear();for(const e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(const e of this.throttleTimers.values())clearTimeout(e);this.throttleTimers.clear(),this.eventHandlers.clear(),this.messageBuffers.clear(),this.filterCache.clear(),this.messageHistory=[],this.errorHistory=[],this.evaluationHistory=[]}trackPerformance(e,t,n){const r=Date.now()-e;Vk(this.evaluationHistory,{input:{},output:n,success:t,duration:r,timestamp:e})}getPerformanceMetrics(){return{totalInitializations:this.evaluationHistory.length,successRate:this.evaluationHistory.filter(e=>e.success).length/Math.max(this.evaluationHistory.length,1),averageDuration:this.evaluationHistory.reduce((e,t)=>e+t.duration,0)/Math.max(this.evaluationHistory.length,1),lastEvaluationTime:this.evaluationHistory[this.evaluationHistory.length-1]?.timestamp||0,evaluationHistory:this.evaluationHistory.slice(-10),totalConnections:this.connections.size,totalMessages:this.messageHistory.length,totalErrors:this.errorHistory.length,totalEventHandlers:this.eventHandlers.size,bufferedMessages:Array.from(this.messageBuffers.values()).reduce((e,t)=>e+t.messages.length,0)}}}const Uk=new Fk;function Kk(e){const t={};return"number"==typeof e.start&&(t.start=e.start),"number"==typeof e.end&&(t.end=e.end),"number"==typeof e.line&&(t.line=e.line),"number"==typeof e.column&&(t.column=e.column),t}function Gk(e){if(!e)return{type:"literal",value:null};switch(e.type){case"eventHandler":return function(e){const t=e.event??"click",n=e.commands??e.body??[],r=n.map(e=>Gk(e)),i=function(e){return{...e.once?{once:!0}:{},...e.debounce?{debounce:e.debounce}:{},...e.throttle?{throttle:e.throttle}:{},...e.prevent?{prevent:!0}:{},...e.stop?{stop:!0}:{},...e.capture?{capture:!0}:{},...e.passive?{passive:!0}:{},...e.from?{from:e.from}:{},...e.selector&&!e.from?{from:e.selector}:{}}}(e);return{type:"event",event:t,modifiers:i,body:r,...Kk(e)}}(e);case"command":return function(e){const t=e.name;if("if"===t||"unless"===t)return function(e){const t=e.args??[];let n,r,i;e.condition?(n=Gk(e.condition),r=(e.thenBranch??e.then??[]).map(e=>Gk(e)),i=e.elseBranch?e.elseBranch.map(e=>Gk(e)):e.else?e.else.map(e=>Gk(e)):void 0):(n=t[0]?Gk(t[0]):{type:"literal",value:!0},r=Qk(t[1]),i=t[2]?Qk(t[2]):void 0);"unless"===e.name&&(n={type:"unary",operator:"not",operand:n});return{type:"if",condition:n,thenBranch:r,...i?{elseBranch:i}:{},...Kk(e)}}(e);if("repeat"===t)return function(e){const t=e.args??[];if(0===t.length)return{type:"repeat",body:[],...Kk(e)};const n=t[0],r=n?.name??n?.value??"forever",i=t[t.length-1];switch(r){case"times":return{type:"repeat",count:t[1]?Gk(t[1]):void 0,body:Qk(i),...Kk(e)};case"for":return{type:"foreach",itemName:t[1]?.value??"item",collection:t[2]?Gk(t[2]):{type:"identifier",value:"[]"},body:Qk(i),...Kk(e)};case"while":return{type:"while",condition:t[1]?Gk(t[1]):{type:"literal",value:!0},body:Qk(i),...Kk(e)};default:return{type:"repeat",body:Qk(i),...Kk(e)}}}(e);const n=(e.args??[]).map(e=>Gk(e)),r=e.target?Gk(e.target):void 0,i=e.modifiers?function(e){const t={};for(const[n,r]of Object.entries(e))t[n]=Gk(r);return t}(e.modifiers):void 0,a=function(e,t,n,r){const i={};switch(e){case"set":{t[0]&&(i.destination=t[0]);const e=n?.to;e&&"object"==typeof e&&"type"in e?i.patient=e:t[1]&&(i.patient=t[1]);break}case"put":if(t[0]&&(i.patient=t[0]),n){for(const e of["into","before","after"]){const t=n[e];if(t&&"object"==typeof t&&"type"in t){i.destination=t,i.method={type:"literal",value:e};break}}"string"==typeof n.position&&(i.method={type:"literal",value:n.position})}!i.destination&&r&&(i.destination=r);break;case"increment":case"decrement":{t[0]&&(i.destination=t[0]);const e=n?.by;e&&"object"==typeof e&&"type"in e?i.quantity=e:t[1]&&(i.quantity=t[1]);break}case"fetch":{t[0]&&(i.source=t[0]);const e=n?.as;e&&"object"==typeof e&&"type"in e?i.responseType=e:"string"==typeof e&&(i.responseType={type:"identifier",value:e,name:e});break}case"wait":case"settle":t[0]&&(i.duration=t[0]);break;case"toggle":case"add":case"send":case"trigger":t[0]&&(i.patient=t[0]),r&&(i.destination=r);break;case"remove":t[0]&&(i.patient=t[0]),r&&(i.source=r);break;default:return null}return Object.keys(i).length>0?i:null}(t,n,i,r);return{type:"command",name:t,args:n,...r?{target:r}:{},...i&&Object.keys(i).length>0?{modifiers:i}:{},...a?{roles:a}:{},...Kk(e)}}(e);case"CommandSequence":return function(e){const t=e.commands??[];if(1===t.length)return Gk(t[0]);return{type:"event",event:"click",body:t.map(e=>Gk(e)),...Kk(e)}}(e);case"block":return function(e){const t=e.commands??[];if(1===t.length)return Gk(t[0]);return{type:"event",event:"click",body:t.map(e=>Gk(e)),...Kk(e)}}(e);case"literal":case"string":case"timeExpression":return{type:"literal",value:e.value,...Kk(e)};case"selector":case"htmlSelector":return{type:"selector",value:e.value??e.selector??"",...Kk(e)};case"contextReference":return{type:"identifier",value:e.name??e.contextType??"",...Kk(e)};case"identifier":return{type:"identifier",value:e.name??e.value??"",name:e.name??"",...Kk(e)};case"propertyAccess":case"possessiveExpression":return function(e){const t=e.object?Gk(e.object):{type:"identifier",value:"me"},n="string"==typeof e.property?e.property:e.property?.name??e.property?.value??"";return{type:"possessive",object:t,property:n,...Kk(e)}}(e);case"memberExpression":return function(e){const t=e.object?Gk(e.object):{type:"identifier",value:"me"},n="string"==typeof e.property?e.property:e.property?Gk(e.property):{type:"literal",value:""};return{type:"member",object:t,property:n,computed:e.computed??!1,...Kk(e)}}(e);case"binaryExpression":return function(e){return{type:"binary",operator:e.operator??"",left:Gk(e.left),right:Gk(e.right),...Kk(e)}}(e);case"callExpression":return function(e){const t="string"==typeof e.callee?{type:"identifier",value:e.callee,name:e.callee}:Gk(e.callee),n=(e.arguments??e.args??[]).map(e=>Gk(e));return{type:"call",callee:t,args:n,...Kk(e)}}(e);case"unaryExpression":return{type:"unary",operator:e.operator,operand:Gk(e.argument??e.operand),...Kk(e)};case"templateLiteral":return{type:"literal",value:e.raw??"",...Kk(e)};case"variable":return{type:"variable",name:e.name??"",scope:e.scope??"local",...Kk(e)};case"positional":return{type:"positional",position:e.position,...e.target?{target:Gk(e.target)}:{},...Kk(e)};case"positionalExpression":return{type:"positional",position:e.operator,...e.argument?{target:Gk(e.argument)}:{},...Kk(e)};default:return{type:"literal",value:e.value??null,...Kk(e)}}}function Qk(e){return e?"block"===e.type?(e.commands??[]).map(e=>Gk(e)):[Gk(e)]:[]}const Jk={start:0,end:0,line:1,column:0};function Yk(e){return{start:e.start??Jk.start,end:e.end??Jk.end,line:e.line??Jk.line,column:e.column??Jk.column}}function Zk(e){if(!e)return{type:"literal",value:null,raw:"null",...Jk};switch(e.type){case"event":return function(e){const t=(e.body??[]).map(e=>Zk(e)),n=function(e){if(!e)return{};const t={};e.once&&(t.once=!0);e.prevent&&(t.prevent=!0);e.stop&&(t.stop=!0);e.capture&&(t.capture=!0);e.passive&&(t.passive=!0);e.debounce&&(t.debounce=e.debounce);e.throttle&&(t.throttle=e.throttle);e.from&&(t.from=e.from);return t}(e.modifiers);return{type:"eventHandler",event:e.event,commands:t,...n,...Yk(e)}}(e);case"command":return function(e){const t={type:"command",name:e.name,args:(e.args??[]).map(e=>Zk(e)),isBlocking:!1,...Yk(e)};e.target&&(t.target=Zk(e.target));if(e.modifiers&&Object.keys(e.modifiers).length>0){const n={};for(const[t,r]of Object.entries(e.modifiers))n[t]=r&&"object"==typeof r&&"type"in r?Zk(r):r;t.modifiers=n}return t}(e);case"if":return function(e){const t={type:"command",name:"if",isBlocking:!0,condition:Zk(e.condition),thenBranch:e.thenBranch.map(e=>Zk(e)),args:[],...Yk(e)};e.elseBranch&&(t.elseBranch=e.elseBranch.map(e=>Zk(e)));return t}(e);case"repeat":return function(e){const t={type:"command",name:"repeat",isBlocking:!0,body:e.body.map(e=>Zk(e)),args:[],...Yk(e)};void 0!==e.count&&(t.count="number"==typeof e.count?{type:"literal",value:e.count,raw:String(e.count),...Jk}:Zk(e.count),t.loopVariant="times");return t}(e);case"foreach":return function(e){return{type:"command",name:"repeat",isBlocking:!0,loopVariant:"for",itemName:e.itemName,...e.indexName?{indexName:e.indexName}:{},collection:Zk(e.collection),body:e.body.map(e=>Zk(e)),args:[],...Yk(e)}}(e);case"while":return function(e){return{type:"command",name:"repeat",isBlocking:!0,loopVariant:"while",condition:Zk(e.condition),body:e.body.map(e=>Zk(e)),args:[],...Yk(e)}}(e);case"literal":return{type:"literal",value:e.value,raw:null===e.value?"null":void 0===e.value?"":String(e.value),...Yk(e)};case"identifier":return{type:"identifier",name:e.name??e.value,...Yk(e)};case"selector":return{type:"selector",value:e.value,...Yk(e)};case"variable":return{type:"identifier",name:e.name,scope:e.scope,...Yk(e)};case"binary":return{type:"binaryExpression",operator:e.operator,left:Zk(e.left),right:Zk(e.right),...Yk(e)};case"unary":return{type:"unaryExpression",operator:e.operator,argument:Zk(e.operand),prefix:!0,...Yk(e)};case"member":return{type:"memberExpression",object:Zk(e.object),property:"string"==typeof e.property?{type:"identifier",name:e.property,...Jk}:Zk(e.property),computed:e.computed??!1,...Yk(e)};case"possessive":return{type:"possessiveExpression",object:Zk(e.object),property:{type:"identifier",name:e.property,...Jk},...Yk(e)};case"call":return{type:"callExpression",callee:Zk(e.callee),arguments:(e.args??[]).map(e=>Zk(e)),...Yk(e)};case"positional":return{type:"callExpression",callee:{type:"identifier",name:e.position,...Jk},arguments:e.target?[Zk(e.target)]:[],...Yk(e)};default:return{type:"literal",value:null,raw:"null",...Jk}}}var Xk,ew,tw;!function(e){e[e.Error=1]="Error",e[e.Warning=2]="Warning",e[e.Information=3]="Information",e[e.Hint=4]="Hint"}(Xk||(Xk={})),function(e){e[e.File=1]="File",e[e.Module=2]="Module",e[e.Namespace=3]="Namespace",e[e.Package=4]="Package",e[e.Class=5]="Class",e[e.Method=6]="Method",e[e.Property=7]="Property",e[e.Field=8]="Field",e[e.Constructor=9]="Constructor",e[e.Enum=10]="Enum",e[e.Interface=11]="Interface",e[e.Function=12]="Function",e[e.Variable=13]="Variable",e[e.Constant=14]="Constant",e[e.String=15]="String",e[e.Number=16]="Number",e[e.Boolean=17]="Boolean",e[e.Array=18]="Array",e[e.Object=19]="Object",e[e.Key=20]="Key",e[e.Null=21]="Null",e[e.EnumMember=22]="EnumMember",e[e.Struct=23]="Struct",e[e.Event=24]="Event",e[e.Operator=25]="Operator",e[e.TypeParameter=26]="TypeParameter"}(ew||(ew={})),function(e){e[e.Text=1]="Text",e[e.Method=2]="Method",e[e.Function=3]="Function",e[e.Constructor=4]="Constructor",e[e.Field=5]="Field",e[e.Variable=6]="Variable",e[e.Class=7]="Class",e[e.Interface=8]="Interface",e[e.Module=9]="Module",e[e.Property=10]="Property",e[e.Unit=11]="Unit",e[e.Value=12]="Value",e[e.Enum=13]="Enum",e[e.Keyword=14]="Keyword",e[e.Snippet=15]="Snippet",e[e.Color=16]="Color",e[e.File=17]="File",e[e.Reference=18]="Reference",e[e.Folder=19]="Folder",e[e.EnumMember=20]="EnumMember",e[e.Constant=21]="Constant",e[e.Struct=22]="Struct",e[e.Event=23]="Event",e[e.Operator=24]="Operator",e[e.TypeParameter=25]="TypeParameter"}(tw||(tw={}));let nw=null;async function rw(){return nw||(nw=await Promise.resolve().then(function(){return Hb})),nw}var iw=Object.freeze({__proto__:null,SemanticGrammarBridge:class{constructor(e={}){this.analyzer=null,this.config={confidenceThreshold:e.confidenceThreshold??rg,fallbackOnLowConfidence:e.fallbackOnLowConfidence??!0}}async initialize(){const e=await rw();this.analyzer=e.createSemanticAnalyzer()}isInitialized(){return null!==this.analyzer}async transform(e,t,n){if(this.isInitialized()||await this.initialize(),t===n)return{output:e,usedSemantic:!1,confidence:1,sourceLang:t,targetLang:n};const r=await rw();try{const i=r.translate(e,t,n);if(i!==e)return{output:i,usedSemantic:!0,confidence:.9,sourceLang:t,targetLang:n}}catch{}return{output:e,usedSemantic:!1,confidence:0,sourceLang:t,targetLang:n}}async parse(e,t){if(this.isInitialized()||await this.initialize(),!this.analyzer)return null;return this.analyzer.analyze(e,t).node??null}async render(e,t){return(await rw()).render(e,t)}async parseToAST(e,t){if(this.isInitialized()||await this.initialize(),!this.analyzer)return null;const n=this.analyzer.analyze(e,t);if(n.confidence>=this.config.confidenceThreshold&&n.node){const e=await rw();try{return e.buildAST(n.node).ast}catch(e){console.warn("[SemanticGrammarBridge] AST build failed, using fallback:",e)}}return null}async parseToASTWithDetails(e,t){if(this.isInitialized()||await this.initialize(),!this.analyzer)return{ast:null,usedDirectPath:!1,confidence:0,lang:t,fallbackText:null};const n=this.analyzer.analyze(e,t),r=await rw();if(n.confidence>=this.config.confidenceThreshold&&n.node)try{const e=r.buildAST(n.node);return{ast:e.ast,usedDirectPath:!0,confidence:n.confidence,lang:t,fallbackText:null,warnings:e.warnings}}catch{}if(n.node&&this.config.fallbackOnLowConfidence){const e=r.render(n.node,"en");return{ast:null,usedDirectPath:!1,confidence:n.confidence,lang:t,fallbackText:e}}return{ast:null,usedDirectPath:!1,confidence:n.confidence,lang:t,fallbackText:null}}async getAllTranslations(e,t){const n=(await rw()).getSupportedLanguages(),r={};for(const i of n)r[i]=await this.transform(e,t,i);return r}}});e.Lexer=hk,e.Runtime=al,e.RuntimeBase=vi,e.Tokens=fk,e.TypedBehaviorsFeatureImplementation=Nk,e.TypedDefFeatureImplementation=Sk,e.TypedEventSourceFeatureImplementation=Fk,e.TypedOnFeatureImplementation=jk,e.TypedSocketsFeatureImplementation=Wk,e.TypedWebWorkerFeatureImplementation=Dk,e.configurePartialValidation=function(e){vo={...vo,...e}},e.createBehaviors=async function(e,t){return(new Nk).initialize({behavior:{name:"defaultBehavior",parameters:[],eventHandlers:[],...e},installation:{parameters:{},autoInstall:!1,scope:"element"},context:{variables:{}},options:{enableLifecycleEvents:!0,enableEventDelegation:!0,enableParameterValidation:!0,maxEventHandlers:50,enableInheritance:!1},environment:"frontend",debug:!1,...t})},e.createBehaviorsFeature=function(){return new Nk},e.createChildContext=_t,e.createContext=Dt,e.createDef=async function(e,t){return(new Sk).initialize({definition:{name:"defaultFunction",parameters:[],body:["return undefined"],isAsync:!1,...e},context:{variables:{}},options:{enableClosures:!0,enableTypeChecking:!0,maxParameterCount:20,allowDynamicParameters:!1},environment:"universal",debug:!1,...t})},e.createDefFeature=function(){return new Sk},e.createEventSource=async function(e,t){return(new Fk).initialize({source:{url:"",withCredentials:!1,headers:{},retry:{enabled:!0,maxAttempts:5,delay:3e3,backoff:"exponential",maxDelay:3e4},timeout:{enabled:!0,duration:6e4},...e},eventHandlers:[],messageProcessing:{format:"text",validation:{enabled:!0},buffer:{enabled:!0,maxSize:100,flushInterval:1e3}},context:{variables:{}},options:{enableAutoConnect:!0,enableMessageBuffer:!0,enableErrorHandling:!0,maxConnections:1,connectionTimeout:3e4},environment:"frontend",debug:!1,...t})},e.createEventSourceFeature=function(){return new Fk},e.createOn=async function(e,t,n){return(new jk).initialize({event:{type:"click",delegated:!1,once:!1,passive:!1,capture:!1,preventDefault:!1,stopPropagation:!1,...e},commands:t,context:{variables:{}},options:{enableErrorHandling:!0,enableEventCapture:!0,enableAsyncExecution:!0,maxCommandCount:100},environment:"frontend",debug:!1,...n})},e.createOnFeature=function(e){return new jk},e.createSockets=async function(e,t){return(new Wk).initialize({socket:{url:"wss://localhost:8080",protocols:[],reconnect:{enabled:!0,maxAttempts:5,delay:1e3,backoff:"exponential",maxDelay:3e4},heartbeat:{enabled:!1,interval:3e4,message:"ping",timeout:5e3},compression:!1,binaryType:"blob",...e},eventHandlers:[],messageHandling:{format:"json",validation:{enabled:!0},queue:{enabled:!0,maxSize:100,persistence:!1}},context:{variables:{}},options:{enableAutoConnect:!0,enableMessageQueue:!0,enableErrorHandling:!0,maxConnections:5,connectionTimeout:1e4},environment:"frontend",debug:!1,...t})},e.createSocketsFeature=function(){return new Wk},e.createWebWorker=async function(e,t){return(new Dk).initialize({worker:{script:"",type:"classic",credentials:"same-origin",inline:!1,...e},messaging:{format:"json",serialization:"structured-clone",transferables:[],validation:{enabled:!0},queue:{enabled:!0,maxSize:100,persistence:!1}},eventHandlers:[],context:{variables:{}},options:{enableAutoStart:!0,enableMessageQueue:!0,enableErrorHandling:!0,maxWorkers:4,workerTimeout:3e4,terminationTimeout:5e3},environment:"frontend",debug:!1,...t})},e.createWebWorkerFeature=function(){return new Dk},e.emitPartialValidationWarnings=No,e.enhancedBehaviorsImplementation=Ok,e.enhancedDefImplementation=Tk,e.enhancedEventSourceImplementation=Uk,e.enhancedOnImplementation=Lk,e.enhancedSocketsImplementation=$k,e.enhancedWebWorkerImplementation=_k,e.formatIssueAsString=Ro,e.formatIssuesAsStrings=Mo,e.formatResultSummary=function(e){if(0===e.totalIssues)return"No validation issues found";const t=[];return e.bySeverity.critical.length>0&&t.push(`${e.bySeverity.critical.length} critical`),e.bySeverity.structural.length>0&&t.push(`${e.bySeverity.structural.length} structural`),e.bySeverity.warning.length>0&&t.push(`${e.bySeverity.warning.length} warning(s)`),`Partial validation: ${t.join(", ")}`},e.fromCoreAST=Gk,e.getPartialValidationConfig=go,e.hyperscript=pk,e.lokascript=mk,e.parse=Nt,e.resetPartialValidationConfig=function(){vo={...yo}},e.toCoreAST=Zk,e.validatePartialContent=ko});
2
+ //# sourceMappingURL=index.min.js.map