@mun-ui/compiler 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/LICENSE +21 -0
  2. package/dist/analysis.d.ts +11 -0
  3. package/dist/analysis.d.ts.map +1 -0
  4. package/dist/analysis.js +80 -0
  5. package/dist/analysis.js.map +1 -0
  6. package/dist/ast.d.ts +121 -0
  7. package/dist/ast.d.ts.map +1 -0
  8. package/dist/ast.js +1017 -0
  9. package/dist/ast.js.map +1 -0
  10. package/dist/builtins.d.ts +47 -0
  11. package/dist/builtins.d.ts.map +1 -0
  12. package/dist/builtins.js +259 -0
  13. package/dist/builtins.js.map +1 -0
  14. package/dist/collection-specialization.d.ts +2 -0
  15. package/dist/collection-specialization.d.ts.map +1 -0
  16. package/dist/collection-specialization.js +475 -0
  17. package/dist/collection-specialization.js.map +1 -0
  18. package/dist/diagnostics.d.ts +12 -0
  19. package/dist/diagnostics.d.ts.map +1 -0
  20. package/dist/diagnostics.js +182 -0
  21. package/dist/diagnostics.js.map +1 -0
  22. package/dist/effect-analysis.d.ts +54 -0
  23. package/dist/effect-analysis.d.ts.map +1 -0
  24. package/dist/effect-analysis.js +318 -0
  25. package/dist/effect-analysis.js.map +1 -0
  26. package/dist/execution-plan.d.ts +63 -0
  27. package/dist/execution-plan.d.ts.map +1 -0
  28. package/dist/execution-plan.js +223 -0
  29. package/dist/execution-plan.js.map +1 -0
  30. package/dist/gpu-island-ir.d.ts +85 -0
  31. package/dist/gpu-island-ir.d.ts.map +1 -0
  32. package/dist/gpu-island-ir.js +159 -0
  33. package/dist/gpu-island-ir.js.map +1 -0
  34. package/dist/gpu-region.d.ts +28 -0
  35. package/dist/gpu-region.d.ts.map +1 -0
  36. package/dist/gpu-region.js +136 -0
  37. package/dist/gpu-region.js.map +1 -0
  38. package/dist/index.d.ts +29 -0
  39. package/dist/index.d.ts.map +1 -0
  40. package/dist/index.js +56 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/kernel-ir.d.ts +13 -0
  43. package/dist/kernel-ir.d.ts.map +1 -0
  44. package/dist/kernel-ir.js +221 -0
  45. package/dist/kernel-ir.js.map +1 -0
  46. package/dist/language-catalog.d.ts +26 -0
  47. package/dist/language-catalog.d.ts.map +1 -0
  48. package/dist/language-catalog.js +27 -0
  49. package/dist/language-catalog.js.map +1 -0
  50. package/dist/lifecycle.d.ts +8 -0
  51. package/dist/lifecycle.d.ts.map +1 -0
  52. package/dist/lifecycle.js +84 -0
  53. package/dist/lifecycle.js.map +1 -0
  54. package/dist/native-contract.d.ts +27 -0
  55. package/dist/native-contract.d.ts.map +1 -0
  56. package/dist/native-contract.js +163 -0
  57. package/dist/native-contract.js.map +1 -0
  58. package/dist/native-member-contract.d.ts +13 -0
  59. package/dist/native-member-contract.d.ts.map +1 -0
  60. package/dist/native-member-contract.js +10 -0
  61. package/dist/native-member-contract.js.map +1 -0
  62. package/dist/native-values.d.ts +40 -0
  63. package/dist/native-values.d.ts.map +1 -0
  64. package/dist/native-values.js +394 -0
  65. package/dist/native-values.js.map +1 -0
  66. package/dist/observable.d.ts +19 -0
  67. package/dist/observable.d.ts.map +1 -0
  68. package/dist/observable.js +203 -0
  69. package/dist/observable.js.map +1 -0
  70. package/dist/pipeline.d.ts +11 -0
  71. package/dist/pipeline.d.ts.map +1 -0
  72. package/dist/pipeline.js +2183 -0
  73. package/dist/pipeline.js.map +1 -0
  74. package/dist/resident-fusion.d.ts +102 -0
  75. package/dist/resident-fusion.d.ts.map +1 -0
  76. package/dist/resident-fusion.js +423 -0
  77. package/dist/resident-fusion.js.map +1 -0
  78. package/dist/resident-js.d.ts +7 -0
  79. package/dist/resident-js.d.ts.map +1 -0
  80. package/dist/resident-js.js +106 -0
  81. package/dist/resident-js.js.map +1 -0
  82. package/dist/resident-planner.d.ts +58 -0
  83. package/dist/resident-planner.d.ts.map +1 -0
  84. package/dist/resident-planner.js +101 -0
  85. package/dist/resident-planner.js.map +1 -0
  86. package/dist/resident-wasm.d.ts +56 -0
  87. package/dist/resident-wasm.d.ts.map +1 -0
  88. package/dist/resident-wasm.js +867 -0
  89. package/dist/resident-wasm.js.map +1 -0
  90. package/dist/scanner.d.ts +63 -0
  91. package/dist/scanner.d.ts.map +1 -0
  92. package/dist/scanner.js +755 -0
  93. package/dist/scanner.js.map +1 -0
  94. package/dist/semantic.d.ts +100 -0
  95. package/dist/semantic.d.ts.map +1 -0
  96. package/dist/semantic.js +669 -0
  97. package/dist/semantic.js.map +1 -0
  98. package/dist/shorthand.d.ts +16 -0
  99. package/dist/shorthand.d.ts.map +1 -0
  100. package/dist/shorthand.js +225 -0
  101. package/dist/shorthand.js.map +1 -0
  102. package/dist/source-map.d.ts +26 -0
  103. package/dist/source-map.d.ts.map +1 -0
  104. package/dist/source-map.js +228 -0
  105. package/dist/source-map.js.map +1 -0
  106. package/dist/specialization.d.ts +34 -0
  107. package/dist/specialization.d.ts.map +1 -0
  108. package/dist/specialization.js +1977 -0
  109. package/dist/specialization.js.map +1 -0
  110. package/dist/state-specialization.d.ts +3 -0
  111. package/dist/state-specialization.d.ts.map +1 -0
  112. package/dist/state-specialization.js +227 -0
  113. package/dist/state-specialization.js.map +1 -0
  114. package/dist/struct-state.d.ts +32 -0
  115. package/dist/struct-state.d.ts.map +1 -0
  116. package/dist/struct-state.js +170 -0
  117. package/dist/struct-state.js.map +1 -0
  118. package/dist/types.d.ts +70 -0
  119. package/dist/types.d.ts.map +1 -0
  120. package/dist/types.js +2 -0
  121. package/dist/types.js.map +1 -0
  122. package/dist/ui-ir.d.ts +151 -0
  123. package/dist/ui-ir.d.ts.map +1 -0
  124. package/dist/ui-ir.js +2685 -0
  125. package/dist/ui-ir.js.map +1 -0
  126. package/dist/value-types.d.ts +74 -0
  127. package/dist/value-types.d.ts.map +1 -0
  128. package/dist/value-types.js +246 -0
  129. package/dist/value-types.js.map +1 -0
  130. package/dist/vite.d.ts +33 -0
  131. package/dist/vite.d.ts.map +1 -0
  132. package/dist/vite.js +233 -0
  133. package/dist/vite.js.map +1 -0
  134. package/dist/vue-host.d.ts +25 -0
  135. package/dist/vue-host.d.ts.map +1 -0
  136. package/dist/vue-host.js +103 -0
  137. package/dist/vue-host.js.map +1 -0
  138. package/dist/web-analysis.d.ts +7 -0
  139. package/dist/web-analysis.d.ts.map +1 -0
  140. package/dist/web-analysis.js +81 -0
  141. package/dist/web-analysis.js.map +1 -0
  142. package/package.json +29 -3
  143. package/README.md +0 -3
