@fluixi/compiler 1.0.0-alpha.83 → 1.0.0-alpha.84

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 (163) hide show
  1. package/dist/analyze/expr-shape.cjs +62 -1
  2. package/dist/analyze/expr-shape.d.cts +14 -0
  3. package/dist/analyze/expr-shape.mjs +41 -1
  4. package/dist/analyze/intrinsics.cjs +80 -1
  5. package/dist/analyze/intrinsics.d.cts +66 -0
  6. package/dist/analyze/intrinsics.mjs +59 -1
  7. package/dist/analyze/paren.cjs +134 -0
  8. package/dist/analyze/paren.d.cts +23 -0
  9. package/dist/analyze/paren.d.ts +24 -0
  10. package/dist/analyze/paren.d.ts.map +1 -0
  11. package/dist/analyze/paren.js +168 -0
  12. package/dist/analyze/paren.mjs +113 -0
  13. package/dist/analyze/props-destructure.cjs +226 -1
  14. package/dist/analyze/props-destructure.d.cts +83 -0
  15. package/dist/analyze/props-destructure.mjs +205 -1
  16. package/dist/analyze/reactive-bindings.cjs +190 -1
  17. package/dist/analyze/reactive-bindings.d.cts +42 -0
  18. package/dist/analyze/reactive-bindings.mjs +167 -1
  19. package/dist/analyze/reactive-expr.cjs +38 -1
  20. package/dist/analyze/reactive-expr.d.cts +38 -0
  21. package/dist/analyze/reactive-expr.mjs +17 -1
  22. package/dist/analyze/static-graph.cjs +811 -1
  23. package/dist/analyze/static-graph.d.cts +102 -0
  24. package/dist/analyze/static-graph.mjs +793 -1
  25. package/dist/babel-NRW4EFTG.mjs +636 -0
  26. package/dist/chunk-3YKZ4GNH.mjs +11 -0
  27. package/dist/chunk-EZR7NZOY.mjs +1718 -0
  28. package/dist/chunk-FSSWUXUR.mjs +16 -0
  29. package/dist/chunk-MJV3UXIL.mjs +158 -0
  30. package/dist/chunk-R2VHAZAX.mjs +1078 -0
  31. package/dist/codegen/backend.cjs +18 -1
  32. package/dist/codegen/backend.d.cts +35 -0
  33. package/dist/codegen/backends/imperative.cjs +542 -1
  34. package/dist/codegen/backends/imperative.d.cts +11 -0
  35. package/dist/codegen/backends/imperative.d.ts.map +1 -1
  36. package/dist/codegen/backends/imperative.js +12 -8
  37. package/dist/codegen/backends/imperative.mjs +519 -1
  38. package/dist/codegen/contract.cjs +52 -1
  39. package/dist/codegen/contract.d.cts +24 -0
  40. package/dist/codegen/contract.mjs +31 -1
  41. package/dist/codegen/partial-template.cjs +176 -1
  42. package/dist/codegen/partial-template.d.cts +61 -0
  43. package/dist/codegen/partial-template.mjs +153 -1
  44. package/dist/codegen/serialize-static.cjs +125 -1
  45. package/dist/codegen/serialize-static.d.cts +38 -0
  46. package/dist/codegen/serialize-static.mjs +104 -1
  47. package/dist/frontend/babel/build-ir-lit.cjs +1509 -1
  48. package/dist/frontend/babel/build-ir-lit.d.cts +26 -0
  49. package/dist/frontend/babel/build-ir-lit.mjs +1478 -1
  50. package/dist/frontend/babel/build-ir.cjs +1524 -1
  51. package/dist/frontend/babel/build-ir.d.cts +35 -0
  52. package/dist/frontend/babel/build-ir.mjs +1495 -1
  53. package/dist/frontend/babel/index.cjs +2186 -1
  54. package/dist/frontend/babel/index.d.cts +33 -0
  55. package/dist/frontend/babel/index.mjs +2156 -1
  56. package/dist/frontend/babel/lower-template.cjs +1507 -1
  57. package/dist/frontend/babel/lower-template.d.cts +23 -0
  58. package/dist/frontend/babel/lower-template.mjs +1478 -1
  59. package/dist/frontend/babel/plugin.cjs +2132 -1
  60. package/dist/frontend/babel/plugin.d.cts +95 -0
  61. package/dist/frontend/babel/plugin.mjs +2103 -1
  62. package/dist/frontend/babel/server-functions.cjs +110 -1
  63. package/dist/frontend/babel/server-functions.d.cts +10 -0
  64. package/dist/frontend/babel/server-functions.mjs +89 -1
  65. package/dist/frontend/babel/types.cjs +18 -1
  66. package/dist/frontend/babel/types.d.cts +33 -0
  67. package/dist/frontend/types.cjs +18 -1
  68. package/dist/frontend/types.d.cts +25 -0
  69. package/dist/frontend/vocabulary.cjs +98 -0
  70. package/dist/frontend/vocabulary.d.cts +79 -0
  71. package/dist/frontend/vocabulary.d.ts +80 -0
  72. package/dist/frontend/vocabulary.d.ts.map +1 -0
  73. package/dist/frontend/vocabulary.js +124 -0
  74. package/dist/frontend/vocabulary.mjs +77 -0
  75. package/dist/index.cjs +1594 -13
  76. package/dist/index.d.cts +27 -0
  77. package/dist/index.mjs +1574 -13
  78. package/dist/integrations.cjs +4307 -25
  79. package/dist/integrations.d.cts +215 -0
  80. package/dist/integrations.mjs +531 -17
  81. package/dist/ir/nodes.cjs +18 -1
  82. package/dist/ir/nodes.d.cts +168 -0
  83. package/dist/lower/compile-template.cjs +1356 -1
  84. package/dist/lower/compile-template.d.cts +69 -0
  85. package/dist/lower/compile-template.mjs +1336 -1
  86. package/dist/lower/jsx.cjs +529 -1
  87. package/dist/lower/jsx.d.cts +25 -0
  88. package/dist/lower/jsx.d.ts.map +1 -1
  89. package/dist/lower/jsx.js +2 -1
  90. package/dist/lower/jsx.mjs +506 -1
  91. package/dist/lower/template.cjs +1061 -1
  92. package/dist/lower/template.d.cts +53 -0
  93. package/dist/lower/template.d.ts.map +1 -1
  94. package/dist/lower/template.js +5 -4
  95. package/dist/lower/template.mjs +1042 -1
  96. package/dist/lower/text.cjs +42 -1
  97. package/dist/lower/text.d.cts +10 -0
  98. package/dist/lower/text.mjs +21 -1
  99. package/dist/optimize/analyze-static.cjs +112 -1
  100. package/dist/optimize/analyze-static.d.cts +39 -0
  101. package/dist/optimize/analyze-static.mjs +91 -1
  102. package/dist/optimize/collapse-strategies.cjs +90 -1
  103. package/dist/optimize/collapse-strategies.d.cts +30 -0
  104. package/dist/optimize/collapse-strategies.mjs +67 -1
  105. package/dist/options.cjs +33 -1
  106. package/dist/options.d.cts +39 -0
  107. package/dist/options.mjs +12 -1
  108. package/dist/resolve/builtins.cjs +73 -1
  109. package/dist/resolve/builtins.d.cts +68 -0
  110. package/dist/resolve/builtins.mjs +53 -1
  111. package/dist/resolve/component-globals.cjs +233 -13
  112. package/dist/resolve/component-globals.d.cts +80 -0
  113. package/dist/resolve/component-globals.mjs +210 -13
  114. package/dist/resolve/component-resolver.cjs +80 -1
  115. package/dist/resolve/component-resolver.d.cts +68 -0
  116. package/dist/resolve/component-resolver.mjs +59 -1
  117. package/dist/resolve/load-directive.cjs +93 -1
  118. package/dist/resolve/load-directive.d.cts +53 -0
  119. package/dist/resolve/load-directive.mjs +72 -1
  120. package/dist/resolve/resolve-ir.cjs +108 -1
  121. package/dist/resolve/resolve-ir.d.cts +53 -0
  122. package/dist/resolve/resolve-ir.mjs +85 -1
  123. package/dist/resolve/write-globals.cjs +318 -13
  124. package/dist/resolve/write-globals.d.cts +30 -0
  125. package/dist/resolve/write-globals.mjs +297 -13
  126. package/dist/server-fns-4ZXN6DYU.mjs +78 -0
  127. package/dist/server-functions-V6D6DRIA.mjs +82 -0
  128. package/dist/transform/bindings.cjs +71 -1
  129. package/dist/transform/bindings.d.cts +16 -0
  130. package/dist/transform/bindings.mjs +50 -1
  131. package/dist/transform/index.cjs +2732 -8
  132. package/dist/transform/index.d.cts +15 -0
  133. package/dist/transform/index.mjs +3773 -17
  134. package/dist/transform/intrinsics.cjs +216 -3
  135. package/dist/transform/intrinsics.d.cts +21 -0
  136. package/dist/transform/intrinsics.mjs +193 -3
  137. package/dist/transform/props.cjs +441 -3
  138. package/dist/transform/props.d.cts +45 -0
  139. package/dist/transform/props.mjs +1482 -12
  140. package/dist/transform/server-fn-id.cjs +35 -1
  141. package/dist/transform/server-fn-id.d.cts +9 -0
  142. package/dist/transform/server-fn-id.mjs +14 -1
  143. package/dist/transform/server-fns.cjs +114 -2
  144. package/dist/transform/server-fns.d.cts +12 -0
  145. package/dist/transform/server-fns.mjs +1155 -11
  146. package/dist/transform/source-locations.cjs +330 -1
  147. package/dist/transform/source-locations.d.cts +43 -0
  148. package/dist/transform/source-locations.mjs +307 -1
  149. package/dist/transform/templates.cjs +2701 -7
  150. package/dist/transform/templates.d.cts +69 -0
  151. package/dist/transform/templates.mjs +3743 -16
  152. package/dist/transform-BT4MMASR.mjs +893 -0
  153. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  154. package/package.json +6 -5
  155. package/dist/babel-VXKH6MRQ.mjs +0 -1
  156. package/dist/chunk-3SAEGOMQ.mjs +0 -1
  157. package/dist/chunk-5KMMN5QP.mjs +0 -1
  158. package/dist/chunk-IBRM4W7I.mjs +0 -10
  159. package/dist/chunk-OHHZCYIQ.mjs +0 -1
  160. package/dist/chunk-YKZ54NVE.mjs +0 -1
  161. package/dist/server-fns-6QM243HC.mjs +0 -2
  162. package/dist/server-functions-E3LKCZ4R.mjs +0 -1
  163. package/dist/transform-C4ZXRVGP.mjs +0 -8
