@stacksjs/stx 0.2.888 → 0.2.890

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 (260) hide show
  1. package/dist/{chunk-c0g30cjs.js → chunk-05x1rd86.js} +2 -2
  2. package/dist/{chunk-6qq3wy3m.js → chunk-062qfv99.js} +2 -2
  3. package/dist/{chunk-s29hp1qw.js → chunk-0jdz31q1.js} +3 -3
  4. package/dist/{chunk-1kc0jyhj.js → chunk-0jkj8thz.js} +1 -1
  5. package/dist/chunk-0k437z3q.js +2 -0
  6. package/dist/chunk-0q0nbq50.js +2 -0
  7. package/dist/{chunk-5ysv0499.js → chunk-0wp23n1d.js} +1 -1
  8. package/dist/{chunk-9f31gs4m.js → chunk-115bb91s.js} +2 -2
  9. package/dist/chunk-12cjs6vs.js +2 -0
  10. package/dist/chunk-1a7a8cjs.js +2 -0
  11. package/dist/{chunk-wpa3r3b9.js → chunk-1bft48gk.js} +2 -2
  12. package/dist/{chunk-9tecekzq.js → chunk-1jtsr42q.js} +18 -18
  13. package/dist/{chunk-vazk5qbh.js → chunk-1knk403z.js} +2 -2
  14. package/dist/chunk-1p4q6t48.js +2 -0
  15. package/dist/chunk-1ph2yhfn.js +3 -0
  16. package/dist/{chunk-c1b0fy70.js → chunk-1t15z230.js} +5 -5
  17. package/dist/{chunk-2assyczz.js → chunk-1w0bqqh5.js} +2 -2
  18. package/dist/chunk-1z6pqvmf.js +2 -0
  19. package/dist/chunk-2nqmw4dv.js +2 -0
  20. package/dist/{chunk-e9tjxnhn.js → chunk-2xnbdqy4.js} +5 -5
  21. package/dist/chunk-35j7gaj5.js +2 -0
  22. package/dist/chunk-3b3mkgpj.js +3 -0
  23. package/dist/{chunk-7mcs59pr.js → chunk-3bsz7zj3.js} +2 -2
  24. package/dist/{chunk-w624s5jf.js → chunk-3qk8vf9m.js} +3 -3
  25. package/dist/chunk-3yvmaphj.js +2 -0
  26. package/dist/{chunk-mk6thhwf.js → chunk-40k0r6z9.js} +2 -2
  27. package/dist/{chunk-6t04tqvh.js → chunk-41z7f41b.js} +2 -2
  28. package/dist/chunk-44teqn0b.js +2 -0
  29. package/dist/{chunk-372xh1g1.js → chunk-49xwf7dk.js} +6 -6
  30. package/dist/chunk-4akw3bym.js +2 -0
  31. package/dist/chunk-4d85str1.js +2 -0
  32. package/dist/{chunk-whsdyf4t.js → chunk-4eescf3s.js} +7 -7
  33. package/dist/chunk-4xbtxeak.js +2 -0
  34. package/dist/chunk-53kcqdjj.js +2 -0
  35. package/dist/{chunk-1xpq83mc.js → chunk-67j2m620.js} +4 -4
  36. package/dist/chunk-690518hw.js +2 -0
  37. package/dist/chunk-6s3jwysv.js +2 -0
  38. package/dist/{chunk-znnvq1jp.js → chunk-6svc4kb8.js} +65 -65
  39. package/dist/chunk-732gb689.js +2 -0
  40. package/dist/{chunk-ah6nc29h.js → chunk-80ky40mm.js} +2 -2
  41. package/dist/chunk-80xzjxah.js +2 -0
  42. package/dist/chunk-850tye3c.js +2 -0
  43. package/dist/{chunk-b8528fra.js → chunk-8ccgty8s.js} +4 -4
  44. package/dist/{chunk-btsgt6w3.js → chunk-8f8qgjjr.js} +2 -2
  45. package/dist/{chunk-ry6w43p6.js → chunk-8hwfdwgn.js} +6 -6
  46. package/dist/chunk-9344rq4r.js +38 -0
  47. package/dist/chunk-94j4p584.js +2 -0
  48. package/dist/{chunk-y76znqmh.js → chunk-97snfzsy.js} +54 -54
  49. package/dist/chunk-9a9cec4x.js +2 -0
  50. package/dist/chunk-9afkttvz.js +2 -0
  51. package/dist/{chunk-0hj5apb9.js → chunk-9rjgq8k4.js} +1 -1
  52. package/dist/chunk-a0aqs5a8.js +3 -0
  53. package/dist/{chunk-9qrgdekg.js → chunk-a3zrwky3.js} +16 -16
  54. package/dist/{chunk-care745q.js → chunk-a7bqrjm5.js} +2 -2
  55. package/dist/{chunk-pm4kn9h2.js → chunk-adsqckg4.js} +10 -10
  56. package/dist/chunk-ah8az9vv.js +2 -0
  57. package/dist/{chunk-605g9qhp.js → chunk-aj5tsksz.js} +9 -9
  58. package/dist/chunk-amb7e0fp.js +2 -0
  59. package/dist/chunk-arr79m90.js +2 -0
  60. package/dist/{chunk-55kwxxm5.js → chunk-b0hj8eg2.js} +2 -2
  61. package/dist/{chunk-r57jz09p.js → chunk-bgfs3mbg.js} +5 -5
  62. package/dist/chunk-bm0mzk3b.js +2 -0
  63. package/dist/{chunk-ymqm898x.js → chunk-bvqgq18r.js} +2 -2
  64. package/dist/{chunk-wbxmn5gk.js → chunk-bw2m1e7g.js} +5 -5
  65. package/dist/{chunk-wm287dz2.js → chunk-c25q87ys.js} +3 -3
  66. package/dist/{chunk-98mj0es1.js → chunk-ch9028z3.js} +1 -1
  67. package/dist/{chunk-sbwvvjkc.js → chunk-cmg9x1ka.js} +3 -3
  68. package/dist/{chunk-11fxbd71.js → chunk-cphc60zw.js} +2 -2
  69. package/dist/{chunk-dj9ztcth.js → chunk-dvjv4c3a.js} +1 -1
  70. package/dist/{chunk-v8e2c2r1.js → chunk-e16ef18k.js} +2 -2
  71. package/dist/chunk-e28czxw3.js +2 -0
  72. package/dist/chunk-e8szp5wa.js +2 -0
  73. package/dist/chunk-eq86wzhr.js +1314 -0
  74. package/dist/chunk-essd43ad.js +2 -0
  75. package/dist/chunk-f60k8j9m.js +2 -0
  76. package/dist/chunk-fsk3rk2x.js +2 -0
  77. package/dist/{chunk-fce8wj3t.js → chunk-g3vce7ka.js} +2 -2
  78. package/dist/{chunk-em6fqvjy.js → chunk-g5nfqzfh.js} +2 -2
  79. package/dist/chunk-gfea8a9y.js +2 -0
  80. package/dist/chunk-hda7t8g6.js +2 -0
  81. package/dist/chunk-hk241gt2.js +2 -0
  82. package/dist/{chunk-c3ca056p.js → chunk-htx5yezj.js} +2 -2
  83. package/dist/{chunk-b0jekg4c.js → chunk-hxws025y.js} +3 -3
  84. package/dist/chunk-hyyh7qxw.js +25 -0
  85. package/dist/chunk-j6fs31va.js +2 -0
  86. package/dist/chunk-j9kejcrx.js +2 -0
  87. package/dist/chunk-j9vfv53x.js +20 -0
  88. package/dist/chunk-jhbz5w30.js +2 -0
  89. package/dist/chunk-jvnsz2x9.js +2 -0
  90. package/dist/chunk-k4x680e3.js +2 -0
  91. package/dist/chunk-k8bk685s.js +2 -0
  92. package/dist/chunk-kexqmwx8.js +2 -0
  93. package/dist/chunk-kfdmm240.js +2 -0
  94. package/dist/{chunk-fepezvdq.js → chunk-kg7vby72.js} +8 -8
  95. package/dist/{chunk-wf8pdjq5.js → chunk-khm56bfm.js} +1 -1
  96. package/dist/{chunk-303vzq80.js → chunk-kk2p2tgv.js} +3 -3
  97. package/dist/chunk-kpjq135z.js +2 -0
  98. package/dist/chunk-kqsm7gf1.js +2 -0
  99. package/dist/{chunk-j51wss7s.js → chunk-kr2400c3.js} +4 -4
  100. package/dist/{chunk-r8xper92.js → chunk-ksmn19qw.js} +2 -2
  101. package/dist/{chunk-7hm1tpw0.js → chunk-mhrnjaka.js} +6 -6
  102. package/dist/chunk-mtfymhy1.js +2 -0
  103. package/dist/{chunk-52mhrbps.js → chunk-n6q1d66k.js} +1 -1
  104. package/dist/chunk-neg6ckjg.js +12 -0
  105. package/dist/{chunk-wscry63p.js → chunk-nhv81gp2.js} +2 -2
  106. package/dist/{chunk-c73c0wf9.js → chunk-nq60tjkz.js} +2 -2
  107. package/dist/{chunk-v47xc2fr.js → chunk-nzpb263k.js} +9 -9
  108. package/dist/{chunk-p33npqjt.js → chunk-p0bjbtdx.js} +33 -33
  109. package/dist/{chunk-gdtj5rfa.js → chunk-p3hbsrk9.js} +6 -6
  110. package/dist/chunk-p82fzxdg.js +2 -0
  111. package/dist/{chunk-0d7ypcjb.js → chunk-pjj54ddk.js} +3 -3
  112. package/dist/{chunk-qsnpqa8q.js → chunk-pnmafbv5.js} +1 -1
  113. package/dist/{chunk-vgsasnwm.js → chunk-pvm48tse.js} +3 -3
  114. package/dist/{chunk-zek9t5za.js → chunk-pwpge9bj.js} +2 -2
  115. package/dist/{chunk-6zq3eh7d.js → chunk-q0y8gv18.js} +2 -2
  116. package/dist/{chunk-7s3j8pqq.js → chunk-qnf7w4xw.js} +3 -3
  117. package/dist/chunk-qsv84cwm.js +2 -0
  118. package/dist/{chunk-xavx271y.js → chunk-r5ecgcx2.js} +5 -5
  119. package/dist/chunk-r7m60q1m.js +2 -0
  120. package/dist/chunk-r98pye4h.js +2 -0
  121. package/dist/{chunk-zf29ahhd.js → chunk-rb2zbdqd.js} +4 -4
  122. package/dist/{chunk-vjfp8n6p.js → chunk-rd663v1m.js} +3 -3
  123. package/dist/{chunk-4nnmrp7w.js → chunk-rf0smj4c.js} +2 -2
  124. package/dist/{chunk-0dq9svfb.js → chunk-sh7a0g09.js} +3 -3
  125. package/dist/chunk-snkbn5y8.js +2 -0
  126. package/dist/chunk-sztr4d5g.js +2 -0
  127. package/dist/{chunk-4c9p434g.js → chunk-t0ttxayz.js} +2 -2
  128. package/dist/{chunk-5ymf5c8m.js → chunk-t3zmfh8w.js} +7 -7
  129. package/dist/chunk-t4gcsbna.js +2 -0
  130. package/dist/chunk-tbh7r1wh.js +2 -0
  131. package/dist/chunk-tspqdt8e.js +2 -0
  132. package/dist/{chunk-6fsnnj5v.js → chunk-v1mwwben.js} +6 -6
  133. package/dist/chunk-v3jyb8k6.js +2 -0
  134. package/dist/chunk-v6gkjg5f.js +3 -0
  135. package/dist/chunk-v90nz5xm.js +54 -0
  136. package/dist/{chunk-7nhgpjjw.js → chunk-vf4ejngv.js} +6 -6
  137. package/dist/chunk-vfcbz0an.js +3 -0
  138. package/dist/{chunk-hxhmhw23.js → chunk-vk2jy6mn.js} +3 -3
  139. package/dist/{chunk-e1qcfesw.js → chunk-vkfw9k1n.js} +8 -8
  140. package/dist/{chunk-mm1eg2pg.js → chunk-vxbvrbqs.js} +10 -10
  141. package/dist/chunk-wedwczed.js +2 -0
  142. package/dist/chunk-wg6fmren.js +4 -0
  143. package/dist/{chunk-s7wp7a2x.js → chunk-whcrca58.js} +31 -31
  144. package/dist/chunk-wmvvrsn0.js +2 -0
  145. package/dist/chunk-wnrh62by.js +2 -0
  146. package/dist/{chunk-q3bkxg2n.js → chunk-wy6vjz1e.js} +21 -21
  147. package/dist/{chunk-mbm3ma63.js → chunk-x5bn2svk.js} +2 -2
  148. package/dist/chunk-x6565mhk.js +2 -0
  149. package/dist/{chunk-brzjass3.js → chunk-xc5esqcb.js} +2 -2
  150. package/dist/{chunk-e2ws79vt.js → chunk-xeyq6d0t.js} +8 -8
  151. package/dist/{chunk-xw291tn7.js → chunk-xmg6bmh6.js} +27 -22
  152. package/dist/{chunk-3fbgpv1d.js → chunk-xvncq3m5.js} +2 -2
  153. package/dist/chunk-xwgdcc7w.js +2 -0
  154. package/dist/chunk-xwrjre34.js +2 -0
  155. package/dist/{chunk-1wkp3pks.js → chunk-xy8smv5e.js} +2 -2
  156. package/dist/{chunk-y8p59h6c.js → chunk-y1d3j2j7.js} +4 -4
  157. package/dist/{chunk-zje94z0k.js → chunk-yesh4dfe.js} +61 -61
  158. package/dist/chunk-ymc1wgb3.js +2 -0
  159. package/dist/{chunk-xy4j8t7w.js → chunk-ytjn0gq2.js} +2 -2
  160. package/dist/chunk-z4tdnfxd.js +2 -0
  161. package/dist/{chunk-w1q86c89.js → chunk-zf68afyh.js} +3 -3
  162. package/dist/{chunk-6c1vm6bs.js → chunk-zkwkhesc.js} +2 -2
  163. package/dist/{chunk-2rmqmajd.js → chunk-zpqjsnz9.js} +3 -3
  164. package/dist/{chunk-vgr7gd8k.js → chunk-zwqkbk2m.js} +2 -2
  165. package/dist/chunk-zxjdfgdx.js +3 -0
  166. package/dist/cli.js +29 -29
  167. package/dist/component-contract.d.ts +1 -0
  168. package/dist/component-contract.js +6 -4
  169. package/dist/component-library.d.ts +2 -1
  170. package/dist/component-library.js +218 -348
  171. package/dist/composition-api.d.ts +7 -1
  172. package/dist/craft-entry.js +2 -2
  173. package/dist/craft.js +2 -2
  174. package/dist/directive-arguments.js +39 -6
  175. package/dist/emits-declaration.d.ts +9 -0
  176. package/dist/emits-declaration.js +64 -0
  177. package/dist/parser/tokenizer.d.ts +2 -1
  178. package/dist/parser/tokenizer.js +7 -5
  179. package/dist/props-declaration.d.ts +66 -0
  180. package/dist/props-declaration.js +379 -0
  181. package/dist/pwa.js +3 -3
  182. package/dist/ssg.js +28 -28
  183. package/dist/utils.js +20 -109
  184. package/package.json +5 -5
  185. package/dist/chunk-000mwmfq.js +0 -1203
  186. package/dist/chunk-043d0en0.js +0 -2
  187. package/dist/chunk-0w66z6eq.js +0 -2
  188. package/dist/chunk-13wd9gf0.js +0 -3
  189. package/dist/chunk-1znqedae.js +0 -2
  190. package/dist/chunk-2drzzjcm.js +0 -2
  191. package/dist/chunk-3c7nt5qp.js +0 -2
  192. package/dist/chunk-3ed2erm6.js +0 -12
  193. package/dist/chunk-3zyzhcd9.js +0 -2
  194. package/dist/chunk-44rb9fk0.js +0 -2
  195. package/dist/chunk-472j3bhp.js +0 -2
  196. package/dist/chunk-4acce1m8.js +0 -2
  197. package/dist/chunk-4kasmp98.js +0 -2
  198. package/dist/chunk-53kkjn23.js +0 -2
  199. package/dist/chunk-5gwvy612.js +0 -2
  200. package/dist/chunk-61vbqrde.js +0 -2
  201. package/dist/chunk-6fpzwryt.js +0 -2
  202. package/dist/chunk-7195598h.js +0 -2
  203. package/dist/chunk-7zvf79vb.js +0 -2
  204. package/dist/chunk-88a735jw.js +0 -2
  205. package/dist/chunk-8v7yjq3b.js +0 -2
  206. package/dist/chunk-94mpe1ny.js +0 -3
  207. package/dist/chunk-97kgrevs.js +0 -4
  208. package/dist/chunk-a8c9j9cj.js +0 -2
  209. package/dist/chunk-acw851e8.js +0 -2
  210. package/dist/chunk-andfvr3g.js +0 -2
  211. package/dist/chunk-aqxh80vh.js +0 -2
  212. package/dist/chunk-ay5zkfdg.js +0 -2
  213. package/dist/chunk-b4gptdtc.js +0 -2
  214. package/dist/chunk-baaw9w7y.js +0 -2
  215. package/dist/chunk-bw2p9h2g.js +0 -2
  216. package/dist/chunk-ce0vv7kz.js +0 -2
  217. package/dist/chunk-d1yj29g2.js +0 -2
  218. package/dist/chunk-dbhmbef1.js +0 -20
  219. package/dist/chunk-dfsykk1r.js +0 -2
  220. package/dist/chunk-e9p596bp.js +0 -2
  221. package/dist/chunk-edysherg.js +0 -25
  222. package/dist/chunk-ftecsa8e.js +0 -2
  223. package/dist/chunk-ge2h5v46.js +0 -2
  224. package/dist/chunk-gqvnz8a7.js +0 -2
  225. package/dist/chunk-j41gp8p3.js +0 -2
  226. package/dist/chunk-jxvccj30.js +0 -2
  227. package/dist/chunk-k5bbre7d.js +0 -2
  228. package/dist/chunk-kd47vgs8.js +0 -2
  229. package/dist/chunk-keqjafdz.js +0 -2
  230. package/dist/chunk-kvxdyg7e.js +0 -3
  231. package/dist/chunk-kz3mejc4.js +0 -2
  232. package/dist/chunk-ngkh0t5b.js +0 -2
  233. package/dist/chunk-nx9895m6.js +0 -2
  234. package/dist/chunk-nxgtt1t1.js +0 -2
  235. package/dist/chunk-nyw2ztar.js +0 -2
  236. package/dist/chunk-p5q27adr.js +0 -2
  237. package/dist/chunk-p6hcrg3r.js +0 -3
  238. package/dist/chunk-pa2vt2ej.js +0 -2
  239. package/dist/chunk-pczb7xav.js +0 -2
  240. package/dist/chunk-ps37r6hj.js +0 -2
  241. package/dist/chunk-pvbhk17r.js +0 -2
  242. package/dist/chunk-q252qvsy.js +0 -2
  243. package/dist/chunk-q5b0vpmm.js +0 -2
  244. package/dist/chunk-qg1kw5yf.js +0 -2
  245. package/dist/chunk-qjy5yq25.js +0 -54
  246. package/dist/chunk-r561zt9v.js +0 -38
  247. package/dist/chunk-sbr85vda.js +0 -2
  248. package/dist/chunk-tkab24xr.js +0 -2
  249. package/dist/chunk-vn59yrjh.js +0 -2
  250. package/dist/chunk-w50yggy3.js +0 -3
  251. package/dist/chunk-w5zzwe2f.js +0 -2
  252. package/dist/chunk-wa9q1gyv.js +0 -2
  253. package/dist/chunk-wbmx0rge.js +0 -2
  254. package/dist/chunk-wpgxhrd7.js +0 -2
  255. package/dist/chunk-x3azrbpr.js +0 -2
  256. package/dist/chunk-x50hk1hq.js +0 -2
  257. package/dist/chunk-xbkbvfcg.js +0 -2
  258. package/dist/chunk-z55rpt3s.js +0 -3
  259. package/dist/chunk-zwde52kw.js +0 -2
  260. package/dist/chunk-zxff7kq9.js +0 -2
