@bquery/bquery 1.1.2 → 1.3.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 (307) hide show
  1. package/README.md +501 -323
  2. package/dist/batch-4LAvfLE7.js +13 -0
  3. package/dist/batch-4LAvfLE7.js.map +1 -0
  4. package/dist/component/component.d.ts +69 -0
  5. package/dist/component/component.d.ts.map +1 -0
  6. package/dist/component/html.d.ts +35 -0
  7. package/dist/component/html.d.ts.map +1 -0
  8. package/dist/component/index.d.ts +3 -126
  9. package/dist/component/index.d.ts.map +1 -1
  10. package/dist/component/props.d.ts +18 -0
  11. package/dist/component/props.d.ts.map +1 -0
  12. package/dist/component/types.d.ts +77 -0
  13. package/dist/component/types.d.ts.map +1 -0
  14. package/dist/component.es.mjs +90 -59
  15. package/dist/component.es.mjs.map +1 -1
  16. package/dist/core/collection.d.ts +36 -0
  17. package/dist/core/collection.d.ts.map +1 -1
  18. package/dist/core/dom.d.ts +6 -0
  19. package/dist/core/dom.d.ts.map +1 -0
  20. package/dist/core/element.d.ts +8 -0
  21. package/dist/core/element.d.ts.map +1 -1
  22. package/dist/core/index.d.ts +1 -0
  23. package/dist/core/index.d.ts.map +1 -1
  24. package/dist/core/utils/array.d.ts +74 -0
  25. package/dist/core/utils/array.d.ts.map +1 -0
  26. package/dist/core/utils/function.d.ts +70 -0
  27. package/dist/core/utils/function.d.ts.map +1 -0
  28. package/dist/core/utils/index.d.ts +70 -0
  29. package/dist/core/utils/index.d.ts.map +1 -0
  30. package/dist/core/utils/misc.d.ts +63 -0
  31. package/dist/core/utils/misc.d.ts.map +1 -0
  32. package/dist/core/utils/number.d.ts +65 -0
  33. package/dist/core/utils/number.d.ts.map +1 -0
  34. package/dist/core/utils/object.d.ts +133 -0
  35. package/dist/core/utils/object.d.ts.map +1 -0
  36. package/dist/core/utils/string.d.ts +80 -0
  37. package/dist/core/utils/string.d.ts.map +1 -0
  38. package/dist/core/utils/type-guards.d.ts +79 -0
  39. package/dist/core/utils/type-guards.d.ts.map +1 -0
  40. package/dist/core-COenAZjD.js +145 -0
  41. package/dist/core-COenAZjD.js.map +1 -0
  42. package/dist/core.es.mjs +411 -448
  43. package/dist/core.es.mjs.map +1 -1
  44. package/dist/full.d.ts +8 -2
  45. package/dist/full.d.ts.map +1 -1
  46. package/dist/full.es.mjs +86 -40
  47. package/dist/full.es.mjs.map +1 -1
  48. package/dist/full.iife.js +6 -1
  49. package/dist/full.iife.js.map +1 -1
  50. package/dist/full.umd.js +6 -1
  51. package/dist/full.umd.js.map +1 -1
  52. package/dist/index.d.ts +3 -0
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.es.mjs +137 -44
  55. package/dist/index.es.mjs.map +1 -1
  56. package/dist/motion/animate.d.ts +25 -0
  57. package/dist/motion/animate.d.ts.map +1 -0
  58. package/dist/motion/easing.d.ts +30 -0
  59. package/dist/motion/easing.d.ts.map +1 -0
  60. package/dist/motion/flip.d.ts +55 -0
  61. package/dist/motion/flip.d.ts.map +1 -0
  62. package/dist/motion/index.d.ts +11 -138
  63. package/dist/motion/index.d.ts.map +1 -1
  64. package/dist/motion/keyframes.d.ts +21 -0
  65. package/dist/motion/keyframes.d.ts.map +1 -0
  66. package/dist/motion/reduced-motion.d.ts +12 -0
  67. package/dist/motion/reduced-motion.d.ts.map +1 -0
  68. package/dist/motion/scroll.d.ts +15 -0
  69. package/dist/motion/scroll.d.ts.map +1 -0
  70. package/dist/motion/spring.d.ts +42 -0
  71. package/dist/motion/spring.d.ts.map +1 -0
  72. package/dist/motion/stagger.d.ts +22 -0
  73. package/dist/motion/stagger.d.ts.map +1 -0
  74. package/dist/motion/timeline.d.ts +21 -0
  75. package/dist/motion/timeline.d.ts.map +1 -0
  76. package/dist/motion/transition.d.ts +22 -0
  77. package/dist/motion/transition.d.ts.map +1 -0
  78. package/dist/motion/types.d.ts +182 -0
  79. package/dist/motion/types.d.ts.map +1 -0
  80. package/dist/motion.es.mjs +320 -61
  81. package/dist/motion.es.mjs.map +1 -1
  82. package/dist/persisted-Dz_ryNuC.js +278 -0
  83. package/dist/persisted-Dz_ryNuC.js.map +1 -0
  84. package/dist/reactive/batch.d.ts +13 -0
  85. package/dist/reactive/batch.d.ts.map +1 -0
  86. package/dist/reactive/computed.d.ts +50 -0
  87. package/dist/reactive/computed.d.ts.map +1 -0
  88. package/dist/reactive/core.d.ts +60 -0
  89. package/dist/reactive/core.d.ts.map +1 -0
  90. package/dist/reactive/effect.d.ts +15 -0
  91. package/dist/reactive/effect.d.ts.map +1 -0
  92. package/dist/reactive/index.d.ts +2 -2
  93. package/dist/reactive/index.d.ts.map +1 -1
  94. package/dist/reactive/internals.d.ts +36 -0
  95. package/dist/reactive/internals.d.ts.map +1 -0
  96. package/dist/reactive/linked.d.ts +36 -0
  97. package/dist/reactive/linked.d.ts.map +1 -0
  98. package/dist/reactive/persisted.d.ts +14 -0
  99. package/dist/reactive/persisted.d.ts.map +1 -0
  100. package/dist/reactive/readonly.d.ts +26 -0
  101. package/dist/reactive/readonly.d.ts.map +1 -0
  102. package/dist/reactive/signal.d.ts +13 -305
  103. package/dist/reactive/signal.d.ts.map +1 -1
  104. package/dist/reactive/type-guards.d.ts +20 -0
  105. package/dist/reactive/type-guards.d.ts.map +1 -0
  106. package/dist/reactive/untrack.d.ts +29 -0
  107. package/dist/reactive/untrack.d.ts.map +1 -0
  108. package/dist/reactive/watch.d.ts +42 -0
  109. package/dist/reactive/watch.d.ts.map +1 -0
  110. package/dist/reactive.es.mjs +30 -154
  111. package/dist/reactive.es.mjs.map +1 -1
  112. package/dist/router/index.d.ts +41 -0
  113. package/dist/router/index.d.ts.map +1 -0
  114. package/dist/router/links.d.ts +44 -0
  115. package/dist/router/links.d.ts.map +1 -0
  116. package/dist/router/match.d.ts +20 -0
  117. package/dist/router/match.d.ts.map +1 -0
  118. package/dist/router/navigation.d.ts +45 -0
  119. package/dist/router/navigation.d.ts.map +1 -0
  120. package/dist/router/query.d.ts +16 -0
  121. package/dist/router/query.d.ts.map +1 -0
  122. package/dist/router/router.d.ts +34 -0
  123. package/dist/router/router.d.ts.map +1 -0
  124. package/dist/router/state.d.ts +27 -0
  125. package/dist/router/state.d.ts.map +1 -0
  126. package/dist/router/types.d.ts +88 -0
  127. package/dist/router/types.d.ts.map +1 -0
  128. package/dist/router/utils.d.ts +65 -0
  129. package/dist/router/utils.d.ts.map +1 -0
  130. package/dist/router.es.mjs +202 -0
  131. package/dist/router.es.mjs.map +1 -0
  132. package/dist/sanitize-1FBEPAFH.js +272 -0
  133. package/dist/sanitize-1FBEPAFH.js.map +1 -0
  134. package/dist/security/constants.d.ts +42 -0
  135. package/dist/security/constants.d.ts.map +1 -0
  136. package/dist/security/csp.d.ts +24 -0
  137. package/dist/security/csp.d.ts.map +1 -0
  138. package/dist/security/index.d.ts +4 -2
  139. package/dist/security/index.d.ts.map +1 -1
  140. package/dist/security/sanitize-core.d.ts +13 -0
  141. package/dist/security/sanitize-core.d.ts.map +1 -0
  142. package/dist/security/sanitize.d.ts +5 -57
  143. package/dist/security/sanitize.d.ts.map +1 -1
  144. package/dist/security/trusted-types.d.ts +25 -0
  145. package/dist/security/trusted-types.d.ts.map +1 -0
  146. package/dist/security/types.d.ts +36 -0
  147. package/dist/security/types.d.ts.map +1 -0
  148. package/dist/security.es.mjs +50 -277
  149. package/dist/security.es.mjs.map +1 -1
  150. package/dist/store/create-store.d.ts +15 -0
  151. package/dist/store/create-store.d.ts.map +1 -0
  152. package/dist/store/define-store.d.ts +28 -0
  153. package/dist/store/define-store.d.ts.map +1 -0
  154. package/dist/store/devtools.d.ts +22 -0
  155. package/dist/store/devtools.d.ts.map +1 -0
  156. package/dist/store/index.d.ts +12 -0
  157. package/dist/store/index.d.ts.map +1 -0
  158. package/dist/store/mapping.d.ts +28 -0
  159. package/dist/store/mapping.d.ts.map +1 -0
  160. package/dist/store/persisted.d.ts +13 -0
  161. package/dist/store/persisted.d.ts.map +1 -0
  162. package/dist/store/plugins.d.ts +13 -0
  163. package/dist/store/plugins.d.ts.map +1 -0
  164. package/dist/store/registry.d.ts +28 -0
  165. package/dist/store/registry.d.ts.map +1 -0
  166. package/dist/store/types.d.ts +71 -0
  167. package/dist/store/types.d.ts.map +1 -0
  168. package/dist/store/utils.d.ts +28 -0
  169. package/dist/store/utils.d.ts.map +1 -0
  170. package/dist/store/watch.d.ts +23 -0
  171. package/dist/store/watch.d.ts.map +1 -0
  172. package/dist/store.es.mjs +27 -0
  173. package/dist/store.es.mjs.map +1 -0
  174. package/dist/type-guards-DRma3-Kc.js +16 -0
  175. package/dist/type-guards-DRma3-Kc.js.map +1 -0
  176. package/dist/untrack-BuEQKH7_.js +6 -0
  177. package/dist/untrack-BuEQKH7_.js.map +1 -0
  178. package/dist/view/directives/bind.d.ts +7 -0
  179. package/dist/view/directives/bind.d.ts.map +1 -0
  180. package/dist/view/directives/class.d.ts +8 -0
  181. package/dist/view/directives/class.d.ts.map +1 -0
  182. package/dist/view/directives/for.d.ts +23 -0
  183. package/dist/view/directives/for.d.ts.map +1 -0
  184. package/dist/view/directives/html.d.ts +7 -0
  185. package/dist/view/directives/html.d.ts.map +1 -0
  186. package/dist/view/directives/if.d.ts +7 -0
  187. package/dist/view/directives/if.d.ts.map +1 -0
  188. package/dist/view/directives/index.d.ts +12 -0
  189. package/dist/view/directives/index.d.ts.map +1 -0
  190. package/dist/view/directives/model.d.ts +7 -0
  191. package/dist/view/directives/model.d.ts.map +1 -0
  192. package/dist/view/directives/on.d.ts +7 -0
  193. package/dist/view/directives/on.d.ts.map +1 -0
  194. package/dist/view/directives/ref.d.ts +7 -0
  195. package/dist/view/directives/ref.d.ts.map +1 -0
  196. package/dist/view/directives/show.d.ts +7 -0
  197. package/dist/view/directives/show.d.ts.map +1 -0
  198. package/dist/view/directives/style.d.ts +7 -0
  199. package/dist/view/directives/style.d.ts.map +1 -0
  200. package/dist/view/directives/text.d.ts +7 -0
  201. package/dist/view/directives/text.d.ts.map +1 -0
  202. package/dist/view/evaluate.d.ts +43 -0
  203. package/dist/view/evaluate.d.ts.map +1 -0
  204. package/dist/view/index.d.ts +111 -0
  205. package/dist/view/index.d.ts.map +1 -0
  206. package/dist/view/mount.d.ts +69 -0
  207. package/dist/view/mount.d.ts.map +1 -0
  208. package/dist/view/process.d.ts +26 -0
  209. package/dist/view/process.d.ts.map +1 -0
  210. package/dist/view/types.d.ts +36 -0
  211. package/dist/view/types.d.ts.map +1 -0
  212. package/dist/view.es.mjs +426 -0
  213. package/dist/view.es.mjs.map +1 -0
  214. package/dist/watch-CXyaBC_9.js +58 -0
  215. package/dist/watch-CXyaBC_9.js.map +1 -0
  216. package/package.json +26 -14
  217. package/src/component/component.ts +289 -0
  218. package/src/component/html.ts +53 -0
  219. package/src/component/index.ts +40 -414
  220. package/src/component/props.ts +116 -0
  221. package/src/component/types.ts +85 -0
  222. package/src/core/collection.ts +588 -454
  223. package/src/core/dom.ts +38 -0
  224. package/src/core/element.ts +746 -740
  225. package/src/core/index.ts +43 -0
  226. package/src/core/utils/array.ts +102 -0
  227. package/src/core/utils/function.ts +110 -0
  228. package/src/core/utils/index.ts +83 -0
  229. package/src/core/utils/misc.ts +82 -0
  230. package/src/core/utils/number.ts +78 -0
  231. package/src/core/utils/object.ts +206 -0
  232. package/src/core/utils/string.ts +112 -0
  233. package/src/core/utils/type-guards.ts +112 -0
  234. package/src/full.ts +187 -106
  235. package/src/index.ts +36 -27
  236. package/src/motion/animate.ts +113 -0
  237. package/src/motion/easing.ts +40 -0
  238. package/src/motion/flip.ts +176 -0
  239. package/src/motion/index.ts +41 -358
  240. package/src/motion/keyframes.ts +46 -0
  241. package/src/motion/reduced-motion.ts +17 -0
  242. package/src/motion/scroll.ts +57 -0
  243. package/src/motion/spring.ts +150 -0
  244. package/src/motion/stagger.ts +43 -0
  245. package/src/motion/timeline.ts +246 -0
  246. package/src/motion/transition.ts +51 -0
  247. package/src/motion/types.ts +198 -0
  248. package/src/reactive/batch.ts +22 -0
  249. package/src/reactive/computed.ts +92 -0
  250. package/src/reactive/core.ts +93 -0
  251. package/src/reactive/effect.ts +43 -0
  252. package/src/reactive/index.ts +23 -22
  253. package/src/reactive/internals.ts +105 -0
  254. package/src/reactive/linked.ts +56 -0
  255. package/src/reactive/persisted.ts +74 -0
  256. package/src/reactive/readonly.ts +35 -0
  257. package/src/reactive/signal.ts +20 -506
  258. package/src/reactive/type-guards.ts +22 -0
  259. package/src/reactive/untrack.ts +31 -0
  260. package/src/reactive/watch.ts +73 -0
  261. package/src/router/index.ts +41 -0
  262. package/src/router/links.ts +130 -0
  263. package/src/router/match.ts +106 -0
  264. package/src/router/navigation.ts +71 -0
  265. package/src/router/query.ts +35 -0
  266. package/src/router/router.ts +211 -0
  267. package/src/router/state.ts +46 -0
  268. package/src/router/types.ts +93 -0
  269. package/src/router/utils.ts +116 -0
  270. package/src/security/constants.ts +209 -0
  271. package/src/security/csp.ts +77 -0
  272. package/src/security/index.ts +4 -12
  273. package/src/security/sanitize-core.ts +343 -0
  274. package/src/security/sanitize.ts +66 -625
  275. package/src/security/trusted-types.ts +69 -0
  276. package/src/security/types.ts +40 -0
  277. package/src/store/create-store.ts +329 -0
  278. package/src/store/define-store.ts +48 -0
  279. package/src/store/devtools.ts +45 -0
  280. package/src/store/index.ts +22 -0
  281. package/src/store/mapping.ts +73 -0
  282. package/src/store/persisted.ts +61 -0
  283. package/src/store/plugins.ts +32 -0
  284. package/src/store/registry.ts +51 -0
  285. package/src/store/types.ts +94 -0
  286. package/src/store/utils.ts +141 -0
  287. package/src/store/watch.ts +52 -0
  288. package/src/view/directives/bind.ts +23 -0
  289. package/src/view/directives/class.ts +70 -0
  290. package/src/view/directives/for.ts +275 -0
  291. package/src/view/directives/html.ts +19 -0
  292. package/src/view/directives/if.ts +30 -0
  293. package/src/view/directives/index.ts +11 -0
  294. package/src/view/directives/model.ts +56 -0
  295. package/src/view/directives/on.ts +41 -0
  296. package/src/view/directives/ref.ts +41 -0
  297. package/src/view/directives/show.ts +26 -0
  298. package/src/view/directives/style.ts +47 -0
  299. package/src/view/directives/text.ts +15 -0
  300. package/src/view/evaluate.ts +274 -0
  301. package/src/view/index.ts +112 -0
  302. package/src/view/mount.ts +200 -0
  303. package/src/view/process.ts +92 -0
  304. package/src/view/types.ts +44 -0
  305. package/dist/core/utils.d.ts +0 -313
  306. package/dist/core/utils.d.ts.map +0 -1
  307. package/src/core/utils.ts +0 -444