@@ -0,0 +1,1718 @@
1
+ /*! @fluixi/compiler v1.0.0-alpha.84 | (c) 2026 Ibrahima Touré and Fluixi contributors | MIT */
2
+ import {
3
+ INTRINSICS,
4
+ RESERVED_COMPONENTS,
5
+ ROUTER_COMPONENTS,
6
+ RUNTIME_PRIMITIVES,
7
+ builtinComponentMap,
8
+ isIntrinsicName,
9
+ isPrimitiveModule
10
+ } from "./chunk-MJV3UXIL.mjs";
11
+
12
+ // src/analyze/expr-shape.ts
13
+ var CALL = /* @__PURE__ */ new Set(["CallExpression", "OptionalCallExpression"]);
14
+ var MEMBER = /* @__PURE__ */ new Set(["MemberExpression", "OptionalMemberExpression"]);
15
+ function shapeOf(node) {
16
+ if (!node) return { kind: "opaque" };
17
+ if (CALL.has(node.type)) return { kind: "call" };
18
+ if (MEMBER.has(node.type)) {
19
+ const property = node.property;
20
+ const computed = node.computed === true;
21
+ return {
22
+ kind: "member",
23
+ property: !computed && property?.type === "Identifier" ? property.name : null
24
+ };
25
+ }
26
+ if (node.type === "ConditionalExpression") {
27
+ return { kind: "compound", parts: [node.test, node.consequent, node.alternate].map(part) };
28
+ }
29
+ if (node.type === "LogicalExpression" || node.type === "BinaryExpression") {
30
+ return { kind: "compound", parts: [node.left, node.right].map(part) };
31
+ }
32
+ if (node.type === "TemplateLiteral") {
33
+ return { kind: "compound", parts: node.expressions.map(part) };
34
+ }
35
+ if (node.type === "ObjectExpression") {
36
+ const props = node.properties.filter(
37
+ (p) => (p.type === "ObjectProperty" || p.type === "Property") && p.computed !== true
38
+ );
39
+ return { kind: "compound", parts: props.map((p) => part(p.value)) };
40
+ }
41
+ if (node.type === "ArrayExpression") {
42
+ const items = node.elements.filter(
43
+ (e) => e != null && e.type !== "SpreadElement"
44
+ );
45
+ return { kind: "compound", parts: items.map(part) };
46
+ }
47
+ return { kind: "opaque" };
48
+ }
49
+ var part = (n) => shapeOf(n);
50
+
51
+ // src/resolve/load-directive.ts
52
+ var EAGER = { kind: "eager" };
53
+ var DEFAULT_INTERACTION_EVENTS = ["pointerdown", "focusin", "keydown"];
54
+ var STRATEGIES = /* @__PURE__ */ new Set(["eager", "idle", "visible", "interaction", "media", "never"]);
55
+ var LoadDirectiveError = class extends Error {
56
+ };
57
+ function isLoadDirective(name) {
58
+ return name.startsWith("load:");
59
+ }
60
+ function parseLoadDirective(name, value) {
61
+ const strategy = name.slice("load:".length);
62
+ if (!STRATEGIES.has(strategy)) {
63
+ throw new LoadDirectiveError(
64
+ `Unknown load strategy 'load:${strategy}'. Expected one of ${[...STRATEGIES].join(", ")}.`
65
+ );
66
+ }
67
+ switch (strategy) {
68
+ case "eager":
69
+ return EAGER;
70
+ case "idle":
71
+ return { kind: "idle" };
72
+ case "never":
73
+ return { kind: "never" };
74
+ case "visible":
75
+ return value ? { kind: "visible", rootMargin: value } : { kind: "visible" };
76
+ case "interaction":
77
+ return {
78
+ kind: "interaction",
79
+ events: value ? splitEvents(value) : [...DEFAULT_INTERACTION_EVENTS]
80
+ };
81
+ case "media":
82
+ if (!value) {
83
+ throw new LoadDirectiveError(
84
+ `'load:media' needs a query, e.g. load:media="(min-width: 1024px)".`
85
+ );
86
+ }
87
+ return { kind: "media", query: value };
88
+ default:
89
+ throw new LoadDirectiveError(`Unhandled load strategy '${strategy}'.`);
90
+ }
91
+ }
92
+ function splitEvents(value) {
93
+ const events = value.split(/[\s,]+/).map((e) => e.trim()).filter(Boolean);
94
+ if (events.length === 0) {
95
+ throw new LoadDirectiveError(`'load:interaction' was given no event names.`);
96
+ }
97
+ return events;
98
+ }
99
+ function isDeferred(strategy) {
100
+ return strategy.kind !== "eager" && strategy.kind !== "never";
101
+ }
102
+
103
+ // src/resolve/resolve-ir.ts
104
+ function resolveComponentSources(root, options = {}) {
105
+ const { resolver, isBound, modules, strategyFor } = options;
106
+ const builtins = builtinComponentMap(modules);
107
+ const resolved = /* @__PURE__ */ new Map();
108
+ const unresolved = /* @__PURE__ */ new Set();
109
+ const annotate = (node) => {
110
+ const { name } = node;
111
+ if (!name || name.includes(".")) return;
112
+ if (isBound?.(name)) return;
113
+ const source = sourceFor(name);
114
+ if (!source) {
115
+ unresolved.add(name);
116
+ return;
117
+ }
118
+ const loading = source.origin === "builtin" && RESERVED_COMPONENTS.has(name) ? EAGER : strategyFor?.(node) ?? EAGER;
119
+ node.source = { ...source, loading };
120
+ resolved.set(name, node.source);
121
+ };
122
+ const sourceFor = (name) => {
123
+ if (RESERVED_COMPONENTS.has(name)) {
124
+ return { module: builtins[name], export: name, origin: "builtin" };
125
+ }
126
+ const rule = resolver?.resolve(name);
127
+ if (rule) return { module: rule.module, export: rule.export, origin: "rule" };
128
+ if (ROUTER_COMPONENTS.includes(name)) {
129
+ return { module: builtins[name], export: name, origin: "builtin" };
130
+ }
131
+ return void 0;
132
+ };
133
+ walk(root, (node) => {
134
+ if (node.kind === "component") annotate(node);
135
+ });
136
+ return { resolved, unresolved: [...unresolved] };
137
+ }
138
+ function walk(root, visit) {
139
+ const nodes = Array.isArray(root) ? root : [root];
140
+ for (const node of nodes) {
141
+ visit(node);
142
+ const children = node.children;
143
+ if (children) walk(children, visit);
144
+ }
145
+ }
146
+
147
+ // src/optimize/collapse-strategies.ts
148
+ function collapseStrategies(root) {
149
+ const components = [];
150
+ walk(root, (node) => {
151
+ if (node.kind === "component" && node.source) components.push(node);
152
+ });
153
+ const eager = /* @__PURE__ */ new Set();
154
+ const never = /* @__PURE__ */ new Set();
155
+ for (const node of components) {
156
+ const { module, loading } = node.source;
157
+ if (loading.kind === "eager") eager.add(module);
158
+ if (loading.kind === "never") never.add(module);
159
+ }
160
+ const collapsed = /* @__PURE__ */ new Map();
161
+ for (const node of components) {
162
+ const source = node.source;
163
+ if (!isDeferred(source.loading)) continue;
164
+ if (!eager.has(source.module)) continue;
165
+ source.loading = { kind: "eager" };
166
+ collapsed.set(source.module, (collapsed.get(source.module) ?? 0) + 1);
167
+ }
168
+ return {
169
+ collapsed,
170
+ conflicted: [...never].filter((m) => eager.has(m))
171
+ };
172
+ }
173
+
174
+ // src/analyze/reactive-bindings.ts
175
+ function patternNames(node, out) {
176
+ if (!node) return;
177
+ switch (node.type) {
178
+ case "Identifier":
179
+ out.add(node.name);
180
+ return;
181
+ case "ObjectPattern":
182
+ for (const p of node.properties ?? []) {
183
+ if (p.type === "RestElement") patternNames(p.argument, out);
184
+ else patternNames(p.value, out);
185
+ }
186
+ return;
187
+ case "ArrayPattern":
188
+ for (const e of node.elements ?? []) patternNames(e, out);
189
+ return;
190
+ case "AssignmentPattern":
191
+ patternNames(node.left, out);
192
+ return;
193
+ case "RestElement":
194
+ patternNames(node.argument, out);
195
+ return;
196
+ }
197
+ }
198
+ function walk2(root, visit) {
199
+ if (!root || typeof root !== "object" || typeof root.type !== "string") return;
200
+ visit(root);
201
+ for (const key of Object.keys(root)) {
202
+ if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
203
+ const value = root[key];
204
+ if (Array.isArray(value)) for (const item of value) walk2(item, visit);
205
+ else if (value && typeof value === "object") walk2(value, visit);
206
+ }
207
+ }
208
+ function calledPrimitive(node, bindings) {
209
+ if (node.type !== "CallExpression") return void 0;
210
+ const callee = node.callee;
211
+ if (callee?.type !== "Identifier") return void 0;
212
+ const name = callee.name;
213
+ const imported = bindings.primitives.get(name);
214
+ if (imported) return imported;
215
+ const intrinsic = INTRINSICS[name];
216
+ if (intrinsic && !bindings.shadowed.has(name)) return intrinsic.returns;
217
+ return void 0;
218
+ }
219
+ function classify(id, returns, kinds) {
220
+ if (Array.isArray(returns)) {
221
+ if (id.type === "ArrayPattern") {
222
+ id.elements.forEach((element, index) => {
223
+ const kind = returns[index];
224
+ if (element?.type === "Identifier" && kind) kinds.set(element.name, kind);
225
+ });
226
+ }
227
+ return;
228
+ }
229
+ if (id.type === "Identifier") kinds.set(id.name, returns);
230
+ }
231
+ function declaredNames(program) {
232
+ const names = /* @__PURE__ */ new Set();
233
+ walk2(program, (node) => {
234
+ switch (node.type) {
235
+ case "VariableDeclarator":
236
+ patternNames(node.id, names);
237
+ return;
238
+ case "FunctionDeclaration":
239
+ case "FunctionExpression":
240
+ case "ArrowFunctionExpression":
241
+ patternNames(node.id, names);
242
+ for (const p of node.params ?? []) patternNames(p, names);
243
+ return;
244
+ case "ClassDeclaration":
245
+ case "ClassExpression":
246
+ patternNames(node.id, names);
247
+ return;
248
+ case "ImportSpecifier":
249
+ case "ImportDefaultSpecifier":
250
+ case "ImportNamespaceSpecifier":
251
+ patternNames(node.local, names);
252
+ return;
253
+ case "CatchClause":
254
+ patternNames(node.param, names);
255
+ return;
256
+ }
257
+ });
258
+ return names;
259
+ }
260
+ function resolveReactiveBindings(program) {
261
+ const bindings = { kinds: /* @__PURE__ */ new Map(), primitives: /* @__PURE__ */ new Map(), shadowed: /* @__PURE__ */ new Set() };
262
+ const root = program;
263
+ walk2(root, (node) => {
264
+ const names = /* @__PURE__ */ new Set();
265
+ if (node.type === "VariableDeclarator") patternNames(node.id, names);
266
+ else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") patternNames(node.id, names);
267
+ else if (node.type === "ImportDefaultSpecifier" || node.type === "ImportNamespaceSpecifier") patternNames(node.local, names);
268
+ else if (node.type === "ImportSpecifier") patternNames(node.local, names);
269
+ else if (node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" || node.type === "FunctionDeclaration") {
270
+ for (const p of node.params ?? []) patternNames(p, names);
271
+ }
272
+ for (const name of names) if (INTRINSICS[name]) bindings.shadowed.add(name);
273
+ });
274
+ for (const statement of root.body ?? []) {
275
+ if (statement.type !== "ImportDeclaration") continue;
276
+ if (!isPrimitiveModule(statement.source?.value)) continue;
277
+ for (const specifier of statement.specifiers ?? []) {
278
+ if (specifier.type !== "ImportSpecifier") continue;
279
+ const importedNode = specifier.imported;
280
+ const imported = importedNode.type === "Identifier" ? importedNode.name : importedNode.value;
281
+ const returns = RUNTIME_PRIMITIVES[imported];
282
+ if (returns) bindings.primitives.set(specifier.local.name, returns);
283
+ }
284
+ }
285
+ walk2(root, (node) => {
286
+ if (node.type !== "VariableDeclarator" || !node.init) return;
287
+ const returns = calledPrimitive(node.init, bindings);
288
+ if (returns) classify(node.id, returns, bindings.kinds);
289
+ });
290
+ return bindings;
291
+ }
292
+
293
+ // src/transform/source-locations.ts
294
+ var SOURCE_MARKER = "__fx_source";
295
+ var COMPONENT_MARKER = "__fx_component";
296
+ var HOLE_MARKER = "__fx_hole";
297
+ var markHole = (accessor, line, column, name) => `(globalThis.${HOLE_MARKER} ?? ((f) => f))(${accessor},${line},${column}${name === void 0 ? "" : `,${JSON.stringify(name)}`})`;
298
+ var PROPS_MARKER = "__fx_props";
299
+ var markProps = (object, at) => `(globalThis.${PROPS_MARKER} ?? ((p) => p))(${object},${JSON.stringify(at)})`;
300
+ var RUNTIME_PRIMITIVES2 = /* @__PURE__ */ new Set([
301
+ "signal",
302
+ "memo",
303
+ "effect",
304
+ "store",
305
+ "resource",
306
+ "watch",
307
+ "createSignal",
308
+ "createMemo",
309
+ "createEffect",
310
+ "createStore",
311
+ "createResource"
312
+ ]);
313
+ function mayHaveReactiveCall(code) {
314
+ for (const name of RUNTIME_PRIMITIVES2) {
315
+ if (code.includes(name)) return true;
316
+ }
317
+ return code.includes("$signal") || code.includes("$memo") || code.includes("$effect") || code.includes("$store");
318
+ }
319
+ var SINGLE_STATEMENT_PARENTS = /* @__PURE__ */ new Set([
320
+ "IfStatement",
321
+ "ForStatement",
322
+ "ForInStatement",
323
+ "ForOfStatement",
324
+ "WhileStatement",
325
+ "DoWhileStatement",
326
+ "LabeledStatement",
327
+ "WithStatement"
328
+ ]);
329
+ function isLoneBranch(statement, parent) {
330
+ if (!parent || statement.type === "BlockStatement") return false;
331
+ return SINGLE_STATEMENT_PARENTS.has(parent.type);
332
+ }
333
+ function isExport(node) {
334
+ return node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration";
335
+ }
336
+ function isStatement(node) {
337
+ return node.type.endsWith("Statement") || node.type === "VariableDeclaration";
338
+ }
339
+ function walk3(node, visit, stack = []) {
340
+ if (!node || typeof node.type !== "string") return;
341
+ visit(node, stack);
342
+ stack.push(node);
343
+ for (const key of Object.keys(node)) {
344
+ if (key === "loc" || key === "parent") continue;
345
+ const value = node[key];
346
+ if (Array.isArray(value)) {
347
+ for (const child of value) walk3(child, visit, stack);
348
+ } else if (value && typeof value.type === "string") {
349
+ walk3(value, visit, stack);
350
+ }
351
+ }
352
+ stack.pop();
353
+ }
354
+ function nameFor(stack) {
355
+ const declarator = stack[stack.length - 1];
356
+ if (declarator?.type !== "VariableDeclarator") return void 0;
357
+ const id = declarator.id;
358
+ if (id?.type === "Identifier") return id.name;
359
+ if (id?.type === "ArrayPattern") {
360
+ const first = id.elements?.[0];
361
+ if (first?.type === "Identifier") return first.name;
362
+ }
363
+ return void 0;
364
+ }
365
+ function componentName(node) {
366
+ if (node.type === "FunctionDeclaration") {
367
+ const name = node.id?.name;
368
+ return name && name[0] === name[0]?.toUpperCase() ? name : void 0;
369
+ }
370
+ if (node.type === "VariableDeclarator") {
371
+ const id = node.id;
372
+ const init = node.init;
373
+ if (id?.type !== "Identifier" || !init) return void 0;
374
+ if (init.type !== "ArrowFunctionExpression" && init.type !== "FunctionExpression") return void 0;
375
+ const name = id.name;
376
+ return name[0] === name[0]?.toUpperCase() ? name : void 0;
377
+ }
378
+ return void 0;
379
+ }
380
+ function collectSourceEdits(program, filename) {
381
+ const edits = [];
382
+ const claimed = /* @__PURE__ */ new Set();
383
+ const { primitives, shadowed } = resolveReactiveBindings(program);
384
+ walk3(program, (node, stack) => {
385
+ const component = componentName(node);
386
+ if (component) {
387
+ const at = node.loc?.start;
388
+ let end2 = node.end;
389
+ for (let i = stack.length - 1; i >= 0; i--) {
390
+ const up = stack[i];
391
+ if (up.type !== "VariableDeclaration" && up.type !== "ExportNamedDeclaration" && up.type !== "ExportDefaultDeclaration") {
392
+ break;
393
+ }
394
+ end2 = up.end;
395
+ }
396
+ if (at) {
397
+ edits.push({
398
+ start: end2,
399
+ end: end2,
400
+ code: `;globalThis.${COMPONENT_MARKER}?.(${JSON.stringify(component)},${JSON.stringify(filename)},${at.line},${at.column});`
401
+ });
402
+ }
403
+ }
404
+ if (node.type !== "CallExpression") return;
405
+ const callee = node.callee;
406
+ if (callee?.type !== "Identifier") return;
407
+ const name = callee.name;
408
+ const intrinsic = isIntrinsicName(name) && !shadowed.has(name) ? INTRINSICS[name] : void 0;
409
+ const imported = primitives.has(name) || RUNTIME_PRIMITIVES2.has(name);
410
+ if (!intrinsic && !imported) return;
411
+ const position = node.loc?.start;
412
+ if (!position) return;
413
+ let statement;
414
+ let parent;
415
+ let index = -1;
416
+ for (let i = stack.length - 1; i >= 0; i--) {
417
+ if (isStatement(stack[i]) || isExport(stack[i])) {
418
+ statement = stack[i];
419
+ parent = stack[i - 1];
420
+ index = i;
421
+ break;
422
+ }
423
+ }
424
+ if (!statement) return;
425
+ let start = statement.start;
426
+ let end = statement.end;
427
+ for (let i = index - 1; i >= 0; i--) {
428
+ if (!isExport(stack[i])) break;
429
+ start = stack[i].start;
430
+ end = stack[i].end;
431
+ parent = stack[i - 1];
432
+ }
433
+ if (claimed.has(start)) return;
434
+ claimed.add(start);
435
+ const label = nameFor(stack);
436
+ const args = [
437
+ JSON.stringify(filename),
438
+ String(position.line),
439
+ String(position.column),
440
+ label ? JSON.stringify(label) : void 0
441
+ ].filter((a) => a !== void 0).join(",");
442
+ const mark = `globalThis.${SOURCE_MARKER}?.(${args});`;
443
+ if (isLoneBranch(statement, parent)) {
444
+ edits.push({ start, end: start, code: `{${mark}` });
445
+ edits.push({ start: end, end, code: "}" });
446
+ return;
447
+ }
448
+ edits.push({ start, end: start, code: mark });
449
+ });
450
+ return { edits, marked: edits.length };
451
+ }
452
+
453
+ // src/codegen/serialize-static.ts
454
+ var VOID_ELEMENTS = /* @__PURE__ */ new Set([
455
+ "area",
456
+ "base",
457
+ "br",
458
+ "col",
459
+ "embed",
460
+ "hr",
461
+ "img",
462
+ "input",
463
+ "link",
464
+ "meta",
465
+ "param",
466
+ "source",
467
+ "track",
468
+ "wbr"
469
+ ]);
470
+ var HTML_NAME = {
471
+ className: "class",
472
+ htmlFor: "for"
473
+ };
474
+ var PROPERTY_ONLY = /* @__PURE__ */ new Set([
475
+ "innerHTML",
476
+ "outerHTML",
477
+ "innerText",
478
+ "textContent",
479
+ "value",
480
+ "checked",
481
+ "selected",
482
+ "muted",
483
+ "defaultValue",
484
+ "defaultChecked",
485
+ "children",
486
+ "ref"
487
+ ]);
488
+ var RAW_TEXT_ELEMENTS = /* @__PURE__ */ new Set(["script", "style", "textarea", "title"]);
489
+ function isRawTextElement(tag) {
490
+ return RAW_TEXT_ELEMENTS.has(tag);
491
+ }
492
+ function htmlAttrName(name) {
493
+ return HTML_NAME[name] ?? name;
494
+ }
495
+ function isPlainLiteralAttr(prop) {
496
+ if (prop.kind !== "attr") return false;
497
+ if (prop.expr !== void 0) return false;
498
+ if (prop.name.includes(":")) return false;
499
+ return !PROPERTY_ONLY.has(prop.name);
500
+ }
501
+ function isSerializable(node) {
502
+ if (!node.static) return false;
503
+ if (isRawTextElement(node.tag)) return false;
504
+ for (const prop of node.props) {
505
+ if (!isPlainLiteralAttr(prop)) return false;
506
+ }
507
+ for (const child of node.children) {
508
+ if (child.kind === "text") continue;
509
+ if (child.kind === "element" && isSerializable(child)) continue;
510
+ return false;
511
+ }
512
+ return true;
513
+ }
514
+ function serializeStatic(node) {
515
+ const attrs = node.props.map(serializeProp).filter(Boolean).join("");
516
+ const open = `<${node.tag}${attrs}>`;
517
+ if (VOID_ELEMENTS.has(node.tag)) return open;
518
+ return `${open}${node.children.map(serializeChild).join("")}</${node.tag}>`;
519
+ }
520
+ function serializeChild(child) {
521
+ if (child.kind === "text") return escapeText(child.value);
522
+ if (child.kind !== "element") throw new Error(`serializeStatic: unexpected ${child.kind}`);
523
+ return serializeStatic(child);
524
+ }
525
+ function serializeProp(prop) {
526
+ const name = HTML_NAME[prop.name] ?? prop.name;
527
+ const value = prop.literal;
528
+ if (value === true || value === void 0) return ` ${name}`;
529
+ if (value === false || value === null) return "";
530
+ return ` ${name}="${escapeAttr(String(value))}"`;
531
+ }
532
+ function escapeAttr(value) {
533
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
534
+ }
535
+ function escapeText(value) {
536
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
537
+ }
538
+ function templatePositions(root) {
539
+ const pos = [];
540
+ let file;
541
+ const walk4 = (el) => {
542
+ file ??= el.at?.file;
543
+ pos.push(el.at?.line ?? 0, el.at?.column ?? 0);
544
+ for (const child of el.children) if (child.kind === "element") walk4(child);
545
+ };
546
+ walk4(root);
547
+ return file && pos.some((n) => n !== 0) ? { file, pos } : void 0;
548
+ }
549
+
550
+ // src/codegen/partial-template.ts
551
+ var HOLE_START = "<!--fx-->";
552
+ var HOLE_END = "<!--fx/-->";
553
+ function isHole(node) {
554
+ return node.kind === "expr" || node.kind === "component" || node.kind === "control";
555
+ }
556
+ function isTemplateChild(node) {
557
+ return node.kind === "text" || node.kind === "element" && isTemplateElement(node);
558
+ }
559
+ function isTemplateElement(node) {
560
+ if (node.svg) return false;
561
+ if (isRawTextElement(node.tag)) return false;
562
+ if (!node.props.every((p) => isPlainLiteralAttr(p))) return false;
563
+ return node.children.every((c) => isTemplateChild(c) || isHole(c));
564
+ }
565
+ function containsHole(node) {
566
+ if (isHole(node)) return true;
567
+ const children = node.children;
568
+ return children ? children.some(containsHole) : false;
569
+ }
570
+ function addressable(el) {
571
+ for (let i = 0; i < el.children.length; i++) {
572
+ const child = el.children[i];
573
+ if (child.kind === "text") {
574
+ if (child.value === "") return false;
575
+ if (el.children[i + 1]?.kind === "text") return false;
576
+ }
577
+ }
578
+ return el.children.every((c) => c.kind !== "element" || addressable(c));
579
+ }
580
+ function planPartialTemplate(root) {
581
+ if (!isTemplateElement(root)) return null;
582
+ if (!addressable(root)) return null;
583
+ if (!root.children.some(containsHole)) return null;
584
+ const steps = [];
585
+ const holes = [];
586
+ let refCount = 0;
587
+ const declare = (expr) => {
588
+ const ref = `_n$${refCount++}`;
589
+ steps.push({ ref, expr });
590
+ return ref;
591
+ };
592
+ walk4(root, "_el$");
593
+ return { html: serializeWithMarkers(root), tag: root.tag, steps, holes };
594
+ function walk4(el, elementRef) {
595
+ let last = -1;
596
+ el.children.forEach((child, i) => {
597
+ if (containsHole(child)) last = i;
598
+ });
599
+ let previous = null;
600
+ for (let i = 0; i <= last; i++) {
601
+ const child = el.children[i];
602
+ const expr = previous ? `${previous}.nextSibling` : `${elementRef}.firstChild`;
603
+ if (isHole(child)) {
604
+ const startRef = declare(expr);
605
+ const endRef = declare(`holeEnd(${startRef})`);
606
+ holes.push({ parentRef: elementRef, startRef, endRef, node: child });
607
+ previous = endRef;
608
+ continue;
609
+ }
610
+ const ref = declare(expr);
611
+ if (child.kind === "element" && containsHole(child)) walk4(child, ref);
612
+ previous = ref;
613
+ }
614
+ }
615
+ }
616
+ function serializeWithMarkers(el) {
617
+ return serializeStatic(withSentinels(el)).split(SENTINEL).join(HOLE_START + HOLE_END);
618
+ }
619
+ function withSentinels(el) {
620
+ return {
621
+ ...el,
622
+ children: el.children.map(
623
+ (child) => isHole(child) ? { kind: "text", value: SENTINEL } : child.kind === "element" ? withSentinels(child) : child
624
+ )
625
+ };
626
+ }
627
+ var SENTINEL = "\0fx-hole\0";
628
+
629
+ // src/codegen/contract.ts
630
+ var RUNTIME_CONTRACT_V1 = {
631
+ version: 1,
632
+ module: "@fluixi/dom",
633
+ symbols: [
634
+ "createNativeElement",
635
+ "insert",
636
+ "spread",
637
+ "setAttribute",
638
+ "delegateEvents",
639
+ "createComponent",
640
+ "createMemo",
641
+ "untrack",
642
+ "Show",
643
+ "For",
644
+ "Index",
645
+ "Switch",
646
+ "Match",
647
+ "Dynamic",
648
+ "ErrorBoundary"
649
+ ]
650
+ };
651
+ var RUNTIME_CONTRACT_V2 = {
652
+ version: 2,
653
+ module: "@fluixi/dom",
654
+ symbols: [...RUNTIME_CONTRACT_V1.symbols, "template", "cloneTemplate", "walk"]
655
+ };
656
+
657
+ // src/analyze/paren.ts
658
+ function skipQuoted(src, start) {
659
+ const quote = src[start];
660
+ for (let i = start + 1; i < src.length; i++) {
661
+ const c = src[i];
662
+ if (c === "\\") i++;
663
+ else if (c === quote) return i + 1;
664
+ else if (c === "\n") return -1;
665
+ }
666
+ return -1;
667
+ }
668
+ function skipTemplate(src, start) {
669
+ let i = start + 1;
670
+ while (i < src.length) {
671
+ const c = src[i];
672
+ if (c === "\\") {
673
+ i += 2;
674
+ } else if (c === "`") {
675
+ return i + 1;
676
+ } else if (c === "$" && src[i + 1] === "{") {
677
+ let depth = 1;
678
+ i += 2;
679
+ while (i < src.length && depth > 0) {
680
+ const k = src[i];
681
+ if (k === "\\") i += 2;
682
+ else if (k === "`") {
683
+ const end = skipTemplate(src, i);
684
+ if (end < 0) return -1;
685
+ i = end;
686
+ } else if (k === '"' || k === "'") {
687
+ const end = skipQuoted(src, i);
688
+ if (end < 0) return -1;
689
+ i = end;
690
+ } else {
691
+ if (k === "{") depth++;
692
+ else if (k === "}") depth--;
693
+ i++;
694
+ }
695
+ }
696
+ } else {
697
+ i++;
698
+ }
699
+ }
700
+ return -1;
701
+ }
702
+ function skipRegex(src, start) {
703
+ let inClass = false;
704
+ for (let i = start + 1; i < src.length; i++) {
705
+ const c = src[i];
706
+ if (c === "\\") i++;
707
+ else if (c === "[") inClass = true;
708
+ else if (c === "]") inClass = false;
709
+ else if (c === "\n") return -1;
710
+ else if (c === "/" && !inClass) {
711
+ let end = i + 1;
712
+ while (end < src.length && /[a-z]/i.test(src[end])) end++;
713
+ return end;
714
+ }
715
+ }
716
+ return -1;
717
+ }
718
+ function divides(prev) {
719
+ return prev !== "" && /[A-Za-z0-9_$)\]]/.test(prev);
720
+ }
721
+ function topLevelComma(src) {
722
+ let depth = 0;
723
+ let prev = "";
724
+ let i = 0;
725
+ while (i < src.length) {
726
+ const c = src[i];
727
+ if (c === '"' || c === "'") {
728
+ const end = skipQuoted(src, i);
729
+ if (end < 0) return null;
730
+ i = end;
731
+ prev = c;
732
+ } else if (c === "`") {
733
+ const end = skipTemplate(src, i);
734
+ if (end < 0) return null;
735
+ i = end;
736
+ prev = c;
737
+ } else if (c === "/" && src[i + 1] === "/") {
738
+ return null;
739
+ } else if (c === "/" && src[i + 1] === "*") {
740
+ const end = src.indexOf("*/", i + 2);
741
+ if (end < 0) return null;
742
+ i = end + 2;
743
+ } else if (c === "/" && !divides(prev)) {
744
+ const end = skipRegex(src, i);
745
+ if (end < 0) return null;
746
+ i = end;
747
+ prev = "/";
748
+ } else {
749
+ if (c === "(" || c === "[" || c === "{") depth++;
750
+ else if (c === ")" || c === "]" || c === "}") {
751
+ depth--;
752
+ if (depth < 0) return null;
753
+ } else if (c === "," && depth === 0) return true;
754
+ if (!/\s/.test(c)) prev = c;
755
+ i++;
756
+ }
757
+ }
758
+ return depth === 0 ? false : null;
759
+ }
760
+ function paren(code, position) {
761
+ const src = code.trim();
762
+ if (src === "") return `(${code})`;
763
+ if (position === "arrowBody" && src[0] === "{") return `(${code})`;
764
+ return topLevelComma(src) === false ? code : `(${code})`;
765
+ }
766
+
767
+ // src/codegen/backends/imperative.ts
768
+ var CONTROL_COMPONENT = {
769
+ show: "Show",
770
+ for: "For",
771
+ index: "Index",
772
+ switch: "Switch",
773
+ match: "Match",
774
+ dynamic: "Dynamic",
775
+ errorBoundary: "ErrorBoundary",
776
+ suspense: "Suspense"
777
+ };
778
+ function isIdent(name) {
779
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
780
+ }
781
+ function propKey(name) {
782
+ return isIdent(name) ? name : JSON.stringify(name);
783
+ }
784
+ function propValue(p) {
785
+ if (p.expr !== void 0) {
786
+ if (p.name === "ref" && p.at)
787
+ return markHole(paren(p.expr, "value"), p.at.line, p.at.column, p.expr);
788
+ if (!p.reactive) return paren(p.expr, "value");
789
+ const accessor = `() => ${paren(p.expr, "arrowBody")}`;
790
+ return p.at ? markHole(accessor, p.at.line, p.at.column, p.directive) : accessor;
791
+ }
792
+ return JSON.stringify(p.literal ?? true);
793
+ }
794
+ function componentPropValue(p) {
795
+ if (p.expr !== void 0) return paren(p.expr, "value");
796
+ return JSON.stringify(p.literal ?? true);
797
+ }
798
+ function emitProps(props, childrenExpr, used) {
799
+ const spreads = props.filter((p) => p.kind === "spread");
800
+ const normal = props.filter((p) => p.kind !== "spread");
801
+ const entries = normal.map((p) => `${propKey(p.name)}: ${propValue(p)}`);
802
+ if (childrenExpr != null) entries.push(`children: ${childrenExpr}`);
803
+ const obj = `{ ${entries.join(", ")} }`;
804
+ if (spreads.length > 0) {
805
+ used.add("mergeProps");
806
+ return `mergeProps(${spreads.map((s) => s.expr).join(", ")}, ${obj})`;
807
+ }
808
+ return obj;
809
+ }
810
+ function markBind(code, at) {
811
+ return at ? markHole(code, at.line, at.column) : code;
812
+ }
813
+ function emitChildren(children, used, templates) {
814
+ if (children.length === 1) return emitNode(children[0], used, templates);
815
+ return `[${children.map((c) => emitNode(c, used, templates)).join(", ")}]`;
816
+ }
817
+ function emitComponent(name, props, children, used, templates, at) {
818
+ used.add("createMemo");
819
+ used.add("createComponent");
820
+ const spreads = props.filter((p) => p.kind === "spread");
821
+ const normal = props.filter((p) => p.kind !== "spread");
822
+ const entries = normal.map(
823
+ (p) => `get ${propKey(p.name)}() { return ${componentPropValue(p)}; }`
824
+ );
825
+ if (children.length > 0) {
826
+ entries.push(`get children() { return ${emitChildren(children, used, templates)}; }`);
827
+ }
828
+ let obj = `{ ${entries.join(", ")} }`;
829
+ if (spreads.length > 0) {
830
+ used.add("mergeProps");
831
+ obj = `mergeProps(${spreads.map((s) => s.expr).join(", ")}, ${obj})`;
832
+ }
833
+ const propAt = {};
834
+ for (const p of normal) if (p.at) propAt[p.name] = [p.at.line, p.at.column];
835
+ if (Object.keys(propAt).length) obj = markProps(obj, propAt);
836
+ const mark = at ? `globalThis.${SOURCE_MARKER}?.(${JSON.stringify(at.file)},${at.line},${at.column},${JSON.stringify(name)}), ` : "";
837
+ return `createMemo(${paren(`${mark}() => createComponent(${name}, ${obj})`, "value")})`;
838
+ }
839
+ function staticAttrAssignment(el, prop) {
840
+ const name = htmlAttrName(prop.name);
841
+ const value = prop.literal;
842
+ if (value === true || value === void 0) return `${el}.setAttribute(${JSON.stringify(name)}, "");`;
843
+ if (value === false || value === null) return "";
844
+ return `${el}.setAttribute(${JSON.stringify(name)}, ${JSON.stringify(String(value))});`;
845
+ }
846
+ var partial = false;
847
+ function emitNode(node, used, templates) {
848
+ switch (node.kind) {
849
+ case "text":
850
+ return JSON.stringify(node.value);
851
+ case "expr": {
852
+ if (!node.reactive) return paren(node.code, "value");
853
+ const accessor = `() => ${paren(node.code, "arrowBody")}`;
854
+ return node.at ? markHole(accessor, node.at.line, node.at.column) : accessor;
855
+ }
856
+ case "fragment":
857
+ if (node.children.length === 0) return "null";
858
+ return emitChildren(node.children, used, templates);
859
+ case "component":
860
+ return markBind(emitComponent(node.name, node.props, node.children, used, templates, node.at), node.bindAt ?? node.at);
861
+ case "control": {
862
+ const name = CONTROL_COMPONENT[node.control] ?? node.control;
863
+ used.add(name);
864
+ return markBind(emitComponent(name, node.props, node.children, used, templates), node.bindAt);
865
+ }
866
+ case "element": {
867
+ if (templates && node.static && !node.svg && isSerializable(node)) {
868
+ used.add("templateNode");
869
+ const id = `_tmpl$${templates.length}`;
870
+ templates.push({ id, html: serializeStatic(node), tag: node.tag, svg: false });
871
+ const at = templatePositions(node);
872
+ return at ? `templateNode(${id}, ${JSON.stringify(node.tag)}, false, false, ${JSON.stringify(at)})` : `templateNode(${id}, ${JSON.stringify(node.tag)})`;
873
+ }
874
+ if (templates && partial) {
875
+ const plan = planPartialTemplate(node);
876
+ if (plan) {
877
+ used.add("templateNode");
878
+ used.add("insert");
879
+ used.add("holeEnd");
880
+ used.add("holeContent");
881
+ used.add("holeScope");
882
+ const id = `_tmpl$${templates.length}`;
883
+ templates.push({ id, html: plan.html, tag: plan.tag, svg: false });
884
+ const at = templatePositions(node);
885
+ const lines = [
886
+ `const _el$ = templateNode(${id}, ${JSON.stringify(plan.tag)}, true${at ? `, false, ${JSON.stringify(at)}` : ""});`
887
+ ];
888
+ for (const step of plan.steps) lines.push(`const ${step.ref} = ${step.expr};`);
889
+ for (const hole of plan.holes) {
890
+ lines.push(
891
+ `insert(${hole.parentRef}, holeScope(${hole.startRef}, () => ${paren(emitNode(hole.node, used, templates), "arrowBody")}), ${hole.endRef}, holeContent(${hole.startRef}, ${hole.endRef}));`
892
+ );
893
+ }
894
+ lines.push("return _el$;");
895
+ return `(() => { ${lines.join(" ")} })()`;
896
+ }
897
+ }
898
+ used.add("createNativeElement");
899
+ const tag = JSON.stringify(node.tag);
900
+ const el = "_el$";
901
+ const parts = [];
902
+ const createArgs = node.at ? `${tag}, ${node.svg}, ${JSON.stringify(node.at)}` : node.svg ? `${tag}, true` : tag;
903
+ parts.push(`const ${el} = createNativeElement(${createArgs});`);
904
+ if (node.props.length > 0) {
905
+ if (!node.svg && node.props.every(isPlainLiteralAttr)) {
906
+ for (const p of node.props) parts.push(staticAttrAssignment(el, p));
907
+ } else {
908
+ used.add("spread");
909
+ const svgFlag = node.svg ? ", isSVG: true" : "";
910
+ parts.push(`spread({ element: ${el}, props: ${emitProps(node.props, null, used)}${svgFlag} });`);
911
+ }
912
+ }
913
+ for (const child of node.children) {
914
+ used.add("insert");
915
+ const childCode = emitNode(child, used, templates);
916
+ const isFn = child.kind === "expr" && child.reactive || child.kind === "component" || child.kind === "control";
917
+ parts.push(isFn ? `insert(${el}, ${childCode}, null);` : `insert(${el}, ${childCode});`);
918
+ }
919
+ parts.push(`return ${el};`);
920
+ return `(() => { ${parts.join(" ")} })()`;
921
+ }
922
+ }
923
+ }
924
+ function inlineTemplates(code, templates) {
925
+ if (!templates || templates.length === 0) return code;
926
+ const byId = new Map(templates.map((t) => [t.id, JSON.stringify(t.html)]));
927
+ return code.replace(/_tmpl\$\d+/g, (id) => byId.get(id) ?? id);
928
+ }
929
+ var imperativeBackend = {
930
+ name: "imperative",
931
+ contract: RUNTIME_CONTRACT_V1,
932
+ emit(node, options) {
933
+ const used = /* @__PURE__ */ new Set();
934
+ const templates = options?.templateClone !== false ? [] : void 0;
935
+ partial = options?.partialTemplates === true;
936
+ const code = emitNode(node, used, templates);
937
+ return { code, imports: Array.from(used), templates };
938
+ }
939
+ };
940
+
941
+ // src/optimize/analyze-static.ts
942
+ function propReason(prop) {
943
+ switch (prop.kind) {
944
+ case "event":
945
+ return "event";
946
+ case "ref":
947
+ return "ref";
948
+ case "spread":
949
+ return "spread";
950
+ case "class":
951
+ case "style":
952
+ return "class-or-style-directive";
953
+ case "attr":
954
+ case "prop":
955
+ if (prop.reactive) return "reactive-prop";
956
+ if (prop.expr !== void 0) return "expression-prop";
957
+ return void 0;
958
+ /* c8 ignore next 2 */
959
+ default:
960
+ return "expression-prop";
961
+ }
962
+ }
963
+ function analyzeStatic(root) {
964
+ const staticElements = [];
965
+ const reasons = /* @__PURE__ */ new Map();
966
+ const visit = (node) => {
967
+ switch (node.kind) {
968
+ case "text":
969
+ return true;
970
+ case "expr":
971
+ return false;
972
+ case "component":
973
+ case "control":
974
+ for (const child of node.children) visit(child);
975
+ return false;
976
+ case "fragment":
977
+ for (const child of node.children) visit(child);
978
+ return false;
979
+ case "element": {
980
+ let childrenStatic = true;
981
+ for (const child of node.children) {
982
+ if (!visit(child)) childrenStatic = false;
983
+ }
984
+ let reason;
985
+ for (const prop of node.props) {
986
+ reason = propReason(prop);
987
+ if (reason) break;
988
+ }
989
+ if (!reason && !childrenStatic) {
990
+ reason = childReason(node);
991
+ }
992
+ node.static = !reason;
993
+ if (reason) reasons.set(node, reason);
994
+ else staticElements.push(node);
995
+ return node.static;
996
+ }
997
+ /* c8 ignore next 2 */
998
+ default:
999
+ return false;
1000
+ }
1001
+ };
1002
+ for (const node of Array.isArray(root) ? root : [root]) visit(node);
1003
+ return { staticElements, reasons };
1004
+ }
1005
+ function childReason(node) {
1006
+ for (const child of node.children) {
1007
+ if (child.kind === "expr") return "expression-child";
1008
+ if (child.kind === "component") return "component-child";
1009
+ if (child.kind === "control") return "control-child";
1010
+ if (child.kind === "element" && !child.static) return "expression-child";
1011
+ if (child.kind === "fragment") return "expression-child";
1012
+ }
1013
+ return "expression-child";
1014
+ }
1015
+
1016
+ // src/analyze/reactive-expr.ts
1017
+ var STABLE_MEMBER = "children";
1018
+ function isReactiveShape(shape) {
1019
+ switch (shape.kind) {
1020
+ case "call":
1021
+ return true;
1022
+ case "member":
1023
+ return shape.property !== STABLE_MEMBER;
1024
+ case "compound":
1025
+ return shape.parts.some(isReactiveShape);
1026
+ case "opaque":
1027
+ return false;
1028
+ }
1029
+ }
1030
+
1031
+ // src/lower/text.ts
1032
+ function cleanTemplateText(value) {
1033
+ const lines = value.split(/\r\n|\n|\r/);
1034
+ let lastNonEmpty = 0;
1035
+ for (let i = 0; i < lines.length; i++) {
1036
+ if (/[^ \t]/.test(lines[i])) lastNonEmpty = i;
1037
+ }
1038
+ let out = "";
1039
+ for (let i = 0; i < lines.length; i++) {
1040
+ let line = lines[i].replace(/\t/g, " ");
1041
+ if (i !== 0) line = line.replace(/^ +/, "");
1042
+ if (i !== lines.length - 1) line = line.replace(/ +$/, "");
1043
+ if (!line) continue;
1044
+ if (i !== lastNonEmpty) line += " ";
1045
+ out += line;
1046
+ }
1047
+ return out;
1048
+ }
1049
+
1050
+ // src/lower/jsx.ts
1051
+ var SVG_TAGS = /* @__PURE__ */ new Set([
1052
+ "svg",
1053
+ "path",
1054
+ "circle",
1055
+ "rect",
1056
+ "line",
1057
+ "polygon",
1058
+ "polyline",
1059
+ "ellipse",
1060
+ "g",
1061
+ "defs",
1062
+ "clipPath",
1063
+ "text"
1064
+ ]);
1065
+ var EVENT_RE = /^on[A-Z]/;
1066
+ var DELEGATED = /* @__PURE__ */ new Set([
1067
+ "click",
1068
+ "dblclick",
1069
+ "input",
1070
+ "change",
1071
+ "submit",
1072
+ "focus",
1073
+ "blur",
1074
+ "keydown",
1075
+ "keyup",
1076
+ "keypress",
1077
+ "mousedown",
1078
+ "mouseup"
1079
+ ]);
1080
+ var isReactive = (node) => isReactiveShape(shapeOf(node));
1081
+ var posOf = (node, ctx) => {
1082
+ if (!ctx.sourceFile) return void 0;
1083
+ const at = node.loc?.start;
1084
+ return at ? { line: at.line, column: at.column } : void 0;
1085
+ };
1086
+ function literalOf(node) {
1087
+ if (node.type === "StringLiteral" || node.type === "NumericLiteral" || node.type === "BooleanLiteral") {
1088
+ return node.value;
1089
+ }
1090
+ if (node.type === "Literal" && (typeof node.value === "string" || typeof node.value === "number" || typeof node.value === "boolean")) {
1091
+ return node.value;
1092
+ }
1093
+ return void 0;
1094
+ }
1095
+ var isString = (node) => !!node && typeof literalOf(node) === "string";
1096
+ function tagInfo(name, ctx) {
1097
+ if (name.type === "JSXIdentifier") {
1098
+ return { tag: name.name, component: name.name[0] !== name.name[0].toLowerCase() };
1099
+ }
1100
+ if (name.type === "JSXMemberExpression") return { tag: ctx.code(name), component: true };
1101
+ if (name.type === "JSXNamespacedName") {
1102
+ return { tag: `${name.namespace.name}:${name.name.name}`, component: false };
1103
+ }
1104
+ return { tag: "div", component: false };
1105
+ }
1106
+ function attrName(name) {
1107
+ if (name.type === "JSXIdentifier") return name.name === "class" ? "className" : name.name;
1108
+ if (name.type === "JSXNamespacedName") return `${name.namespace.name}:${name.name.name}`;
1109
+ return "unknown";
1110
+ }
1111
+ function buildAttr(attr, ctx) {
1112
+ const name = attrName(attr.name);
1113
+ const isEvent = EVENT_RE.test(name);
1114
+ const isHandler = isEvent || name.startsWith("on:") || name === "ref";
1115
+ const kind = isEvent ? "event" : "attr";
1116
+ const base = { name, kind };
1117
+ if (isEvent) {
1118
+ const evt = name.slice(2).toLowerCase();
1119
+ base.event = { name: evt, delegated: DELEGATED.has(evt) };
1120
+ }
1121
+ const v = attr.value;
1122
+ if (v == null) {
1123
+ base.literal = true;
1124
+ base.at = posOf(attr, ctx);
1125
+ return base;
1126
+ }
1127
+ if (isString(v)) {
1128
+ base.literal = literalOf(v);
1129
+ base.at = posOf(v, ctx);
1130
+ return base;
1131
+ }
1132
+ if (v.type === "JSXExpressionContainer" && v.expression?.type !== "JSXEmptyExpression") {
1133
+ const expr = v.expression;
1134
+ const literal = literalOf(expr);
1135
+ if (literal !== void 0) {
1136
+ base.literal = literal;
1137
+ base.at = posOf(expr, ctx);
1138
+ return base;
1139
+ }
1140
+ base.expr = ctx.code(expr);
1141
+ base.reactive = isHandler ? false : isReactive(expr);
1142
+ base.at = posOf(expr, ctx);
1143
+ if (expr.type === "JSXElement" || expr.type === "JSXFragment") base.jsxElement = true;
1144
+ return base;
1145
+ }
1146
+ base.literal = true;
1147
+ return base;
1148
+ }
1149
+ function attrExprCode(attr, ctx) {
1150
+ const v = attr.value;
1151
+ if (v == null) return null;
1152
+ if (isString(v)) return JSON.stringify(literalOf(v));
1153
+ if (v.type === "JSXExpressionContainer" && v.expression?.type !== "JSXEmptyExpression") {
1154
+ return ctx.code(v.expression);
1155
+ }
1156
+ return null;
1157
+ }
1158
+ function buildProps(attrs, ctx) {
1159
+ const props = [];
1160
+ const usePairs = [];
1161
+ for (const a of attrs) {
1162
+ if (a.type === "JSXSpreadAttribute") {
1163
+ props.push({ name: "", kind: "spread", expr: ctx.code(a.argument) });
1164
+ continue;
1165
+ }
1166
+ if (a.type !== "JSXAttribute") continue;
1167
+ if (isLoadDirective(attrName(a.name))) continue;
1168
+ const ns = a.name.type === "JSXNamespacedName" ? a.name.namespace.name : null;
1169
+ if (ns === "use") {
1170
+ const dir = a.name.name.name;
1171
+ ctx.used.add(dir);
1172
+ const opts = attrExprCode(a, ctx);
1173
+ usePairs.push(opts != null ? `[${dir}, () => ${paren(opts, "arrowBody")}]` : `[${dir}]`);
1174
+ continue;
1175
+ }
1176
+ if (ns === "oncapture") {
1177
+ const evt = a.name.name.name.toLowerCase();
1178
+ const h = attrExprCode(a, ctx) ?? "undefined";
1179
+ props.push({ name: "on:" + evt, kind: "attr", expr: `[${h}, { capture: true }]` });
1180
+ continue;
1181
+ }
1182
+ props.push(buildAttr(a, ctx));
1183
+ }
1184
+ if (usePairs.length > 0) props.push({ name: "use", kind: "attr", expr: `[${usePairs.join(", ")}]` });
1185
+ return props;
1186
+ }
1187
+ function buildChildren(children, ctx) {
1188
+ const out = [];
1189
+ for (const child of children) {
1190
+ if (child.type === "JSXText") {
1191
+ const text = cleanTemplateText(child.value);
1192
+ if (text) out.push({ kind: "text", value: text });
1193
+ } else if (child.type === "JSXExpressionContainer") {
1194
+ if (child.expression?.type !== "JSXEmptyExpression") {
1195
+ const expr = child.expression;
1196
+ const reactive = isReactive(expr);
1197
+ out.push({
1198
+ kind: "expr",
1199
+ code: ctx.code(expr),
1200
+ reactive,
1201
+ ...reactive ? { at: posOf(expr, ctx) } : {}
1202
+ });
1203
+ }
1204
+ } else if (child.type === "JSXElement" || child.type === "JSXFragment") {
1205
+ out.push(buildNode(child, ctx));
1206
+ } else if (child.type === "JSXSpreadChild") {
1207
+ out.push({ kind: "expr", code: ctx.code(child.expression), reactive: false });
1208
+ }
1209
+ }
1210
+ return out;
1211
+ }
1212
+ function readLoad(attrs) {
1213
+ for (const a of attrs) {
1214
+ if (a.type !== "JSXAttribute") continue;
1215
+ const name = attrName(a.name);
1216
+ if (!isLoadDirective(name)) continue;
1217
+ if (a.value && !isString(a.value)) {
1218
+ throw new LoadDirectiveError(
1219
+ `'${name}' needs a literal value, not an expression — the strategy is compile-time.`
1220
+ );
1221
+ }
1222
+ return parseLoadDirective(name, a.value ? literalOf(a.value) : null);
1223
+ }
1224
+ return void 0;
1225
+ }
1226
+ function buildNode(node, ctx) {
1227
+ if (node.type === "JSXFragment") {
1228
+ return { kind: "fragment", children: buildChildren(node.children, ctx) };
1229
+ }
1230
+ const { tag, component } = tagInfo(node.openingElement.name, ctx);
1231
+ const props = buildProps(node.openingElement.attributes, ctx);
1232
+ const children = buildChildren(node.children, ctx);
1233
+ const at = ctx.sourceFile && node.loc?.start ? { file: ctx.sourceFile, line: node.loc.start.line, column: node.loc.start.column } : void 0;
1234
+ if (component) {
1235
+ const load = readLoad(node.openingElement.attributes);
1236
+ return { kind: "component", name: tag, props, children, ...load ? { load } : {}, ...at ? { at } : {} };
1237
+ }
1238
+ return { kind: "element", tag, svg: SVG_TAGS.has(tag), props, children, static: false, ...at ? { at } : {} };
1239
+ }
1240
+ function buildJsxIR(node, ctx) {
1241
+ const ir = buildNode(node, ctx);
1242
+ analyzeStatic(ir);
1243
+ return ir;
1244
+ }
1245
+
1246
+ // src/lower/template.ts
1247
+ import {
1248
+ parseTemplate
1249
+ } from "@fluixi/template-parser";
1250
+ var DELEGATED2 = /* @__PURE__ */ new Set([
1251
+ "click",
1252
+ "dblclick",
1253
+ "input",
1254
+ "change",
1255
+ "submit",
1256
+ "focus",
1257
+ "blur",
1258
+ "keydown",
1259
+ "keyup",
1260
+ "keypress",
1261
+ "mousedown",
1262
+ "mouseup"
1263
+ ]);
1264
+ function escapeTemplate(s) {
1265
+ return s.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/g, "\\${");
1266
+ }
1267
+ function capitalize(s) {
1268
+ return s.charAt(0).toUpperCase() + s.slice(1);
1269
+ }
1270
+ var Lowerer = class {
1271
+ constructor(holes, used, sourceFile, positionAt) {
1272
+ this.holes = holes;
1273
+ this.used = used;
1274
+ this.sourceFile = sourceFile;
1275
+ this.positionAt = positionAt;
1276
+ }
1277
+ /**
1278
+ * Where a tag is written, for the mark a component node carries.
1279
+ *
1280
+ * The parser reports offsets, and they are offsets into the file: the pieces it was given
1281
+ * carry the positions the front-end recorded. Only built when the host asked for source
1282
+ * locations, which is the only time either of these is set.
1283
+ */
1284
+ tagAt(node) {
1285
+ const start = node.loc?.start;
1286
+ if (!this.sourceFile || !this.positionAt || start == null) return void 0;
1287
+ const { line, column } = this.positionAt(start);
1288
+ return { file: this.sourceFile, line, column };
1289
+ }
1290
+ hole(i) {
1291
+ return this.holes[i] ?? { code: "undefined", reactive: false };
1292
+ }
1293
+ /** Emit a nested IR subtree to code (for `Show` fallback / `For` children). */
1294
+ emit(node) {
1295
+ const { code, imports, templates } = imperativeBackend.emit(node, {});
1296
+ for (const s of imports) this.used.add(s);
1297
+ return inlineTemplates(code, templates);
1298
+ }
1299
+ // --- content ------------------------------------------------------------
1300
+ lowerRoot(children) {
1301
+ const nodes = this.lowerChildren(children);
1302
+ if (nodes.length === 1) return nodes[0];
1303
+ return { kind: "fragment", children: nodes };
1304
+ }
1305
+ /** Lower a sibling list, handling text-drop and if/else/each restructuring. */
1306
+ lowerChildren(children) {
1307
+ const out = [];
1308
+ for (let i = 0; i < children.length; i++) {
1309
+ const child = children[i];
1310
+ if (child.kind === "Element" || child.kind === "Component") {
1311
+ const ifDir = child.attributes.find((a) => a.kind === "IfDirective");
1312
+ if (ifDir && ifDir.kind === "IfDirective") {
1313
+ let elseIdx = i + 1;
1314
+ if (elseIdx < children.length && this.isBlankText(children[elseIdx])) elseIdx++;
1315
+ const elseNode = children[elseIdx];
1316
+ const hasElse = elseNode && (elseNode.kind === "Element" || elseNode.kind === "Component") && elseNode.attributes.some((a) => a.kind === "ElseDirective");
1317
+ out.push(this.lowerIf(child, ifDir.hole, hasElse ? elseNode : null));
1318
+ if (hasElse) i = elseIdx;
1319
+ continue;
1320
+ }
1321
+ if (child.attributes.some((a) => a.kind === "EachDirective")) {
1322
+ out.push(this.lowerEach(child));
1323
+ continue;
1324
+ }
1325
+ }
1326
+ const node = this.lowerNode(child);
1327
+ if (node) out.push(node);
1328
+ }
1329
+ return out;
1330
+ }
1331
+ isBlankText(n) {
1332
+ return n.kind === "Text" && !n.raw && cleanTemplateText(n.value) === "";
1333
+ }
1334
+ lowerNode(node) {
1335
+ switch (node.kind) {
1336
+ case "Text": {
1337
+ if (node.raw) return { kind: "text", value: node.value };
1338
+ const cleaned = cleanTemplateText(node.value);
1339
+ return cleaned ? { kind: "text", value: cleaned } : null;
1340
+ }
1341
+ case "Comment":
1342
+ return null;
1343
+ // dropped, like JSX comments
1344
+ case "Expression": {
1345
+ const h = this.hole(node.hole);
1346
+ return { kind: "expr", code: h.code, reactive: h.reactive, ...h.at ? { at: h.at } : {} };
1347
+ }
1348
+ case "Fragment":
1349
+ return { kind: "fragment", children: this.lowerChildren(node.children) };
1350
+ case "Element":
1351
+ return this.lowerElement(node);
1352
+ case "Component":
1353
+ return this.lowerComponent(node);
1354
+ default:
1355
+ return null;
1356
+ }
1357
+ }
1358
+ lowerElement(el) {
1359
+ const isAttr = el.attributes.find((a) => a.kind === "Attribute" && a.name === "is");
1360
+ if (el.tag === "component" && isAttr && isAttr.value && isAttr.value.kind === "hole") {
1361
+ const rest = el.attributes.filter((a) => a !== isAttr);
1362
+ const node = this.lowerComponent({ ...el, kind: "Component", tag: "Dynamic", tagHole: null, attributes: rest });
1363
+ node.props.unshift({ name: "component", kind: "attr", expr: `() => ${paren(this.hole(isAttr.value.hole).code, "arrowBody")}` });
1364
+ return node;
1365
+ }
1366
+ const at = this.tagAt(el);
1367
+ return {
1368
+ kind: "element",
1369
+ tag: el.tag,
1370
+ svg: el.namespace === "svg",
1371
+ props: this.lowerAttributes(el.attributes),
1372
+ children: this.lowerChildren(el.children),
1373
+ static: false,
1374
+ ...at ? { at } : {}
1375
+ };
1376
+ }
1377
+ lowerComponent(el) {
1378
+ const name = el.tagHole != null ? this.hole(el.tagHole).code : el.tag;
1379
+ const props = this.lowerAttributes(el.attributes);
1380
+ const { slots, rest } = this.partitionSlots(el.children);
1381
+ for (const [slotName, nodes] of slots) {
1382
+ const ir = nodes.length === 1 ? nodes[0] : { kind: "fragment", children: nodes };
1383
+ const slotProp = {
1384
+ name: slotName,
1385
+ kind: "attr",
1386
+ expr: this.emit(ir),
1387
+ jsxElement: true
1388
+ };
1389
+ const clash = props.findIndex((p) => p.name === slotName);
1390
+ if (clash >= 0) props[clash] = slotProp;
1391
+ else props.push(slotProp);
1392
+ }
1393
+ const loadAttr = el.attributes.find((a) => a.kind === "LoadDirective");
1394
+ const load = loadAttr ? parseLoadDirective(`load:${loadAttr.strategy}`, loadAttr.modifier) : void 0;
1395
+ const bindAt = props.find((p) => p.at && p.reactive)?.at;
1396
+ const at = this.tagAt(el);
1397
+ return {
1398
+ kind: "component",
1399
+ name,
1400
+ props,
1401
+ children: this.lowerChildren(rest),
1402
+ ...at ? { at } : {},
1403
+ ...bindAt ? { bindAt } : {},
1404
+ ...load ? { load } : {}
1405
+ };
1406
+ }
1407
+ /** Split a component's children into named slots (`slot="x"`) and the rest. */
1408
+ partitionSlots(children) {
1409
+ const slots = /* @__PURE__ */ new Map();
1410
+ const rest = [];
1411
+ for (const child of children) {
1412
+ if (child.kind === "Element" || child.kind === "Component") {
1413
+ const slot = child.attributes.find(
1414
+ (a) => a.kind === "Attribute" && a.name === "slot"
1415
+ );
1416
+ if (slot && slot.value && slot.value.kind === "static") {
1417
+ const stripped = { ...child, attributes: child.attributes.filter((a) => a !== slot) };
1418
+ const ir = stripped.kind === "Element" ? this.lowerElement(stripped) : this.lowerComponent(stripped);
1419
+ const bucket = slots.get(slot.value.value) ?? [];
1420
+ bucket.push(ir);
1421
+ slots.set(slot.value.value, bucket);
1422
+ continue;
1423
+ }
1424
+ }
1425
+ rest.push(child);
1426
+ }
1427
+ return { slots, rest };
1428
+ }
1429
+ // --- control-flow sugar -------------------------------------------------
1430
+ /** `<el if=${cond}>…</el>` (+ optional `<el else>`) → `<Show when fallback>`. */
1431
+ lowerIf(el, condHole, elseEl) {
1432
+ const cond = this.hole(condHole);
1433
+ const props = [
1434
+ { name: "when", kind: "attr", expr: cond.code, reactive: cond.reactive, ...cond.at ? { at: cond.at } : {} }
1435
+ ];
1436
+ if (elseEl) {
1437
+ const elseIR = this.stripAndLower(elseEl, (a) => a.kind === "ElseDirective");
1438
+ props.push({ name: "fallback", kind: "attr", expr: this.emit(elseIR), jsxElement: true });
1439
+ }
1440
+ const child = this.stripAndLower(el, (a) => a.kind === "IfDirective");
1441
+ const at = this.tagAt(el);
1442
+ return { kind: "component", name: "Show", props, children: [child], ...at ? { at } : {}, ...cond.at ? { bindAt: cond.at } : {} };
1443
+ }
1444
+ /** `<el each=${items} key?>${item => …}</el>` → `<For each>{item => <el>…</el>}</For>`. */
1445
+ lowerEach(el) {
1446
+ const eachDir = el.attributes.find((a) => a.kind === "EachDirective");
1447
+ if (!eachDir || eachDir.kind !== "EachDirective") return this.lowerNode(el);
1448
+ const each = this.hole(eachDir.hole);
1449
+ const props = [{ name: "each", kind: "attr", expr: each.code, reactive: each.reactive, ...each.at ? { at: each.at } : {} }];
1450
+ if (eachDir.key) {
1451
+ const by = "static" in eachDir.key ? `(item) => item[${JSON.stringify(eachDir.key.static)}]` : this.hole(eachDir.key.hole).code;
1452
+ props.push({ name: "by", kind: "attr", expr: by });
1453
+ }
1454
+ const arrow = this.itemArrow(el);
1455
+ let childrenCode;
1456
+ if (arrow) {
1457
+ const bodyIR = { kind: "expr", code: arrow.body, reactive: arrow.bodyReactive };
1458
+ const repeated = this.rebuildWithChildren(el, [bodyIR]);
1459
+ childrenCode = `(${arrow.params.join(", ")}) => ${paren(this.emit(repeated), "arrowBody")}`;
1460
+ } else {
1461
+ const repeated = this.stripAndLower(el, (a) => a.kind === "EachDirective");
1462
+ childrenCode = `() => ${paren(this.emit(repeated), "arrowBody")}`;
1463
+ }
1464
+ const children = [{ kind: "expr", code: childrenCode, reactive: false }];
1465
+ const at = this.tagAt(el);
1466
+ return { kind: "component", name: "For", props, children, ...at ? { at } : {}, ...each.at ? { bindAt: each.at } : {} };
1467
+ }
1468
+ /** The single `${item => expr}` child arrow, if that's the element's content. */
1469
+ itemArrow(el) {
1470
+ const kids = el.children.filter((c) => !this.isBlankText(c));
1471
+ if (kids.length !== 1 || kids[0].kind !== "Expression") return null;
1472
+ return this.hole(kids[0].hole).arrow ?? null;
1473
+ }
1474
+ /** Lower an element to IR, dropping the directive attribute matched by `drop`. */
1475
+ stripAndLower(el, drop) {
1476
+ const clone = { ...el, attributes: el.attributes.filter((a) => !drop(a)) };
1477
+ return clone.kind === "Element" ? this.lowerElement(clone) : this.lowerComponent(clone);
1478
+ }
1479
+ /** Same element (minus each/key) but with explicit IR children. */
1480
+ rebuildWithChildren(el, children) {
1481
+ const props = this.lowerAttributes(
1482
+ el.attributes.filter((a) => a.kind !== "EachDirective")
1483
+ );
1484
+ if (el.kind === "Element") {
1485
+ const at = this.tagAt(el);
1486
+ return {
1487
+ kind: "element",
1488
+ tag: el.tag,
1489
+ svg: el.namespace === "svg",
1490
+ props,
1491
+ children,
1492
+ static: false,
1493
+ ...at ? { at } : {}
1494
+ };
1495
+ }
1496
+ return { kind: "component", name: el.tag, props, children };
1497
+ }
1498
+ // --- attributes ---------------------------------------------------------
1499
+ lowerAttributes(attrs) {
1500
+ const props = [];
1501
+ const classEntries = [];
1502
+ let classReactive = false;
1503
+ let classAt;
1504
+ const styleEntries = [];
1505
+ let styleReactive = false;
1506
+ let styleAt;
1507
+ const usePairs = [];
1508
+ for (const a of attrs) {
1509
+ switch (a.kind) {
1510
+ case "IfDirective":
1511
+ case "EachDirective":
1512
+ case "ElseDirective":
1513
+ break;
1514
+ // handled as control-flow at the parent level
1515
+ case "Attribute":
1516
+ props.push(this.plainAttr(a));
1517
+ break;
1518
+ case "PropertyBinding":
1519
+ props.push({
1520
+ name: a.name,
1521
+ kind: "prop",
1522
+ expr: this.hole(a.hole).code,
1523
+ reactive: this.hole(a.hole).reactive,
1524
+ ...this.hole(a.hole).at ? { at: this.hole(a.hole).at } : {}
1525
+ });
1526
+ break;
1527
+ case "EventBinding":
1528
+ props.push(this.eventProp(a));
1529
+ break;
1530
+ case "RefBinding":
1531
+ props.push({
1532
+ name: "ref",
1533
+ kind: "ref",
1534
+ expr: this.hole(a.hole).code,
1535
+ reactive: this.hole(a.hole).reactive,
1536
+ // Which variable ends up holding the element, and where it was written.
1537
+ ...this.hole(a.hole).at ? { at: this.hole(a.hole).at } : {}
1538
+ });
1539
+ break;
1540
+ case "Spread":
1541
+ props.push({ name: "", kind: "spread", expr: this.hole(a.hole).code });
1542
+ break;
1543
+ case "ClassDirective": {
1544
+ const h = this.hole(a.hole);
1545
+ classEntries.push(`${JSON.stringify(a.name)}: ${h.code}`);
1546
+ classReactive = classReactive || h.reactive;
1547
+ classAt ??= h.at;
1548
+ break;
1549
+ }
1550
+ case "StyleDirective": {
1551
+ const h = this.hole(a.hole);
1552
+ styleEntries.push(`${JSON.stringify(a.name)}: ${h.code}`);
1553
+ styleReactive = styleReactive || h.reactive;
1554
+ styleAt ??= h.at;
1555
+ break;
1556
+ }
1557
+ case "BindDirective":
1558
+ props.push(...this.bindProps(a.name, this.hole(a.hole)));
1559
+ break;
1560
+ case "UseDirective": {
1561
+ const dir = a.name ?? (a.hole != null ? this.hole(a.hole).code : null);
1562
+ if (!dir) break;
1563
+ usePairs.push(a.name != null && a.hole != null ? `[${dir}, () => ${paren(this.hole(a.hole).code, "arrowBody")}]` : `[${dir}]`);
1564
+ break;
1565
+ }
1566
+ }
1567
+ }
1568
+ if (classEntries.length > 0) {
1569
+ props.push({
1570
+ name: "classList",
1571
+ kind: "attr",
1572
+ expr: `{ ${classEntries.join(", ")} }`,
1573
+ reactive: classReactive,
1574
+ ...classAt ? { at: classAt } : {}
1575
+ });
1576
+ }
1577
+ if (styleEntries.length > 0) {
1578
+ props.push({
1579
+ name: "style",
1580
+ kind: "attr",
1581
+ expr: `{ ${styleEntries.join(", ")} }`,
1582
+ reactive: styleReactive,
1583
+ ...styleAt ? { at: styleAt } : {}
1584
+ });
1585
+ }
1586
+ if (usePairs.length > 0) {
1587
+ props.push({ name: "use", kind: "attr", expr: `[${usePairs.join(", ")}]` });
1588
+ }
1589
+ return props;
1590
+ }
1591
+ /**
1592
+ * Lower an event binding. Plain `@click`/`onClick` (no modifiers) stays a
1593
+ * DELEGATED handler (unchanged, byte-identical with JSX). `on:click` or any
1594
+ * modifier (`.capture`/`.once`/`.passive`/`.prevent`/`.stop`/`.self`) emits a
1595
+ * NATIVE `on:name` prop the runtime attaches via addEventListener.
1596
+ */
1597
+ eventProp(a) {
1598
+ const dom = a.name.toLowerCase();
1599
+ const handler = this.hole(a.hole).code;
1600
+ const native = a.syntax === "colon" || a.modifiers.length > 0;
1601
+ if (!native) {
1602
+ return {
1603
+ name: "on" + capitalize(a.name),
1604
+ kind: "event",
1605
+ event: { name: dom, delegated: DELEGATED2.has(dom) },
1606
+ expr: handler
1607
+ };
1608
+ }
1609
+ const wrapped = this.wrapHandler(handler, a.modifiers);
1610
+ const options = this.eventOptions(a.modifiers);
1611
+ const value = options ? `[${wrapped}, ${options}]` : wrapped;
1612
+ return { name: "on:" + dom, kind: "attr", expr: value };
1613
+ }
1614
+ /** Wrap a handler for `.prevent`/`.stop`/`.self` (no wrap when none apply). */
1615
+ wrapHandler(handler, mods) {
1616
+ const guard = mods.includes("self") ? "if (e.target !== e.currentTarget) return; " : "";
1617
+ const pre = [];
1618
+ if (mods.includes("prevent")) pre.push("e.preventDefault();");
1619
+ if (mods.includes("stop")) pre.push("e.stopPropagation();");
1620
+ if (!guard && pre.length === 0) return handler;
1621
+ return `(e) => { ${guard}${pre.join(" ")} return (${handler})(e); }`;
1622
+ }
1623
+ /** addEventListener options object from `.capture`/`.once`/`.passive`, or null. */
1624
+ eventOptions(mods) {
1625
+ const opts = [];
1626
+ if (mods.includes("capture")) opts.push("capture: true");
1627
+ if (mods.includes("once")) opts.push("once: true");
1628
+ if (mods.includes("passive")) opts.push("passive: true");
1629
+ return opts.length ? `{ ${opts.join(", ")} }` : null;
1630
+ }
1631
+ /** `bind:value=${sig}` → `value={read()}` + `onInput={e => write(e…value)}`. */
1632
+ bindProps(prop, h) {
1633
+ const sigCode = h.code;
1634
+ const checked = prop === "checked";
1635
+ const evt = checked ? "change" : "input";
1636
+ const accessor = checked ? "checked" : "value";
1637
+ this.used.add("bindPair");
1638
+ const sig = `bindPair(${sigCode})`;
1639
+ return [
1640
+ {
1641
+ name: prop,
1642
+ kind: "attr",
1643
+ expr: `${sig}[0]()`,
1644
+ reactive: true,
1645
+ directive: `bind:${prop}`,
1646
+ ...h.at ? { at: h.at } : {}
1647
+ },
1648
+ {
1649
+ name: "on" + capitalize(evt),
1650
+ kind: "event",
1651
+ event: { name: evt, delegated: DELEGATED2.has(evt) },
1652
+ // delegated handler: `target` is the bound element (currentTarget is the root)
1653
+ expr: `(e) => ${sig}[1](e.target.${accessor})`
1654
+ }
1655
+ ];
1656
+ }
1657
+ /** A plain attribute (incl. lit `?bool`, mixed values) — old `mkProp` behavior. */
1658
+ plainAttr(a) {
1659
+ const v = a.value;
1660
+ let name = a.name;
1661
+ if (a.name === "class") {
1662
+ name = v && v.kind === "hole" && this.hole(v.hole).object ? "classList" : "className";
1663
+ } else if (a.name === "html") {
1664
+ name = "innerHTML";
1665
+ }
1666
+ const kind = "attr";
1667
+ const base = { name, kind };
1668
+ if (v == null) {
1669
+ base.literal = true;
1670
+ return base;
1671
+ }
1672
+ if (v.kind === "static") {
1673
+ base.literal = v.value;
1674
+ return base;
1675
+ }
1676
+ if (v.kind === "hole") {
1677
+ const h = this.hole(v.hole);
1678
+ base.expr = h.code;
1679
+ base.reactive = h.reactive;
1680
+ if (h.at) base.at = h.at;
1681
+ return base;
1682
+ }
1683
+ let reactive = false;
1684
+ let at;
1685
+ const body = v.parts.map((p) => {
1686
+ if ("text" in p) return escapeTemplate(p.text);
1687
+ const h = this.hole(p.hole);
1688
+ reactive = reactive || h.reactive;
1689
+ at ??= h.at;
1690
+ return "${" + h.code + "}";
1691
+ }).join("");
1692
+ base.expr = "`" + body + "`";
1693
+ base.reactive = reactive;
1694
+ if (at) base.at = at;
1695
+ return base;
1696
+ }
1697
+ };
1698
+ function lowerTemplate(pieces, holes, used, opts = {}) {
1699
+ const { root } = parseTemplate(pieces, { svg: opts.svg });
1700
+ return new Lowerer(holes, used, opts.sourceFile, opts.positionAt).lowerRoot(root.children);
1701
+ }
1702
+
1703
+ export {
1704
+ isDeferred,
1705
+ resolveComponentSources,
1706
+ collapseStrategies,
1707
+ declaredNames,
1708
+ resolveReactiveBindings,
1709
+ mayHaveReactiveCall,
1710
+ collectSourceEdits,
1711
+ inlineTemplates,
1712
+ imperativeBackend,
1713
+ lowerTemplate,
1714
+ analyzeStatic,
1715
+ isReactiveShape,
1716
+ shapeOf,
1717
+ buildJsxIR
1718
+ };