@@ -1,4 +1,5 @@
1
1
  import { scanHtmlScriptElements } from "./html-masking.js";
2
+ import { parseEmitsDeclaration } from "./emits-declaration.js";
2
3
  import { mkdir, readFile, readdir, realpath, stat, writeFile } from "node:fs/promises";
3
4
  import path from "node:path";
4
5
  import { builtinModules } from "node:module";
@@ -6,6 +7,8 @@ import { scriptAttributes, scriptContainsCode } from "./script-attributes.js";
6
7
  import { topLevelDeclarationSites } from "./client-parameter-bindings.js";
7
8
  import { bracketDepths, stripCommentsAndLiterals } from "./strip-literals.js";
8
9
  import { Tokenizer } from "./parser/tokenizer.js";
10
+ import { literalValue, localType, parseDefaults, parsePropsDeclaration, skipBalanced, splitTopLevel } from "./props-declaration.js";
11
+ export { parseDefaults } from "./props-declaration.js";
9
12
  function reservedMethodMessage(name) {
10
13
  if (name === "connectedCallback")
11
14
  return `method "${name}" is reserved; define "onConnect" instead, which the element calls once it is connected, rendered and bound`;
@@ -165,22 +168,24 @@ export function methodDeclaration(method) {
165
168
  return `${method.name}${method.generic}(${parameters}): ${method.returns || (method.async ? "Promise<unknown>" : "unknown")}`;
166
169
  }
167
170
  function extractClientMethods(source, file) {
168
- const methods = {}, declarations = {}, types = [], imports = [], scripts = scanHtmlScriptElements(componentScriptSource(source));
171
+ const methods = {}, declarations = {}, types = [], imports = [], scripts = scanHtmlScriptElements(componentScriptSource(source)).map((script) => ({
172
+ code: source.slice(script.bodyStart, script.bodyEnd),
173
+ attributes: scriptAttributes(script.attrs)
174
+ })).filter(({ attributes }) => !["src", "server", "component", "stx:component"].some((name) => attributes.has(name)) && scriptContainsCode(attributes)), combined = scripts.map((script) => script.code).join(`
175
+ `), publicProps = parsePropsDeclaration(combined), publicEmits = parseEmitsDeclaration(combined);
169
176
  for (const script of scripts) {
170
- const code = source.slice(script.bodyStart, script.bodyEnd), attributes = scriptAttributes(script.attrs);
171
- if (attributes.has("src") || attributes.has("server") || attributes.has("component") || attributes.has("stx:component") || !scriptContainsCode(attributes))
172
- continue;
177
+ const { code } = script;
173
178
  try {
174
179
  new Bun.Transpiler({ loader: "ts" }).transformSync(code);
175
180
  } catch (error) {
176
181
  throw Error(`${file}: failed to transpile <script client> (${error.message})`);
177
182
  }
178
- const extracted = attributes.has("client") ? clientMethods(code) : [], overloads = new Set(extracted.filter((method) => !method.source).map((method) => method.name));
183
+ const extracted = clientMethods(code), overloads = new Set(extracted.filter((method) => !method.source).map((method) => method.name));
179
184
  for (const method of extracted) {
180
185
  if (RESERVED_METHODS.has(method.name))
181
186
  throw Error(`${file}: client ${reservedMethodMessage(method.name)}`);
182
187
  if (method.source)
183
- methods[method.name] = new Bun.Transpiler({ loader: "ts" }).transformSync(method.source).trim().replace(/^(?:export\s+)?(async\s+)?function\s+/, "$1");
188
+ methods[method.name] = `${method.name}(...args) { return this._callScopeMethod(${JSON.stringify(method.name)}, args); }`;
184
189
  if (!method.source || !overloads.has(method.name))
185
190
  (declarations[method.name] ??= []).push(methodDeclaration(method));
186
191
  }
@@ -220,20 +225,34 @@ function extractClientMethods(source, file) {
220
225
  } catch {}
221
226
  }
222
227
  }
223
- types.push(code.slice(match.index, cursor).replace(/^export\s+/, "").trim());
228
+ const declaration = code.slice(match.index, cursor), declarationStart = match.index, name = /(?:interface|type)\s+([A-Za-z_$][\w$]*)/.exec(match[0])?.[1], remaining = scripts.map((other) => {
229
+ const body = other === script ? code.slice(0, declarationStart) + code.slice(cursor) : other.code;
230
+ return stripCommentsAndLiterals(body.replace(parsePropsDeclaration(other.code)?.text ?? "\x00", "").replace(parseEmitsDeclaration(other.code)?.text ?? "\x00", ""));
231
+ }).join(`
232
+ `);
233
+ if (!((publicProps?.typeName === name || publicEmits?.typeName === name) && !/^export\s/.test(declaration) && name && !new RegExp(`\\b${name}\\b`).test(remaining)))
234
+ types.push(declaration.replace(/^export\s+/, "").trim());
224
235
  typePattern.lastIndex = cursor + 1;
225
236
  }