@@ -0,0 +1 @@
1
+ {"version":3,"file":"view.es.mjs","sources":["../src/view/evaluate.ts","../src/view/directives/bind.ts","../src/view/directives/class.ts","../src/view/directives/for.ts","../src/view/directives/html.ts","../src/view/directives/if.ts","../src/view/directives/model.ts","../src/view/directives/on.ts","../src/view/directives/ref.ts","../src/view/directives/show.ts","../src/view/directives/style.ts","../src/view/directives/text.ts","../src/view/process.ts","../src/view/mount.ts"],"sourcesContent":["import { isComputed, isSignal, type Signal } from '../reactive/index';\nimport type { BindingContext } from './types';\n\n/** Maximum number of cached expression functions before LRU eviction */\nconst MAX_CACHE_SIZE = 500;\n\n/** Compiled function type for expression evaluation */\ntype CompiledFn = (ctx: BindingContext) => unknown;\n\n/**\n * Simple LRU cache for compiled expression functions.\n * Uses Map's insertion order to track recency - accessed items are re-inserted.\n * @internal\n */\nclass LRUCache {\n private cache = new Map<string, CompiledFn>();\n private maxSize: number;\n\n constructor(maxSize: number) {\n this.maxSize = maxSize;\n }\n\n get(key: string): CompiledFn | undefined {\n const value = this.cache.get(key);\n if (value !== undefined) {\n // Move to end (most recently used) by re-inserting\n this.cache.delete(key);\n this.cache.set(key, value);\n }\n return value;\n }\n\n set(key: string, value: CompiledFn): void {\n // Delete first if exists to update insertion order\n if (this.cache.has(key)) {\n this.cache.delete(key);\n } else if (this.cache.size >= this.maxSize) {\n // Evict oldest (first) entry\n const oldest = this.cache.keys().next().value;\n if (oldest !== undefined) {\n this.cache.delete(oldest);\n }\n }\n this.cache.set(key, value);\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n get size(): number {\n return this.cache.size;\n }\n}\n\n/** LRU cache for compiled evaluate functions, keyed by expression string */\nconst evaluateCache = new LRUCache(MAX_CACHE_SIZE);\n\n/** LRU cache for compiled evaluateRaw functions, keyed by expression string */\nconst evaluateRawCache = new LRUCache(MAX_CACHE_SIZE);\n\n/**\n * Clears all cached compiled expression functions.\n * Call this when unmounting views or to free memory after heavy template usage.\n *\n * @example\n * ```ts\n * import { clearExpressionCache } from 'bquery/view';\n *\n * // After destroying a view or when cleaning up\n * clearExpressionCache();\n * ```\n */\nexport const clearExpressionCache = (): void => {\n evaluateCache.clear();\n evaluateRawCache.clear();\n};\n\n/**\n * Creates a proxy that lazily unwraps signals/computed only when accessed.\n * This avoids subscribing to signals that aren't referenced in the expression.\n * @internal\n */\nconst createLazyContext = (context: BindingContext): BindingContext =>\n new Proxy(context, {\n get(target, prop: string | symbol) {\n // Only handle string keys for BindingContext indexing\n if (typeof prop !== 'string') {\n return Reflect.get(target, prop);\n }\n const value = target[prop];\n // Auto-unwrap signals/computed only when actually accessed\n if (isSignal(value) || isComputed(value)) {\n return (value as Signal<unknown>).value;\n }\n return value;\n },\n has(target, prop: string | symbol) {\n // Required for `with` statement to resolve identifiers correctly\n if (typeof prop !== 'string') {\n return Reflect.has(target, prop);\n }\n return prop in target;\n },\n });\n\n/**\n * Evaluates an expression in the given context using `new Function()`.\n *\n * Signals and computed values in the context are lazily unwrapped only when\n * accessed by the expression, avoiding unnecessary subscriptions to unused values.\n *\n * @security **WARNING:** This function uses dynamic code execution via `new Function()`.\n * - NEVER pass expressions derived from user input or untrusted sources\n * - Expressions should only come from developer-controlled templates\n * - Malicious expressions can access and exfiltrate context data\n * - Consider this equivalent to `eval()` in terms of security implications\n *\n * @internal\n */\nexport const evaluate = <T = unknown>(expression: string, context: BindingContext): T => {\n try {\n // Create a proxy that lazily unwraps signals/computed on access\n const lazyContext = createLazyContext(context);\n\n // Use cached function or compile and cache a new one\n let fn = evaluateCache.get(expression);\n if (!fn) {\n // Use `with` to enable direct property access from proxy scope.\n // Note: `new Function()` runs in non-strict mode, so `with` is allowed.\n fn = new Function('$ctx', `with($ctx) { return (${expression}); }`) as (\n ctx: BindingContext\n ) => unknown;\n evaluateCache.set(expression, fn);\n }\n return fn(lazyContext) as T;\n } catch (error) {\n console.error(`bQuery view: Error evaluating \"${expression}\"`, error);\n return undefined as T;\n }\n};\n\n/**\n * Evaluates an expression and returns the raw value (for signal access).\n *\n * @security **WARNING:** Uses dynamic code execution. See {@link evaluate} for security notes.\n * @internal\n */\nexport const evaluateRaw = <T = unknown>(expression: string, context: BindingContext): T => {\n try {\n // Use cached function or compile and cache a new one\n let fn = evaluateRawCache.get(expression);\n if (!fn) {\n // Use `with` to enable direct property access from context scope.\n // Unlike `evaluate`, we don't use a lazy proxy - values are accessed directly.\n fn = new Function('$ctx', `with($ctx) { return (${expression}); }`) as (\n ctx: BindingContext\n ) => unknown;\n evaluateRawCache.set(expression, fn);\n }\n return fn(context) as T;\n } catch (error) {\n console.error(`bQuery view: Error evaluating \"${expression}\"`, error);\n return undefined as T;\n }\n};\n\n/**\n * Parses object expression like \"{ active: isActive, disabled: !enabled }\".\n * Handles nested structures like function calls, arrays, and template literals.\n * @internal\n */\nexport const parseObjectExpression = (expression: string): Record<string, string> => {\n const result: Record<string, string> = {};\n\n // Remove outer braces and trim\n const inner = expression\n .trim()\n .replace(/^\\{|\\}$/g, '')\n .trim();\n if (!inner) return result;\n\n // Split by comma at depth 0, respecting strings and nesting\n const parts: string[] = [];\n let current = '';\n let depth = 0;\n let inString: string | null = null;\n\n for (let i = 0; i < inner.length; i++) {\n const char = inner[i];\n const prevChar = i > 0 ? inner[i - 1] : '';\n\n // Handle string literals (including escape sequences)\n if ((char === '\"' || char === \"'\" || char === '`') && prevChar !== '\\\\') {\n if (inString === null) {\n inString = char;\n } else if (inString === char) {\n inString = null;\n }\n current += char;\n continue;\n }\n\n // Skip if inside string\n if (inString !== null) {\n current += char;\n continue;\n }\n\n // Track nesting depth for parentheses, brackets, and braces\n if (char === '(' || char === '[' || char === '{') {\n depth++;\n current += char;\n } else if (char === ')' || char === ']' || char === '}') {\n depth--;\n current += char;\n } else if (char === ',' && depth === 0) {\n // Top-level comma - split point\n parts.push(current.trim());\n current = '';\n } else {\n current += char;\n }\n }\n\n // Add the last part\n if (current.trim()) {\n parts.push(current.trim());\n }\n\n // Parse each part to extract key and value\n for (const part of parts) {\n // Find the first colon at depth 0 (to handle ternary operators in values)\n let colonIndex = -1;\n let partDepth = 0;\n let partInString: string | null = null;\n\n for (let i = 0; i < part.length; i++) {\n const char = part[i];\n const prevChar = i > 0 ? part[i - 1] : '';\n\n if ((char === '\"' || char === \"'\" || char === '`') && prevChar !== '\\\\') {\n if (partInString === null) {\n partInString = char;\n } else if (partInString === char) {\n partInString = null;\n }\n continue;\n }\n\n if (partInString !== null) continue;\n\n if (char === '(' || char === '[' || char === '{') {\n partDepth++;\n } else if (char === ')' || char === ']' || char === '}') {\n partDepth--;\n } else if (char === ':' && partDepth === 0) {\n colonIndex = i;\n break;\n }\n }\n\n if (colonIndex > -1) {\n const key = part\n .slice(0, colonIndex)\n .trim()\n .replace(/^['\"]|['\"]$/g, '');\n const value = part.slice(colonIndex + 1).trim();\n result[key] = value;\n }\n }\n\n return result;\n};\n","import { effect } from '../../reactive/index';\nimport { evaluate } from '../evaluate';\nimport type { DirectiveHandler } from '../types';\n\n/**\n * Handles bq-bind:attr directive - attribute binding.\n * @internal\n */\nexport const handleBind = (attrName: string): DirectiveHandler => {\n return (el, expression, context, cleanups) => {\n const cleanup = effect(() => {\n const value = evaluate(expression, context);\n if (value == null || value === false) {\n el.removeAttribute(attrName);\n } else if (value === true) {\n el.setAttribute(attrName, '');\n } else {\n el.setAttribute(attrName, String(value));\n }\n });\n cleanups.push(cleanup);\n };\n};\n","import { effect } from '../../reactive/index';\nimport { evaluate, parseObjectExpression } from '../evaluate';\nimport type { DirectiveHandler } from '../types';\n\n/**\n * Handles bq-class directive - dynamic class binding.\n * Tracks previously added classes to ensure proper cleanup when expressions change.\n * @internal\n */\nexport const handleClass: DirectiveHandler = (el, expression, context, cleanups) => {\n // Track classes added by this directive to clean them up on re-evaluation\n let previousClasses: Set<string> = new Set();\n\n const cleanup = effect(() => {\n const newClasses: Set<string> = new Set();\n\n if (expression.trimStart().startsWith('{')) {\n // Object syntax: { active: isActive, disabled: !enabled }\n const classMap = parseObjectExpression(expression);\n for (const [className, conditionExpr] of Object.entries(classMap)) {\n const condition = evaluate<boolean>(conditionExpr, context);\n el.classList.toggle(className, Boolean(condition));\n // Track class regardless of condition - toggle handles add/remove\n newClasses.add(className);\n }\n } else if (/^\\s*\\[/.test(expression)) {\n // Array literal syntax: [class1, class2]\n const classes = evaluate<string[]>(expression, context);\n if (Array.isArray(classes)) {\n for (const cls of classes) {\n if (cls) {\n el.classList.add(cls);\n newClasses.add(cls);\n }\n }\n }\n } else {\n // Single expression returning string or array\n const result = evaluate<string | string[]>(expression, context);\n if (typeof result === 'string') {\n result.split(/\\s+/).forEach((cls) => {\n if (cls) {\n el.classList.add(cls);\n newClasses.add(cls);\n }\n });\n } else if (Array.isArray(result)) {\n result.forEach((cls) => {\n if (cls) {\n el.classList.add(cls);\n newClasses.add(cls);\n }\n });\n }\n }\n\n // Remove classes that were previously added but are no longer in the new set\n // This keeps directive-managed classes in sync across all syntax forms and provides\n // defensive cleanup behavior for edge cases (e.g. external classList changes)\n for (const cls of previousClasses) {\n if (!newClasses.has(cls)) {\n el.classList.remove(cls);\n }\n }\n\n previousClasses = newClasses;\n });\n\n cleanups.push(cleanup);\n};\n","import { effect, signal, type CleanupFn, type Signal } from '../../reactive/index';\nimport { evaluate } from '../evaluate';\nimport type { BindingContext, DirectiveHandler } from '../types';\n\ntype ProcessElementFn = (\n el: Element,\n context: BindingContext,\n prefix: string,\n cleanups: CleanupFn[]\n) => void;\n\ntype ProcessChildrenFn = (\n el: Element,\n context: BindingContext,\n prefix: string,\n cleanups: CleanupFn[]\n) => void;\n\n/**\n * Represents a rendered item in bq-for with its DOM element and associated cleanup functions.\n * @internal\n */\ntype RenderedItem = {\n key: unknown;\n element: Element;\n cleanups: CleanupFn[];\n item: unknown;\n index: number;\n itemSignal: Signal<unknown>; // Reactive item value for item-dependent bindings\n indexSignal: Signal<number> | null; // Reactive index for index-dependent bindings\n};\n\n/**\n * Extracts a key from an item using the key expression or falls back to index.\n * @internal\n */\nconst getItemKey = (\n item: unknown,\n index: number,\n keyExpression: string | null,\n itemName: string,\n indexName: string | undefined,\n context: BindingContext\n): unknown => {\n if (!keyExpression) {\n return index; // Fallback to index-based keying\n }\n\n const keyContext: BindingContext = {\n ...context,\n [itemName]: item,\n };\n if (indexName) {\n keyContext[indexName] = index;\n }\n\n return evaluate(keyExpression, keyContext);\n};\n\n/**\n * Handles bq-for directive - list rendering with keyed reconciliation.\n *\n * Supports optional `:key` attribute for efficient DOM reuse:\n * ```html\n * <li bq-for=\"item in items\" :key=\"item.id\">...</li>\n * ```\n *\n * Without a key, falls back to index-based tracking (less efficient for reordering).\n *\n * @internal\n */\nexport const createForHandler = (options: {\n prefix: string;\n processElement: ProcessElementFn;\n processChildren: ProcessChildrenFn;\n}): DirectiveHandler => {\n const { prefix, processElement, processChildren } = options;\n\n return (el, expression, context, cleanups) => {\n const parent = el.parentNode;\n if (!parent) return;\n\n // Parse expression: \"item in items\" or \"(item, index) in items\"\n // Use \\S.* instead of .+ to prevent ReDoS by requiring non-whitespace start\n const match = expression.match(/^\\(?(\\w+)(?:\\s*,\\s*(\\w+))?\\)?\\s+in\\s+(\\S.*)$/);\n if (!match) {\n console.error(`bQuery view: Invalid bq-for expression \"${expression}\"`);\n return;\n }\n\n const [, itemName, indexName, listExpression] = match;\n\n // Extract :key attribute if present\n const keyExpression = el.getAttribute(':key') || el.getAttribute(`${prefix}-key`);\n\n const template = el.cloneNode(true) as Element;\n template.removeAttribute(`${prefix}-for`);\n template.removeAttribute(':key');\n template.removeAttribute(`${prefix}-key`);\n\n // Create placeholder comment\n const placeholder = document.createComment(`bq-for: ${expression}`);\n parent.replaceChild(placeholder, el);\n\n // Track rendered items by key for reconciliation\n let renderedItemsMap = new Map<unknown, RenderedItem>();\n let renderedOrder: unknown[] = [];\n\n /**\n * Creates a new DOM element for an item.\n */\n const createItemElement = (item: unknown, index: number, key: unknown): RenderedItem => {\n const clone = template.cloneNode(true) as Element;\n const itemCleanups: CleanupFn[] = [];\n\n // Create reactive signals for item and index\n const itemSig = signal(item);\n const indexSig = indexName ? signal(index) : null;\n\n const childContext: BindingContext = {\n ...context,\n [itemName]: itemSig,\n };\n if (indexName && indexSig) {\n childContext[indexName] = indexSig;\n }\n\n // Process bindings on the clone\n processElement(clone, childContext, prefix, itemCleanups);\n processChildren(clone, childContext, prefix, itemCleanups);\n\n return {\n key,\n element: clone,\n cleanups: itemCleanups,\n item,\n index,\n itemSignal: itemSig,\n indexSignal: indexSig,\n };\n };\n\n /**\n * Removes a rendered item and cleans up its effects.\n */\n const removeItem = (rendered: RenderedItem): void => {\n for (const cleanup of rendered.cleanups) {\n cleanup();\n }\n rendered.element.remove();\n };\n\n /**\n * Updates an existing item's data and index when reused.\n * Updates the reactive signals so bindings re-render.\n */\n const updateItem = (rendered: RenderedItem, newItem: unknown, newIndex: number): void => {\n // Update item if it changed\n if (!Object.is(rendered.item, newItem)) {\n rendered.item = newItem;\n rendered.itemSignal.value = newItem;\n }\n\n // Update index if it changed\n if (rendered.index !== newIndex) {\n rendered.index = newIndex;\n if (rendered.indexSignal) {\n rendered.indexSignal.value = newIndex;\n }\n }\n };\n\n const cleanup = effect(() => {\n const list = evaluate<unknown[]>(listExpression, context);\n\n if (!Array.isArray(list)) {\n // Clear all if list is invalid\n for (const rendered of renderedItemsMap.values()) {\n removeItem(rendered);\n }\n renderedItemsMap.clear();\n renderedOrder = [];\n return;\n }\n\n // Build new key order and detect changes\n const newKeys: unknown[] = [];\n const newItemsByKey = new Map<unknown, { item: unknown; index: number }>();\n const seenKeys = new Set<unknown>();\n\n list.forEach((item, index) => {\n let key = getItemKey(item, index, keyExpression, itemName, indexName, context);\n\n // Detect duplicate keys - warn developer and fall back to unique composite key\n if (seenKeys.has(key)) {\n console.warn(\n `bq-for: Duplicate key \"${String(key)}\" detected at index ${index}. ` +\n `Falling back to index-based key for this item. ` +\n `Ensure :key expressions produce unique values for each item.`\n );\n // Create a unique composite key to avoid corrupting rendered output\n key = { __bqDuplicateKey: key, __bqIndex: index };\n }\n seenKeys.add(key);\n\n newKeys.push(key);\n newItemsByKey.set(key, { item, index });\n });\n\n // Identify items to remove (in old but not in new)\n const keysToRemove: unknown[] = [];\n for (const key of renderedOrder) {\n if (!newItemsByKey.has(key)) {\n keysToRemove.push(key);\n }\n }\n\n // Remove deleted items\n for (const key of keysToRemove) {\n const rendered = renderedItemsMap.get(key);\n if (rendered) {\n removeItem(rendered);\n renderedItemsMap.delete(key);\n }\n }\n\n // Process new list: create new items, update indices, reorder\n const newRenderedMap = new Map<unknown, RenderedItem>();\n let lastInsertedElement: Element | Comment = placeholder;\n\n for (let i = 0; i < newKeys.length; i++) {\n const key = newKeys[i];\n const { item, index } = newItemsByKey.get(key)!;\n let rendered = renderedItemsMap.get(key);\n\n if (rendered) {\n // Reuse existing element\n updateItem(rendered, item, index);\n newRenderedMap.set(key, rendered);\n\n // Check if element needs to be moved\n const currentNext: ChildNode | null = lastInsertedElement.nextSibling;\n if (currentNext !== rendered.element) {\n // Move element to correct position\n lastInsertedElement.after(rendered.element);\n }\n lastInsertedElement = rendered.element;\n } else {\n // Create new element\n rendered = createItemElement(item, index, key);\n newRenderedMap.set(key, rendered);\n\n // Insert at correct position\n lastInsertedElement.after(rendered.element);\n lastInsertedElement = rendered.element;\n }\n }\n\n // Update tracking state\n renderedItemsMap = newRenderedMap;\n renderedOrder = newKeys;\n });\n\n // When the bq-for itself is cleaned up, also cleanup all rendered items\n cleanups.push(() => {\n cleanup();\n for (const rendered of renderedItemsMap.values()) {\n for (const itemCleanup of rendered.cleanups) {\n itemCleanup();\n }\n }\n renderedItemsMap.clear();\n });\n };\n};\n","import { effect } from '../../reactive/index';\nimport { sanitizeHtml } from '../../security/index';\nimport { evaluate } from '../evaluate';\nimport type { DirectiveHandler } from '../types';\n\n/**\n * Handles bq-html directive - sets innerHTML (sanitized by default).\n * @internal\n */\nexport const handleHtml = (sanitize: boolean): DirectiveHandler => {\n return (el, expression, context, cleanups) => {\n const cleanup = effect(() => {\n const value = evaluate<string>(expression, context);\n const html = String(value ?? '');\n el.innerHTML = sanitize ? sanitizeHtml(html) : html;\n });\n cleanups.push(cleanup);\n };\n};\n","import { effect } from '../../reactive/index';\nimport { evaluate } from '../evaluate';\nimport type { DirectiveHandler } from '../types';\n\n/**\n * Handles bq-if directive - conditional rendering.\n * @internal\n */\nexport const handleIf: DirectiveHandler = (el, expression, context, cleanups) => {\n const placeholder = document.createComment(`bq-if: ${expression}`);\n\n // Store original element state\n let isInserted = true;\n\n const cleanup = effect(() => {\n const condition = evaluate<boolean>(expression, context);\n\n if (condition && !isInserted) {\n // Insert element using replaceWith to handle moved elements\n placeholder.replaceWith(el);\n isInserted = true;\n } else if (!condition && isInserted) {\n // Remove element using replaceWith to handle moved elements\n el.replaceWith(placeholder);\n isInserted = false;\n }\n });\n\n cleanups.push(cleanup);\n};\n","import { effect, isSignal, type Signal } from '../../reactive/index';\nimport { evaluateRaw } from '../evaluate';\nimport type { DirectiveHandler } from '../types';\n\n/**\n * Handles bq-model directive - two-way binding.\n * @internal\n */\nexport const handleModel: DirectiveHandler = (el, expression, context, cleanups) => {\n const input = el as HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;\n const rawValue = evaluateRaw<Signal<unknown>>(expression, context);\n\n if (!isSignal(rawValue)) {\n console.warn(`bQuery view: bq-model requires a signal, got \"${expression}\"`);\n return;\n }\n\n const sig = rawValue as Signal<unknown>;\n\n // Initial value sync\n const isCheckbox = input.type === 'checkbox';\n const isRadio = input.type === 'radio';\n\n const updateInput = () => {\n if (isCheckbox) {\n (input as HTMLInputElement).checked = Boolean(sig.value);\n } else if (isRadio) {\n (input as HTMLInputElement).checked = sig.value === input.value;\n } else {\n input.value = String(sig.value ?? '');\n }\n };\n\n // Effect to sync signal -> input\n const cleanup = effect(() => {\n updateInput();\n });\n cleanups.push(cleanup);\n\n // Event listener to sync input -> signal\n const eventType = input.tagName === 'SELECT' ? 'change' : 'input';\n const handler = () => {\n if (isCheckbox) {\n sig.value = (input as HTMLInputElement).checked;\n } else if (isRadio) {\n if ((input as HTMLInputElement).checked) {\n sig.value = input.value;\n }\n } else {\n sig.value = input.value;\n }\n };\n\n input.addEventListener(eventType, handler);\n cleanups.push(() => input.removeEventListener(eventType, handler));\n};\n","import { evaluateRaw } from '../evaluate';\nimport type { DirectiveHandler } from '../types';\n\n/**\n * Handles bq-on:event directive - event binding.\n * @internal\n */\nexport const handleOn = (eventName: string): DirectiveHandler => {\n return (el, expression, context, cleanups) => {\n const handler = (event: Event) => {\n // Add $event to context for expression evaluation\n const eventContext = { ...context, $event: event, $el: el };\n\n // Check if expression contains a function call (has parentheses)\n // If not, it might be a plain function reference like \"handleClick\"\n // Note: Method references like \"handlers.onClick\" will lose their receiver\n // when auto-invoked. For methods, use explicit calls: \"handlers.onClick($event)\"\n const containsCall = expression.includes('(');\n\n if (!containsCall) {\n // Evaluate the expression - if it returns a function, invoke it with $event\n const result = evaluateRaw<unknown>(expression, eventContext);\n if (typeof result === 'function') {\n // Auto-invoke with event. Note: `this` will be undefined for method references.\n // For proper method binding, use explicit syntax: \"obj.method($event)\"\n result(event);\n return;\n }\n // If not a function, the expression was already evaluated (e.g., \"count.value++\")\n return;\n }\n\n // Otherwise evaluate as expression using evaluateRaw to allow signal mutations\n // (e.g., \"count.value++\" or \"handleClick($event)\")\n evaluateRaw(expression, eventContext);\n };\n\n el.addEventListener(eventName, handler);\n cleanups.push(() => el.removeEventListener(eventName, handler));\n };\n};\n","import { isSignal, type Signal } from '../../reactive/index';\nimport { evaluateRaw } from '../evaluate';\nimport type { DirectiveHandler } from '../types';\n\n/**\n * Checks if an object has a writable `value` property.\n * Returns true if `value` is an own data property or an accessor with a setter.\n * @internal\n */\nfunction hasWritableValue(obj: object): obj is { value: Element | null } {\n const descriptor = Object.getOwnPropertyDescriptor(obj, 'value');\n if (!descriptor) return false;\n // Data property: check writable flag\n if ('value' in descriptor) return descriptor.writable === true;\n // Accessor property: check for setter\n return typeof descriptor.set === 'function';\n}\n\n/**\n * Handles bq-ref directive - element reference.\n * @internal\n */\nexport const handleRef: DirectiveHandler = (el, expression, context, cleanups) => {\n const rawValue = evaluateRaw<Signal<Element | null> | { value: Element | null }>(\n expression,\n context\n );\n\n if (isSignal(rawValue)) {\n rawValue.value = el;\n cleanups.push(() => {\n rawValue.value = null;\n });\n } else if (typeof rawValue === 'object' && rawValue !== null && hasWritableValue(rawValue)) {\n // Object with writable .value property (e.g., { value: null })\n rawValue.value = el;\n cleanups.push(() => {\n rawValue.value = null;\n });\n }\n};\n","import { effect } from '../../reactive/index';\nimport { evaluate } from '../evaluate';\nimport type { DirectiveHandler } from '../types';\n\n/**\n * Handles bq-show directive - toggle visibility.\n * @internal\n */\nexport const handleShow: DirectiveHandler = (el, expression, context, cleanups) => {\n const htmlEl = el as HTMLElement;\n // Capture the computed display value to properly restore visibility.\n // If inline display is 'none' or empty, we need to use the computed value.\n // Use ownerDocument.defaultView for cross-document/iframe compatibility.\n let originalDisplay = htmlEl.style.display;\n if (!originalDisplay || originalDisplay === 'none') {\n const computed = htmlEl.ownerDocument.defaultView?.getComputedStyle(htmlEl).display ?? '';\n originalDisplay = computed !== 'none' ? computed : '';\n }\n\n const cleanup = effect(() => {\n const condition = evaluate<boolean>(expression, context);\n htmlEl.style.display = condition ? originalDisplay : 'none';\n });\n\n cleanups.push(cleanup);\n};\n","import { effect } from '../../reactive/index';\nimport { evaluate, parseObjectExpression } from '../evaluate';\nimport type { DirectiveHandler } from '../types';\n\n/**\n * Handles bq-style directive - dynamic style binding.\n * @internal\n */\nexport const handleStyle: DirectiveHandler = (el, expression, context, cleanups) => {\n const htmlEl = el as HTMLElement;\n let appliedStyles: Set<string> = new Set();\n\n const cleanup = effect(() => {\n const newStyles = new Set<string>();\n\n if (expression.trimStart().startsWith('{')) {\n const styleMap = parseObjectExpression(expression);\n for (const [prop, valueExpr] of Object.entries(styleMap)) {\n const value = evaluate<string>(valueExpr, context);\n const cssProp = prop.replace(/([A-Z])/g, '-$1').toLowerCase();\n htmlEl.style.setProperty(cssProp, String(value ?? ''));\n newStyles.add(cssProp);\n }\n } else {\n const result = evaluate<Record<string, string>>(expression, context);\n if (result && typeof result === 'object') {\n for (const [prop, value] of Object.entries(result)) {\n const cssProp = prop.replace(/([A-Z])/g, '-$1').toLowerCase();\n htmlEl.style.setProperty(cssProp, String(value ?? ''));\n newStyles.add(cssProp);\n }\n }\n }\n\n // Remove styles that were previously applied but are no longer present\n for (const cssProp of appliedStyles) {\n if (!newStyles.has(cssProp)) {\n htmlEl.style.removeProperty(cssProp);\n }\n }\n\n // Update the set of applied styles\n appliedStyles = newStyles;\n });\n\n cleanups.push(cleanup);\n};\n","import { effect } from '../../reactive/index';\nimport { evaluate } from '../evaluate';\nimport type { DirectiveHandler } from '../types';\n\n/**\n * Handles bq-text directive - sets text content.\n * @internal\n */\nexport const handleText: DirectiveHandler = (el, expression, context, cleanups) => {\n const cleanup = effect(() => {\n const value = evaluate(expression, context);\n el.textContent = String(value ?? '');\n });\n cleanups.push(cleanup);\n};\n","import type { CleanupFn } from '../reactive/index';\nimport type { BindingContext, DirectiveHandler } from './types';\n\nexport type DirectiveHandlers = {\n text: DirectiveHandler;\n html: DirectiveHandler;\n if: DirectiveHandler;\n show: DirectiveHandler;\n class: DirectiveHandler;\n style: DirectiveHandler;\n model: DirectiveHandler;\n ref: DirectiveHandler;\n for: DirectiveHandler;\n bind: (attrName: string) => DirectiveHandler;\n on: (eventName: string) => DirectiveHandler;\n};\n\n/**\n * Processes a single element for directives.\n * @internal\n */\nexport const processElement = (\n el: Element,\n context: BindingContext,\n prefix: string,\n cleanups: CleanupFn[],\n handlers: DirectiveHandlers\n): void => {\n const attributes = Array.from(el.attributes);\n\n for (const attr of attributes) {\n const { name, value } = attr;\n\n if (!name.startsWith(`${prefix}-`)) continue;\n\n const directive = name.slice(prefix.length + 1); // Remove prefix and dash\n\n // Handle bq-for specially (creates new scope)\n if (directive === 'for') {\n handlers.for(el, value, context, cleanups);\n return; // Don't process children, bq-for handles it\n }\n\n // Handle other directives\n if (directive === 'text') {\n handlers.text(el, value, context, cleanups);\n } else if (directive === 'html') {\n handlers.html(el, value, context, cleanups);\n } else if (directive === 'if') {\n handlers.if(el, value, context, cleanups);\n } else if (directive === 'show') {\n handlers.show(el, value, context, cleanups);\n } else if (directive === 'class') {\n handlers.class(el, value, context, cleanups);\n } else if (directive === 'style') {\n handlers.style(el, value, context, cleanups);\n } else if (directive === 'model') {\n handlers.model(el, value, context, cleanups);\n } else if (directive === 'ref') {\n handlers.ref(el, value, context, cleanups);\n } else if (directive.startsWith('bind:')) {\n const attrName = directive.slice(5);\n handlers.bind(attrName)(el, value, context, cleanups);\n } else if (directive.startsWith('on:')) {\n const eventName = directive.slice(3);\n handlers.on(eventName)(el, value, context, cleanups);\n }\n }\n};\n\n/**\n * Recursively processes children of an element.\n * @internal\n */\nexport const processChildren = (\n el: Element,\n context: BindingContext,\n prefix: string,\n cleanups: CleanupFn[],\n handlers: DirectiveHandlers\n): void => {\n const children = Array.from(el.children);\n for (const child of children) {\n // Skip if element has bq-for (handled separately)\n if (!child.hasAttribute(`${prefix}-for`)) {\n processElement(child, context, prefix, cleanups, handlers);\n processChildren(child, context, prefix, cleanups, handlers);\n } else {\n processElement(child, context, prefix, cleanups, handlers);\n }\n }\n};\n","import type { CleanupFn } from '../reactive/index';\nimport {\n createForHandler,\n handleBind,\n handleClass,\n handleHtml,\n handleIf,\n handleModel,\n handleOn,\n handleRef,\n handleShow,\n handleStyle,\n handleText,\n} from './directives/index';\nimport { processChildren, processElement, type DirectiveHandlers } from './process';\nimport type { BindingContext, MountOptions, View } from './types';\n\n/**\n * Mounts a reactive view to an element.\n *\n * @param selector - CSS selector or Element\n * @param context - Binding context with signals, computed, and functions\n * @param options - Mount options\n * @returns The mounted View instance\n *\n * @security **WARNING:** Directive expressions (bq-text, bq-if, bq-on, etc.) are evaluated\n * using `new Function()` at runtime. This means:\n * - Template attributes must come from trusted sources only\n * - NEVER load templates containing bq-* attributes from user input or untrusted APIs\n * - If you must use external templates, validate/sanitize attribute values first\n *\n * @example\n * ```ts\n * import { mount } from 'bquery/view';\n * import { signal, computed } from 'bquery/reactive';\n *\n * const name = signal('World');\n * const greeting = computed(() => `Hello, ${name.value}!`);\n * const items = signal([\n * { id: 1, text: 'Item 1' },\n * { id: 2, text: 'Item 2' },\n * ]);\n *\n * const view = mount('#app', {\n * name,\n * greeting,\n * items,\n * addItem: () => {\n * items.value = [...items.value, { id: Date.now(), text: 'New Item' }];\n * },\n * });\n *\n * // Later, cleanup\n * view.destroy();\n * ```\n */\nexport const mount = (\n selector: string | Element,\n context: BindingContext,\n options: MountOptions = {}\n): View => {\n const { prefix = 'bq', sanitize = true } = options;\n\n const el = typeof selector === 'string' ? document.querySelector(selector) : selector;\n\n if (!el) {\n throw new Error(`bQuery view: Element \"${selector}\" not found.`);\n }\n\n // Reject if root element has bq-for directive\n // bq-for replaces the element with a placeholder comment, which would leave View.el detached\n if (el.hasAttribute(`${prefix}-for`)) {\n throw new Error(\n `bQuery view: Cannot mount on element with ${prefix}-for directive. ` +\n `Wrap the ${prefix}-for element in a container instead.`\n );\n }\n\n const cleanups: CleanupFn[] = [];\n\n const handlers: DirectiveHandlers = {\n text: handleText,\n html: handleHtml(sanitize),\n if: handleIf,\n show: handleShow,\n class: handleClass,\n style: handleStyle,\n model: handleModel,\n ref: handleRef,\n for: createForHandler({\n prefix,\n processElement: (node, nodeContext, nodePrefix, nodeCleanups) =>\n processElement(node, nodeContext, nodePrefix, nodeCleanups, handlers),\n processChildren: (node, nodeContext, nodePrefix, nodeCleanups) =>\n processChildren(node, nodeContext, nodePrefix, nodeCleanups, handlers),\n }),\n bind: handleBind,\n on: handleOn,\n };\n\n const processWithHandlers = (\n node: Element,\n nodeContext: BindingContext,\n nodeCleanups: CleanupFn[]\n ) => {\n // Check if element has bq-for before processing\n // bq-for replaces the element and handles its children internally\n const hasFor = node.hasAttribute(`${prefix}-for`);\n\n processElement(node, nodeContext, prefix, nodeCleanups, handlers);\n\n // Skip processChildren if bq-for was on this element - it handles children itself\n if (!hasFor) {\n processChildren(node, nodeContext, prefix, nodeCleanups, handlers);\n }\n };\n\n // Process the root element and its children\n processWithHandlers(el, context, cleanups);\n\n return {\n el,\n context,\n\n update: (newContext: Partial<BindingContext>) => {\n Object.assign(context, newContext);\n },\n\n destroy: () => {\n for (const cleanup of cleanups) {\n cleanup();\n }\n cleanups.length = 0;\n },\n };\n};\n\n/**\n * Creates a reactive template function.\n *\n * @param template - HTML template string\n * @returns A function that creates a mounted element with the given context\n *\n * @example\n * ```ts\n * import { createTemplate } from 'bquery/view';\n * import { signal } from 'bquery/reactive';\n *\n * const TodoItem = createTemplate(`\n * <li bq-class=\"{ completed: done }\">\n * <input type=\"checkbox\" bq-model=\"done\" />\n * <span bq-text=\"text\"></span>\n * </li>\n * `);\n *\n * const item = TodoItem({\n * done: signal(false),\n * text: 'Buy groceries',\n * });\n *\n * document.querySelector('#list').append(item.el);\n * ```\n */\nexport const createTemplate = (\n template: string,\n options: MountOptions = {}\n): ((context: BindingContext) => View) => {\n return (context: BindingContext) => {\n const container = document.createElement('div');\n container.innerHTML = template.trim();\n\n const el = container.firstElementChild;\n if (!el) {\n throw new Error('bQuery view: Template must contain a single root element.');\n }\n\n // We know at least one element exists (firstElementChild is not null above)\n // Reject if there are multiple root elements\n if (container.childElementCount > 1) {\n throw new Error(\n `bQuery view: Template must contain exactly one root element, found ${container.childElementCount}.`\n );\n }\n\n const { prefix = 'bq' } = options;\n // Reject templates with bq-for or bq-if on the root element\n // These directives replace the element with a placeholder comment, which would leave View.el detached\n // Since processing happens while el is still in the temporary container, the placeholder\n // would remain there while view.el is inserted elsewhere, causing desync on future toggles\n if (el.hasAttribute(`${prefix}-for`) || el.hasAttribute(`${prefix}-if`)) {\n const directive = el.hasAttribute(`${prefix}-for`) ? 'for' : 'if';\n throw new Error(\n `bQuery view: Template root element cannot have ${prefix}-${directive} directive. ` +\n `Wrap the ${prefix}-${directive} element in a container instead.`\n );\n }\n\n return mount(el, context, options);\n };\n};\n"],"names":["MAX_CACHE_SIZE","LRUCache","maxSize","key","value","oldest","evaluateCache","evaluateRawCache","clearExpressionCache","createLazyContext","context","target","prop","isSignal","isComputed","evaluate","expression","lazyContext","fn","error","evaluateRaw","parseObjectExpression","result","inner","parts","current","depth","inString","i","char","prevChar","part","colonIndex","partDepth","partInString","handleBind","attrName","el","cleanups","cleanup","effect","handleClass","previousClasses","newClasses","classMap","className","conditionExpr","condition","classes","cls","getItemKey","item","index","keyExpression","itemName","indexName","keyContext","createForHandler","options","prefix","processElement","processChildren","parent","match","listExpression","template","placeholder","renderedItemsMap","renderedOrder","createItemElement","clone","itemCleanups","itemSig","signal","indexSig","childContext","removeItem","rendered","updateItem","newItem","newIndex","list","newKeys","newItemsByKey","seenKeys","keysToRemove","newRenderedMap","lastInsertedElement","itemCleanup","handleHtml","sanitize","html","sanitizeHtml","handleIf","isInserted","handleModel","input","rawValue","sig","isCheckbox","isRadio","updateInput","eventType","handler","handleOn","eventName","event","eventContext","hasWritableValue","obj","descriptor","handleRef","handleShow","htmlEl","originalDisplay","computed","handleStyle","appliedStyles","newStyles","styleMap","valueExpr","cssProp","handleText","handlers","attributes","attr","name","directive","children","child","mount","selector","node","nodeContext","nodePrefix","nodeCleanups","hasFor","newContext","createTemplate","container"],"mappings":";;;;;AAIA,MAAMA,IAAiB;AAUvB,MAAMC,EAAS;AAAA,EAIb,YAAYC,GAAiB;AAH7B,SAAQ,4BAAY,IAAA,GAIlB,KAAK,UAAUA;AAAA,EACjB;AAAA,EAEA,IAAIC,GAAqC;AACvC,UAAMC,IAAQ,KAAK,MAAM,IAAID,CAAG;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AGoBtF,GAAI3B,GAAS4B,CAAQ,GAElC;AAAA,IACL,IAAAD;AAAA,IACA,SAAA3B;AAAA,IAEA,QAAQ,CAAC+H,MAAwC;AAC/C,aAAO,OAAO/H,GAAS+H,CAAU;AAAA,IACnC;AAAA,IAEA,SAAS,MAAM;AACb,iBAAWlG,KAAWD;AACpB,QAAAC,EAAA;AAEF,MAAAD,EAAS,SAAS;AAAA,IACpB;AAAA,EAAA;AAEJ,GA4BaoG,KAAiB,CAC5BzE,GACAP,IAAwB,OAEjB,CAAChD,MAA4B;AAClC,QAAMiI,IAAY,SAAS,cAAc,KAAK;AAC9C,EAAAA,EAAU,YAAY1E,EAAS,KAAA;AAE/B,QAAM5B,IAAKsG,EAAU;AACrB,MAAI,CAACtG;AACH,UAAM,IAAI,MAAM,2DAA2D;AAK7E,MAAIsG,EAAU,oBAAoB;AAChC,UAAM,IAAI;AAAA,MACR,sEAAsEA,EAAU,iBAAiB;AAAA,IAAA;AAIrG,QAAM,EAAE,QAAAhF,IAAS,KAAA,IAASD;AAK1B,MAAIrB,EAAG,aAAa,GAAGsB,CAAM,MAAM,KAAKtB,EAAG,aAAa,GAAGsB,CAAM,KAAK,GAAG;AACvE,UAAMoE,IAAY1F,EAAG,aAAa,GAAGsB,CAAM,MAAM,IAAI,QAAQ;AAC7D,UAAM,IAAI;AAAA,MACR,kDAAkDA,CAAM,IAAIoE,CAAS,wBACvDpE,CAAM,IAAIoE,CAAS;AAAA,IAAA;AAAA,EAErC;AAEA,SAAOG,GAAM7F,GAAI3B,GAASgD,CAAO;AACnC;"}
@@ -0,0 +1,58 @@
1
+ import { s as c } from "./core-COenAZjD.js";
2
+ import { e as n } from "./type-guards-DRma3-Kc.js";
3
+ const m = (s, o) => {
4
+ let l = !1, t = null;
5
+ try {
6
+ if (t = globalThis.localStorage, t) {
7
+ const e = `__bquery_test_${Math.random().toString(36).slice(2, 9)}__`, a = "__test__";
8
+ try {
9
+ t.setItem(e, a), t.getItem(e), l = !0;
10
+ } finally {
11
+ try {
12
+ t.removeItem(e);
13
+ } catch {
14
+ }
15
+ }
16
+ }
17
+ } catch {
18
+ l = !1;
19
+ }
20
+ let i = o;
21
+ if (l && t)
22
+ try {
23
+ const e = t.getItem(s);
24
+ e !== null && (i = JSON.parse(e));
25
+ } catch {
26
+ }
27
+ const r = c(i);
28
+ return l && t && n(() => {
29
+ try {
30
+ t.setItem(s, JSON.stringify(r.value));
31
+ } catch {
32
+ }
33
+ }), r;
34
+ }, g = (s) => ({
35
+ get value() {
36
+ return s.value;
37
+ },
38
+ peek() {
39
+ return s.peek();
40
+ }
41
+ }), _ = (s, o, l = {}) => {
42
+ const { immediate: t = !1, equals: i = Object.is } = l;
43
+ let r, e = !0;
44
+ return n(() => {
45
+ const a = s.value;
46
+ if (e) {
47
+ e = !1, r = a, t && o(a, void 0);
48
+ return;
49
+ }
50
+ i(a, r) || (o(a, r), r = a);
51
+ });
52
+ };
53
+ export {
54
+ m as p,
55
+ g as r,
56
+ _ as w
57
+ };
58
+ //# sourceMappingURL=watch-CXyaBC_9.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"watch-CXyaBC_9.js","sources":["../src/reactive/persisted.ts","../src/reactive/readonly.ts","../src/reactive/watch.ts"],"sourcesContent":["/**\n * LocalStorage-backed signals.\n */\n\nimport { signal, Signal } from './core';\nimport { effect } from './effect';\n\n/**\n * Creates a signal that persists to localStorage.\n *\n * @template T - The type of the signal value\n * @param key - The localStorage key\n * @param initialValue - The initial value if not found in storage\n * @returns A Signal that syncs with localStorage (falls back to in-memory if unavailable)\n */\nexport const persistedSignal = <T>(key: string, initialValue: T): Signal<T> => {\n // Check if localStorage is available and accessible\n let hasLocalStorage = false;\n let storage: Storage | null = null;\n\n try {\n // In Safari private mode, accessing localStorage can throw SecurityError\n storage = globalThis.localStorage;\n if (storage) {\n // Test actual access to ensure it's not just present but usable\n // Use a randomized test key to avoid overwriting real user data\n const testKey = `__bquery_test_${Math.random().toString(36).slice(2, 9)}__`;\n const testValue = '__test__';\n try {\n storage.setItem(testKey, testValue);\n storage.getItem(testKey);\n hasLocalStorage = true;\n } finally {\n // Ensure we don't leave any test data behind\n try {\n storage.removeItem(testKey);\n } catch {\n // Ignore cleanup errors (e.g., storage becoming unavailable)\n }\n }\n }\n } catch {\n // localStorage unavailable or access denied (Safari private mode, sandboxed iframes, etc.)\n hasLocalStorage = false;\n }\n\n let stored: T = initialValue;\n\n if (hasLocalStorage && storage) {\n try {\n const raw = storage.getItem(key);\n if (raw !== null) {\n stored = JSON.parse(raw) as T;\n }\n } catch {\n // Use initial value on parse error or access denial\n }\n }\n\n const sig = signal(stored);\n\n // Only set up persistence effect if localStorage is available\n if (hasLocalStorage && storage) {\n effect(() => {\n try {\n storage!.setItem(key, JSON.stringify(sig.value));\n } catch {\n // Ignore storage errors (quota exceeded, sandboxed iframes, etc.)\n }\n });\n }\n\n return sig;\n};\n","/**\n * Read-only signal wrappers.\n */\n\nimport type { Signal } from './core';\n\n/**\n * A readonly wrapper around a signal that prevents writes.\n * Provides read-only access to a signal's value while maintaining reactivity.\n *\n * @template T - The type of the wrapped value\n */\nexport interface ReadonlySignal<T> {\n /** Gets the current value with dependency tracking. */\n readonly value: T;\n /** Gets the current value without dependency tracking. */\n peek(): T;\n}\n\n/**\n * Creates a read-only view of a signal.\n * Useful for exposing reactive state without allowing modifications.\n *\n * @template T - The type of the signal value\n * @param sig - The signal to wrap\n * @returns A readonly signal wrapper\n */\nexport const readonly = <T>(sig: Signal<T>): ReadonlySignal<T> => ({\n get value(): T {\n return sig.value;\n },\n peek(): T {\n return sig.peek();\n },\n});\n","/**\n * Value watching helpers.\n */\n\nimport type { Computed } from './computed';\nimport type { Signal } from './core';\nimport type { CleanupFn } from './internals';\n\nimport { effect } from './effect';\n\n/**\n * Options for the watch function.\n */\nexport interface WatchOptions<T> {\n /** If true, the callback is invoked immediately with the current value. */\n immediate?: boolean;\n /** Custom equality function. Defaults to Object.is. */\n equals?: (a: T, b: T | undefined) => boolean;\n}\n\n/**\n * Watches a signal or computed value and calls a callback with old and new values.\n * Unlike effect, watch provides access to the previous value.\n * The callback is only invoked when the value actually changes (compared via Object.is or custom equals).\n *\n * @template T - The type of the watched value\n * @param source - The signal or computed to watch\n * @param callback - Function called with (newValue, oldValue) on changes\n * @param options - Watch options\n * @returns A cleanup function to stop watching\n *\n * @example\n * ```ts\n * const count = signal(0);\n * watch(count, (newVal, oldVal) => {\n * console.log(`Changed from ${oldVal} to ${newVal}`);\n * });\n *\n * // With custom equality for objects\n * const user = signal({ id: 1, name: 'Alice' });\n * watch(user, (newVal, oldVal) => { ... }, {\n * equals: (a, b) => a?.id === b?.id\n * });\n * ```\n */\nexport const watch = <T>(\n source: Signal<T> | Computed<T>,\n callback: (newValue: T, oldValue: T | undefined) => void,\n options: WatchOptions<T> = {}\n): CleanupFn => {\n const { immediate = false, equals = Object.is } = options;\n let oldValue: T | undefined;\n let isFirst = true;\n\n return effect(() => {\n const newValue = source.value;\n\n if (isFirst) {\n isFirst = false;\n oldValue = newValue;\n if (immediate) {\n callback(newValue, undefined);\n }\n return;\n }\n\n // Only call callback if value actually changed\n if (!equals(newValue, oldValue)) {\n callback(newValue, oldValue);\n oldValue = newValue;\n }\n });\n};\n"],"names":["persistedSignal","key","initialValue","hasLocalStorage","storage","testKey","testValue","stored","raw","sig","signal","effect","readonly","watch","source","callback","options","immediate","equals","oldValue","isFirst","newValue"],"mappings":";;AAeO,MAAMA,IAAkB,CAAIC,GAAaC,MAA+B;AAE7E,MAAIC,IAAkB,IAClBC,IAA0B;AAE9B,MAAI;AAGF,QADAA,IAAU,WAAW,cACjBA,GAAS;AAGX,YAAMC,IAAU,iBAAiB,KAAK,OAAA,EAAS,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC,CAAC,MACjEC,IAAY;AAClB,UAAI;AACF,QAAAF,EAAQ,QAAQC,GAASC,CAAS,GAClCF,EAAQ,QAAQC,CAAO,GACvBF,IAAkB;AAAA,MACpB,UAAA;AAEE,YAAI;AACF,UAAAC,EAAQ,WAAWC,CAAO;AAAA,QAC5B,QAAQ;AAAA,QAER;AAAA,MACF;AAAA,IACF;AAAA,EACF,QAAQ;AAEN,IAAAF,IAAkB;AAAA,EACpB;AAEA,MAAII,IAAYL;AAEhB,MAAIC,KAAmBC;AACrB,QAAI;AACF,YAAMI,IAAMJ,EAAQ,QAAQH,CAAG;AAC/B,MAAIO,MAAQ,SACVD,IAAS,KAAK,MAAMC,CAAG;AAAA,IAE3B,QAAQ;AAAA,IAER;AAGF,QAAMC,IAAMC,EAAOH,CAAM;AAGzB,SAAIJ,KAAmBC,KACrBO,EAAO,MAAM;AACX,QAAI;AACF,MAAAP,EAAS,QAAQH,GAAK,KAAK,UAAUQ,EAAI,KAAK,CAAC;AAAA,IACjD,QAAQ;AAAA,IAER;AAAA,EACF,CAAC,GAGIA;AACT,GC9CaG,IAAW,CAAIH,OAAuC;AAAA,EACjE,IAAI,QAAW;AACb,WAAOA,EAAI;AAAA,EACb;AAAA,EACA,OAAU;AACR,WAAOA,EAAI,KAAA;AAAA,EACb;AACF,ICWaI,IAAQ,CACnBC,GACAC,GACAC,IAA2B,CAAA,MACb;AACd,QAAM,EAAE,WAAAC,IAAY,IAAO,QAAAC,IAAS,OAAO,OAAOF;AAClD,MAAIG,GACAC,IAAU;AAEd,SAAOT,EAAO,MAAM;AAClB,UAAMU,IAAWP,EAAO;AAExB,QAAIM,GAAS;AACX,MAAAA,IAAU,IACVD,IAAWE,GACPJ,KACFF,EAASM,GAAU,MAAS;AAE9B;AAAA,IACF;AAGA,IAAKH,EAAOG,GAAUF,CAAQ,MAC5BJ,EAASM,GAAUF,CAAQ,GAC3BA,IAAWE;AAAA,EAEf,CAAC;AACH;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bquery/bquery",
3
- "version": "1.1.2",
3
+ "version": "1.3.0",
4
4
  "description": "The jQuery for the Modern Web Platform - Zero build, TypeScript-first library with reactivity, components, and motion",