@@ -0,0 +1,2183 @@
1
+ import * as ts from "typescript";
2
+ import { parseMunBuilder, parseMunStructs, lowerMunBuilderAst } from "./ast.js";
3
+ import { findBuilder, findRawHtml, identifierAt, matching, previousSignificantCharacter, previousWord, regexCanStart, rawHtmlAt, skipComment, skipRegex, skipString, skipTrivia, splitStatements, splitTopLevel, syntaxError, topLevelColon, } from "./scanner.js";
4
+ import * as Core from "@mun-ui/core/compat";
5
+ import { resolveSemanticCall, swiftUIModifierLowering } from "@mun-ui/core/compat";
6
+ import { lowerImplicitMemberShorthand, lowerNamedAnimationFactoryCalls, lowerShorthand } from "./shorthand.js";
7
+ import { foldStaticResults, hoistStaticViewSubtrees, lowerCompiledViewTemplates, lowerContentTransitionArgument, lowerStaticSemanticSpecializations, staticModifierNames } from "./specialization.js";
8
+ import { lowerCompiledCollections } from "./collection-specialization.js";
9
+ import { lowerStateArrayMaps } from "./state-specialization.js";
10
+ import { lowerBoolToggle, lowerStructStateAccess, lowerSwiftInterpolation } from "./struct-state.js";
11
+ import { lowerLabeledCalls, lowerObservableClasses, lowerParameters, lowerSwiftKeyPaths } from "./observable.js";
12
+ import { lowerLifecycleModifiers } from "./lifecycle.js";
13
+ import { validateWebBindings, validateWebLowering } from "./web-analysis.js";
14
+ import { canonicalViewSymbols } from "./semantic.js";
15
+ import { addNamedImports, munBuiltinSymbols, resolveMunBuiltins } from "./builtins.js";
16
+ import { createMunSourceMap, mapGeneratedPosition } from "./source-map.js";
17
+ // Nested named calls are uncommon in ordinary argument expressions. Keep the
18
+ // recursive lowering path behind a cheap lexical hint so every positional
19
+ // argument does not rescan itself with the full balanced-call scanner.
20
+ const nestedNamedMunCallHint = /\b(?:[A-Z][A-Za-z0-9_$]*\.)*[A-Z][A-Za-z0-9_$]*\s*\([^()\n]*:[^()\n]*\)/;
21
+ const validationSourceFileCache = new Map();
22
+ const maximumValidationSourceFiles = 32;
23
+ function validationSourceFile(source) {
24
+ const cached = validationSourceFileCache.get(source);
25
+ if (cached) {
26
+ validationSourceFileCache.delete(source);
27
+ validationSourceFileCache.set(source, cached);
28
+ return cached;
29
+ }
30
+ const file = ts.createSourceFile("mun-call-validation.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
31
+ validationSourceFileCache.set(source, file);
32
+ while (validationSourceFileCache.size > maximumValidationSourceFiles) {
33
+ const oldest = validationSourceFileCache.keys().next().value;
34
+ if (oldest === undefined)
35
+ break;
36
+ validationSourceFileCache.delete(oldest);
37
+ }
38
+ return file;
39
+ }
40
+ /**
41
+ * Compiler-facing view metadata starts with every runtime View so Mun-native
42
+ * and compatibility APIs remain usable. Canonical SwiftUI Views are then
43
+ * replaced by the SDK-audited manifest contract, preventing runtime-only
44
+ * overloads from silently becoming SwiftUI source syntax.
45
+ */
46
+ const canonicalInitializerSymbols = new Map();
47
+ for (const symbol of munBuiltinSymbols().values()) {
48
+ if (symbol.kind === "view" && symbol.initializers)
49
+ canonicalInitializerSymbols.set(symbol.name, symbol.initializers);
50
+ }
51
+ // Native-only canonical Views keep their contract for call validation; the
52
+ // built-in registry reports them as unavailable on the web.
53
+ for (const [name, symbol] of canonicalViewSymbols()) {
54
+ if (!canonicalInitializerSymbols.has(name))
55
+ canonicalInitializerSymbols.set(name, symbol.initializers);
56
+ }
57
+ function symbolsForCall(call, registry = canonicalInitializerSymbols) {
58
+ return registry.get(call.callee);
59
+ }
60
+ class MunInitializerSyntaxError extends SyntaxError {
61
+ code = "MUN_INITIALIZER";
62
+ offset;
63
+ constructor(message, offset) {
64
+ super(message);
65
+ this.name = "MunInitializerSyntaxError";
66
+ this.offset = offset;
67
+ }
68
+ }
69
+ function buttonInitializerMessage(call) {
70
+ const labels = call.arguments.flatMap(argument => argument.label ? [argument.label] : []);
71
+ if (labels.includes("label") && labels.includes("action") && labels.indexOf("label") < labels.indexOf("action")) {
72
+ return "Button arguments must follow declaration order: action:, label:.";
73
+ }
74
+ return "Button must use either Button(\"Title\") { action } or Button(action: { ... }) { label }.";
75
+ }
76
+ function knownCallArguments(call) {
77
+ const arguments_ = call.arguments.flatMap((argument, argumentIndex) => {
78
+ if (argument.value.kind === "closure")
79
+ return [{ label: argument.label, type: "function" }];
80
+ if (call.callee === "ForEach" && argumentIndex === 1 && /^\{\s*(?:id|key)\s*:/.test(argument.value.source) && /=>/.test(argument.value.source)) {
81
+ return [{ label: "key", type: "function" }];
82
+ }
83
+ const named = /^namedArguments\s*\(\s*\{([\s\S]*)\}\s*\)$/.exec(argument.value.source.trim());
84
+ if (named)
85
+ return splitTopLevel(named[1]).map(value => compilerSemanticArgument(value));
86
+ return [compilerSemanticArgument(argument.label ? `${argument.label}: ${argument.value.source}` : argument.value.source)];
87
+ });
88
+ return call.trailing ? [...arguments_, { type: "function", trailing: true }] : arguments_;
89
+ }
90
+ function canDeferDynamicButton(call, arguments_) {
91
+ if (!arguments_.some(argument => argument.type === "unknown"))
92
+ return false;
93
+ if (call.trailing)
94
+ return call.arguments.length === 1 && (!call.arguments[0]?.label || call.arguments[0]?.label === "action");
95
+ const labels = call.arguments.map(argument => argument.label);
96
+ return labels.length === 2 && labels[0] === "action" && labels[1] === "label";
97
+ }
98
+ function resolveKnownCall(call, registry = canonicalInitializerSymbols) {
99
+ const symbols = symbolsForCall(call, registry);
100
+ if (!symbols)
101
+ return undefined;
102
+ const viewType = {
103
+ kind: "view",
104
+ name: call.callee,
105
+ qualifiedName: call.callee,
106
+ initializers: symbols,
107
+ fields: [],
108
+ };
109
+ const arguments_ = knownCallArguments(call);
110
+ const result = resolveSemanticCall(viewType, arguments_);
111
+ if (!result.resolvedInitializer) {
112
+ if (call.callee === "Button" && canDeferDynamicButton(call, arguments_))
113
+ return undefined;
114
+ if (call.callee === "Button")
115
+ throw new MunInitializerSyntaxError(buttonInitializerMessage(call), call.range.start);
116
+ if (call.trailing && canonicalInitializerSymbols.get(call.callee) !== symbols) {
117
+ throw new MunInitializerSyntaxError(result.diagnostics[0]?.message ?? `No matching initializer for ${call.callee}.`, call.range.start);
118
+ }
119
+ return undefined;
120
+ }
121
+ return { symbols, initializerIndex: result.resolvedInitializer.index, resolution: result };
122
+ }
123
+ function validateKnownCalls(program, registry = canonicalInitializerSymbols) {
124
+ const visit = (node) => {
125
+ if (node.kind === "call") {
126
+ if (node.callee === "Button" || node.trailing)
127
+ resolveKnownCall(node, registry);
128
+ for (const argument of node.arguments)
129
+ if (argument.value.kind === "closure")
130
+ validateKnownCalls(argument.value.body, registry);
131
+ if (node.trailing)
132
+ validateKnownCalls(node.trailing.body, registry);
133
+ return;
134
+ }
135
+ if (node.kind === "conditional") {
136
+ validateKnownCalls(node.then, registry);
137
+ if (node.otherwise) {
138
+ if (node.otherwise.kind === "conditional")
139
+ validateKnownCalls({ ...node.then, statements: [node.otherwise] }, registry);
140
+ else
141
+ validateKnownCalls(node.otherwise, registry);
142
+ }
143
+ }
144
+ };
145
+ for (const node of program.statements)
146
+ visit(node);
147
+ }
148
+ function validateKnownTypeScriptCalls(source, registry = canonicalInitializerSymbols, parsedSource) {
149
+ // SwiftUI-style labels/trailing closures are scanner-owned. Plain positional
150
+ // JS/TS calls deliberately remain the compatibility surface; only Button's
151
+ // constrained positional form needs this AST-side validation.
152
+ if (!/\bButton\s*\(/.test(source))
153
+ return;
154
+ const file = parsedSource ?? validationSourceFile(source);
155
+ const visit = (node) => {
156
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "Button" && registry.has("Button")) {
157
+ // The Mun scanner owns trailing closures. TypeScript sees the call
158
+ // prefix as a complete call, so leave that shape to validateKnownCalls.
159
+ const callText = source.slice(node.expression.end, node.end);
160
+ const hasMunLabels = /(?:^|,)\s*[A-Za-z_$][A-Za-z0-9_$]*\s*:/.test(callText);
161
+ if (!hasMunLabels && source[skipTrivia(source, node.end)] !== "{") {
162
+ const callSource = `Button(${node.arguments.map(argument => argument.getText(file)).join(", ")})`;
163
+ const parsed = parseMunBuilder(callSource, node.expression.getStart(file)).statements[0];
164
+ if (parsed?.kind === "call")
165
+ resolveKnownCall(parsed, registry);
166
+ }
167
+ }
168
+ ts.forEachChild(node, visit);
169
+ };
170
+ visit(file);
171
+ }
172
+ function closureRoleForKnownCall(call, context, registry = canonicalInitializerSymbols) {
173
+ if ((call.callee === "withAnimation" || call.callee === "withTransaction") && context.position === "trailing")
174
+ return "action";
175
+ // This helper is also called while lowering the argument list of a call
176
+ // whose trailing closure has already been split off by the scanner. Such a
177
+ // synthetic prefix can be incomplete (notably Button(action:) before its
178
+ // trailing label), so role inference must fall back to manifest metadata
179
+ // rather than re-diagnosing the partial call.
180
+ let resolved;
181
+ try {
182
+ resolved = resolveKnownCall(call, registry);
183
+ }
184
+ catch (error) {
185
+ if (!(error instanceof MunInitializerSyntaxError))
186
+ throw error;
187
+ resolved = undefined;
188
+ }
189
+ const resolvedArgumentIndex = context.position === "trailing"
190
+ ? Math.max(0, knownCallArguments(call).length - 1)
191
+ : context.label
192
+ ? call.arguments.findIndex(argument => argument.label === context.label)
193
+ : context.argumentIndex ?? 0;
194
+ const sharedRole = resolved?.resolution.closureRoles[resolvedArgumentIndex];
195
+ if (sharedRole)
196
+ return sharedRole === "binding" ? undefined : sharedRole;
197
+ const symbols = resolved?.symbols ?? symbolsForCall(call, registry) ?? [];
198
+ const parameters = resolved?.symbols[resolved.initializerIndex]?.parameters
199
+ ?? (context.position === "trailing"
200
+ ? symbols.find(symbol => symbol.parameters.at(-1)?.trailing)?.parameters
201
+ : context.label
202
+ ? symbols.find(symbol => symbol.parameters.some(parameter => parameter.label === context.label))?.parameters
203
+ : undefined)
204
+ ?? [];
205
+ const role = (kind) => kind === "binding" ? undefined : kind;
206
+ if (context.position === "trailing")
207
+ return role(parameters.at(-1)?.kind);
208
+ if (context.label)
209
+ return role(parameters.find(parameter => parameter.label === context.label)?.kind);
210
+ const index = context.argumentIndex ?? 0;
211
+ let positional = 0;
212
+ for (const argument of call.arguments.slice(0, index))
213
+ if (!argument.label)
214
+ positional += 1;
215
+ return role(parameters[positional]?.kind);
216
+ }
217
+ function containsAwaitKeyword(source) {
218
+ for (let cursor = 0; cursor < source.length; cursor += 1) {
219
+ const character = source[cursor];
220
+ if (character === "\"" || character === "'" || character === "`") {
221
+ cursor = skipString(source, cursor) - 1;
222
+ continue;
223
+ }
224
+ if (character === "/" && (source[cursor + 1] === "/" || source[cursor + 1] === "*")) {
225
+ cursor = skipComment(source, cursor) - 1;
226
+ continue;
227
+ }
228
+ if (character === "/" && regexCanStart(source, cursor)) {
229
+ cursor = skipRegex(source, cursor) - 1;
230
+ continue;
231
+ }
232
+ const identifier = identifierAt(source, cursor);
233
+ if (!identifier)
234
+ continue;
235
+ if (identifier.name === "await")
236
+ return true;
237
+ cursor = identifier.end - 1;
238
+ }
239
+ return false;
240
+ }
241
+ function isViewBuilderExpression(expression) {
242
+ if (ts.isParenthesizedExpression(expression)
243
+ || ts.isAsExpression(expression)
244
+ || ts.isTypeAssertionExpression(expression)
245
+ || ts.isNonNullExpression(expression)
246
+ || ts.isSatisfiesExpression(expression)
247
+ || ts.isAwaitExpression(expression)) {
248
+ return isViewBuilderExpression(expression.expression);
249
+ }
250
+ if (ts.isConditionalExpression(expression)) {
251
+ return isViewBuilderExpression(expression.whenTrue) || isViewBuilderExpression(expression.whenFalse);
252
+ }
253
+ if (ts.isBinaryExpression(expression)) {
254
+ const operator = expression.operatorToken.kind;
255
+ if (operator === ts.SyntaxKind.AmpersandAmpersandToken
256
+ || operator === ts.SyntaxKind.BarBarToken
257
+ || operator === ts.SyntaxKind.QuestionQuestionToken) {
258
+ return isViewBuilderExpression(expression.left) || isViewBuilderExpression(expression.right);
259
+ }
260
+ return false;
261
+ }
262
+ if (ts.isArrayLiteralExpression(expression))
263
+ return expression.elements.some(item => ts.isExpression(item) && isViewBuilderExpression(item));
264
+ if (ts.isCallExpression(expression) || ts.isNewExpression(expression))
265
+ return true;
266
+ if (ts.isIdentifier(expression) || ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression))
267
+ return true;
268
+ return false;
269
+ }
270
+ function lowerViewBuilderAstStatements(source, registry, childrenName) {
271
+ // First lower nested Mun-only expressions (trailing closures, raw HTML,
272
+ // binding shorthand) so the statement tree is valid TypeScript. Then let
273
+ // TypeScript own control-flow parsing instead of maintaining a second,
274
+ // incomplete statement grammar in Mun.
275
+ // Labeled Mun arguments are not valid TypeScript syntax. They must be
276
+ // converted before the TypeScript parser sees statement-bearing builders;
277
+ // otherwise parser recovery rewrites `Foo(value, label: other)` into the
278
+ // semantically different `Foo(value, label, other)` and leaks `label` as an
279
+ // undeclared runtime identifier.
280
+ const lowered = lowerRange(lowerNamedMunCalls(source, registry), registry);
281
+ const wrapper = `function __mun_builder__() {\n${lowered}\n}`;
282
+ const file = ts.createSourceFile("mun-view-builder.ts", wrapper, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
283
+ const fn = file.statements.find(ts.isFunctionDeclaration);
284
+ if (!fn?.body)
285
+ return lowered;
286
+ const factory = ts.factory;
287
+ let activeChildrenName = childrenName;
288
+ let conditionalIndex = 0;
289
+ const pushExpression = (expression) => factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier(activeChildrenName), "push"), undefined, [expression]));
290
+ const transformStatement = (statement) => {
291
+ if (ts.isExpressionStatement(statement)) {
292
+ return isViewBuilderExpression(statement.expression) ? pushExpression(statement.expression) : statement;
293
+ }
294
+ if (ts.isBlock(statement))
295
+ return factory.updateBlock(statement, statement.statements.map(transformStatement));
296
+ if (ts.isIfStatement(statement)) {
297
+ // Keep each conditional in a permanent structural slot. Flattening its
298
+ // children into the parent lets removing one branch renumber its siblings.
299
+ const index = conditionalIndex++;
300
+ let branchName = `${childrenName}Branch${index}`;
301
+ while (new RegExp(`\\b${branchName}\\b`).test(source))
302
+ branchName += "_";
303
+ const parentChildrenName = activeChildrenName;
304
+ activeChildrenName = branchName;
305
+ const conditional = factory.updateIfStatement(statement, statement.expression, transformStatement(statement.thenStatement), statement.elseStatement ? transformStatement(statement.elseStatement) : undefined);
306
+ activeChildrenName = parentChildrenName;
307
+ const fragment = factory.createCallExpression(factory.createIdentifier("viewFragment"), undefined, [factory.createIdentifier(branchName)]);
308
+ return factory.createBlock([
309
+ factory.createVariableStatement(undefined, factory.createVariableDeclarationList([
310
+ factory.createVariableDeclaration(branchName, undefined, undefined, factory.createArrayLiteralExpression()),
311
+ ], ts.NodeFlags.Const)),
312
+ conditional,
313
+ pushExpression(factory.createCallExpression(factory.createPropertyAccessExpression(fragment, "id"), undefined, [
314
+ factory.createBinaryExpression(factory.createStringLiteral(`mun:conditional:${index}:`), ts.SyntaxKind.PlusToken, factory.createPropertyAccessExpression(factory.createIdentifier(parentChildrenName), "length")),
315
+ ])),
316
+ ], true);
317
+ }
318
+ if (ts.isForStatement(statement)) {
319
+ return factory.updateForStatement(statement, statement.initializer, statement.condition, statement.incrementor, transformStatement(statement.statement));
320
+ }
321
+ if (ts.isForInStatement(statement)) {
322
+ return factory.updateForInStatement(statement, statement.initializer, statement.expression, transformStatement(statement.statement));
323
+ }
324
+ if (ts.isForOfStatement(statement)) {
325
+ return factory.updateForOfStatement(statement, statement.awaitModifier, statement.initializer, statement.expression, transformStatement(statement.statement));
326
+ }
327
+ if (ts.isWhileStatement(statement))
328
+ return factory.updateWhileStatement(statement, statement.expression, transformStatement(statement.statement));
329
+ if (ts.isDoStatement(statement))
330
+ return factory.updateDoStatement(statement, transformStatement(statement.statement), statement.expression);
331
+ if (ts.isSwitchStatement(statement)) {
332
+ const clauses = statement.caseBlock.clauses.map(clause => ts.isCaseClause(clause)
333
+ ? factory.updateCaseClause(clause, clause.expression, clause.statements.map(transformStatement))
334
+ : factory.updateDefaultClause(clause, clause.statements.map(transformStatement)));
335
+ return factory.updateSwitchStatement(statement, statement.expression, factory.updateCaseBlock(statement.caseBlock, clauses));
336
+ }
337
+ if (ts.isTryStatement(statement)) {
338
+ const tryBlock = factory.updateBlock(statement.tryBlock, statement.tryBlock.statements.map(transformStatement));
339
+ const catchClause = statement.catchClause
340
+ ? factory.updateCatchClause(statement.catchClause, statement.catchClause.variableDeclaration, factory.updateBlock(statement.catchClause.block, statement.catchClause.block.statements.map(transformStatement)))
341
+ : undefined;
342
+ const finallyBlock = statement.finallyBlock
343
+ ? factory.updateBlock(statement.finallyBlock, statement.finallyBlock.statements.map(transformStatement))
344
+ : undefined;
345
+ return factory.updateTryStatement(statement, tryBlock, catchClause, finallyBlock);
346
+ }
347
+ if (ts.isLabeledStatement(statement))
348
+ return factory.updateLabeledStatement(statement, statement.label, transformStatement(statement.statement));
349
+ if (ts.isWithStatement(statement))
350
+ return factory.updateWithStatement(statement, statement.expression, transformStatement(statement.statement));
351
+ // Function/class declarations intentionally remain opaque. A Text() call
352
+ // inside a helper function is not a child of the surrounding ViewBuilder.
353
+ return statement;
354
+ };
355
+ const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed, removeComments: false });
356
+ return fn.body.statements
357
+ .map(transformStatement)
358
+ .map(statement => printer.printNode(ts.EmitHint.Unspecified, statement, file))
359
+ .join("\n");
360
+ }
361
+ function needsStatementAwareViewBody(source) {
362
+ return /\b(?:const|let|var|return|throw|if|else|switch|case|for|while|do|try|catch|finally|break|continue|debugger)\b/.test(source);
363
+ }
364
+ function lowerViewBuilderClosure(body, parameter, registry) {
365
+ if (!needsStatementAwareViewBody(body)) {
366
+ const lowered = lowerMunBuilderAst(parseMunBuilder(body), {
367
+ transformRaw: value => lowerRange(value, registry),
368
+ transformArgument: (value, call, argumentIndex) => lowerForEachIdentityOptions(value, call, argumentIndex, registry),
369
+ closure: (nestedBody, nestedParameter, nestedRole) => lowerAstClosure(nestedBody, nestedParameter, nestedRole, registry),
370
+ closureRole: (nestedCall, context) => closureRoleForKnownCall(nestedCall, context, registry),
371
+ }).join(", ");
372
+ return `${parameter ? `(${parameter})` : "()"} => [${lowered}]`;
373
+ }
374
+ const prefix = parameter ? `(${parameter})` : "()";
375
+ let childrenName = "__munChildren";
376
+ let suffix = 0;
377
+ while (new RegExp(`\\b${childrenName}\\b`).test(body))
378
+ childrenName = `__munChildren${++suffix}`;
379
+ const statements = lowerViewBuilderAstStatements(body, registry, childrenName);
380
+ return `${prefix} => { const ${childrenName} = []; ${statements} return ${childrenName}; }`;
381
+ }
382
+ function lowerClosure(value, role, registry = canonicalInitializerSymbols) {
383
+ const source = value.trim();
384
+ if (!source.startsWith("{") || matching(source, 0, "{", "}") !== source.length - 1)
385
+ return lowerRange(source, registry);
386
+ const inner = source.slice(1, -1).trim();
387
+ const parameterMatch = /^([A-Za-z_$][A-Za-z0-9_$]*)\s+in\s+([\s\S]*)$/.exec(inner);
388
+ const parameter = parameterMatch?.[1];
389
+ const body = parameterMatch?.[2] ?? inner;
390
+ if (role === "viewBuilder")
391
+ return lowerViewBuilderClosure(body, parameter, registry);
392
+ const lowered = lowerStatements(body, registry);
393
+ const asynchronous = containsAwaitKeyword(body);
394
+ if (role === "action")
395
+ return `${asynchronous ? "async " : ""}(${parameter ?? ""}) => {${lowerRange(body, registry)}}`;
396
+ if (parameter)
397
+ return `(${parameter}) => [${lowered}]`;
398
+ const action = asynchronous || /\b(const|let|var|return|throw)\b/.test(body);
399
+ const builder = action ? "() => []" : `() => [${lowered}]`;
400
+ return `overloadClosure(${builder}, ${asynchronous ? "async " : ""}() => {${lowerRange(body, registry)}})`;
401
+ }
402
+ function lowerArguments(source, calleeName, registry = canonicalInitializerSymbols) {
403
+ const parsed = calleeName ? parseMunBuilder(`${calleeName}(${source})`).statements[0] : undefined;
404
+ const call = parsed?.kind === "call" ? parsed : undefined;
405
+ const positional = [];
406
+ const named = [];
407
+ for (const [argumentIndex, argument] of splitTopLevel(source).entries()) {
408
+ const colon = topLevelColon(argument);
409
+ const labelStart = skipTrivia(argument, 0);
410
+ if (colon >= 0 && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(argument.slice(labelStart, colon).trim())) {
411
+ const label = argument.slice(labelStart, colon).trim();
412
+ const role = call ? closureRoleForKnownCall(call, { position: "argument", argumentIndex, label }, registry) : undefined;
413
+ named.push(`${label}: ${lowerClosureOrExpression(argument.slice(colon + 1), role, registry)}`);
414
+ }
415
+ else {
416
+ const role = call ? closureRoleForKnownCall(call, { position: "argument", argumentIndex }, registry) : undefined;
417
+ positional.push(lowerClosureOrExpression(argument, role, registry));
418
+ }
419
+ }
420
+ if (named.length === 0)
421
+ return positional.join(", ");
422
+ return [...positional, `namedArguments({ ${named.join(", ")} })`].join(", ");
423
+ }
424
+ function lowerClosureOrExpression(source, role, registry = canonicalInitializerSymbols) {
425
+ const value = source.trim();
426
+ if (value.startsWith("{") && matching(value, 0, "{", "}") === value.length - 1 && !/^(?:\s*(?:[A-Za-z_$][A-Za-z0-9_$]*|["'][^"']*["']|-?\d+(?:\.\d+)?)\s*:)/.test(value.slice(1, -1)))
427
+ return lowerClosure(value, role, registry);
428
+ // Named Mun calls can be nested inside an argument expression. Lower them
429
+ // from the already-isolated argument rather than restarting a global scan
430
+ // over the whole module for each inner call.
431
+ const lowered = lowerRange(value, registry);
432
+ return lowerImplicitMemberShorthand(lowerShorthand(nestedNamedMunCallHint.test(lowered) ? lowerNamedMunCalls(lowered, registry) : lowered));
433
+ }
434
+ function lowerForEachIdentityOptions(source, call, argumentIndex, registry) {
435
+ const value = source.trim();
436
+ if (call.callee !== "ForEach" || argumentIndex !== 1 || !value.startsWith("{") || matching(value, 0, "{", "}") !== value.length - 1) {
437
+ return lowerImplicitMemberShorthand(lowerRange(source, registry));
438
+ }
439
+ const entries = splitTopLevel(value.slice(1, -1)).map(entry => {
440
+ const colon = topLevelColon(entry);
441
+ return colon < 0 ? undefined : { name: entry.slice(0, colon).trim(), value: entry.slice(colon + 1).trim() };
442
+ }).filter((entry) => entry !== undefined);
443
+ const identity = entries.find(entry => entry.name === "id" || entry.name === "key");
444
+ if (!identity)
445
+ return lowerRange(source, registry);
446
+ return `namedArguments({ key: ${lowerRange(identity.value, registry)} })`;
447
+ }
448
+ function lowerConditional(source, registry = canonicalInitializerSymbols) {
449
+ const match = /^if\s*\(/.exec(source);
450
+ if (!match)
451
+ return undefined;
452
+ const open = source.indexOf("(", match.index + match[0].length - 1);
453
+ const close = matching(source, open, "(", ")");
454
+ const thenOpen = skipTrivia(source, close + 1);
455
+ if (source[thenOpen] !== "{")
456
+ return undefined;
457
+ const thenClose = matching(source, thenOpen, "{", "}");
458
+ const afterThen = skipTrivia(source, thenClose + 1);
459
+ const condition = source.slice(open + 1, close).trim();
460
+ const thenValue = `[${lowerStatements(source.slice(thenOpen + 1, thenClose), registry)}]`;
461
+ if (source.slice(afterThen, afterThen + 4) !== "else"
462
+ || /[A-Za-z0-9_$]/.test(source[afterThen + 4] ?? "")) {
463
+ return afterThen === source.length ? `(${lowerShorthand(condition)} ? ${thenValue} : [])` : undefined;
464
+ }
465
+ const elseOpen = skipTrivia(source, afterThen + 4);
466
+ if (source[elseOpen] !== "{")
467
+ return undefined;
468
+ const elseClose = matching(source, elseOpen, "{", "}");
469
+ if (skipTrivia(source, elseClose + 1) !== source.length)
470
+ return undefined;
471
+ return `(${lowerShorthand(condition)} ? ${thenValue} : [${lowerStatements(source.slice(elseOpen + 1, elseClose), registry)}])`;
472
+ }
473
+ function lowerStatements(source, registry = canonicalInitializerSymbols) {
474
+ const values = [];
475
+ for (const statement of splitStatements(source)) {
476
+ const conditional = lowerConditional(statement, registry);
477
+ if (conditional)
478
+ values.push(conditional);
479
+ else if (/^\s*(const|let|var|return|throw)\b/.test(statement))
480
+ continue;
481
+ else
482
+ values.push(lowerRange(statement, registry));
483
+ }
484
+ return values.join(", ");
485
+ }
486
+ function lowerAstClosure(body, parameter, role, registry = canonicalInitializerSymbols) {
487
+ if (role === "viewBuilder")
488
+ return lowerViewBuilderClosure(body, parameter, registry);
489
+ const parsed = parseMunBuilder(body);
490
+ const lowered = lowerMunBuilderAst(parsed, {
491
+ transformRaw: value => lowerRange(value, registry),
492
+ transformArgument: (value, call, argumentIndex) => lowerForEachIdentityOptions(value, call, argumentIndex, registry),
493
+ closure: (nestedBody, nestedParameter, nestedRole) => lowerAstClosure(nestedBody, nestedParameter, nestedRole, registry),
494
+ closureRole: (nestedCall, context) => closureRoleForKnownCall(nestedCall, context, registry),
495
+ }).join(", ");
496
+ const asynchronous = containsAwaitKeyword(body);
497
+ if (role === "action")
498
+ return `${asynchronous ? "async " : ""}(${parameter ?? ""}) => {${lowerRange(body, registry)}}`;
499
+ if (parameter)
500
+ return `(${parameter}) => [${lowered}]`;
501
+ const action = asynchronous || /\b(const|let|var|return|throw)\b/.test(body);
502
+ const builder = action ? "() => []" : `() => [${lowered}]`;
503
+ return `overloadClosure(${builder}, ${asynchronous ? "async " : ""}() => {${lowerRange(body, registry)}})`;
504
+ }
505
+ function lowerBuilder(call, source, registry = canonicalInitializerSymbols) {
506
+ const parsed = parseMunBuilder(source.slice(call.start, call.end), call.start);
507
+ // The scanner intentionally finds call-shaped blocks before the AST knows
508
+ // whether the block is a Mun closure. If it is an object/ordinary block,
509
+ // preserve it as source instead of feeding the same span back into
510
+ // lowerRange forever.
511
+ if (parsed.statements.length === 1 && parsed.statements[0]?.kind === "raw") {
512
+ return source.slice(call.start, call.end);
513
+ }
514
+ const lowered = lowerMunBuilderAst(parsed, {
515
+ transformRaw: value => lowerRange(value, registry),
516
+ transformArgument: (value, call, argumentIndex) => lowerForEachIdentityOptions(value, call, argumentIndex, registry),
517
+ closure: (body, parameter, role) => lowerAstClosure(body, parameter, role, registry),
518
+ closureRole: (nestedCall, context) => closureRoleForKnownCall(nestedCall, context, registry),
519
+ });
520
+ if (lowered.length === 1)
521
+ return lowered[0];
522
+ return `${call.name}(${lowerArguments(call.argumentSource, call.name, registry)})`;
523
+ }
524
+ function lowerRange(source, registry = canonicalInitializerSymbols) {
525
+ let output = "";
526
+ let cursor = 0;
527
+ let iterations = 0;
528
+ while (cursor < source.length) {
529
+ if (++iterations > source.length + 1)
530
+ throw syntaxError("Mun lowering did not advance past a builder expression", cursor);
531
+ const call = findBuilder(source, cursor);
532
+ const html = findRawHtml(source, cursor, value => lowerRange(value, registry));
533
+ if (!call && !html)
534
+ break;
535
+ if (html && (!call || html.start < call.start)) {
536
+ output += lowerShorthand(source.slice(cursor, html.start));
537
+ output += html.code;
538
+ cursor = html.end;
539
+ continue;
540
+ }
541
+ output += lowerShorthand(source.slice(cursor, call.start));
542
+ output += lowerBuilder(call, source, registry);
543
+ cursor = call.end;
544
+ }
545
+ output += lowerShorthand(source.slice(cursor));
546
+ return output;
547
+ }
548
+ function structParameter(source) {
549
+ const kind = source.includes("@ViewBuilder") ? "viewBuilder" : source.includes("@Action") ? "action" : source.includes("@Binding") ? "binding" : "value";
550
+ const clean = source.replace(/@(?:ViewBuilder|Action|Binding)\s*/g, "").trim();
551
+ const defaultIndex = topLevelEquals(clean);
552
+ const declaration = defaultIndex < 0 ? clean : clean.slice(0, defaultIndex).trim();
553
+ const defaultValue = defaultIndex < 0 ? undefined : clean.slice(defaultIndex + 1).trim();
554
+ const colon = topLevelColon(declaration);
555
+ const head = (colon < 0 ? declaration : declaration.slice(0, colon)).trim();
556
+ const words = head.split(/\s+/).filter(Boolean);
557
+ const name = words[words.length - 1]?.replace(/^_+/, "");
558
+ if (!name)
559
+ throw new SyntaxError(`Invalid struct initializer parameter: ${source}`);
560
+ return {
561
+ name,
562
+ label: words[0] === "_" ? undefined : words[0],
563
+ kind,
564
+ required: defaultIndex < 0,
565
+ defaultValue,
566
+ type: colon < 0 ? undefined : declaration.slice(colon + 1).trim(),
567
+ };
568
+ }
569
+ function topLevelEquals(source) {
570
+ let parens = 0;
571
+ let brackets = 0;
572
+ let braces = 0;
573
+ for (let cursor = 0; cursor < source.length; cursor += 1) {
574
+ const character = source[cursor];
575
+ if (character === "\"" || character === "'" || character === "`") {
576
+ cursor = skipString(source, cursor) - 1;
577
+ continue;
578
+ }
579
+ if (character === "(")
580
+ parens += 1;
581
+ else if (character === ")")
582
+ parens -= 1;
583
+ else if (character === "[")
584
+ brackets += 1;
585
+ else if (character === "]")
586
+ brackets -= 1;
587
+ else if (character === "{")
588
+ braces += 1;
589
+ else if (character === "}")
590
+ braces -= 1;
591
+ else if (character === "=" && parens === 0 && brackets === 0 && braces === 0 && source[cursor + 1] !== ">")
592
+ return cursor;
593
+ }
594
+ return -1;
595
+ }
596
+ function structInitializerPlans(declaration) {
597
+ const fields = declaration.fields.map(field => ({
598
+ name: field.name,
599
+ kind: field.kind === "state" ? "state" : field.kind === "binding" ? "binding" : "value",
600
+ type: field.type,
601
+ defaultValue: field.initializer,
602
+ }));
603
+ return declaration.initializers.length > 0
604
+ ? declaration.initializers.map(item => structInitializerPlan(item.parametersSource, item.bodySource))
605
+ : [structInitializerPlan(fields.filter(field => field.kind !== "state").map(field => `${field.kind === "binding" ? "@Binding " : ""}${field.name}: unknown${field.defaultValue === undefined ? "" : ` = ${field.defaultValue}`}`).join(", "), "")];
606
+ }
607
+ function structInitializerPlan(parameterSource, bodySource) {
608
+ const parsedParameters = splitTopLevel(parameterSource).filter(Boolean).map(structParameter);
609
+ const parameters = parsedParameters.map((parameter, index) => ({
610
+ ...parameter,
611
+ trailing: index === parsedParameters.length - 1 && (parameter.kind === "viewBuilder" || parameter.kind === "action"),
612
+ labelRequired: parameter.label !== undefined && !(index === parsedParameters.length - 1 && (parameter.kind === "viewBuilder" || parameter.kind === "action")),
613
+ }));
614
+ const assignments = structFieldAssignments(bodySource);
615
+ const delegationMatch = /\bself\.init\s*\(/.exec(bodySource);
616
+ if (!delegationMatch)
617
+ return { parameters, assignments };
618
+ const open = bodySource.indexOf("(", delegationMatch.index);
619
+ const close = matching(bodySource, open, "(", ")");
620
+ return { parameters, assignments, delegation: splitTopLevel(bodySource.slice(open + 1, close)).filter(Boolean) };
621
+ }
622
+ /**
623
+ * Collect `self.<field> = <value>` assignments from an initializer body with
624
+ * quote-, comment-, and nesting-aware value boundaries. A naive
625
+ * line-oriented capture corrupts single-line bodies such as
626
+ * `{ if (v < 0) { self.v = 0 } else { self.v = v } }` by swallowing the
627
+ * closing braces into the field expression.
628
+ */
629
+ function structFieldAssignments(bodySource) {
630
+ const assignments = new Map();
631
+ let cursor = 0;
632
+ while (cursor < bodySource.length) {
633
+ const character = bodySource[cursor];
634
+ if (character === '"' || character === "'" || character === "`") {
635
+ cursor = skipString(bodySource, cursor);
636
+ continue;
637
+ }
638
+ if (character === "/" && (bodySource[cursor + 1] === "/" || bodySource[cursor + 1] === "*")) {
639
+ cursor = skipComment(bodySource, cursor);
640
+ continue;
641
+ }
642
+ if (character !== "s") {
643
+ cursor += 1;
644
+ continue;
645
+ }
646
+ const header = /^self\.[A-Za-z_$][A-Za-z0-9_$]*\s*=(?![=>])/.exec(bodySource.slice(cursor));
647
+ if (!header || (cursor > 0 && /[\w$.]/.test(bodySource[cursor - 1]))) {
648
+ cursor += 1;
649
+ continue;
650
+ }
651
+ const name = /^self\.([A-Za-z_$][A-Za-z0-9_$]*)/.exec(header.input)?.[1];
652
+ if (!name) {
653
+ cursor += 1;
654
+ continue;
655
+ }
656
+ let valueStart = cursor + header[0].length;
657
+ while (valueStart < bodySource.length && /\s/.test(bodySource[valueStart]))
658
+ valueStart += 1;
659
+ let parens = 0;
660
+ let brackets = 0;
661
+ let braces = 0;
662
+ let end = valueStart;
663
+ while (end < bodySource.length) {
664
+ const valueCharacter = bodySource[end];
665
+ if (valueCharacter === '"' || valueCharacter === "'" || valueCharacter === "`") {
666
+ end = skipString(bodySource, end);
667
+ continue;
668
+ }
669
+ if (valueCharacter === "/" && (bodySource[end + 1] === "/" || bodySource[end + 1] === "*")) {
670
+ end = skipComment(bodySource, end);
671
+ continue;
672
+ }
673
+ if (valueCharacter === "(") {
674
+ parens += 1;
675
+ }
676
+ else if (valueCharacter === "[") {
677
+ brackets += 1;
678
+ }
679
+ else if (valueCharacter === "{") {
680
+ braces += 1;
681
+ }
682
+ else if (valueCharacter === ")") {
683
+ if (parens === 0)
684
+ break;
685
+ parens -= 1;
686
+ }
687
+ else if (valueCharacter === "]") {
688
+ if (brackets === 0)
689
+ break;
690
+ brackets -= 1;
691
+ }
692
+ else if (valueCharacter === "}") {
693
+ if (braces === 0)
694
+ break;
695
+ braces -= 1;
696
+ }
697
+ else if ((valueCharacter === ";" || valueCharacter === "\n") && parens === 0 && brackets === 0 && braces === 0) {
698
+ if (valueCharacter !== "\n")
699
+ break;
700
+ // Continue multi-line expressions whose current line ends with a
701
+ // binary operator or an open assignment (`self.title = "Hello" +\n"`).
702
+ if (!/[+\-*/%&|^<>?:=]$/.test(bodySource.slice(valueStart, end).trimEnd()))
703
+ break;
704
+ let next = end + 1;
705
+ while (next < bodySource.length && /\s/.test(bodySource[next]))
706
+ next += 1;
707
+ end = next;
708
+ continue;
709
+ }
710
+ end += 1;
711
+ }
712
+ assignments.set(name, bodySource.slice(valueStart, end).trim());
713
+ cursor = Math.max(end, cursor + header[0].length);
714
+ }
715
+ return assignments;
716
+ }
717
+ function structArgument(source) {
718
+ const colon = topLevelColon(source);
719
+ if (colon < 0)
720
+ return { value: source.trim() };
721
+ return { label: source.slice(0, colon).trim(), value: source.slice(colon + 1).trim() };
722
+ }
723
+ function delegatedParameterValues(parameters, arguments_) {
724
+ const values = new Map();
725
+ const used = new Set();
726
+ let nextPositional = 0;
727
+ for (const source of arguments_) {
728
+ const argument = structArgument(source);
729
+ let index = argument.label === undefined
730
+ ? (() => {
731
+ while (used.has(nextPositional))
732
+ nextPositional += 1;
733
+ return nextPositional;
734
+ })()
735
+ : parameters.findIndex(parameter => parameter.label === argument.label || parameter.name === argument.label);
736
+ if (index < 0 || index >= parameters.length || used.has(index))
737
+ return undefined;
738
+ used.add(index);
739
+ if (argument.label === undefined)
740
+ nextPositional = index + 1;
741
+ values.set(parameters[index].name, argument.value);
742
+ }
743
+ for (let index = 0; index < parameters.length; index += 1) {
744
+ const parameter = parameters[index];
745
+ if (!values.has(parameter.name)) {
746
+ if (parameter.required)
747
+ return undefined;
748
+ values.set(parameter.name, parameter.defaultValue ?? "undefined");
749
+ }
750
+ }
751
+ return values;
752
+ }
753
+ function compilerInitializerArguments(source) {
754
+ return splitTopLevel(source).flatMap(argument => {
755
+ const named = /^namedArguments\s*\(\s*\{([\s\S]*)\}\s*\)$/.exec(argument.trim());
756
+ return named ? splitTopLevel(named[1]) : [argument];
757
+ });
758
+ }
759
+ function compilerSemanticArgument(source) {
760
+ const argument = structArgument(source);
761
+ const value = argument.value.trim();
762
+ if (/^(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`)$/.test(value))
763
+ return { label: argument.label, type: "string" };
764
+ if (/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(value))
765
+ return { label: argument.label, type: "number" };
766
+ if (/^(?:true|false)$/.test(value))
767
+ return { label: argument.label, type: "boolean" };
768
+ if (/^(?:overloadClosure|function)\s*\(/.test(value) || /=>/.test(value))
769
+ return { label: argument.label, type: "function" };
770
+ if (/^Binding\s*\(/.test(value))
771
+ return { label: argument.label, kind: "binding", type: "binding", underlyingType: "dynamic" };
772
+ if (/^State\s*\(/.test(value))
773
+ return { label: argument.label, type: "state" };
774
+ return { label: argument.label, type: "unknown" };
775
+ }
776
+ function canonicalRuntimeBindings(file) {
777
+ const names = new Map();
778
+ const namespaces = new Set();
779
+ for (const statement of file.statements) {
780
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
781
+ continue;
782
+ if (statement.moduleSpecifier.text !== "@mun-ui/core/compat"
783
+ && statement.moduleSpecifier.text !== "@mun-ui/react")
784
+ continue;
785
+ const clause = statement.importClause;
786
+ if (!clause || clause.isTypeOnly)
787
+ continue;
788
+ const bindings = clause.namedBindings;
789
+ if (bindings && ts.isNamespaceImport(bindings))
790
+ namespaces.add(bindings.name.text);
791
+ if (bindings && ts.isNamedImports(bindings)) {
792
+ for (const element of bindings.elements) {
793
+ if (element.isTypeOnly)
794
+ continue;
795
+ const exported = element.propertyName?.text ?? element.name.text;
796
+ if (canonicalInitializerSymbols.has(exported))
797
+ names.set(element.name.text, exported);
798
+ }
799
+ }
800
+ }
801
+ return { names, namespaces };
802
+ }
803
+ function canonicalCallName(call, bindings, shadowed) {
804
+ const callee = unwrapTsExpression(call.expression);
805
+ if (ts.isIdentifier(callee)) {
806
+ if (shadowed.has(callee.text))
807
+ return undefined;
808
+ const exportedName = bindings.names.get(callee.text);
809
+ return exportedName ? { localSource: callee.text, exportedName } : undefined;
810
+ }
811
+ if (!ts.isPropertyAccessExpression(callee))
812
+ return undefined;
813
+ const owner = unwrapTsExpression(callee.expression);
814
+ if (!ts.isIdentifier(owner) || shadowed.has(owner.text) || !bindings.namespaces.has(owner.text))
815
+ return undefined;
816
+ return canonicalInitializerSymbols.has(callee.name.text)
817
+ ? { localSource: `${owner.text}.${callee.name.text}`, exportedName: callee.name.text }
818
+ : undefined;
819
+ }
820
+ /**
821
+ * Resolve the common intrinsic calls that need no TypeChecker from Mun's
822
+ * canonical initializer manifest. Unknown/dynamic arguments deliberately stay
823
+ * untouched for the semantic TypeScript pass below.
824
+ */
825
+ function lowerStaticCanonicalCalls(source) {
826
+ if (!/(?:from\s*|import\s*\()\s*["'](?:mun|@mun-ui\/(?:core|react))["']/.test(source))
827
+ return source;
828
+ const file = ts.createSourceFile("mun-canonical-calls.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
829
+ const bindings = canonicalRuntimeBindings(file);
830
+ if (bindings.names.size === 0 && bindings.namespaces.size === 0)
831
+ return source;
832
+ const edits = [];
833
+ const visit = (node, shadowed) => {
834
+ if (ts.isCallExpression(node)) {
835
+ const candidate = canonicalCallName(node, bindings, shadowed);
836
+ if (candidate && !node.arguments.some(argument => /^namedArguments\s*\(/.test(argument.getText(file)))) {
837
+ const semanticArguments = node.arguments.map(argument => compilerSemanticArgument(argument.getText(file)));
838
+ if (semanticArguments.every(argument => argument.type !== "unknown")) {
839
+ const symbols = canonicalInitializerSymbols.get(candidate.exportedName) ?? [];
840
+ const viewType = {
841
+ kind: "view",
842
+ name: candidate.exportedName,
843
+ qualifiedName: candidate.exportedName,
844
+ initializers: symbols,
845
+ fields: [],
846
+ };
847
+ const resolution = resolveSemanticCall(viewType, semanticArguments);
848
+ const selected = resolution.resolvedInitializer;
849
+ if (selected && !selected.parameters.some(parameter => parameter.variadic || parameter.kind === "viewBuilder" || parameter.kind === "binding")) {
850
+ edits.push({
851
+ start: node.getStart(file),
852
+ end: node.end,
853
+ replacement: `${candidate.localSource}.viewType.createNodeCompiled(${selected.index}, [${node.arguments.map(argument => argument.getText(file)).join(", ")}])`,
854
+ });
855
+ return;
856
+ }
857
+ }
858
+ }
859
+ }
860
+ if (ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) {
861
+ const local = new Set(shadowed);
862
+ for (const parameter of node.parameters)
863
+ for (const name of bindingNames(parameter.name))
864
+ local.add(name);
865
+ if (ts.isFunctionDeclaration(node) && node.name)
866
+ local.add(node.name.text);
867
+ if (node.body)
868
+ visit(node.body, local);
869
+ return;
870
+ }
871
+ if (ts.isBlock(node)) {
872
+ const local = new Set(shadowed);
873
+ for (const name of directBlockBindings(node))
874
+ local.add(name);
875
+ ts.forEachChild(node, child => visit(child, local));
876
+ return;
877
+ }
878
+ if (ts.isCatchClause(node)) {
879
+ const local = new Set(shadowed);
880
+ if (node.variableDeclaration)
881
+ for (const name of bindingNames(node.variableDeclaration.name))
882
+ local.add(name);
883
+ visit(node.block, local);
884
+ return;
885
+ }
886
+ ts.forEachChild(node, child => visit(child, shadowed));
887
+ };
888
+ visit(file, new Set());
889
+ if (edits.length === 0)
890
+ return source;
891
+ let result = source;
892
+ for (const edit of edits.sort((left, right) => right.start - left.start)) {
893
+ result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);
894
+ }
895
+ return result;
896
+ }
897
+ function legacyHostCoercion(type) {
898
+ const normalized = type?.replace(/\s+/g, "") ?? "";
899
+ if (/(?:^|\|)boolean(?:\||$)/.test(normalized))
900
+ return "boolean";
901
+ if (/(?:^|\|)number(?:\||$)/.test(normalized))
902
+ return "number";
903
+ return "identity";
904
+ }
905
+ function legacyHostPlanSource(plans) {
906
+ return `{ initializers: [${plans.map((plan, index) => `{ index: ${index}, parameters: [${plan.parameters.map(parameter => `{ name: ${JSON.stringify(parameter.name)}, label: ${parameter.label === undefined ? "undefined" : JSON.stringify(parameter.label)}, kind: ${JSON.stringify(parameter.kind)}, required: ${parameter.required}, trailing: ${parameter.trailing === true}, coercion: ${JSON.stringify(legacyHostCoercion(parameter.type))} }`).join(", ")}] }`).join(", ")}] }`;
907
+ }
908
+ function semanticInitializerSymbol(name, plan, index) {
909
+ return {
910
+ kind: "initializer",
911
+ index,
912
+ signature: `${name}(${plan.parameters.map(parameter => `${parameter.kind === "viewBuilder" ? "@ViewBuilder " : parameter.kind === "action" ? "@Action " : parameter.kind === "binding" ? "@Binding " : ""}${parameter.label ?? parameter.name}`).join(", ")})`,
913
+ parameters: plan.parameters,
914
+ };
915
+ }
916
+ function staticInitializerIndex(declaration, argumentSource, offset = 0) {
917
+ const plans = structInitializerPlans(declaration);
918
+ const arguments_ = compilerInitializerArguments(argumentSource).map(compilerSemanticArgument);
919
+ const initializers = plans.map((plan, index) => semanticInitializerSymbol(declaration.name, plan, index));
920
+ const viewType = {
921
+ kind: "view",
922
+ name: declaration.name,
923
+ qualifiedName: declaration.name,
924
+ genericParameters: declaration.genericParameters,
925
+ fields: [],
926
+ initializers,
927
+ };
928
+ const result = resolveSemanticCall(viewType, arguments_);
929
+ if (result.resolvedInitializer)
930
+ return result.resolvedInitializer.index;
931
+ if (result.diagnostics[0]?.code === "MUN_INITIALIZER" && arguments_.some(argument => argument.type === "unknown"))
932
+ return undefined;
933
+ throw new MunInitializerSyntaxError(result.diagnostics[0]?.message ?? `No matching initializer for ${declaration.name}.`, offset);
934
+ }
935
+ function findDelegatedInitializer(plans, arguments_, excludedIndex) {
936
+ for (let index = 0; index < plans.length; index += 1) {
937
+ if (index === excludedIndex)
938
+ continue;
939
+ const plan = plans[index];
940
+ const values = delegatedParameterValues(plan.parameters, arguments_);
941
+ if (values)
942
+ return { plan, values };
943
+ }
944
+ return undefined;
945
+ }
946
+ function substituteStructParameters(expression, values) {
947
+ let result = expression;
948
+ for (const [name, value] of values)
949
+ result = result.replace(new RegExp(`\\b${name}\\b`, "g"), `(${value})`);
950
+ return result;
951
+ }
952
+ function resolvedStructFields(index, plans, fields, stack = new Set()) {
953
+ if (stack.has(index))
954
+ return new Map();
955
+ const nextStack = new Set(stack).add(index);
956
+ const plan = plans[index];
957
+ const values = new Map();
958
+ if (plan.delegation) {
959
+ const delegated = findDelegatedInitializer(plans, plan.delegation, index);
960
+ if (delegated) {
961
+ const targetIndex = plans.indexOf(delegated.plan);
962
+ const targetFields = resolvedStructFields(targetIndex, plans, fields, nextStack);
963
+ for (const [field, expression] of targetFields)
964
+ values.set(field, substituteStructParameters(expression, delegated.values));
965
+ }
966
+ }
967
+ for (const [field, expression] of plan.assignments)
968
+ values.set(field, expression);
969
+ for (const field of fields) {
970
+ if (values.has(field.name))
971
+ continue;
972
+ const parameter = plan.parameters.find(item => item.name === field.name);
973
+ if (parameter)
974
+ values.set(field.name, parameter.name);
975
+ else if (field.defaultValue !== undefined && field.kind !== "state")
976
+ values.set(field.name, `(${field.defaultValue})`);
977
+ else
978
+ values.set(field.name, "undefined");
979
+ }
980
+ return values;
981
+ }
982
+ function delegatedStructInitializer(name, plan, fields, plans, index) {
983
+ const parameters = plan.parameters;
984
+ const assignments = resolvedStructFields(index, plans, fields);
985
+ const checks = parameters.map((parameter, parameterIndex) => parameter.kind === "value"
986
+ ? "true"
987
+ : parameter.kind === "binding"
988
+ ? `(args[${parameterIndex}] && typeof args[${parameterIndex}] === "object" && (Object.getOwnPropertyDescriptor(args[${parameterIndex}], "value")?.get || Object.getOwnPropertyDescriptor(args[${parameterIndex}], "value")?.set))`
989
+ : parameter.required
990
+ ? `typeof args[${parameterIndex}] === "function"`
991
+ : `(args[${parameterIndex}] === undefined || typeof args[${parameterIndex}] === "function")`);
992
+ const values = fields.map(field => {
993
+ const expression = assignments.get(field.name) ?? "undefined";
994
+ const parameter = parameters.find(item => item.name === field.name);
995
+ const resolved = parameter?.kind === "viewBuilder" && (expression === `${parameter.name}()` || expression === `(${parameter.name})()`)
996
+ ? `resolveBuilderInput(${parameter.name})`
997
+ : expression;
998
+ return `${field.name}: ${resolved}`;
999
+ });
1000
+ const signature = `${name}(${parameters.map(parameter => `${parameter.kind === "viewBuilder" ? "@ViewBuilder " : parameter.kind === "action" ? "@Action " : parameter.kind === "binding" ? "@Binding " : ""}${parameter.label ?? parameter.name}${parameter.defaultValue === undefined ? "" : ` = ${parameter.defaultValue}`}`).join(", ")})`;
1001
+ const metadata = `[${parameters.map(parameter => `{ name: ${JSON.stringify(parameter.name)}, kind: ${JSON.stringify(parameter.kind)}, label: ${parameter.label ? JSON.stringify(parameter.label) : "undefined"}, labelRequired: ${parameter.labelRequired === true}, required: ${parameter.required}, trailing: ${parameter.trailing === true}, type: ${parameter.type ? JSON.stringify(parameter.type) : "undefined"} }`).join(", ")}]`;
1002
+ const required = parameters.filter(parameter => parameter.required).length;
1003
+ const maximum = parameters.length;
1004
+ return `initializer(${JSON.stringify(signature)}, args => args.length >= ${required} && args.length <= ${maximum}${checks.length ? ` && ${checks.join(" && ")}` : ""}, args => { ${parameters.map((parameter, parameterIndex) => `const ${parameter.name} = args[${parameterIndex}]${parameter.defaultValue ? ` === undefined ? (${parameter.defaultValue}) : args[${parameterIndex}]` : ""}`).join("; ")}; return { ${values.join(", ")} } }, ${metadata})`;
1005
+ }
1006
+ function parsedCompilerExpression(source) {
1007
+ const file = ts.createSourceFile("mun-struct-body.ts", `const __munBody = (${source})`, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
1008
+ if ((file.parseDiagnostics?.length ?? 0) > 0)
1009
+ return undefined;
1010
+ const statement = file.statements[0];
1011
+ if (!statement || !ts.isVariableStatement(statement))
1012
+ return undefined;
1013
+ const initializer = statement.declarationList.declarations[0]?.initializer;
1014
+ return initializer ? unwrapTsExpression(initializer) : undefined;
1015
+ }
1016
+ function lowerStructDefinition(declaration, registry = canonicalInitializerSymbols, stateProof) {
1017
+ const fields = declaration.fields.map(field => ({
1018
+ name: field.name,
1019
+ kind: field.kind === "state" ? "state" : field.kind === "binding" ? "binding" : "value",
1020
+ type: field.type,
1021
+ defaultValue: field.initializer,
1022
+ }));
1023
+ const plans = structInitializerPlans(declaration);
1024
+ const initializers = plans.map((plan, index) => delegatedStructInitializer(declaration.name, plan, fields, plans, index));
1025
+ const stateFields = fields.filter(field => field.kind === "state");
1026
+ const state = stateFields.length === 0
1027
+ ? ""
1028
+ : `, state: () => ({ ${stateFields.map(field => `${field.name}: ${field.defaultValue !== undefined && /^State\s*\(/.test(field.defaultValue) ? field.defaultValue : `State(${field.defaultValue ?? "undefined"})`}`).join(", ")} })`;
1029
+ const bodySource = declaration.bodyExpressionSource.trim().replace(/^return\s+/, "").replace(/;\s*$/, "");
1030
+ // Struct bodies are lowered before the module-wide named-call pass. Keep
1031
+ // SwiftUI-style labels intact by lowering them here as well; otherwise a
1032
+ // call such as Button(action: ..., label: { ... }) is consumed by the
1033
+ // builder pass and can reach TypeScript as `Button(action, ..., label, ...)`.
1034
+ const stateNames = new Set(stateFields.map(field => field.name));
1035
+ const storageNames = new Set(fields.filter(field => field.kind !== "value").map(field => field.name));
1036
+ const methodNames = new Set((declaration.methods ?? []).map(method => method.name));
1037
+ // Swift-only member syntax becomes ordinary call syntax before builder lowering.
1038
+ const prepare = (source) => lowerLabeledCalls(lowerLifecycleModifiers(lowerSwiftInterpolation(source)), methodNames);
1039
+ const loweredBody = lowerBoolToggle(lowerStructStateAccess(lowerRange(lowerNamedMunCalls(prepare(bodySource), registry), registry), storageNames));
1040
+ const environment = (declaration.environment ?? []).map(value => ` const ${value.name} = environmentValue(${lowerSwiftKeyPaths(value.key)});`).join("");
1041
+ // Methods are function declarations, so computed properties and each other may call them in any order.
1042
+ const methods = (declaration.methods ?? []).map(method => {
1043
+ const lowered = lowerStructStateAccess(`${method.asynchronous ? "async " : ""}function ${method.name}(${lowerParameters(method.parametersSource)})${method.returnType ? `: ${method.asynchronous ? `Promise<${method.returnType}>` : method.returnType}` : ""} {${lowerRange(prepare(method.bodySource), registry)}}`, storageNames);
1044
+ return ` ${lowerBoolToggle(lowered)}`;
1045
+ }).join("");
1046
+ const computed = environment + methods + lowerComputedProperties(declaration.computed ?? [], storageNames, registry, prepare);
1047
+ const bodyExpression = stateFields.length > 0 && stateProof ? parsedCompilerExpression(loweredBody) : undefined;
1048
+ const dependenciesComplete = bodyExpression && stateProof && computed === ""
1049
+ ? hasCompleteStaticStateDependencies(bodyExpression, stateNames, stateNames, stateProof.values, stateProof.namespaces)
1050
+ : false;
1051
+ const dependencies = stateFields.length === 0
1052
+ ? ""
1053
+ : `, dependencies: (props: any) => [${stateFields.map(field => `props.${field.name}`).join(", ")}]${dependenciesComplete ? ", dependenciesComplete: true" : ""}`;
1054
+ const fieldMetadata = `fields: [${declaration.fields.map(field => `{ name: ${JSON.stringify(field.name)}, kind: ${JSON.stringify(field.kind)}, type: ${field.type === undefined ? "undefined" : JSON.stringify(field.type)}, defaultValue: ${field.initializer === undefined ? "undefined" : JSON.stringify(field.initializer)} }`).join(", ")}]`;
1055
+ const definitionMetadata = [
1056
+ declaration.genericParameters === undefined ? undefined : `genericParameters: ${JSON.stringify(declaration.genericParameters)}`,
1057
+ fieldMetadata,
1058
+ `legacyHost: ${legacyHostPlanSource(plans)}`,
1059
+ ].filter((item) => item !== undefined).join(", ");
1060
+ return `defineView(${JSON.stringify(declaration.name)}, { ${definitionMetadata}, initializers: [${initializers.join(", ")}]${state}${dependencies}, body: (__munProps: any) => { const { ${fields.map(field => field.name).join(", ")} } = __munProps;${computed} return ${loweredBody} } })`;
1061
+ }
1062
+ /**
1063
+ * Computed properties become body-local constants, evaluated after the
1064
+ * members they read. A single expression is the value (Swift's implicit
1065
+ * return); a statement body runs as an immediately invoked block.
1066
+ */
1067
+ function lowerComputedProperties(properties, storageNames, registry, prepare) {
1068
+ if (properties.length === 0)
1069
+ return "";
1070
+ const lowered = new Map(properties.map(property => {
1071
+ const source = prepare(property.bodySource).trim();
1072
+ const statements = /^(?:return|const|let|var|if|for|while|switch|guard|throw)\b/m.test(source);
1073
+ const value = statements
1074
+ ? `(() => {${lowerRange(source, registry)}})()`
1075
+ : `(${lowerRange(lowerNamedMunCalls(source, registry), registry)})`;
1076
+ return [property.name, lowerBoolToggle(lowerStructStateAccess(value, storageNames))];
1077
+ }));
1078
+ const ordered = [];
1079
+ const visiting = new Set();
1080
+ const visit = (name) => {
1081
+ if (ordered.includes(name))
1082
+ return;
1083
+ if (visiting.has(name))
1084
+ throw syntaxError(`Computed property '${name}' depends on itself`, 0);
1085
+ visiting.add(name);
1086
+ for (const other of lowered.keys()) {
1087
+ if (other !== name && new RegExp(`(?<![\\w$.])${other.replace(/\$/g, "\\$")}(?![\\w$])`).test(lowered.get(name)))
1088
+ visit(other);
1089
+ }
1090
+ visiting.delete(name);
1091
+ ordered.push(name);
1092
+ };
1093
+ for (const name of lowered.keys())
1094
+ visit(name);
1095
+ return ordered.map(name => ` const ${name} = ${lowered.get(name)};`).join("");
1096
+ }
1097
+ function lowerStructs(source, registry = canonicalInitializerSymbols, stateProof) {
1098
+ const declarations = parseMunStructs(source);
1099
+ if (declarations.length === 0)
1100
+ return source;
1101
+ const proof = stateProof ?? importedMunValueBindings(validationSourceFile(source));
1102
+ let output = source;
1103
+ for (const declaration of [...declarations].sort((left, right) => right.range.start - left.range.start)) {
1104
+ const definition = lowerStructDefinition(declaration, registry, proof);
1105
+ const nested = declaration.nested ?? [];
1106
+ const replacement = nested.length === 0
1107
+ ? `const ${declaration.name} = ${definition}`
1108
+ : `const ${declaration.name} = (() => { ${nested.map(item => `const ${item.name} = ${lowerStructDefinition(item, registry, proof)}`).join("; ")}; return Object.assign(${definition}, { ${nested.map(item => item.name).join(", ")} }); })()`;
1109
+ output = output.slice(0, declaration.range.start) + replacement + output.slice(declaration.range.end);
1110
+ }
1111
+ return output;
1112
+ }
1113
+ function lowerStaticStructCalls(source, declarations) {
1114
+ if (declarations.length === 0)
1115
+ return source;
1116
+ const known = new Map();
1117
+ const add = (declaration) => {
1118
+ known.set(declaration.name, known.has(declaration.name) ? undefined : declaration);
1119
+ for (const nested of declaration.nested ?? [])
1120
+ add(nested);
1121
+ };
1122
+ for (const declaration of declarations)
1123
+ add(declaration);
1124
+ const file = ts.createSourceFile("mun-specialization.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
1125
+ const edits = [];
1126
+ const simpleBuilderValue = (value) => {
1127
+ const expression = /^\s*\(\s*\)\s*=>\s*(\[[\s\S]*\])\s*$/.exec(value);
1128
+ if (expression)
1129
+ return expression[1];
1130
+ const block = /^\s*\(\s*\)\s*=>\s*\{\s*return\s+(\[[\s\S]*\])\s*;?\s*\}\s*$/.exec(value);
1131
+ return block?.[1];
1132
+ };
1133
+ const visit = (node) => {
1134
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
1135
+ const declaration = known.get(node.expression.text);
1136
+ const initializerIndex = declaration && staticInitializerIndex(declaration, node.arguments.map(argument => argument.getText(file)).join(", "), node.expression.getStart(file));
1137
+ if (initializerIndex !== undefined && declaration) {
1138
+ const plan = structInitializerPlans(declaration)[initializerIndex];
1139
+ const flattened = plan
1140
+ ? compilerInitializerArguments(node.arguments.map(argument => argument.getText(file)).join(", "))
1141
+ : [];
1142
+ const values = plan ? delegatedParameterValues(plan.parameters, flattened) : undefined;
1143
+ const compiled = !!plan && !!values;
1144
+ const argumentsSource = compiled
1145
+ ? plan.parameters.map(parameter => {
1146
+ const value = values.get(parameter.name) ?? "undefined";
1147
+ return parameter.kind === "viewBuilder" ? simpleBuilderValue(value) ?? value : value;
1148
+ }).join(", ")
1149
+ : node.arguments.map(argument => argument.getText(file)).join(", ");
1150
+ const method = compiled ? "createNodeCompiled" : "createNodeSpecialized";
1151
+ edits.push({
1152
+ start: node.expression.getStart(file),
1153
+ end: node.end,
1154
+ replacement: `${node.expression.text}.viewType.${method}(${initializerIndex}, [${argumentsSource}])`,
1155
+ });
1156
+ return;
1157
+ }
1158
+ }
1159
+ ts.forEachChild(node, visit);
1160
+ };
1161
+ visit(file);
1162
+ let result = source;
1163
+ for (const edit of edits.sort((left, right) => right.start - left.start)) {
1164
+ result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);
1165
+ }
1166
+ return result;
1167
+ }
1168
+ function isMunPackage(moduleName) {
1169
+ return moduleName.startsWith("@mun-ui/");
1170
+ }
1171
+ function bindingNames(name) {
1172
+ if (ts.isIdentifier(name))
1173
+ return [name.text];
1174
+ if (ts.isObjectBindingPattern(name) || ts.isArrayBindingPattern(name)) {
1175
+ return name.elements.flatMap(element => ts.isOmittedExpression(element) ? [] : bindingNames(element.name));
1176
+ }
1177
+ return [];
1178
+ }
1179
+ function munApiBindings(file) {
1180
+ const state = new Set();
1181
+ const view = new Set();
1182
+ const namespaces = new Set();
1183
+ let blockedState = false;
1184
+ let blockedView = false;
1185
+ for (const statement of file.statements) {
1186
+ if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {
1187
+ const mun = isMunPackage(statement.moduleSpecifier.text);
1188
+ const clause = statement.importClause;
1189
+ if (clause?.name) {
1190
+ if (!mun && clause.name.text === "State")
1191
+ blockedState = true;
1192
+ if (!mun && clause.name.text === "view")
1193
+ blockedView = true;
1194
+ }
1195
+ const bindings = clause?.namedBindings;
1196
+ if (bindings && ts.isNamespaceImport(bindings)) {
1197
+ if (mun)
1198
+ namespaces.add(bindings.name.text);
1199
+ continue;
1200
+ }
1201
+ if (bindings && ts.isNamedImports(bindings)) {
1202
+ for (const element of bindings.elements) {
1203
+ const imported = element.propertyName?.text ?? element.name.text;
1204
+ const local = element.name.text;
1205
+ if (mun && imported === "State")
1206
+ state.add(local);
1207
+ else if (!mun && local === "State")
1208
+ blockedState = true;
1209
+ if (mun && imported === "view")
1210
+ view.add(local);
1211
+ else if (!mun && local === "view")
1212
+ blockedView = true;
1213
+ }
1214
+ }
1215
+ continue;
1216
+ }
1217
+ const names = [];
1218
+ if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && statement.name)
1219
+ names.push(statement.name.text);
1220
+ if (ts.isVariableStatement(statement)) {
1221
+ for (const declaration of statement.declarationList.declarations)
1222
+ names.push(...bindingNames(declaration.name));
1223
+ }
1224
+ if (names.includes("State"))
1225
+ blockedState = true;
1226
+ if (names.includes("view"))
1227
+ blockedView = true;
1228
+ }
1229
+ return { state, view, namespaces, blockedState, blockedView };
1230
+ }
1231
+ function unwrapTsExpression(expression) {
1232
+ let current = expression;
1233
+ while (ts.isParenthesizedExpression(current)
1234
+ || ts.isAsExpression(current)
1235
+ || ts.isTypeAssertionExpression(current)
1236
+ || ts.isNonNullExpression(current)
1237
+ || ts.isSatisfiesExpression(current)) {
1238
+ current = current.expression;
1239
+ }
1240
+ return current;
1241
+ }
1242
+ function isMunApiCall(call, api, bindings) {
1243
+ const expression = unwrapTsExpression(call.expression);
1244
+ const named = api === "State" ? bindings.state : bindings.view;
1245
+ const blocked = api === "State" ? bindings.blockedState : bindings.blockedView;
1246
+ if (ts.isIdentifier(expression)) {
1247
+ if (named.has(expression.text))
1248
+ return true;
1249
+ // `.mun.ts` supports the canonical names without an explicit import; do
1250
+ // not claim them when the file has provided an unrelated binding.
1251
+ return expression.text === api && !blocked && named.size === 0;
1252
+ }
1253
+ if (ts.isPropertyAccessExpression(expression)
1254
+ && expression.name.text === api
1255
+ && ts.isIdentifier(expression.expression)
1256
+ && bindings.namespaces.has(expression.expression.text))
1257
+ return true;
1258
+ return false;
1259
+ }
1260
+ function collectTopLevelStates(file, bindings) {
1261
+ const states = [];
1262
+ for (const statement of file.statements) {
1263
+ if (!ts.isVariableStatement(statement))
1264
+ continue;
1265
+ const isConst = (statement.declarationList.flags & ts.NodeFlags.Const) !== 0;
1266
+ const exported = statement.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword) ?? false;
1267
+ for (const declaration of statement.declarationList.declarations) {
1268
+ if (!declaration.initializer)
1269
+ continue;
1270
+ const initializer = unwrapTsExpression(declaration.initializer);
1271
+ if (!ts.isCallExpression(initializer) || !isMunApiCall(initializer, "State", bindings))
1272
+ continue;
1273
+ states.push({
1274
+ name: ts.isIdentifier(declaration.name) ? declaration.name.text : undefined,
1275
+ statement,
1276
+ declaration,
1277
+ initializer: declaration.initializer,
1278
+ eligible: isConst && !exported && ts.isIdentifier(declaration.name),
1279
+ });
1280
+ }
1281
+ }
1282
+ return states;
1283
+ }
1284
+ function isNonReferenceIdentifier(node) {
1285
+ const parent = node.parent;
1286
+ if (ts.isPropertyAccessExpression(parent) && parent.name === node)
1287
+ return true;
1288
+ if (ts.isPropertyAssignment(parent) && parent.name === node)
1289
+ return true;
1290
+ if (ts.isMethodDeclaration(parent) && parent.name === node)
1291
+ return true;
1292
+ if (ts.isPropertyDeclaration(parent) && parent.name === node)
1293
+ return true;
1294
+ if (ts.isMethodSignature(parent) && parent.name === node)
1295
+ return true;
1296
+ if (ts.isPropertySignature(parent) && parent.name === node)
1297
+ return true;
1298
+ if (ts.isVariableDeclaration(parent) && parent.name === node)
1299
+ return true;
1300
+ if (ts.isParameter(parent) && parent.name === node)
1301
+ return true;
1302
+ if (ts.isBindingElement(parent) && parent.name === node)
1303
+ return true;
1304
+ if (ts.isFunctionDeclaration(parent) && parent.name === node)
1305
+ return true;
1306
+ if (ts.isClassDeclaration(parent) && parent.name === node)
1307
+ return true;
1308
+ if (ts.isImportSpecifier(parent) || ts.isImportClause(parent) || ts.isNamespaceImport(parent))
1309
+ return true;
1310
+ return false;
1311
+ }
1312
+ function directBlockBindings(node) {
1313
+ const bindings = new Set();
1314
+ for (const statement of node.statements) {
1315
+ if (ts.isVariableStatement(statement)) {
1316
+ for (const declaration of statement.declarationList.declarations) {
1317
+ for (const name of bindingNames(declaration.name))
1318
+ bindings.add(name);
1319
+ }
1320
+ }
1321
+ else if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && statement.name) {
1322
+ bindings.add(statement.name.text);
1323
+ }
1324
+ }
1325
+ return bindings;
1326
+ }
1327
+ function referencedStateNames(root, stateNames, skipped = new Set()) {
1328
+ const result = new Set();
1329
+ const visit = (node, shadowed) => {
1330
+ if (skipped.has(node))
1331
+ return;
1332
+ if (ts.isIdentifier(node) && stateNames.has(node.text) && !shadowed.has(node.text) && !isNonReferenceIdentifier(node))
1333
+ result.add(node.text);
1334
+ if (ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) {
1335
+ const local = new Set(shadowed);
1336
+ for (const parameter of node.parameters)
1337
+ for (const name of bindingNames(parameter.name))
1338
+ local.add(name);
1339
+ if (ts.isFunctionDeclaration(node) && node.name)
1340
+ local.add(node.name.text);
1341
+ if (node.body)
1342
+ visit(node.body, local);
1343
+ return;
1344
+ }
1345
+ if (ts.isBlock(node)) {
1346
+ const local = new Set(shadowed);
1347
+ for (const name of directBlockBindings(node))
1348
+ local.add(name);
1349
+ ts.forEachChild(node, child => visit(child, local));
1350
+ return;
1351
+ }
1352
+ if (ts.isCatchClause(node)) {
1353
+ const local = new Set(shadowed);
1354
+ if (node.variableDeclaration)
1355
+ for (const name of bindingNames(node.variableDeclaration.name))
1356
+ local.add(name);
1357
+ visit(node.block, local);
1358
+ return;
1359
+ }
1360
+ ts.forEachChild(node, child => visit(child, shadowed));
1361
+ };
1362
+ visit(root, new Set());
1363
+ return result;
1364
+ }
1365
+ function collectMunViewCalls(file, bindings) {
1366
+ const calls = [];
1367
+ const visit = (node) => {
1368
+ if (ts.isCallExpression(node) && isMunApiCall(node, "view", bindings)) {
1369
+ calls.push(node);
1370
+ return;
1371
+ }
1372
+ ts.forEachChild(node, visit);
1373
+ };
1374
+ visit(file);
1375
+ return calls.sort((left, right) => left.getStart(file) - right.getStart(file));
1376
+ }
1377
+ function stateDependencies(state, stateNames) {
1378
+ return referencedStateNames(state.initializer, stateNames);
1379
+ }
1380
+ function importedMunValueBindings(file) {
1381
+ const values = new Set();
1382
+ const namespaces = new Set();
1383
+ for (const statement of file.statements) {
1384
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier) || !isMunPackage(statement.moduleSpecifier.text))
1385
+ continue;
1386
+ const clause = statement.importClause;
1387
+ if (!clause || clause.isTypeOnly)
1388
+ continue;
1389
+ if (clause.name)
1390
+ values.add(clause.name.text);
1391
+ const named = clause.namedBindings;
1392
+ if (named && ts.isNamespaceImport(named))
1393
+ namespaces.add(named.name.text);
1394
+ if (named && ts.isNamedImports(named)) {
1395
+ for (const element of named.elements)
1396
+ if (!element.isTypeOnly)
1397
+ values.add(element.name.text);
1398
+ }
1399
+ }
1400
+ return { values, namespaces };
1401
+ }
1402
+ const compilerPureCallNames = new Set([
1403
+ "String", "Number", "Boolean", "BigInt",
1404
+ "namedArguments", "overloadClosure", "resolveBuilderInput", "Element",
1405
+ ]);
1406
+ const compilerAnimationFactoryNames = new Set([
1407
+ "linear", "easeIn", "easeOut", "easeInOut", "spring",
1408
+ "interactiveSpring", "smooth", "snappy", "bouncy",
1409
+ ]);
1410
+ const compilerAnimationTransformNames = new Set(["delay", "speed", "repeatCount", "repeatForever"]);
1411
+ function isProvenAnimationExpression(expression, munValues) {
1412
+ const value = unwrapTsExpression(expression);
1413
+ if (!ts.isCallExpression(value))
1414
+ return false;
1415
+ const callee = unwrapTsExpression(value.expression);
1416
+ if (!ts.isPropertyAccessExpression(callee))
1417
+ return false;
1418
+ const owner = unwrapTsExpression(callee.expression);
1419
+ if (compilerAnimationFactoryNames.has(callee.name.text))
1420
+ return ts.isIdentifier(owner) && munValues.has(owner.text);
1421
+ return compilerAnimationTransformNames.has(callee.name.text) && isProvenAnimationExpression(owner, munValues);
1422
+ }
1423
+ function isProvenAnimationMember(expression, munValues) {
1424
+ const owner = unwrapTsExpression(expression.expression);
1425
+ if (compilerAnimationFactoryNames.has(expression.name.text))
1426
+ return ts.isIdentifier(owner) && munValues.has(owner.text);
1427
+ return compilerAnimationTransformNames.has(expression.name.text) && isProvenAnimationExpression(owner, munValues);
1428
+ }
1429
+ function valueBindingNames(root) {
1430
+ const names = new Set();
1431
+ const addBinding = (name) => {
1432
+ for (const value of bindingNames(name))
1433
+ names.add(value);
1434
+ };
1435
+ const visit = (node) => {
1436
+ if (ts.isVariableDeclaration(node) || ts.isParameter(node))
1437
+ addBinding(node.name);
1438
+ else if ((ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isEnumDeclaration(node)) && node.name)
1439
+ names.add(node.name.text);
1440
+ else if (ts.isCatchClause(node) && node.variableDeclaration)
1441
+ addBinding(node.variableDeclaration.name);
1442
+ else if (ts.isImportClause(node) && node.name && !node.isTypeOnly)
1443
+ names.add(node.name.text);
1444
+ else if (ts.isNamespaceImport(node))
1445
+ names.add(node.name.text);
1446
+ else if (ts.isImportSpecifier(node) && !node.isTypeOnly)
1447
+ names.add(node.name.text);
1448
+ ts.forEachChild(node, visit);
1449
+ };
1450
+ visit(root);
1451
+ return names;
1452
+ }
1453
+ function isProvenMunViewExpression(expression, munValues, munNamespaces) {
1454
+ const value = unwrapTsExpression(expression);
1455
+ if (!ts.isCallExpression(value))
1456
+ return false;
1457
+ const callee = unwrapTsExpression(value.expression);
1458
+ if (ts.isIdentifier(callee))
1459
+ return munValues.has(callee.text) && canonicalInitializerSymbols.has(callee.text);
1460
+ if (!ts.isPropertyAccessExpression(callee))
1461
+ return false;
1462
+ const owner = unwrapTsExpression(callee.expression);
1463
+ if (staticModifierNames.has(callee.name.text))
1464
+ return isProvenMunViewExpression(owner, munValues, munNamespaces);
1465
+ return ts.isIdentifier(owner)
1466
+ && munNamespaces.has(owner.text)
1467
+ && canonicalInitializerSymbols.has(callee.name.text);
1468
+ }
1469
+ /**
1470
+ * Prove a deliberately small closed world for State reads. A false result is
1471
+ * not an error; it simply keeps runtime dependency discovery enabled. This
1472
+ * avoids unsoundly skipping a shared/module State that is read through an
1473
+ * opaque helper, getter, or other user-controlled call.
1474
+ */
1475
+ function hasCompleteStaticStateDependencies(root, ownedStateNames, allStateNames, munValues, munNamespaces, shadowedPureCalls = new Set()) {
1476
+ const directlyReferenced = referencedStateNames(root, allStateNames);
1477
+ if ([...directlyReferenced].some(name => !ownedStateNames.has(name)))
1478
+ return false;
1479
+ const localBindings = valueBindingNames(root);
1480
+ const pureCallAllowed = (name) => compilerPureCallNames.has(name)
1481
+ && !shadowedPureCalls.has(name)
1482
+ && !localBindings.has(name);
1483
+ let safe = true;
1484
+ const visit = (node) => {
1485
+ if (!safe)
1486
+ return;
1487
+ if (ts.isPropertyAccessExpression(node)) {
1488
+ const expression = unwrapTsExpression(node.expression);
1489
+ const ownedStateValue = node.name.text === "value" && ts.isIdentifier(expression) && ownedStateNames.has(expression.text);
1490
+ const munNamespaceMember = ts.isIdentifier(expression) && munNamespaces.has(expression.text);
1491
+ const provenViewModifier = staticModifierNames.has(node.name.text)
1492
+ && isProvenMunViewExpression(node.expression, munValues, munNamespaces);
1493
+ const provenAnimationMember = isProvenAnimationMember(node, munValues);
1494
+ // Modifier names alone are not enough: a user object may expose an
1495
+ // `opacity()`/`padding()` method. Only a chain rooted in an imported Mun
1496
+ // View constructor is admitted into the static dependency proof. Immutable
1497
+ // Animation factory/configuration chains are also closed and pure.
1498
+ if (!ownedStateValue && !munNamespaceMember && !provenViewModifier && !provenAnimationMember) {
1499
+ safe = false;
1500
+ return;
1501
+ }
1502
+ }
1503
+ if (ts.isElementAccessExpression(node)) {
1504
+ safe = false;
1505
+ return;
1506
+ }
1507
+ if (ts.isCallExpression(node)) {
1508
+ const callee = unwrapTsExpression(node.expression);
1509
+ if (ts.isIdentifier(callee)) {
1510
+ if (!munValues.has(callee.text) && !pureCallAllowed(callee.text)) {
1511
+ safe = false;
1512
+ return;
1513
+ }
1514
+ }
1515
+ else if (ts.isPropertyAccessExpression(callee)) {
1516
+ const owner = unwrapTsExpression(callee.expression);
1517
+ const namespaceCall = ts.isIdentifier(owner) && munNamespaces.has(owner.text);
1518
+ const modifierCall = staticModifierNames.has(callee.name.text)
1519
+ && isProvenMunViewExpression(owner, munValues, munNamespaces);
1520
+ const animationCall = isProvenAnimationMember(callee, munValues);
1521
+ if (!namespaceCall && !modifierCall && !animationCall) {
1522
+ safe = false;
1523
+ return;
1524
+ }
1525
+ }
1526
+ else {
1527
+ safe = false;
1528
+ return;
1529
+ }
1530
+ }
1531
+ ts.forEachChild(node, visit);
1532
+ };
1533
+ visit(root);
1534
+ return safe;
1535
+ }
1536
+ function transitiveStateClosure(initial, eligible, dependencies) {
1537
+ const result = new Set();
1538
+ const queue = [...initial];
1539
+ while (queue.length > 0) {
1540
+ const name = queue.pop();
1541
+ if (!eligible.has(name) || result.has(name))
1542
+ continue;
1543
+ result.add(name);
1544
+ for (const dependency of dependencies.get(name) ?? [])
1545
+ queue.push(dependency);
1546
+ }
1547
+ return result;
1548
+ }
1549
+ function lowerTopLevelState(source) {
1550
+ // Aliases still contain the exported name in their import declaration
1551
+ // (`State as LocalState`), so this is a safe conservative preflight.
1552
+ if (!/\bState\b/.test(source))
1553
+ return source;
1554
+ const file = ts.createSourceFile("mun-state.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
1555
+ const bindings = munApiBindings(file);
1556
+ const munValues = importedMunValueBindings(file);
1557
+ const fileValueBindings = valueBindingNames(file);
1558
+ const states = collectTopLevelStates(file, bindings);
1559
+ const eligibleStates = states.filter((state) => state.eligible && state.name !== undefined);
1560
+ if (eligibleStates.length === 0)
1561
+ return source;
1562
+ const byName = new Map(eligibleStates.map(state => [state.name, state]));
1563
+ const eligibleNames = new Set(byName.keys());
1564
+ const allNames = new Set(states.flatMap(state => state.name ? [state.name] : []));
1565
+ const dependencies = new Map();
1566
+ for (const state of eligibleStates)
1567
+ dependencies.set(state.name, stateDependencies(state, allNames));
1568
+ const views = collectMunViewCalls(file, bindings);
1569
+ if (views.length === 0)
1570
+ return source;
1571
+ const viewSet = new Set(views);
1572
+ // Any reference outside a Mun view keeps that State module-scoped. This
1573
+ // includes helper functions and ineligible/exported/mutable State factories.
1574
+ const directOutside = new Set();
1575
+ const stateDeclarations = new Set(states.map(state => state.declaration));
1576
+ for (const statement of file.statements) {
1577
+ if (ts.isVariableStatement(statement)) {
1578
+ for (const declaration of statement.declarationList.declarations) {
1579
+ if (stateDeclarations.has(declaration)) {
1580
+ const state = states.find(item => item.declaration === declaration);
1581
+ if (state && !state.eligible) {
1582
+ for (const dependency of referencedStateNames(state.initializer, allNames))
1583
+ directOutside.add(dependency);
1584
+ }
1585
+ continue;
1586
+ }
1587
+ if (declaration.initializer)
1588
+ for (const name of referencedStateNames(declaration.initializer, allNames, viewSet))
1589
+ directOutside.add(name);
1590
+ }
1591
+ continue;
1592
+ }
1593
+ for (const name of referencedStateNames(statement, allNames, viewSet))
1594
+ directOutside.add(name);
1595
+ }
1596
+ const outside = transitiveStateClosure(directOutside, eligibleNames, dependencies);
1597
+ const owners = new Map();
1598
+ const statesByView = new Map();
1599
+ views.forEach((view, index) => {
1600
+ const direct = referencedStateNames(view.arguments[0] ?? view, allNames);
1601
+ const closure = transitiveStateClosure(direct, eligibleNames, dependencies);
1602
+ for (const name of closure) {
1603
+ const set = owners.get(name) ?? new Set();
1604
+ set.add(index);
1605
+ owners.set(name, set);
1606
+ }
1607
+ });
1608
+ for (const state of eligibleStates) {
1609
+ const stateOwners = owners.get(state.name);
1610
+ if (outside.has(state.name) || stateOwners?.size !== 1)
1611
+ continue;
1612
+ const owner = [...stateOwners][0];
1613
+ const list = statesByView.get(owner) ?? [];
1614
+ list.push(state);
1615
+ statesByView.set(owner, list);
1616
+ }
1617
+ if (statesByView.size === 0)
1618
+ return source;
1619
+ const hoisted = new Set([...statesByView.values()].flat().map(state => state.declaration));
1620
+ const hoistedSpans = [];
1621
+ const removalEdits = [];
1622
+ // Remove each hoisted declarator individually instead of rewriting the whole
1623
+ // variable statement from original source text. A whole-statement rewrite
1624
+ // clobbers any nested view() replacement inside a preserved sibling
1625
+ // declarator (e.g. `const count = State(0), app = view(() => Text(count))`).
1626
+ for (const statement of file.statements) {
1627
+ if (!ts.isVariableStatement(statement))
1628
+ continue;
1629
+ const declarations = statement.declarationList.declarations;
1630
+ const removedIndexes = declarations.map((declaration, index) => hoisted.has(declaration) ? index : -1).filter(index => index >= 0);
1631
+ if (removedIndexes.length === 0)
1632
+ continue;
1633
+ const hasPreserved = declarations.some(declaration => !hoisted.has(declaration));
1634
+ if (!hasPreserved) {
1635
+ removalEdits.push({ start: statement.getStart(file), end: statement.end, replacement: "" });
1636
+ for (const declaration of declarations) {
1637
+ if (!hoisted.has(declaration))
1638
+ continue;
1639
+ hoistedSpans.push({ start: declaration.getStart(file), end: declaration.end });
1640
+ }
1641
+ continue;
1642
+ }
1643
+ for (const index of removedIndexes) {
1644
+ const declaration = declarations[index];
1645
+ let start = declaration.getStart(file);
1646
+ let end = declaration.end;
1647
+ const trailingSeparator = /^\s*,/.exec(source.slice(end));
1648
+ if (trailingSeparator)
1649
+ end += trailingSeparator[0].length;
1650
+ else {
1651
+ const leadingSeparator = /,\s*$/.exec(source.slice(0, start));
1652
+ if (leadingSeparator)
1653
+ start -= leadingSeparator[0].length;
1654
+ }
1655
+ removalEdits.push({ start, end, replacement: "" });
1656
+ hoistedSpans.push({ start: declaration.getStart(file), end: declaration.end });
1657
+ }
1658
+ }
1659
+ // A view replacement lexically inside a removed State declarator cannot be
1660
+ // applied safely alongside the removal; leave that call on the runtime path.
1661
+ const viewEdits = [...statesByView]
1662
+ .flatMap(([viewIndex]) => {
1663
+ const call = views[viewIndex];
1664
+ if (!call)
1665
+ return [];
1666
+ if (hoistedSpans.some(span => call.getStart(file) < span.end && span.start < call.end))
1667
+ return [];
1668
+ return [viewIndex];
1669
+ })
1670
+ .map(viewIndex => {
1671
+ const call = views[viewIndex];
1672
+ const argument = call.arguments[0];
1673
+ if (!argument || call.arguments.length !== 1)
1674
+ return undefined;
1675
+ const callee = call.expression.getText(file);
1676
+ const body = argument.getText(file);
1677
+ const unwrapped = unwrapTsExpression(argument);
1678
+ const functionBody = ts.isArrowFunction(unwrapped) || ts.isFunctionExpression(unwrapped);
1679
+ const hasProps = functionBody && unwrapped.parameters.length > 0;
1680
+ const names = statesByView.get(viewIndex).map(state => state.name);
1681
+ const declarations = statesByView.get(viewIndex)
1682
+ .sort((left, right) => left.declaration.getStart(file) - right.declaration.getStart(file))
1683
+ .map(state => `const ${state.name} = ${state.initializer.getText(file)};`)
1684
+ .join(" ");
1685
+ const renderedBody = functionBody ? `((${body})(${hasProps ? "props" : ""}))` : `(${body})`;
1686
+ const bodyParameters = hasProps ? `({ ${names.join(", ")} }, props)` : `({ ${names.join(", ")} })`;
1687
+ const dependencyParameters = `({ ${names.join(", ")} })`;
1688
+ const ownedNames = new Set(names);
1689
+ const dependenciesComplete = !hasProps && hasCompleteStaticStateDependencies(argument, ownedNames, allNames, munValues.values, munValues.namespaces, fileValueBindings);
1690
+ const completeness = dependenciesComplete ? `, dependenciesComplete: true` : "";
1691
+ const replacement = `${callee}({ state: () => { ${declarations} return { ${names.join(", ")} } }, dependencies: ${dependencyParameters} => [${names.join(", ")}]${completeness}, body: ${bodyParameters} => ${renderedBody} })`;
1692
+ return { start: call.getStart(file), end: call.end, replacement };
1693
+ })
1694
+ .filter((edit) => edit !== undefined);
1695
+ const edits = [...removalEdits, ...viewEdits].sort((left, right) => right.start - left.start);
1696
+ let result = source;
1697
+ for (const edit of edits)
1698
+ result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);
1699
+ return result;
1700
+ }
1701
+ /**
1702
+ * `.mun` modules resolve built-ins statically: every free identifier of the
1703
+ * lowered module is looked up in the shared registry after lexical scoping, so
1704
+ * local declarations and explicit imports shadow built-ins and only the
1705
+ * built-ins actually read become (tree-shakable) named imports.
1706
+ */
1707
+ function importMunBuiltins(source, lowered, fileName, externalScope) {
1708
+ const file = ts.createSourceFile(fileName + ".ts", lowered, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
1709
+ // A module TypeScript cannot parse is reported by validateWebLowering with
1710
+ // the parser's own message; scope analysis of a broken tree would only add noise.
1711
+ if ((file.parseDiagnostics ?? []).length > 0)
1712
+ return lowered;
1713
+ const resolution = resolveMunBuiltins(file);
1714
+ const unresolved = externalScope ? undefined : resolution.unresolved[0];
1715
+ if (unresolved) {
1716
+ const position = file.getLineAndCharacterOfPosition(unresolved.offset);
1717
+ const mapped = mapGeneratedPosition(createMunSourceMap(source, lowered, fileName), { line: position.line + 1, column: position.character + 1 });
1718
+ const offset = source.split("\n").slice(0, mapped.line - 1).reduce((sum, line) => sum + line.length + 1, 0) + mapped.column - 1;
1719
+ throw Object.assign(new SyntaxError(unresolved.message), { offset, code: "MUN_SYNTAX" });
1720
+ }
1721
+ let result = lowered;
1722
+ for (const [module, names] of [...resolution.imports].reverse())
1723
+ result = addNamedImports(result, module, names);
1724
+ return result;
1725
+ }
1726
+ function ensureImports(source, includeViewBuiltins = false) {
1727
+ const callableRequired = ["defineView", "initializer", "resolveBuilderInput", "namedArguments", "overloadClosure", "viewFragment", "withAnimation", "withTransaction", "Binding", "State", "Element", "modifiedContent", "modifiedContentCompiled", "compiledTemplate", "defineCompiledTemplate", "Observable", "environmentValue"]
1728
+ .filter(name => new RegExp(`\\b${name}(?:<[^()\\n]*>)?\\s*\\(`).test(source) || (name === "defineView" && /const\s+[A-Z]\w*\s*=\s*defineView/.test(source)));
1729
+ const valueRequired = ["Transition", "Animation", "ContentTransition", "SymbolEffect"].filter(name => {
1730
+ if (!new RegExp(`\\b${name}\\s*\\.`).test(source))
1731
+ return false;
1732
+ return !new RegExp(`\\b(?:const|let|var|class|function|enum|namespace)\\s+${name}\\b`).test(source);
1733
+ });
1734
+ const viewRequired = includeViewBuiltins
1735
+ ? [...canonicalInitializerSymbols.keys()].filter(name => {
1736
+ if (!new RegExp(`\\b${name}\\s*\\(`).test(source))
1737
+ return false;
1738
+ return !new RegExp(`\\b(?:const|let|var|class|function|enum|namespace)\\s+${name}\\b`).test(source);
1739
+ })
1740
+ : [];
1741
+ const required = [...new Set([...callableRequired, ...valueRequired, ...viewRequired])];
1742
+ let result = source;
1743
+ const internalRequired = ["compiledCollectionContent", "mapStateArrayData"].filter(name => new RegExp(`\\b${name}\\s*\\(`).test(source));
1744
+ if (required.length === 0 && internalRequired.length === 0)
1745
+ return result;
1746
+ const imports = [...result.matchAll(/import\s*\{([^}]*)\}\s*from\s*(["'])(@mun-ui\/core\/compat|@mun-ui\/react)\2[\t ]*;?/g)];
1747
+ // Respect local named bindings from every entrypoint, including @mun-ui/core
1748
+ // and @mun-ui/ui, so adding implicit helpers cannot duplicate explicit imports.
1749
+ const imported = new Set([...result.matchAll(/import\s*\{([^}]*)\}\s*from\s*["'][^"']+["']/g)]
1750
+ .flatMap(match => match[1].split(",").map(value => value.trim()).filter(value => value && !/^type\s/.test(value))
1751
+ .map(value => value.split(/\s+as\s+/).at(-1))));
1752
+ const missing = required.filter(name => !imported.has(name));
1753
+ if (missing.length > 0) {
1754
+ const existingCore = imports.find(match => match[3] === "@mun-ui/core/compat");
1755
+ if (!existingCore)
1756
+ result = `import { ${missing.join(", ")} } from "@mun-ui/core/compat"\n${result}`;
1757
+ else {
1758
+ const names = existingCore[1].split(",").map(value => value.trim()).filter(Boolean);
1759
+ for (const name of missing)
1760
+ if (!names.includes(name))
1761
+ names.push(name);
1762
+ const replacement = `import { ${names.join(", ")} } from ${existingCore[2]}@mun-ui/core/compat${existingCore[2]}`;
1763
+ result = result.slice(0, existingCore.index) + replacement + result.slice(existingCore.index + existingCore[0].length);
1764
+ }
1765
+ }
1766
+ if (internalRequired.length > 0) {
1767
+ const internalImport = /import\s*\{([^}]*)\}\s*from\s*(["'])@mun-ui\/core\/internal\/runtime\2[\t ]*;?/.exec(result);
1768
+ if (!internalImport)
1769
+ result = `import { ${internalRequired.join(", ")} } from "@mun-ui/core/internal/runtime"\n${result}`;
1770
+ else {
1771
+ const names = internalImport[1].split(",").map(value => value.trim()).filter(Boolean);
1772
+ for (const name of internalRequired)
1773
+ if (!names.includes(name))
1774
+ names.push(name);
1775
+ const replacement = `import { ${names.join(", ")} } from ${internalImport[2]}@mun-ui/core/internal/runtime${internalImport[2]}`;
1776
+ result = result.slice(0, internalImport.index) + replacement + result.slice(internalImport.index + internalImport[0].length);
1777
+ }
1778
+ }
1779
+ return result;
1780
+ }
1781
+ function lowerNamedMunCalls(source, registry = canonicalInitializerSymbols) {
1782
+ // A labeled call must contain a colon. Most host TypeScript modules do not,
1783
+ // so avoid even collecting uppercase call candidates in that common case.
1784
+ if (!source.includes(":"))
1785
+ return source;
1786
+ const candidates = [];
1787
+ for (const match of source.matchAll(/\b(?:[A-Z][A-Za-z0-9_$]*\.)*[A-Z][A-Za-z0-9_$]*\s*\(/g)) {
1788
+ const start = match.index ?? 0;
1789
+ const callee = /^(?:[A-Z][A-Za-z0-9_$]*\.)*[A-Z][A-Za-z0-9_$]*/.exec(match[0])?.[0];
1790
+ if (!callee)
1791
+ continue;
1792
+ const previous = previousSignificantCharacter(source, start);
1793
+ const word = previousWord(source, start);
1794
+ const wordBeforeStar = previous === "*" ? previousWord(source, start - 2) : undefined;
1795
+ if (previous === "." || word === "function" || word === "class" || word === "interface" || word === "type" || word === "new" || wordBeforeStar === "function")
1796
+ continue;
1797
+ const open = source.indexOf("(", start + callee.length);
1798
+ const close = matching(source, open, "(", ")");
1799
+ const argumentSource = source.slice(open + 1, close);
1800
+ if (!splitTopLevel(argumentSource).some(argument => topLevelColon(argument) >= 0))
1801
+ continue;
1802
+ candidates.push({ start, end: close + 1, callee, open, close });
1803
+ }
1804
+ if (candidates.length === 0)
1805
+ return source;
1806
+ if (candidates.length === 1) {
1807
+ const candidate = candidates[0];
1808
+ const value = `${candidate.callee}(${lowerArguments(source.slice(candidate.open + 1, candidate.close), candidate.callee.split(".").at(-1), registry)})`;
1809
+ return source.slice(0, candidate.start) + value + source.slice(candidate.end);
1810
+ }
1811
+ // An outer labeled call owns any nested labeled calls in its arguments.
1812
+ // lowerArguments recursively lowers those isolated expressions, so only
1813
+ // the maximal candidates become edits and no overlapping slices are kept.
1814
+ const maximal = [];
1815
+ const active = [];
1816
+ for (const candidate of candidates) {
1817
+ while (active.length > 0 && candidate.start >= active.at(-1).end)
1818
+ active.pop();
1819
+ if (active.length === 0)
1820
+ maximal.push(candidate);
1821
+ active.push(candidate);
1822
+ }
1823
+ const edits = maximal
1824
+ .map(candidate => ({
1825
+ start: candidate.start,
1826
+ end: candidate.end,
1827
+ value: `${candidate.callee}(${lowerArguments(source.slice(candidate.open + 1, candidate.close), candidate.callee.split(".").at(-1), registry)})`,
1828
+ }))
1829
+ .sort((left, right) => right.start - left.start);
1830
+ let output = source;
1831
+ for (const edit of edits)
1832
+ output = output.slice(0, edit.start) + edit.value + output.slice(edit.end);
1833
+ return output;
1834
+ }
1835
+ /**
1836
+ * SwiftUI modifiers use argument labels even though their JavaScript runtime
1837
+ * implementation ultimately receives positional values or an option record.
1838
+ * Lower those labels before the source reaches TypeScript so authoring syntax
1839
+ * can stay SwiftUI-shaped without teaching TypeScript a second call grammar.
1840
+ */
1841
+ function lowerNamedModifierCalls(source) {
1842
+ let output = source;
1843
+ let iterations = 0;
1844
+ while (true) {
1845
+ if (++iterations > output.length + 1)
1846
+ throw syntaxError("Mun modifier argument lowering did not advance", 0);
1847
+ let candidate;
1848
+ for (let cursor = 0; cursor < output.length; cursor += 1) {
1849
+ const character = output[cursor];
1850
+ if (character === "\"" || character === "'" || character === "`") {
1851
+ cursor = skipString(output, cursor) - 1;
1852
+ continue;
1853
+ }
1854
+ // Raw HTML may contain closing tags (`</span>`). Treat the complete tag
1855
+ // as an opaque token before the generic slash/regex scanner sees the
1856
+ // closing slash as a regular-expression opener.
1857
+ if (character === "<") {
1858
+ const html = rawHtmlAt(output, cursor);
1859
+ if (html) {
1860
+ cursor = html.end - 1;
1861
+ continue;
1862
+ }
1863
+ }
1864
+ if (character === "/" && (output[cursor + 1] === "/" || output[cursor + 1] === "*")) {
1865
+ cursor = skipComment(output, cursor) - 1;
1866
+ continue;
1867
+ }
1868
+ if (character === "/" && regexCanStart(output, cursor)) {
1869
+ cursor = skipRegex(output, cursor) - 1;
1870
+ continue;
1871
+ }
1872
+ if (character !== ".")
1873
+ continue;
1874
+ const identifier = identifierAt(output, cursor + 1);
1875
+ if (!identifier || !staticModifierNames.has(identifier.name))
1876
+ continue;
1877
+ const open = skipTrivia(output, identifier.end);
1878
+ if (output[open] !== "(")
1879
+ continue;
1880
+ const close = matching(output, open, "(", ")");
1881
+ const argumentsSource = output.slice(open + 1, close);
1882
+ const contentTransitionShorthand = identifier.name === "contentTransition" && /^\s*\./.test(argumentsSource);
1883
+ const swiftClosure = splitTopLevel(argumentsSource).some(argument => /^\s*\{\s*[A-Za-z_$][A-Za-z0-9_$]*\s+in\b/.test(argument));
1884
+ if ((!swiftUIModifierLowering(identifier.name) && !swiftClosure)
1885
+ || (!swiftClosure && !contentTransitionShorthand && !splitTopLevel(argumentsSource).some(argument => topLevelColon(argument) >= 0))) {
1886
+ cursor = close;
1887
+ continue;
1888
+ }
1889
+ candidate = { name: identifier.name, open, close };
1890
+ cursor = close;
1891
+ }
1892
+ if (!candidate)
1893
+ return output;
1894
+ const lowering = swiftUIModifierLowering(candidate.name);
1895
+ const entries = splitTopLevel(output.slice(candidate.open + 1, candidate.close)).map(source => {
1896
+ const colon = topLevelColon(source);
1897
+ const label = colon < 0 ? undefined : source.slice(skipTrivia(source, 0), colon).trim();
1898
+ const validLabel = label && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(label) ? label : undefined;
1899
+ return {
1900
+ label: validLabel,
1901
+ value: (validLabel ? source.slice(colon + 1) : source).trim(),
1902
+ };
1903
+ });
1904
+ const lowerCallback = (value, parameterized) => {
1905
+ const source = value.trim();
1906
+ if (!source.startsWith("{") || matching(source, 0, "{", "}") !== source.length - 1) {
1907
+ return lowerImplicitMemberShorthand(lowerShorthand(source));
1908
+ }
1909
+ const body = source.slice(1, -1).trim();
1910
+ if (parameterized) {
1911
+ const match = /^([A-Za-z_$][A-Za-z0-9_$]*)\s+in\s+([\s\S]*)$/.exec(body);
1912
+ if (match)
1913
+ return `(${match[1]}) => {${lowerRange(match[2])}}`;
1914
+ }
1915
+ return `() => {${lowerRange(body)}}`;
1916
+ };
1917
+ const lowerModifierValue = (value, label) => {
1918
+ if (/^\s*\{\s*[A-Za-z_$][A-Za-z0-9_$]*\s+in\b/.test(value))
1919
+ return lowerCallback(value, true);
1920
+ if (candidate.name === "contentTransition")
1921
+ return lowerContentTransitionArgument(value);
1922
+ if (candidate.name === "onTapGesture" && label === "perform")
1923
+ return lowerCallback(value, false);
1924
+ if (candidate.name === "onLongPressGesture" && label === "perform")
1925
+ return lowerCallback(value, false);
1926
+ if (candidate.name === "onLongPressGesture" && label === "onPressingChanged")
1927
+ return lowerCallback(value, true);
1928
+ if (candidate.name === "onHover" && label === "perform")
1929
+ return lowerCallback(value, true);
1930
+ return lowerImplicitMemberShorthand(lowerShorthand(value));
1931
+ };
1932
+ const positional = entries.filter(entry => !entry.label).map(entry => lowerModifierValue(entry.value));
1933
+ const named = new Map();
1934
+ for (const entry of entries) {
1935
+ if (!entry.label)
1936
+ continue;
1937
+ if (named.has(entry.label))
1938
+ throw syntaxError(`Duplicate labeled argument ${entry.label}: in .${candidate.name}(...)`, candidate.open);
1939
+ named.set(entry.label, lowerModifierValue(entry.value, entry.label));
1940
+ }
1941
+ let lowered;
1942
+ if (!lowering || named.size === 0) {
1943
+ lowered = positional.join(", ");
1944
+ }
1945
+ else if (lowering.kind === "object") {
1946
+ if (positional.length > 0)
1947
+ throw syntaxError(`.${candidate.name}(...) does not mix positional and labeled arguments in this overload`, candidate.open);
1948
+ for (const label of named.keys())
1949
+ if (!lowering.labels.includes(label))
1950
+ throw syntaxError(`Unknown labeled argument ${label}: in .${candidate.name}(...)`, candidate.open);
1951
+ lowered = `{ ${lowering.labels.flatMap(label => named.has(label) ? [`${label}: ${named.get(label)}`] : []).join(", ")} }`;
1952
+ }
1953
+ else if (lowering.kind === "ordered") {
1954
+ for (const label of named.keys())
1955
+ if (!lowering.labels.includes(label))
1956
+ throw syntaxError(`Unknown labeled argument ${label}: in .${candidate.name}(...)`, candidate.open);
1957
+ lowered = [...positional, ...lowering.labels.flatMap(label => named.has(label) ? [named.get(label)] : [])].join(", ");
1958
+ }
1959
+ else if (lowering.kind === "slots") {
1960
+ const allowed = new Set(lowering.labels.filter((label) => label !== null));
1961
+ for (const label of named.keys())
1962
+ if (!allowed.has(label))
1963
+ throw syntaxError(`Unknown labeled argument ${label}: in .${candidate.name}(...)`, candidate.open);
1964
+ // Fill explicitly: sparse Array holes are skipped by .map(), which used
1965
+ // to serialize omitted leading Swift defaults as `.shadow(, 8)` instead
1966
+ // of the intentional `.shadow(undefined, 8)` runtime call.
1967
+ const slots = new Array(lowering.labels.length).fill(undefined);
1968
+ let positionalIndex = 0;
1969
+ for (let index = 0; index < lowering.labels.length; index += 1) {
1970
+ const label = lowering.labels[index];
1971
+ if (label !== null && named.has(label))
1972
+ slots[index] = named.get(label);
1973
+ else if (label === null && positionalIndex < positional.length)
1974
+ slots[index] = positional[positionalIndex++];
1975
+ }
1976
+ if (positionalIndex < positional.length)
1977
+ throw syntaxError(`Too many positional arguments in .${candidate.name}(...)`, candidate.open);
1978
+ let last = slots.length - 1;
1979
+ while (last >= 0 && slots[last] === undefined)
1980
+ last -= 1;
1981
+ lowered = Array.from({ length: last + 1 }, (_value, index) => slots[index] ?? "undefined").join(", ");
1982
+ }
1983
+ else {
1984
+ const allowed = new Set([...lowering.objectLabels, ...lowering.orderedLabels]);
1985
+ for (const label of named.keys())
1986
+ if (!allowed.has(label))
1987
+ throw syntaxError(`Unknown labeled argument ${label}: in .${candidate.name}(...)`, candidate.open);
1988
+ const objectEntries = lowering.objectLabels.flatMap(label => named.has(label) ? [`${label}: ${named.get(label)}`] : []);
1989
+ if (objectEntries.length > 0 && positional.length > 0)
1990
+ throw syntaxError(`.${candidate.name}(...) cannot mix its x/y labeled overload with a positional scale`, candidate.open);
1991
+ lowered = [
1992
+ ...(objectEntries.length > 0 ? [`{ ${objectEntries.join(", ")} }`] : positional),
1993
+ ...lowering.orderedLabels.flatMap(label => named.has(label) ? [named.get(label)] : []),
1994
+ ].join(", ");
1995
+ }
1996
+ output = output.slice(0, candidate.open + 1) + lowered + output.slice(candidate.close);
1997
+ }
1998
+ }
1999
+ function initializerRegistryFor(declarations) {
2000
+ const registry = new Map(canonicalInitializerSymbols);
2001
+ const add = (declaration) => {
2002
+ registry.set(declaration.name, structInitializerPlans(declaration).map((plan, index) => semanticInitializerSymbol(declaration.name, plan, index)));
2003
+ for (const nested of declaration.nested ?? [])
2004
+ add(nested);
2005
+ };
2006
+ for (const declaration of declarations)
2007
+ add(declaration);
2008
+ return registry;
2009
+ }
2010
+ function lowerVueComponentImports(source) {
2011
+ if (!/\.vue["']/.test(source))
2012
+ return source;
2013
+ const file = ts.createSourceFile("mun-vue-imports.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
2014
+ const existingNames = new Set();
2015
+ const collectNames = (node) => {
2016
+ if (ts.isIdentifier(node))
2017
+ existingNames.add(node.text);
2018
+ ts.forEachChild(node, collectNames);
2019
+ };
2020
+ collectNames(file);
2021
+ const replacements = [];
2022
+ let index = 0;
2023
+ for (const statement of file.statements) {
2024
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
2025
+ continue;
2026
+ if (!/\.vue$/i.test(statement.moduleSpecifier.text) || statement.importClause?.isTypeOnly)
2027
+ continue;
2028
+ const importedName = statement.importClause?.name?.text
2029
+ ?? (statement.importClause?.namedBindings && ts.isNamedImports(statement.importClause.namedBindings)
2030
+ ? statement.importClause.namedBindings.elements.find(element => element.propertyName?.text === "default")?.name.text
2031
+ : undefined);
2032
+ if (!importedName)
2033
+ continue;
2034
+ let adapterName = `__munForeignComponent${index++}`;
2035
+ while (existingNames.has(adapterName))
2036
+ adapterName = `__munForeignComponent${index++}`;
2037
+ existingNames.add(adapterName);
2038
+ const quote = source[statement.moduleSpecifier.getStart(file)];
2039
+ const module = statement.moduleSpecifier.text;
2040
+ const lineStart = source.lastIndexOf("\n", statement.getStart(file) - 1) + 1;
2041
+ const indent = source.slice(lineStart, statement.getStart(file)).match(/^[ \t]*/)?.[0] ?? "";
2042
+ replacements.push({
2043
+ start: statement.getStart(file),
2044
+ end: statement.end,
2045
+ value: `${indent}import ${adapterName} from ${quote}${module}${quote}\n${indent}const ${importedName} = __munForeignComponent(${adapterName})`,
2046
+ });
2047
+ }
2048
+ if (replacements.length === 0)
2049
+ return source;
2050
+ let result = source;
2051
+ for (const replacement of replacements.reverse())
2052
+ result = result.slice(0, replacement.start) + replacement.value + result.slice(replacement.end);
2053
+ return `import { foreignComponent as __munForeignComponent } from "@mun-ui/vue"\n${result}`;
2054
+ }
2055
+ function lowerReactComponentImports(source) {
2056
+ if (!/\.(?:tsx|jsx)["']/.test(source))
2057
+ return source;
2058
+ const file = ts.createSourceFile("mun-react-imports.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
2059
+ const existingNames = new Set();
2060
+ const collectNames = (node) => {
2061
+ if (ts.isIdentifier(node))
2062
+ existingNames.add(node.text);
2063
+ ts.forEachChild(node, collectNames);
2064
+ };
2065
+ collectNames(file);
2066
+ const replacements = [];
2067
+ let index = 0;
2068
+ for (const statement of file.statements) {
2069
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
2070
+ continue;
2071
+ if (!/\.(?:tsx|jsx)$/i.test(statement.moduleSpecifier.text) || statement.importClause?.isTypeOnly)
2072
+ continue;
2073
+ const importedName = statement.importClause?.name?.text;
2074
+ if (!importedName)
2075
+ continue;
2076
+ let adapterName = `__munReactComponent${index++}`;
2077
+ while (existingNames.has(adapterName))
2078
+ adapterName = `__munReactComponent${index++}`;
2079
+ existingNames.add(adapterName);
2080
+ const quote = source[statement.moduleSpecifier.getStart(file)];
2081
+ const module = statement.moduleSpecifier.text;
2082
+ const lineStart = source.lastIndexOf("\n", statement.getStart(file) - 1) + 1;
2083
+ const indent = source.slice(lineStart, statement.getStart(file)).match(/^[ \t]*/)?.[0] ?? "";
2084
+ replacements.push({
2085
+ start: statement.getStart(file),
2086
+ end: statement.end,
2087
+ value: `${indent}import ${adapterName} from ${quote}${module}${quote}\n${indent}const ${importedName} = __munReactComponent(${adapterName})`,
2088
+ });
2089
+ }
2090
+ if (replacements.length === 0)
2091
+ return source;
2092
+ let result = source;
2093
+ for (const replacement of replacements.reverse())
2094
+ result = result.slice(0, replacement.start) + replacement.value + result.slice(replacement.end);
2095
+ return `import { reactComponent as __munReactComponent } from "@mun-ui/react"\n${result}`;
2096
+ }
2097
+ export function transformMunSource(source, fileName = "mun-source.ts", options = {}) {
2098
+ if (/\.mun$/i.test(fileName)) {
2099
+ const originalDeclarations = parseMunStructs(source);
2100
+ validateWebBindings(originalDeclarations, initializerRegistryFor(originalDeclarations));
2101
+ }
2102
+ const withVueImports = lowerVueComponentImports(lowerSwiftKeyPaths(lowerObservableClasses(source)));
2103
+ const withForeignImports = lowerReactComponentImports(withVueImports);
2104
+ const withAnimationArguments = lowerNamedAnimationFactoryCalls(withForeignImports);
2105
+ const withModifierArguments = lowerNamedModifierCalls(withAnimationArguments);
2106
+ const declarations = parseMunStructs(withModifierArguments);
2107
+ const registry = initializerRegistryFor(declarations);
2108
+ // Button validation and struct dependency proof both need the same pre-lowered
2109
+ // TypeScript syntax snapshot. Build it at most once and share it rather than
2110
+ // reparsing the module independently in two compiler stages.
2111
+ const needsValidationSyntax = declarations.length > 0 || /\bButton\s*\(/.test(withModifierArguments);
2112
+ const validationSyntax = needsValidationSyntax ? validationSourceFile(withModifierArguments) : undefined;
2113
+ validateKnownCalls(parseMunBuilder(withModifierArguments), registry);
2114
+ validateKnownTypeScriptCalls(withModifierArguments, registry, validationSyntax);
2115
+ for (const declaration of declarations) {
2116
+ validateKnownCalls(parseMunBuilder(declaration.bodyExpressionSource, declaration.bodyExpressionRange.start), registry);
2117
+ }
2118
+ const structStateProof = declarations.length > 0 && validationSyntax
2119
+ ? importedMunValueBindings(validationSyntax)
2120
+ : undefined;
2121
+ const withStructs = lowerStructs(withModifierArguments, registry, structStateProof);
2122
+ const withNamedArguments = lowerNamedMunCalls(withStructs, registry);
2123
+ const withBuilderSyntax = lowerRange(withNamedArguments, registry);
2124
+ // State ownership is resolved only after Mun-only syntax has become valid
2125
+ // TypeScript. This lets the TypeScript AST see complete view() arguments
2126
+ // instead of truncating them at trailing builder blocks.
2127
+ const lowered = lowerTopLevelState(withBuilderSyntax);
2128
+ // Capture common authored collection rows before any later specialization
2129
+ // turns Text/Element calls into more opaque compiled templates. A second
2130
+ // collection pass below still picks up shapes exposed by constant folding
2131
+ // or static struct specialization.
2132
+ const withStateArrayMaps = lowerStateArrayMaps(lowered);
2133
+ const withAuthoredCollections = lowerCompiledCollections(withStateArrayMaps);
2134
+ const withStaticResults = foldStaticResults(withAuthoredCollections);
2135
+ const withStaticStructCalls = lowerStaticStructCalls(withStaticResults, declarations);
2136
+ // Collection planning must see authored Text/Element rows before general
2137
+ // semantic specialization lowers those calls into templates. Otherwise
2138
+ // making a core View canonical can accidentally disable the faster keyed
2139
+ // flat-row plan. The fallback closure may still be specialized afterwards.
2140
+ const withCompiledCollections = lowerCompiledCollections(withStaticStructCalls);
2141
+ const withCanonicalCalls = lowerStaticCanonicalCalls(withCompiledCollections);
2142
+ const withSemanticSpecializations = lowerStaticSemanticSpecializations(withCanonicalCalls, fileName);
2143
+ const withCompiledTemplates = lowerCompiledViewTemplates(withSemanticSpecializations);
2144
+ // Hoisting only needs the imports authored/retained by the source. Injecting
2145
+ // compiler helper imports first makes the final static pass parse a larger
2146
+ // module and can only add irrelevant bindings to its candidate set.
2147
+ const withStaticHoists = hoistStaticViewSubtrees(withCompiledTemplates);
2148
+ const output = /\.mun$/i.test(fileName) ? importMunBuiltins(source, withStaticHoists, fileName, options.externalScope === true) : ensureImports(withStaticHoists);
2149
+ if (/\.mun$/i.test(fileName))
2150
+ validateWebLowering(source, output, fileName);
2151
+ return output;
2152
+ }
2153
+ function hasNamedMunArguments(source) {
2154
+ const calls = /\b[A-Z][A-Za-z0-9_$]*\s*\(/g;
2155
+ let match;
2156
+ while ((match = calls.exec(source))) {
2157
+ const open = source.indexOf("(", match.index);
2158
+ const close = matching(source, open, "(", ")");
2159
+ if (previousWord(source, match.index) === "function") {
2160
+ calls.lastIndex = close + 1;
2161
+ continue;
2162
+ }
2163
+ if (splitTopLevel(source.slice(open + 1, close)).some(argument => topLevelColon(argument) >= 0))
2164
+ return true;
2165
+ calls.lastIndex = close + 1;
2166
+ }
2167
+ return false;
2168
+ }
2169
+ function hasBindingShorthand(source) {
2170
+ return lowerShorthand(source) !== source;
2171
+ }
2172
+ function hasStaticModifierSyntax(source) {
2173
+ return Array.from(staticModifierNames).some(name => new RegExp(`\\.${name}\\s*\\(`).test(source));
2174
+ }
2175
+ export function hasMunSyntax(source, allowRawHtml = true) {
2176
+ return /\bstruct\s+[A-Z][A-Za-z0-9_$]*(?:\s*<[^>{}]*>)?\s*:\s*View/.test(source)
2177
+ || (allowRawHtml && findRawHtml(source) !== undefined)
2178
+ || findBuilder(source, 0, true) !== undefined
2179
+ || hasBindingShorthand(source)
2180
+ || hasNamedMunArguments(source)
2181
+ || hasStaticModifierSyntax(source);
2182
+ }
2183
+ //# sourceMappingURL=pipeline.js.map