226
237
  }
227
238
  const referenced = Object.values(declarations).flat().join(`
228
239
  `) + `
229
240
  ` + types.join(`
230
- `), usedImports = imports.filter((imported) => (imported.binding.match(/[A-Za-z_$][\w$]*/g) || []).filter((name) => !["type", "as"].includes(name)).some((name) => new RegExp(`\\b${name}\\b`).test(referenced)));
241
+ `) + `
242
+ ` + Object.values(publicEmits?.events || {}).map((event) => event.detailType).join(`
243
+ `), referenceTokens = new Tokenizer(referenced, "javascript").tokenize().filter((token) => !["WHITESPACE", "COMMENT"].includes(token.type)), typeReferences = new Set(referenceTokens.filter((token, index) => {
244
+ if (referenceTokens[index - 1]?.value === ".")
245
+ return !1;
246
+ const next = referenceTokens[index + 1]?.value;
247
+ return next !== ":" && !(next === "?" && referenceTokens[index + 2]?.value === ":");
248
+ }).map((token) => token.value)), usedImports = imports.filter((imported) => (imported.binding.match(/[A-Za-z_$][\w$]*/g) || []).filter((name) => !["type", "as"].includes(name)).some((name) => typeReferences.has(name)));
231
249
  for (const imported of usedImports)
232
250
  if (imported.module.startsWith(".") || path.isAbsolute(imported.module))
233
251
  throw Error(`${file}: public method types import ${JSON.stringify(imported.module)} outside the generated package; declare these types in the component or import them from a published dependency`);
234
252
  const typeImports = [...new Set(usedImports.map((imported) => `import type ${imported.binding.replace(/\btype\s+/g, "")} from ${JSON.stringify(imported.module)}`))];
235
- return { methods, declarations, types: [...typeImports, ...types].join(`
253
+ return { methods, declarations, types: types.join(`
236
254
 
255
+ `), typeImports: typeImports.join(`
237
256
  `) };