5
5
  "type": "module",
6
6
  "main": "./dist/full.umd.js",
@@ -10,14 +10,14 @@
10
10
  "jsdelivr": "./dist/full.umd.js",
11
11
  "exports": {
12
12
  ".": {
13
+ "types": "./dist/index.d.ts",
13
14
  "import": "./dist/index.es.mjs",
14
- "require": "./dist/full.umd.js",
15
- "types": "./dist/index.d.ts"
15
+ "require": "./dist/full.umd.js"
16
16
  },
17
17
  "./full": {
18
+ "types": "./dist/full.d.ts",
18
19
  "import": "./dist/full.es.mjs",
19
- "require": "./dist/full.umd.js",
20
- "types": "./dist/full.d.ts"
20
+ "require": "./dist/full.umd.js"
21
21
  },
22
22
  "./core": {
23
23
  "import": "./dist/core.es.mjs",
@@ -42,6 +42,18 @@
42
42
  "./platform": {
43
43
  "import": "./dist/platform.es.mjs",
44
44
  "types": "./dist/platform/index.d.ts"
45
+ },
46
+ "./router": {
47
+ "import": "./dist/router.es.mjs",
48
+ "types": "./dist/router/index.d.ts"
49
+ },
50
+ "./store": {
51
+ "import": "./dist/store.es.mjs",
52
+ "types": "./dist/store/index.d.ts"
53
+ },
54
+ "./view": {
55
+ "import": "./dist/view.es.mjs",
56
+ "types": "./dist/view/index.d.ts"
45
57
  }
46
58
  },
47
59
  "files": [
@@ -103,18 +115,18 @@
103
115
  "node": ">=18.0.0"
104
116
  },
105
117
  "devDependencies": {
106
- "@typescript-eslint/eslint-plugin": "^8.53.1",
107
- "@typescript-eslint/parser": "^8.53.1",
108
- "bun-types": "^1.3.6",
118
+ "@typescript-eslint/eslint-plugin": "^8.54.0",
119
+ "@typescript-eslint/parser": "^8.54.0",
120
+ "bun-types": "^1.3.8",
109
121
  "eslint": "^9.39.2",
110
- "eslint-config-prettier": "^9.1.2",
111
- "globals": "^15.15.0",
112
- "happy-dom": "^20.3.7",
122
+ "eslint-config-prettier": "^10.1.8",
123
+ "globals": "^17.2.0",
124
+ "happy-dom": "^20.4.0",
113
125
  "prettier": "^3.8.1",
114
- "rimraf": "^5.0.10",
115
- "typedoc": "^0.25.13",
126
+ "rimraf": "^6.1.2",
127
+ "typedoc": "^0.28.16",
116
128
  "typescript": "^5.9.3",
117
- "vite": "^5.4.21",
129
+ "vite": "^7.3.1",
118
130
  "vitepress": "^1.6.4"
119
131
  }
120
132
  }
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Web Component factory and registry.
3
+ *
4
+ * @module bquery/component
5
+ */
6
+
7
+ import { sanitizeHtml } from '../security/sanitize';
8
+ import { coercePropValue } from './props';
9
+ import type { ComponentDefinition, PropDefinition } from './types';
10
+
11
+ /**
12
+ * Creates a custom element class for a component definition.
13
+ *
14
+ * This is useful when you want to extend or register the class manually
15
+ * (e.g. with different tag names in tests or custom registries).
16
+ *
17
+ * @template TProps - Type of the component's props
18
+ * @param tagName - The custom element tag name (used for diagnostics)
19
+ * @param definition - The component configuration
20
+ */
21
+ export const defineComponent = <TProps extends Record<string, unknown>>(
22
+ tagName: string,
23
+ definition: ComponentDefinition<TProps>
24
+ ): typeof HTMLElement => {
25
+ class BQueryComponent extends HTMLElement {
26
+ /** Internal state object for the component */
27
+ private readonly state = { ...(definition.state ?? {}) };
28
+ /** Typed props object populated from attributes */
29
+ private props = {} as TProps;
30
+ /** Tracks missing required props for validation during connectedCallback */
31
+ private missingRequiredProps = new Set<string>();
32
+ /** Tracks whether the component has completed its initial mount */
33
+ private hasMounted = false;
34
+
35
+ constructor() {
36
+ super();
37
+ this.attachShadow({ mode: 'open' });
38
+ this.syncProps();
39
+ }
40
+
41
+ /**
42
+ * Returns the list of attributes to observe for changes.
43
+ */
44
+ static get observedAttributes(): string[] {
45
+ return Object.keys(definition.props ?? {});
46
+ }
47
+
48
+ /**
49
+ * Called when the element is added to the DOM.
50
+ */
51
+ connectedCallback(): void {
52
+ try {
53
+ // Defer initial render until all required props are present
54
+ // This allows attributes to be set after element creation
55
+ if (this.missingRequiredProps.size > 0) {
56
+ // Component will mount once all required props are satisfied
57
+ // via attributeChangedCallback
58
+ return;
59
+ }
60
+ this.mount();
61
+ } catch (error) {
62
+ this.handleError(error as Error);
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Performs the initial mount of the component.
68
+ * Called when the element is connected and all required props are present.
69
+ * @internal
70
+ */
71
+ private mount(): void {
72
+ if (this.hasMounted) return;
73
+ definition.beforeMount?.call(this);
74
+ definition.connected?.call(this);
75
+ this.render();
76
+ this.hasMounted = true;
77
+ }
78
+
79
+ /**
80
+ * Called when the element is removed from the DOM.
81
+ */
82
+ disconnectedCallback(): void {
83
+ try {
84
+ definition.disconnected?.call(this);
85
+ } catch (error) {
86
+ this.handleError(error as Error);
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Called when an observed attribute changes.
92
+ */
93
+ attributeChangedCallback(
94
+ _name: string,
95
+ _oldValue: string | null,
96
+ _newValue: string | null
97
+ ): void {
98
+ try {
99
+ this.syncProps();
100
+
101
+ if (this.hasMounted) {
102
+ // Component already mounted - trigger update render
103
+ this.render(true);
104
+ } else if (this.isConnected && this.missingRequiredProps.size === 0) {
105
+ // All required props are now satisfied and element is connected
106
+ // Trigger the deferred initial mount
107
+ this.mount();
108
+ }
109
+ } catch (error) {
110
+ this.handleError(error as Error);
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Handles errors during component lifecycle.
116
+ * @internal
117
+ */
118
+ private handleError(error: Error): void {
119
+ if (definition.onError) {
120
+ definition.onError.call(this, error);
121
+ } else {
122
+ console.error(`bQuery component error in <${tagName}>:`, error);
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Updates a state property and triggers a re-render.
128
+ *
129
+ * @param key - The state property key
130
+ * @param value - The new value
131
+ */
132
+ setState(key: string, value: unknown): void {
133
+ this.state[key] = value;
134
+ this.render(true);
135
+ }
136
+
137
+ /**
138
+ * Gets a state property value.
139
+ *
140
+ * @param key - The state property key
141
+ * @returns The current value
142
+ */
143
+ getState<T = unknown>(key: string): T {
144
+ return this.state[key] as T;
145
+ }
146
+
147
+ /**
148
+ * Synchronizes props from attributes.
149
+ * @internal
150
+ */
151
+ private syncProps(): void {
152
+ const props = definition.props ?? {};
153
+ for (const [key, config] of Object.entries(props) as [string, PropDefinition][]) {
154
+ const attrValue = this.getAttribute(key);
155
+ let value: unknown;
156
+
157
+ if (attrValue == null) {
158
+ if (config.required && config.default === undefined) {
159
+ // Mark as missing instead of throwing - validate during connectedCallback
160
+ this.missingRequiredProps.add(key);
161
+ value = undefined;
162
+ } else {
163
+ value = config.default ?? undefined;
164
+ }
165
+ } else {
166
+ // Attribute is present, remove from missing set if it was there
167
+ if (this.missingRequiredProps.has(key)) {
168
+ this.missingRequiredProps.delete(key);
169
+ }
170
+ value = coercePropValue(attrValue, config);
171
+ }
172
+
173
+ if (config.validator && value !== undefined) {
174
+ const isValid = config.validator(value);
175
+ if (!isValid) {
176
+ throw new Error(
177
+ `bQuery component: validation failed for prop "${key}" with value ${JSON.stringify(value)}`
178
+ );
179
+ }
180
+ }
181
+
182
+ (this.props as Record<string, unknown>)[key] = value;
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Renders the component to its shadow root.
188
+ * @internal
189
+ */
190
+ private render(triggerUpdated = false): void {
191
+ try {
192
+ if (triggerUpdated && definition.beforeUpdate) {
193
+ const shouldUpdate = definition.beforeUpdate.call(this, this.props);
194
+ if (shouldUpdate === false) return;
195
+ }
196
+
197
+ const emit = (event: string, detail?: unknown): void => {
198
+ this.dispatchEvent(new CustomEvent(event, { detail, bubbles: true, composed: true }));
199
+ };
200
+
201
+ if (!this.shadowRoot) return;
202
+
203
+ const markup = definition.render({
204
+ props: this.props,
205
+ state: this.state,
206
+ emit,
207
+ });
208
+
209
+ const sanitizedMarkup = sanitizeHtml(markup);
210
+ this.shadowRoot.innerHTML = sanitizedMarkup;
211
+
212
+ if (definition.styles) {
213
+ const styleElement = document.createElement('style');
214
+ styleElement.textContent = definition.styles;
215
+ this.shadowRoot.prepend(styleElement);
216
+ }
217
+
218
+ if (triggerUpdated) {
219
+ definition.updated?.call(this);
220
+ }
221
+ } catch (error) {
222
+ this.handleError(error as Error);
223
+ }
224
+ }
225
+ }
226
+
227
+ return BQueryComponent;
228
+ };
229
+
230
+ /**
231
+ * Defines and registers a custom Web Component.
232
+ *
233
+ * This function creates a new custom element with the given tag name
234
+ * and configuration. The component uses Shadow DOM for encapsulation
235
+ * and automatically re-renders when observed attributes change.
236
+ *
237
+ * @template TProps - Type of the component's props
238
+ * @param tagName - The custom element tag name (must contain a hyphen)
239
+ * @param definition - The component configuration
240
+ *
241
+ * @example
242
+ * ```ts
243
+ * component('counter-button', {
244
+ * props: {
245
+ * start: { type: Number, default: 0 },
246
+ * },
247
+ * state: { count: 0 },
248
+ * styles: `
249
+ * button { padding: 0.5rem 1rem; }
250
+ * `,
251
+ * connected() {
252
+ * // Use event delegation on shadow root so handler survives re-renders
253
+ * const handleClick = (event: Event) => {
254
+ * const target = event.target as HTMLElement | null;
255
+ * if (target?.matches('button')) {
256
+ * this.setState('count', (this.getState('count') as number) + 1);
257
+ * }
258
+ * };
259
+ * this.shadowRoot?.addEventListener('click', handleClick);
260
+ * // Store handler for cleanup
261
+ * (this as any)._handleClick = handleClick;
262
+ * },
263
+ * disconnected() {
264
+ * // Clean up event listener to prevent memory leaks
265
+ * const handleClick = (this as any)._handleClick;
266
+ * if (handleClick) {
267
+ * this.shadowRoot?.removeEventListener('click', handleClick);
268
+ * }
269
+ * },
270
+ * render({ props, state }) {
271
+ * return html`
272
+ * <button>
273
+ * Count: ${state.count}
274
+ * </button>
275
+ * `;
276
+ * },
277
+ * });
278
+ * ```
279
+ */
280
+ export const component = <TProps extends Record<string, unknown>>(
281
+ tagName: string,
282
+ definition: ComponentDefinition<TProps>
283
+ ): void => {
284
+ const elementClass = defineComponent(tagName, definition);
285
+
286
+ if (!customElements.get(tagName)) {
287
+ customElements.define(tagName, elementClass);
288
+ }
289
+ };
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Tagged template literal for creating HTML strings.
3
+ *
4
+ * This function handles interpolation of values into HTML templates,
5
+ * converting null/undefined to empty strings.
6
+ *
7
+ * @param strings - Template literal string parts
8
+ * @param values - Interpolated values
9
+ * @returns Combined HTML string
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * const name = 'World';
14
+ * const greeting = html`<h1>Hello, ${name}!</h1>`;
15
+ * // Result: '<h1>Hello, World!</h1>'
16
+ * ```
17
+ */
18
+ export const html = (strings: TemplateStringsArray, ...values: unknown[]): string => {
19
+ return strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, '');
20
+ };
21
+
22
+ /**
23
+ * Escapes HTML entities in interpolated values for XSS prevention.
24
+ * Use this when you need to safely embed user content in templates.
25
+ *
26
+ * @param strings - Template literal string parts
27
+ * @param values - Interpolated values to escape
28
+ * @returns Combined HTML string with escaped values
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * const userInput = '<script>alert("xss")</script>';
33
+ * const safe = safeHtml`<div>${userInput}</div>`;
34
+ * // Result: '<div>&lt;script&gt;alert("xss")&lt;/script&gt;</div>'
35
+ * ```
36
+ */
37
+ export const safeHtml = (strings: TemplateStringsArray, ...values: unknown[]): string => {
38
+ const escapeMap: Record<string, string> = {
39
+ '&': '&amp;',
40
+ '<': '&lt;',
41
+ '>': '&gt;',
42
+ '"': '&quot;',
43
+ "'": '&#x27;',
44
+ '`': '&#x60;',
45
+ };
46
+
47
+ const escape = (value: unknown): string => {
48
+ const str = String(value ?? '');
49
+ return str.replace(/[&<>"'`]/g, (char) => escapeMap[char]);
50
+ };
51
+
52
+ return strings.reduce((acc, part, index) => `${acc}${part}${escape(values[index])}`, '');
53
+ };