238
257
  }
239
258
  function extractTemplate(source) {
@@ -271,21 +290,6 @@ function inferPropertyType(fallback) {
271
290
  return "string";
272
291
  return "object";
273
292
  }
274
- function literalValue(fallback) {
275
- if (fallback === "true")
276
- return !0;
277
- if (fallback === "false")
278
- return !1;
279
- if (/^-?\d+(?:\.\d+)?$/.test(fallback))
280
- return Number(fallback);
281
- if (/^['"`]/.test(fallback))
282
- return fallback.slice(1, -1);
283
- try {
284
- return JSON.parse(fallback);
285
- } catch {
286
- return;
287
- }
288
- }
289
293
  export function componentDirectiveExpression(source, open) {
290
294
  if (source[open] !== "(")
291
295
  return null;
@@ -317,7 +321,7 @@ export function parseNativeComponentLoop(expression) {
317
321
  const pair = /^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec(expression.trim());
318
322
  return pair ? { iterable: pair[1], key: pair[2], value: pair[3] } : void 0;
319
323
  }
320
- function compileTemplateToRender(template) {
324
+ function compileTemplateToRender(template, handlers) {
321
325
  const parts = [];
322
326
  let cursor = 0;
323
327
  const source = template.replace(/\{\{--[\s\S]*?--\}\}/g, ""), directive = /@(if|elseif|else|endif|foreach|endforeach)\s*/g;
@@ -326,12 +330,12 @@ function compileTemplateToRender(template) {
326
330
  if (raw === "")
327
331
  return;
328
332
  let index = 0;
329
- const interpolation = /\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g;
333
+ const interpolation = /\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}|(data-stx-on-[\w:-]+=")(\d+)(")/g;
330
334
  let hit;
331
335
  while (hit = interpolation.exec(raw)) {
332
336
  if (hit.index > index)
333
337
  parts.push(`out += ${JSON.stringify(raw.slice(index, hit.index))};`);
334
- parts.push(hit[1] !== void 0 ? `out += __raw(${hit[1]});` : `out += __escape(${hit[2]});`);
338
+ parts.push(hit[3] !== void 0 ? `out += ${JSON.stringify(hit[3])} + (this._handlers.push(${handlers[Number(hit[4])]}) - 1) + ${JSON.stringify(hit[5])};` : hit[1] !== void 0 ? `out += __raw(${hit[1]});` : `out += __escape(${hit[2]});`);
335
339
  index = hit.index + hit[0].length;
336
340
  }
337
341
  if (index < raw.length)
@@ -376,279 +380,6 @@ function compileTemplateToRender(template) {
376
380
  return parts.join(`
377
381
  `);
378
382
  }
379
- function skipBalanced(source, index, open, close) {
380
- if (source[index] !== open)
381
- return -1;
382
- let depth = 0, quote = null;
383
- for (let i = index;i < source.length; i++) {
384
- const char = source[i];
385
- if (quote) {
386
- if (char === "\\") {
387
- i++;
388
- continue;
389
- }
390
- if (char === quote)
391
- quote = null;
392
- continue;
393
- }
394
- if (char === "'" || char === '"' || char === "`") {
395
- quote = char;
396
- continue;
397
- }
398
- if (char === open)
399
- depth++;
400
- else if (char === close) {
401
- if (close === ">" && source[i - 1] === "=")
402
- continue;
403
- depth--;
404
- if (depth === 0)
405
- return i + 1;
406
- }
407
- }
408
- return -1;
409
- }
410
- function splitTopLevel(body, separators, angles) {
411
- const opening = angles ? "([{<" : "([{", closing = angles ? ")]}>" : ")]}", parts = [];
412
- let depth = 0, quote = null, current = "";
413
- for (let i = 0;i < body.length; i++) {
414
- const char = body[i];
415
- if (quote) {
416
- current += char;
417
- if (char === "\\") {
418
- current += body[++i] ?? "";
419
- continue;
420
- }
421
- if (char === quote)
422
- quote = null;
423
- continue;
424
- }
425
- if (char === "'" || char === '"' || char === "`") {
426
- quote = char;
427
- current += char;
428
- continue;
429
- }
430
- if (opening.includes(char))
431
- depth++;
432
- else if (closing.includes(char) && !(angles && char === ">" && body[i - 1] === "="))
433
- depth--;
434
- if (depth === 0 && separators.includes(char)) {
435
- parts.push(current);
436
- current = "";
437
- continue;
438
- }
439
- current += char;
440
- }
441
- parts.push(current);
442
- return parts.map((part) => part.trim()).filter(Boolean);
443
- }
444
- function defaultAssignmentIndex(entry) {
445
- let depth = 0, quote = null;
446
- for (let i = 0;i < entry.length; i++) {
447
- const char = entry[i];
448
- if (quote) {
449
- if (char === "\\") {
450
- i++;
451
- continue;
452
- }
453
- if (char === quote)
454
- quote = null;
455
- continue;
456
- }
457
- if (char === "'" || char === '"' || char === "`") {
458
- quote = char;
459
- continue;
460
- }
461
- if ("([{".includes(char))
462
- depth++;
463
- else if (")]}".includes(char))
464
- depth--;
465
- if (depth !== 0 || char !== "=")
466
- continue;
467
- const previous = entry[i - 1];
468
- if (entry[i + 1] === "=" || previous === "=" || previous === "!" || previous === "<" || previous === ">")
469
- continue;
470
- return i;
471
- }
472
- return -1;
473
- }
474
- function typeFromConstructor(value) {
475
- switch (value.trim()) {
476
- case "String":
477
- return "string";
478
- case "Number":
479
- return "number";
480
- case "Boolean":
481
- return "boolean";
482
- case "Array":
483
- return "unknown[]";
484
- case "Object":
485
- return "Record<string, unknown>";
486
- default:
487
- return;
488
- }
489
- }
490
- function parsePropsDeclaration(code) {
491
- const call = /\bdefineProps\b/.exec(code);
492
- if (!call)
493
- return null;
494
- const keyword = /(?:^|[\s;{}()])(const|let|var)\s+/g;
495
- let start = -1;
496
- for (let found = keyword.exec(code);found && found.index < call.index; found = keyword.exec(code))
497
- start = found.index + found[0].indexOf(found[1]);
498
- if (start === -1)
499
- return null;
500
- const declared = {}, defaults = {}, propNames = [], propBindings = {};
501
- let cursor = start + (/^(?:const|let|var)\s+/.exec(code.slice(start))?.[0].length ?? 0);
502
- const skipSpace = () => {
503
- while (cursor < code.length && /\s/.test(code[cursor]))
504
- cursor++;
505
- };
506
- let pattern;
507
- if (code[cursor] === "{") {
508
- const end = skipBalanced(code, cursor, "{", "}");
509
- if (end === -1)
510
- return null;
511
- pattern = code.slice(cursor, end);
512
- cursor = end;
513
- } else {
514
- const identifier = /^[A-Za-z_$][\w$]*/.exec(code.slice(cursor));
515
- if (!identifier)
516
- return null;
517
- pattern = identifier[0];
518
- cursor += identifier[0].length;
519
- }
520
- skipSpace();
521
- if (code[cursor] !== "=")
522
- return null;
523
- cursor++;
524
- skipSpace();
525
- const wrapper = /^withDefaults\s*\(\s*/.exec(code.slice(cursor)), wrapped = Boolean(wrapper);
526
- if (wrapper)
527
- cursor += wrapper[0].length;
528
- const marker = /^defineProps\b/.exec(code.slice(cursor));
529
- if (!marker)
530
- return null;
531
- cursor += marker[0].length;
532
- let typeText = "";
533
- skipSpace();
534
- if (code[cursor] === "<") {
535
- const end = skipBalanced(code, cursor, "<", ">");
536
- if (end === -1)
537
- return null;
538
- typeText = code.slice(cursor + 1, end - 1).trim();
539
- cursor = end;
540
- }
541
- skipSpace();
542
- if (code[cursor] !== "(")
543
- return null;
544
- const callEnd = skipBalanced(code, cursor, "(", ")");
545
- if (callEnd === -1)
546
- return null;
547
- const runtimeArgument = code.slice(cursor + 1, callEnd - 1).trim();
548
- cursor = callEnd;
549
- if (wrapped) {
550
- skipSpace();
551
- if (code[cursor] === ",") {
552
- cursor++;
553
- skipSpace();
554
- }
555
- if (code[cursor] === "{") {
556
- const end = skipBalanced(code, cursor, "{", "}");
557
- if (end === -1)
558
- return null;
559
- for (const [name, value] of parseDefaults(code.slice(cursor, end)))
560
- defaults[name] = value;
561
- cursor = end;
562
- }
563
- skipSpace();
564
- if (code[cursor] === ",") {
565
- cursor++;
566
- skipSpace();
567
- }
568
- if (code[cursor] === ")")
569
- cursor++;
570
- }
571
- if (code[cursor] === ";")
572
- cursor++;
573
- const typeName = /^[A-Za-z_$][\w$]*$/.test(typeText) ? typeText : void 0;
574
- if (typeText.startsWith("{"))
575
- for (const member of splitTopLevel(typeText.replace(/^\{/, "").replace(/\}$/, ""), ",;", !0)) {
576
- const parsed = /^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(member);
577
- if (parsed)
578
- declared[parsed[1]] = parsed[2].trim();
579
- }
580
- if (runtimeArgument.startsWith("{"))
581
- for (const [name, value] of parseDefaults(runtimeArgument)) {
582
- propNames.push(name);
583
- if (!value.startsWith("{")) {
584
- const fromConstructor = typeFromConstructor(value);
585
- if (fromConstructor)
586
- declared[name] = fromConstructor;
587
- continue;
588
- }
589
- for (const [key, inner] of parseDefaults(value))
590
- if (key === "default")
591
- defaults[name] = inner;
592
- else if (key === "type") {
593
- const fromConstructor = typeFromConstructor(inner);
594
- if (fromConstructor)
595
- declared[name] = fromConstructor;
596
- }
597
- }
598
- else if (runtimeArgument.startsWith("["))
599
- for (const entry of splitTopLevel(runtimeArgument.slice(1, -1), ",", !1))
600
- propNames.push(entry.replace(/^['"`]/, "").replace(/['"`]$/, ""));
601
- if (pattern.startsWith("{")) {
602
- propNames.length = 0;
603
- for (const entry of splitTopLevel(pattern.replace(/^\{/, "").replace(/\}$/, ""), ",", !1)) {
604
- const assignment = defaultAssignmentIndex(entry), binding = assignment === -1 ? entry : entry.slice(0, assignment), name = binding.split(":")[0].trim().replace(/^\.\.\./, "");
605
- if (!name)
606
- continue;
607
- propNames.push(name);
608
- propBindings[name] = binding.trim();
609
- if (assignment !== -1)
610
- defaults[name] = entry.slice(assignment + 1).trim();
611
- }
612
- } else if (propNames.length === 0)
613
- propNames.push(...Object.keys(declared));
614
- return { text: code.slice(start, cursor), propNames, propBindings, defaults, declared, typeName };
615
- }
616
- export function parseDefaults(object) {
617
- const body = object.trim().replace(/^\{/, "").replace(/\}$/, ""), pairs = [];
618
- let index = 0;
619
- while (index < body.length) {
620
- const key = /\s*([A-Za-z_$][\w$]*)\s*:/y;
621
- key.lastIndex = index;
622
- const match = key.exec(body);
623
- if (!match)
624
- break;
625
- index = key.lastIndex;
626
- let depth = 0, quote = "";
627
- const start = index;
628
- while (index < body.length) {
629
- const char = body[index];
630
- if (quote) {
631
- if (char === "\\")
632
- index++;
633
- else if (char === quote)
634
- quote = "";
635
- } else if (char === "'" || char === '"' || char === "`")
636
- quote = char;
637
- else if (char === "{" || char === "[" || char === "(")
638
- depth++;
639
- else if (char === "}" || char === "]" || char === ")")
640
- depth--;
641
- else if (char === "," && depth === 0)
642
- break;
643
- index++;
644
- }
645
- const value = body.slice(start, index).trim();
646
- if (value)
647
- pairs.push([match[1], value]);
648
- index++;
649
- }
650
- return pairs;
651
- }
652
383
  function hoistScriptImports(code) {
653
384
  const masked = stripCommentsAndLiterals(code), depths = bracketDepths(masked).depths, imports = [], spans = [];
654
385
  for (const match of masked.matchAll(/\bimport\b/g)) {
@@ -689,7 +420,7 @@ function hoistScriptImports(code) {
689
420
  last++;
690
421
  const end = start + tokens[last].end;
691
422
  spans.push({ start, end });
692
- if (specifier.value.slice(1, -1) !== "stx")
423
+ if (!["stx", "@stacksjs/stx"].includes(specifier.value.slice(1, -1)))
693
424
  imports.push(code.slice(start, end));
694
425
  }
695
426
  let body = code;
@@ -698,14 +429,15 @@ function hoistScriptImports(code) {
698
429
  return { imports, body };
699
430
  }
700
431
  function compileScriptScope(source) {
701
- const block = scanHtmlScriptElements(componentScriptSource(source)).find((script) => {
432
+ const blocks = scanHtmlScriptElements(componentScriptSource(source)).filter((script) => {
702
433
  const attrs = scriptAttributes(script.attrs);
703
- return scriptContainsCode(attrs) && !["component", "stx:component", "client", "server", "src"].some((name) => attrs.has(name));
434
+ return scriptContainsCode(attrs) && !["component", "stx:component", "server", "src"].some((name) => attrs.has(name));
704
435
  });
705
- if (!block)
706
- return { imports: [], body: "", propNames: [], propBindings: {}, defaults: {}, declared: {} };
707
- let code = source.slice(block.bodyStart, block.bodyEnd);
708
- const imports = [], propNames = [], propBindings = {}, defaults = {}, declared = {}, hoisted = hoistScriptImports(code);
436
+ if (!blocks.length)
437
+ return { imports: [], body: "", propNames: [], propBindings: {}, defaults: {}, declared: {}, apis: [] };
438
+ let code = blocks.map((block) => source.slice(block.bodyStart, block.bodyEnd)).join(`
439
+ `);
440
+ const imports = [], propNames = [], propBindings = Object.create(null), defaults = Object.create(null), declared = Object.create(null), hoisted = hoistScriptImports(code);
709
441
  imports.push(...hoisted.imports);
710
442
  code = hoisted.body;
711
443
  const props = parsePropsDeclaration(code);
@@ -714,33 +446,40 @@ function compileScriptScope(source) {
714
446
  Object.assign(propBindings, props.propBindings);
715
447
  Object.assign(defaults, props.defaults);
716
448
  Object.assign(declared, props.declared);
717
- code = code.replace(props.text, "");
718
- }
719
- const interfaceMembers = {};
720
- for (const block of code.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)) {
721
- const members = [];
722
- for (const member of block[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm)) {
723
- declared[member[1]] = member[2].trim();
724
- members.push(member[1]);
725
- }
726
- interfaceMembers[block[1]] = members;
449
+ code = code.replace(props.text, props.identifier ? `const ${props.identifier} = this._props();` : "");
727
450
  }
728
- if (props && props.propNames.length === 0 && props.typeName) {
729
- for (const name of interfaceMembers[props.typeName] ?? [])
730
- if (!propNames.includes(name))
731
- propNames.push(name);
451
+ if (props?.typeName) {
452
+ const type = localType(code, props.typeName);
453
+ if (type)
454
+ for (const member of splitTopLevel(type.slice(1, -1), `;,
455
+ `, !0)) {
456
+ const parsed = /^(?:readonly\s+)?([A-Za-z_$][\w$]*)\??\s*:\s*([\s\S]+)$/.exec(member);
457
+ if (!parsed)
458
+ continue;
459
+ declared[parsed[1]] = parsed[2].trim();
460
+ if (!propNames.includes(parsed[1]))
461
+ propNames.push(parsed[1]);
462
+ }
732
463
  }
733
- code = code.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g, "");
734
- return { imports, body: code.trim(), propNames, propBindings, defaults, declared };
464
+ const emits = parseEmitsDeclaration(code);
465
+ if (emits)
466
+ code = code.replace(emits.text, "this._emitScope.bind(this)");
467
+ const publicMask = stripCommentsAndLiterals(code), publicDepths = bracketDepths(publicMask).depths;
468
+ for (const match of [...publicMask.matchAll(/\bexport\s+(?=(?:interface|type|const|let|var|async|function)\b)/g)].reverse())
469
+ if (publicDepths[match.index] === 0)
470
+ code = code.slice(0, match.index) + " ".repeat(match[0].length) + code.slice(match.index + match[0].length);
471
+ const locals = new Set(topLevelDeclarationSites(code).map((site) => site.name)), masked = stripCommentsAndLiterals(code), apis = ["state", "derived", "effect", "batch", "onMount", "onDestroy"].filter((name) => !locals.has(name) && new RegExp(`\\b${name}\\s*(?:<|\\()`).test(masked));
472
+ return { imports, body: code.trim(), propNames, propBindings, defaults, declared, apis };
735
473
  }
736
474
  function compileEventDirectives(template) {
737
- const eventTypes = new Set;
738
- return { template: template.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi, (_match, eventName, modifiers, _quote, method) => {
475
+ const eventTypes = new Set, handlers = [];
476
+ return { template: template.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([\s\S]*?)\3/gi, (_match, eventName, modifiers, _quote, expression) => {
739
477
  const event = eventName.toLowerCase();
740
478
  eventTypes.add(event);
741
- const normalizedModifiers = (modifiers || "").split(".").filter(Boolean).join(" ");
742
- return ` data-stx-on-${event}="${method}"${normalizedModifiers ? ` data-stx-mod-${event}="${normalizedModifiers}"` : ""}`;
743
- }), eventTypes: [...eventTypes].sort() };
479
+ const normalizedModifiers = (modifiers || "").split(".").filter(Boolean).join(" "), id = handlers.length;
480
+ handlers.push(/^[A-Za-z_$][\w$]*$/.test(expression.trim()) ? `($event) => (typeof ${expression} === 'function' ? ${expression} : this[${JSON.stringify(expression.trim())}]).call(this, $event)` : `($event) => { ${expression} }`);
481
+ return ` data-stx-on-${event}="${id}"${normalizedModifiers ? ` data-stx-mod-${event}="${normalizedModifiers}"` : ""}`;
482
+ }), eventTypes: [...eventTypes].sort(), handlers };
744
483
  }
745
484
  function compileDynamicBindings(template) {
746
485
  const bindings = [];
@@ -781,7 +520,7 @@ async function compileComponent(inputDir, entry, defaults) {
781
520
  scope.imports.push(...hoistScriptImports(source.slice(script.bodyStart, script.bodyEnd)).imports);
782
521
  }
783
522
  scope.imports = [...new Set(scope.imports)];
784
- const render = compileTemplateToRender(bindingCompilation.template);
523
+ const render = compileTemplateToRender(bindingCompilation.template, eventCompilation.handlers);
785
524
  for (const propertyName of scope.propNames) {
786
525
  if (properties[propertyName])
787
526
  continue;
@@ -803,11 +542,18 @@ async function compileComponent(inputDir, entry, defaults) {
803
542
  shadowMode: normalizeShadowMode(entry.shadowDOM ?? metadata.shadowDOM ?? defaults.shadowDOM),
804
543
  progressive: entry.progressive ?? metadata.progressive ?? defaults.progressive ?? !0,
805
544
  properties,
806
- events: entry.events || metadata.events || {},
545
+ events: { ...parseEmitsDeclaration(scanHtmlScriptElements(componentScriptSource(source)).filter((script) => {
546
+ const attrs = scriptAttributes(script.attrs);
547
+ return scriptContainsCode(attrs) && !["server", "component", "stx:component", "src"].some((name) => attrs.has(name));
548
+ }).map((script) => source.slice(script.bodyStart, script.bodyEnd)).join(`
549
+ `))?.events || {}, ...entry.events || metadata.events || {} },
807
550
  methods: { ...metadataMethods, ...configuredMethods, ...extractedMethods.methods },
808
551
  methodDeclarations: extractedMethods.declarations,
809
552
  declarationTypes: extractedMethods.types,
553
+ declarationImports: extractedMethods.typeImports,
810
554
  eventTypes: eventCompilation.eventTypes,
555
+ handlers: eventCompilation.handlers,
556
+ scopeMethods: Object.keys(extractedMethods.methods),
811
557
  bindings: bindingCompilation.bindings,
812
558
  slots: extractSlots(bindingCompilation.template),
813
559
  cssProperties: extractCssProperties(extractStyles(source)),
@@ -815,9 +561,10 @@ async function compileComponent(inputDir, entry, defaults) {
815
561
  render
816
562
  };
817
563
  }
818
- function runtimeModule() {
564
+ function runtimeModule(signals = !1) {
819
565
  const rawInterpolation = JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"), escapedInterpolation = JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");
820
- return `const HTMLElementBase = globalThis.HTMLElement || class {};
566
+ return `${signals ? `import { state as nativeState, derived as nativeDerived, effect as nativeEffect, batch as nativeBatch } from './signals.js';
567
+ ` : ""}const HTMLElementBase = globalThis.HTMLElement || class {};
821
568
 
822
569
  const escapeHTML = (value) => String(value ?? '')
823
570
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
@@ -879,6 +626,14 @@ export class StxElement extends HTMLElementBase {
879
626
  this._initializing = false;
880
627
  this._updatePending = false;
881
628
  this._listeners = new Map();
629
+ this._scopeStates = [];
630
+ this._scopeDerived = [];
631
+ this._scopeEffects = [];
632
+ this._scopeSubscriptions = [];
633
+ this._scopeMounts = [];
634
+ this._scopeDestroys = [];
635
+ this._scopeConnectionDestroys = [];
636
+ this._scopeMountCleanups = [];
882
637
  const definition = this.constructor.definition;
883
638
  for (const [name, property] of Object.entries(definition.properties || {})) {
884
639
  this._values[name] = defaultFor(property);
@@ -909,7 +664,10 @@ export class StxElement extends HTMLElementBase {
909
664
  const hasMarkup = [...(root.childNodes || [])].some(node => node.nodeType !== 3 || node.textContent.trim());
910
665
  const firstConnection = !this._hasConnected;
911
666
  if (!(firstConnection && definition.progressive && hasMarkup)) this._render();
912
- else this._upgradeDeclarativeEvents();
667
+ else {
668
+ if (typeof this.render === 'function') this.render(RENDER_HELPERS);
669
+ this._upgradeDeclarativeEvents();
670
+ }
913
671
  this._bindEvents();
914
672
  if (firstConnection) {
915
673
  this._hasConnected = true;
@@ -919,6 +677,7 @@ export class StxElement extends HTMLElementBase {
919
677
  // Called last, so a component that acquires something sees its own rendered
920
678
  // markup and its events already bound. Reported rather than rethrown: a
921
679
  // component that fails to set up must not take the element down with it.
680
+ this._runScopeMounts();
922
681
  try { this.onConnect?.(); }
923
682
  catch (error) { console.error('[stx] onConnect failed', error); }
924
683
  }
@@ -931,6 +690,13 @@ export class StxElement extends HTMLElementBase {
931
690
  try { this.onDisconnect?.(); }
932
691
  catch (error) { console.error('[stx] onDisconnect failed', error); }
933
692
  finally {
693
+ this._disposeScopeEffects();
694
+ for (const dispose of this._scopeSubscriptions.splice(0)) {
695
+ try { dispose?.(); } catch (error) { console.error('[stx] scope subscription cleanup failed', error); }
696
+ }
697
+ for (const cleanup of [...this._scopeDestroys.splice(0), ...this._scopeConnectionDestroys.splice(0), ...this._scopeMountCleanups.splice(0)]) {
698
+ try { cleanup(); } catch (error) { console.error('[stx] scope cleanup failed', error); }
699
+ }
934
700
  for (const [event, listener] of this._listeners) this.renderRoot.removeEventListener(event, listener);
935
701
  this._listeners.clear();
936
702
  }
@@ -979,6 +745,66 @@ export class StxElement extends HTMLElementBase {
979
745
  }));
980
746
  }
981
747
 
748
+ _disposeScopeEffects() {
749
+ for (const dispose of this._scopeEffects.splice(0)) {
750
+ try { dispose(); } catch (error) { console.error('[stx] effect cleanup failed', error); }
751
+ }
752
+ }
753
+
754
+ _runScopeMounts() {
755
+ for (const mount of this._scopeMounts) {
756
+ try { const cleanup = mount(); if (typeof cleanup === 'function') this._scopeMountCleanups.push(cleanup); }
757
+ catch (error) { console.error('[stx] onMount failed', error); }
758
+ }
759
+ }
760
+
761
+ ${signals ? ` _beginScope() {
762
+ this._disposeScopeEffects();
763
+ this._scopeMounts = [];
764
+ this._scopeDestroys = [];
765
+ let stateIndex = 0, derivedIndex = 0;
766
+ let rendering = true;
767
+ return {
768
+ finish: () => { rendering = false; },
769
+ state: (initial) => {
770
+ const index = stateIndex++;
771
+ const value = this._scopeStates[index] ||= nativeState(initial);
772
+ if (this._connected && !this._scopeSubscriptions[index]) this._scopeSubscriptions[index] = value.subscribe(() => this.requestUpdate());
773
+ return value;
774
+ },
775
+ derived: (compute, options) => {
776
+ const index = derivedIndex++;
777
+ let entry = this._scopeDerived[index];
778
+ if (!entry) {
779
+ entry = { compute, revision: nativeState(0) };
780
+ entry.value = nativeDerived(() => { entry.revision(); return entry.compute(); }, options);
781
+ this._scopeDerived[index] = entry;
782
+ } else {
783
+ entry.compute = compute;
784
+ entry.revision.update(value => value + 1);
785
+ }
786
+ return entry.value;
787
+ },
788
+ effect: (callback, options) => {
789
+ const dispose = nativeEffect(callback, options);
790
+ this._scopeEffects.push(dispose);
791
+ return dispose;
792
+ },
793
+ batch: nativeBatch,
794
+ onMount: callback => this._scopeMounts.push(callback),
795
+ onDestroy: callback => (rendering ? this._scopeDestroys : this._scopeConnectionDestroys).push(callback),
796
+ };
797
+ }
798
+
799
+ ` : ""} _emitScope(name, ...args) {
800
+ return this.emit(name, args.length === 1 ? args[0] : args, { cancelable: true });
801
+ }
802
+
803
+ _callScopeMethod(name, args) {
804
+ if (!this._scopeMethods || this._updatePending) this.render(RENDER_HELPERS);
805
+ return this._scopeMethods[name].apply(this, args);
806
+ }
807
+
982
808
  _upgradeProperty(name) {
983
809
  if (!Object.prototype.hasOwnProperty.call(this, name)) return;
984
810
  const value = this[name];
@@ -1007,10 +833,12 @@ export class StxElement extends HTMLElementBase {
1007
833
  const target = $event.target?.closest?.(selector);
1008
834
  if (!target || !this.renderRoot.contains(target)) return;
1009
835
  const modifiers = (target.getAttribute('data-stx-mod-' + event) || '').split(' ');
836
+ if (modifiers.includes('self') && target !== $event.target) return;
1010
837
  if (modifiers.includes('prevent')) $event.preventDefault();
1011
838
  if (modifiers.includes('stop')) $event.stopPropagation();
1012
839
  const method = target.getAttribute('data-stx-on-' + event);
1013
- if (typeof this[method] === 'function') this[method]($event);
840
+ if (this._handlers?.[method]) this._handlers[method]($event);
841
+ else if (typeof this[method] === 'function') this[method]($event);
1014
842
  };
1015
843
  this.renderRoot.addEventListener(event, listener);
1016
844
  this._listeners.set(event, listener);
@@ -1160,7 +988,12 @@ ${body}
1160
988
  }`;
1161
989
  }).join(`
1162
990
 
1163
- `), scope = component.scope, destructured = [...new Set([...Object.keys(component.properties), ...scope.propNames])].map((name) => {
991
+ `), scope = component.scope, localNames = new Set(new Tokenizer([scope.body, ...scope.imports, ...Object.keys(component.properties), ...Object.values(scope.propBindings)].join(`
992
+ `)).tokenize().map((token) => token.value));
993
+ let scopeOwner = "__stxScope";
994
+ while (localNames.has(scopeOwner))
995
+ scopeOwner += "$";
996
+ const destructured = [...new Set([...Object.keys(component.properties), ...scope.propNames])].map((name) => {
1164
997
  const binding = scope.propBindings[name] || name;
1165
998
  return scope.defaults[name] === void 0 ? binding : `${binding} = ${scope.defaults[name]}`;
1166
999
  }).join(", "), indent = (code) => code.split(`
@@ -1169,10 +1002,15 @@ ${body}
1169
1002
  let renderMethod = "";
1170
1003
  if (component.render.trim() !== "" || scope.body !== "" || destructured !== "") {
1171
1004
  const inner = [
1005
+ scope.apis.length ? `const ${scopeOwner} = this._beginScope();
1006
+ const { ${scope.apis.join(", ")} } = ${scopeOwner};` : "",
1172
1007
  destructured ? `const { ${destructured} } = this._props();` : "",
1173
1008
  scope.body,
1009
+ component.scopeMethods.length ? `this._scopeMethods = { ${component.scopeMethods.join(", ")} };` : "",
1010
+ component.handlers.length ? "this._handlers = [];" : "",
1174
1011
  "let out = '';",
1175
1012
  component.render,
1013
+ scope.apis.length ? `${scopeOwner}.finish();` : "",
1176
1014
  "return out;"
1177
1015
  ].filter(Boolean).join(`
1178
1016
  `);
@@ -1222,13 +1060,31 @@ export function typeForProperty(property) {
1222
1060
  }
1223
1061
  }
1224
1062
  function componentDeclaration(component) {
1225
- const props = Object.entries(component.properties).map(([name, property]) => ` ${name}${property.required ? "" : "?"}: ${typeForProperty(property)}`).join(`
1226
- `), events = Object.entries(component.events).map(([name, event]) => ` ${JSON.stringify(name)}: CustomEvent<${event.detailType || "unknown"}>`).join(`
1063
+ const authoredTypes = [component.declarationTypes, component.declarationImports, component.name, ...Object.values(component.methodDeclarations).flat(), ...Object.values(component.events).map((event) => event.detailType)].join(`
1064
+ `), identifiers = new Set(new Tokenizer(authoredTypes).tokenize().map((token) => token.value)), unique = (base) => {
1065
+ let name = base;
1066
+ while (identifiers.has(name))
1067
+ name += "$";
1068
+ identifiers.add(name);
1069
+ return name;
1070
+ }, support = unique("__StxSupport"), publicMethods = unique("__Methods"), eventDetails = unique("__Details"), scoped = !!component.declarationTypes, props = Object.entries(component.properties).map(([name, property]) => ` ${name}${property.required ? "" : "?"}: ${typeForProperty(property)}`).join(`
1071
+ `), events = Object.entries(component.events).map(([name, event]) => ` ${JSON.stringify(name)}: CustomEvent<${scoped ? `${support}.${eventDetails}[${JSON.stringify(name)}]` : event.detailType || "unknown"}>`).join(`
1227
1072
  `), methods = Object.keys(component.methods).flatMap((name) => component.methodDeclarations[name] || [`${name}($event?: Event): unknown`]).map((signature) => ` ${signature}`).join(`
1228
- `);
1229
- return `${component.declarationTypes ? `${component.declarationTypes}
1073
+ `), supportDeclaration = scoped ? `declare namespace ${support} {
1074
+ ${component.declarationTypes}
1075
+ export interface ${publicMethods} {
1076
+ ${methods}
1077
+ }
1078
+ export interface ${eventDetails} {
1079
+ ${Object.entries(component.events).map(([name, event]) => ` ${JSON.stringify(name)}: ${event.detailType || "unknown"}`).join(`
1080
+ `)}
1081
+ }
1082
+ }
1083
+
1084
+ ` : "";
1085
+ return `${component.declarationImports ? component.declarationImports + `
1230
1086
 
1231
- ` : ""}export interface ${component.name}Props {
1087
+ ` : ""}${supportDeclaration}export interface ${component.name}Props {
1232
1088
  ${props}
1233
1089
  }
1234
1090
 
@@ -1236,10 +1092,16 @@ export interface ${component.name}EventMap {
1236
1092
  ${events}
1237
1093
  }
1238
1094
 
1239
- export interface ${component.name} extends Required<Pick<${component.name}Props, Exclude<keyof ${component.name}Props, keyof HTMLElement>>> {}
1095
+ export interface ${component.name} extends Required<Pick<${component.name}Props, Exclude<keyof ${component.name}Props, keyof HTMLElement>>>${scoped ? `, ${support}.${publicMethods}` : ""} {}
1240
1096
 
1241
1097
  export declare class ${component.name} extends HTMLElement {
1242
- ${methods}
1098
+ ${scoped ? "" : methods}
1099
+ addEventListener<K extends keyof ${component.name}EventMap>(type: K, listener: (this: ${component.name}, event: ${component.name}EventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void
1100
+ addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, event: HTMLElementEventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void
1101
+ addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void
1102
+ removeEventListener<K extends keyof ${component.name}EventMap>(type: K, listener: (this: ${component.name}, event: ${component.name}EventMap[K]) => unknown, options?: boolean | EventListenerOptions): void
1103
+ removeEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, event: HTMLElementEventMap[K]) => unknown, options?: boolean | EventListenerOptions): void
1104
+ removeEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions): void
1243
1105
  readonly updateComplete: Promise<void>
1244
1106
  requestUpdate(): Promise<void>
1245
1107
  emit<T = unknown>(name: string, detail?: T, options?: CustomEventInit<T>): boolean
@@ -1261,7 +1123,7 @@ function customElementsDeclaration(components) {
1261
1123
  ${components.map((component) => {
1262
1124
  const props = Object.entries(component.properties).map(([name, property]) => ` ${JSON.stringify(name)}?: ${typeForProperty(property)}`).join(`
1263
1125
  `), events = Object.keys(component.events).map((event) => {
1264
- return ` ${`on${event.split(/[-:]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("")}`}?: (event: CustomEvent<${component.events[event].detailType || "unknown"}>) => void`;
1126
+ return ` ${`on${event.split(/[-:]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("")}`}?: (event: import('./${component.tag}.js').${component.name}EventMap[${JSON.stringify(event)}]) => void`;
1265
1127
  }).join(`
1266
1128
  `);
1267
1129
  return ` ${JSON.stringify(component.tag)}: {
@@ -1395,8 +1257,10 @@ export async function buildComponentLibrary(config) {
1395
1257
  if (!files.includes(target))
1396
1258
  files.push(target);
1397
1259
  return target;
1398
- };
1399
- await emit("runtime.js", runtimeModule());
1260
+ }, signals = components.some((component) => component.scope.apis.length), extension = import.meta.url.endsWith(".ts") ? ".ts" : ".js", nativeSignals = new URL(`./signals-api${extension}`, import.meta.url).pathname;
1261
+ if (signals)
1262
+ await emit("signals.js", `export * from ${JSON.stringify(nativeSignals)};`);
1263
+ await emit("runtime.js", runtimeModule(signals));
1400
1264
  for (const component of components) {
1401
1265
  await emit(`${component.tag}.js`, componentModule(component));
1402
1266
  if (config.declarations !== !1)
@@ -1407,11 +1271,15 @@ export async function buildComponentLibrary(config) {
1407
1271
  }
1408
1272
  }
1409
1273
  const importScanner = new Bun.Transpiler({ loader: "ts" });
1410
- if (components.some((component) => component.scope.imports.length || importScanner.scanImports(componentModule(component)).some((imported) => imported.kind === "dynamic-import"))) {
1274
+ if (signals || components.some((component) => component.scope.imports.length || importScanner.scanImports(componentModule(component)).some((imported) => imported.kind === "dynamic-import"))) {
1411
1275
  const entrypoints = components.map((component) => path.join(outputDir, `${component.tag}.js`)), canonicalEntries = new Map(await Promise.all(entrypoints.map(async (file, index) => [await realpath(file), components[index]])));
1412
1276
  for (const [index, file] of entrypoints.entries())
1413
1277
  canonicalEntries.set(file, components[index]);
1414
- const sourceEntries = new Map(components.map((component) => [path.join(path.dirname(component.sourcePath), `.stx-library-${component.tag}.ts`), component])), runtimePath = path.join(outputDir, "runtime.js"), built = await Bun.build({
1278
+ const sourceEntries = new Map(components.map((component) => [path.join(path.dirname(component.sourcePath), `.stx-library-${component.tag}.ts`), component])), runtimePath = path.join(outputDir, "runtime.js");
1279
+ entrypoints.push(runtimePath);
1280
+ if (signals)
1281
+ entrypoints.push(path.join(outputDir, "signals.js"));
1282
+ const built = await Bun.build({
1415
1283
  entrypoints,
1416
1284
  outdir: outputDir,
1417
1285
  root: outputDir,
@@ -1429,7 +1297,9 @@ export async function buildComponentLibrary(config) {
1429
1297
  if (!args.importer && entry)
1430
1298
  return { path: path.join(path.dirname(entry.sourcePath), `.stx-library-${entry.tag}.ts`) };
1431
1299
  if (args.path === runtimePath && sourceEntries.has(args.importer))
1432
- return { path: "./runtime.js", external: !0 };
1300
+ return { path: runtimePath };
1301
+ if (/^(?:@stacksjs\/stx|stx)\/signals-api(?:\.[jt]s)?$/.test(args.path))
1302
+ return { path: nativeSignals };
1433
1303
  });
1434
1304
  builder.onLoad({ filter: /\.ts$/ }, (args) => {
1435
1305
  const component = sourceEntries.get(args.path);