@mmapp/react-compiler 0.1.0-alpha.18 → 0.1.0-alpha.20

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 (199) hide show
  1. package/dist/babel/index.d.mts +1 -1
  2. package/dist/babel/index.d.ts +1 -1
  3. package/dist/babel/index.js +9 -6
  4. package/dist/babel/index.mjs +1 -1
  5. package/dist/chunk-26U577GB.mjs +3465 -0
  6. package/dist/chunk-2FBDFAX6.mjs +2362 -0
  7. package/dist/chunk-2REDFOER.mjs +931 -0
  8. package/dist/{chunk-FPAMQXKB.mjs → chunk-2UTXM2QX.mjs} +10 -20
  9. package/dist/chunk-2YDQTFAL.mjs +879 -0
  10. package/dist/chunk-2ZRKQE74.mjs +175 -0
  11. package/dist/chunk-3QHG2JWV.mjs +154 -0
  12. package/dist/chunk-466OWSTT.mjs +186 -0
  13. package/dist/chunk-467SFYOD.mjs +3127 -0
  14. package/dist/chunk-4AIJO7DZ.mjs +214 -0
  15. package/dist/chunk-4D43TZYL.mjs +7495 -0
  16. package/dist/chunk-4FP5DXY4.mjs +3456 -0
  17. package/dist/chunk-4HX4PI4R.mjs +734 -0
  18. package/dist/chunk-4VU56NTZ.mjs +544 -0
  19. package/dist/chunk-4XHK6FWL.mjs +2058 -0
  20. package/dist/chunk-52C2JKH2.mjs +186 -0
  21. package/dist/chunk-52XHYD2V.mjs +214 -0
  22. package/dist/chunk-5GUFFFGL.mjs +148 -0
  23. package/dist/chunk-5N2FDDS6.mjs +214 -0
  24. package/dist/chunk-5ZSJXWZT.mjs +1646 -0
  25. package/dist/chunk-6CQOAAMV.mjs +1803 -0
  26. package/dist/chunk-6SEVAAVT.mjs +3516 -0
  27. package/dist/chunk-6YLR5ZDA.mjs +2829 -0
  28. package/dist/chunk-77UJB356.mjs +244 -0
  29. package/dist/chunk-7QOAJPQF.mjs +774 -0
  30. package/dist/chunk-A5RCMIBP.mjs +1795 -0
  31. package/dist/chunk-A63R3GKH.mjs +1803 -0
  32. package/dist/chunk-ABNTZXF5.mjs +951 -0
  33. package/dist/chunk-ADHWW56I.mjs +214 -0
  34. package/dist/chunk-AOGY2GK6.mjs +3292 -0
  35. package/dist/chunk-AXXUXRNA.mjs +1434 -0
  36. package/dist/chunk-BZLU5YK5.mjs +1025 -0
  37. package/dist/chunk-C7XCDDBH.mjs +1802 -0
  38. package/dist/chunk-CHLVKMQW.mjs +175 -0
  39. package/dist/chunk-CKGOZAB7.mjs +939 -0
  40. package/dist/chunk-CSXYDIVC.mjs +214 -0
  41. package/dist/chunk-CXTV4VGG.mjs +148 -0
  42. package/dist/chunk-D34RAZUX.mjs +2223 -0
  43. package/dist/chunk-DDIC7WM6.mjs +3127 -0
  44. package/dist/chunk-DPUQOBU6.mjs +4810 -0
  45. package/dist/chunk-E6MDVTGT.mjs +148 -0
  46. package/dist/chunk-EGKMUEM6.mjs +544 -0
  47. package/dist/chunk-EO6SYNCG.mjs +175 -0
  48. package/dist/chunk-EQGA6A6D.mjs +121 -0
  49. package/dist/chunk-EY2CSXYA.mjs +822 -0
  50. package/dist/chunk-EYLOSECJ.mjs +544 -0
  51. package/dist/chunk-FF5BQVII.mjs +148 -0
  52. package/dist/chunk-FIQ65CDR.mjs +925 -0
  53. package/dist/chunk-FOZXJFAR.mjs +186 -0
  54. package/dist/chunk-G2IAZ5Q6.mjs +148 -0
  55. package/dist/chunk-G7SMOWOL.mjs +828 -0
  56. package/dist/chunk-GK7NU6DO.mjs +214 -0
  57. package/dist/chunk-HDSCPEHY.mjs +4061 -0
  58. package/dist/chunk-HJELFNEA.mjs +186 -0
  59. package/dist/chunk-HOIUP6IF.mjs +690 -0
  60. package/dist/chunk-HRJGDPNE.mjs +148 -0
  61. package/dist/chunk-I3AU7GRD.mjs +120 -0
  62. package/dist/chunk-I3VQQJZ6.mjs +2843 -0
  63. package/dist/chunk-I6SSPILI.mjs +550 -0
  64. package/dist/chunk-IPTX5MJU.mjs +3223 -0
  65. package/dist/chunk-ITGUSH2Z.mjs +2783 -0
  66. package/dist/chunk-IXHBCAMF.mjs +3306 -0
  67. package/dist/chunk-J7JUAHS4.mjs +186 -0
  68. package/dist/chunk-J7TWJ3TM.mjs +2784 -0
  69. package/dist/chunk-JDPLDGVF.mjs +4810 -0
  70. package/dist/chunk-JK72MQ4N.mjs +877 -0
  71. package/dist/chunk-K2HHCAS2.mjs +148 -0
  72. package/dist/chunk-K5HX2SVL.mjs +1902 -0
  73. package/dist/chunk-KAUEQ2F3.mjs +148 -0
  74. package/dist/chunk-KFVVOS5N.mjs +925 -0
  75. package/dist/chunk-KIH4AN3Y.mjs +154 -0
  76. package/dist/chunk-KPDMN5IX.mjs +175 -0
  77. package/dist/chunk-LZL2IRCH.mjs +186 -0
  78. package/dist/chunk-MIZV3TAN.mjs +3293 -0
  79. package/dist/chunk-MRH4J7IX.mjs +2846 -0
  80. package/dist/chunk-NKBL5GUC.mjs +186 -0
  81. package/dist/chunk-NQCNSCF6.mjs +148 -0
  82. package/dist/chunk-NRP5J3BR.mjs +4811 -0
  83. package/dist/chunk-NTB7OEX2.mjs +2918 -0
  84. package/dist/chunk-NUPJYPFU.mjs +801 -0
  85. package/dist/chunk-NVQUTSQX.mjs +3128 -0
  86. package/dist/chunk-OGMG64EY.mjs +148 -0
  87. package/dist/chunk-OL5B2HTH.mjs +175 -0
  88. package/dist/chunk-OPJKP747.mjs +7506 -0
  89. package/dist/chunk-OQLGGBNE.mjs +2918 -0
  90. package/dist/chunk-OW4AQUDL.mjs +544 -0
  91. package/dist/chunk-OWI6XWCD.mjs +3375 -0
  92. package/dist/chunk-OZT2EAF2.mjs +2776 -0
  93. package/dist/chunk-PBRBRKIQ.mjs +175 -0
  94. package/dist/chunk-PRUMNNDI.mjs +3192 -0
  95. package/dist/chunk-QPNHDTSM.mjs +4839 -0
  96. package/dist/chunk-RNEIAJDR.mjs +897 -0
  97. package/dist/chunk-RY7POBNT.mjs +3127 -0
  98. package/dist/chunk-S6FJ4DXL.mjs +1813 -0
  99. package/dist/chunk-SU4E6E7B.mjs +3153 -0
  100. package/dist/chunk-SYUUKW5A.mjs +3379 -0
  101. package/dist/chunk-THB5SX2S.mjs +113 -0
  102. package/dist/chunk-THFYE5ZX.mjs +244 -0
  103. package/dist/chunk-TK3QMXIP.mjs +2921 -0
  104. package/dist/chunk-TRR2NPAV.mjs +248 -0
  105. package/dist/chunk-TTTTOT7P.mjs +1803 -0
  106. package/dist/chunk-TXONBY6A.mjs +7509 -0
  107. package/dist/chunk-U2PX3JSY.mjs +1933 -0
  108. package/dist/chunk-U6F7CTHK.mjs +550 -0
  109. package/dist/chunk-UASOWKDI.mjs +186 -0
  110. package/dist/chunk-UDDTWG5J.mjs +734 -0
  111. package/dist/chunk-UIWLAQCL.mjs +175 -0
  112. package/dist/chunk-UL2XZEMA.mjs +3128 -0
  113. package/dist/chunk-US3AVDAI.mjs +3456 -0
  114. package/dist/chunk-V5DIDOTT.mjs +148 -0
  115. package/dist/chunk-VLTKQDJ3.mjs +244 -0
  116. package/dist/chunk-VVC42PTS.mjs +175 -0
  117. package/dist/chunk-VX3T3NIR.mjs +897 -0
  118. package/dist/chunk-WBYMW4NQ.mjs +3450 -0
  119. package/dist/chunk-XMWUHQVV.mjs +939 -0
  120. package/dist/chunk-XUQ5R6F3.mjs +213 -0
  121. package/dist/chunk-Y6FXYEAI.mjs +10 -0
  122. package/dist/chunk-YCWC2SCO.mjs +148 -0
  123. package/dist/chunk-YFS6JMYO.mjs +3342 -0
  124. package/dist/chunk-ZE67HOSN.mjs +148 -0
  125. package/dist/chunk-ZSK5TPIV.mjs +148 -0
  126. package/dist/cli/index.js +329 -653
  127. package/dist/cli/index.mjs +9 -9
  128. package/dist/config-PL24KEWL.mjs +219 -0
  129. package/dist/deploy-VAHWALWB.mjs +9 -0
  130. package/dist/dev-server-Bs_sz2DG.d.mts +111 -0
  131. package/dist/dev-server-Bs_sz2DG.d.ts +111 -0
  132. package/dist/dev-server-RmGHIntF.d.mts +113 -0
  133. package/dist/dev-server-RmGHIntF.d.ts +113 -0
  134. package/dist/dev-server.js +205 -522
  135. package/dist/dev-server.mjs +4 -4
  136. package/dist/engine-binary-KQB23JDR.mjs +97 -0
  137. package/dist/envelope-DD7v0v6E.d.mts +265 -0
  138. package/dist/envelope-DD7v0v6E.d.ts +265 -0
  139. package/dist/envelope.js +9 -6
  140. package/dist/envelope.mjs +2 -2
  141. package/dist/index-B5gSgvnd.d.mts +44 -0
  142. package/dist/index-B5gSgvnd.d.ts +44 -0
  143. package/dist/index-Bs0MnR54.d.mts +103 -0
  144. package/dist/index-Bs0MnR54.d.ts +103 -0
  145. package/dist/index-DR0nNc_f.d.mts +101 -0
  146. package/dist/index-DR0nNc_f.d.ts +101 -0
  147. package/dist/index-revho_gS.d.mts +104 -0
  148. package/dist/index-revho_gS.d.ts +104 -0
  149. package/dist/index-vQjwYekL.d.mts +104 -0
  150. package/dist/index-vQjwYekL.d.ts +104 -0
  151. package/dist/index.d.mts +2 -2
  152. package/dist/index.d.ts +2 -2
  153. package/dist/index.js +210 -525
  154. package/dist/index.mjs +10 -9
  155. package/dist/init-2XLTUF7O.mjs +407 -0
  156. package/dist/init-7FJENUDK.mjs +407 -0
  157. package/dist/init-AVZJHZYY.mjs +538 -0
  158. package/dist/init-DQDX3QK6.mjs +369 -0
  159. package/dist/init-K3GVM4JS.mjs +538 -0
  160. package/dist/init-NXS5BJN3.mjs +454 -0
  161. package/dist/init-UC3FWPIW.mjs +367 -0
  162. package/dist/init-UNV5XIDE.mjs +367 -0
  163. package/dist/project-compiler-2HOPO7GC.mjs +10 -0
  164. package/dist/project-compiler-D245L5QR.mjs +10 -0
  165. package/dist/project-compiler-FUQRMB4X.mjs +10 -0
  166. package/dist/project-compiler-LA5OBI5P.mjs +10 -0
  167. package/dist/project-compiler-OP2VVGJQ.mjs +10 -0
  168. package/dist/project-compiler-PZNFE6AH.mjs +10 -0
  169. package/dist/project-compiler-QBVF6MFI.mjs +10 -0
  170. package/dist/project-compiler-VFR6CSDX.mjs +10 -0
  171. package/dist/project-compiler-WMJZA4UH.mjs +10 -0
  172. package/dist/project-compiler-XXS27TZT.mjs +10 -0
  173. package/dist/project-compiler-YYGDSHY5.mjs +10 -0
  174. package/dist/project-decompiler-5GY2KSG4.mjs +7 -0
  175. package/dist/project-decompiler-7I2OMUVY.mjs +7 -0
  176. package/dist/project-decompiler-QCZYY4TW.mjs +7 -0
  177. package/dist/project-decompiler-US7GAVIC.mjs +7 -0
  178. package/dist/pull-2Q53HF3H.mjs +107 -0
  179. package/dist/pull-5AFHD3QG.mjs +109 -0
  180. package/dist/pull-5WJ4LW4U.mjs +109 -0
  181. package/dist/pull-65GUSX6F.mjs +109 -0
  182. package/dist/pull-6LVI4LMM.mjs +109 -0
  183. package/dist/pull-A2QUHW4K.mjs +109 -0
  184. package/dist/pull-B6T5BUKV.mjs +109 -0
  185. package/dist/pull-CKHWZT33.mjs +109 -0
  186. package/dist/pull-GM74ERRT.mjs +109 -0
  187. package/dist/pull-JBEQWVPE.mjs +109 -0
  188. package/dist/pull-P44LDRWB.mjs +109 -0
  189. package/dist/pull-W2US3T3E.mjs +109 -0
  190. package/dist/testing/index.js +9 -6
  191. package/dist/testing/index.mjs +1 -1
  192. package/dist/verify-3PPS4XAM.mjs +1833 -0
  193. package/dist/verify-GKEH5FZQ.mjs +1833 -0
  194. package/dist/verify-HDKUNHZ4.mjs +1833 -0
  195. package/dist/verify-SEIXUGN4.mjs +1833 -0
  196. package/dist/vite/index.js +10 -7
  197. package/dist/vite/index.mjs +2 -2
  198. package/mm-dev.db +0 -0
  199. package/package.json +2 -2
@@ -0,0 +1,1646 @@
1
+ import {
2
+ babelPlugin
3
+ } from "./chunk-HDSCPEHY.mjs";
4
+
5
+ // src/project-compiler.ts
6
+ import { transformSync as transformSync3 } from "@babel/core";
7
+
8
+ // src/babel/extractors/router-extractor.ts
9
+ function pathToStateName(routePath) {
10
+ if (!routePath || routePath === "" || routePath === "/") return "HOME";
11
+ return routePath.split("/").filter(Boolean).map((segment) => {
12
+ if (segment.startsWith("[") && segment.endsWith("]")) {
13
+ return segment.slice(1, -1);
14
+ }
15
+ return segment;
16
+ }).join("_").replace(/([a-z])([A-Z])/g, "$1_$2").toUpperCase().replace(/-/g, "_");
17
+ }
18
+ function pathToUrlPattern(relativePath, pageFileName = "page.tsx") {
19
+ let routePath = relativePath.replace(new RegExp(`/?${pageFileName.replace(".", "\\.")}$`), "");
20
+ routePath = routePath.replace(/\[([^\]]+)\]/g, ":$1");
21
+ return "/" + routePath;
22
+ }
23
+ function extractParams(relativePath) {
24
+ const params = [];
25
+ const paramRegex = /\[([^\]]+)\]/g;
26
+ let match;
27
+ while ((match = paramRegex.exec(relativePath)) !== null) {
28
+ params.push(match[1]);
29
+ }
30
+ return params;
31
+ }
32
+ function extractRouterWorkflow(pages, options = {}) {
33
+ const {
34
+ slug = "app-router",
35
+ pageFileName = "page.tsx",
36
+ layoutFileName = "layout.tsx"
37
+ } = options;
38
+ const pageFiles = pages.filter((p) => !p.isLayout && p.relativePath.endsWith(pageFileName));
39
+ const layoutFiles = pages.filter((p) => p.isLayout || p.relativePath.endsWith(layoutFileName));
40
+ const routeStates = [];
41
+ const stateMap = /* @__PURE__ */ new Map();
42
+ for (const page of pageFiles) {
43
+ const routePath = page.relativePath.replace(new RegExp(`/?${pageFileName.replace(".", "\\.")}$`), "");
44
+ const stateName = pathToStateName(routePath);
45
+ const urlPattern = pathToUrlPattern(page.relativePath, pageFileName);
46
+ const params = extractParams(page.relativePath);
47
+ const layoutBoundary = findLayoutBoundary(page.relativePath, layoutFiles);
48
+ const routeState = {
49
+ name: stateName,
50
+ path: urlPattern,
51
+ params,
52
+ layoutBoundary,
53
+ sourceFile: page.relativePath,
54
+ type: stateName === "HOME" ? "START" : "REGULAR"
55
+ };
56
+ routeStates.push(routeState);
57
+ stateMap.set(stateName, routeState);
58
+ }
59
+ if (!stateMap.has("HOME") && routeStates.length > 0) {
60
+ routeStates[0].type = "START";
61
+ }
62
+ const states = routeStates.map((rs) => ({
63
+ name: rs.name,
64
+ type: rs.type,
65
+ description: `Route: ${rs.path}`,
66
+ on_enter: [],
67
+ during: [],
68
+ on_exit: []
69
+ }));
70
+ const transitions = [];
71
+ let transitionId = 0;
72
+ for (const page of pageFiles) {
73
+ if (!page.navigationTargets) continue;
74
+ const fromPath = page.relativePath.replace(new RegExp(`/?${pageFileName.replace(".", "\\.")}$`), "");
75
+ const fromState = pathToStateName(fromPath);
76
+ for (const target of page.navigationTargets) {
77
+ const targetPath = target.replace(/^\//, "").replace(/\/page\.(tsx|ts|jsx|js)$/, "");
78
+ const toState = pathToStateName(targetPath);
79
+ if (stateMap.has(toState) || toState === fromState) continue;
80
+ const transitionName = `navigate_to_${toState.toLowerCase()}`;
81
+ transitions.push({
82
+ name: transitionName,
83
+ from: [fromState],
84
+ to: toState,
85
+ actions: [],
86
+ conditions: []
87
+ });
88
+ transitionId++;
89
+ }
90
+ }
91
+ if (routeStates.length > 1) {
92
+ for (const rs of routeStates) {
93
+ if (rs.type !== "START") {
94
+ transitions.push({
95
+ name: `navigate_home_from_${rs.name.toLowerCase()}`,
96
+ from: [rs.name],
97
+ to: "HOME",
98
+ actions: [],
99
+ conditions: []
100
+ });
101
+ }
102
+ }
103
+ }
104
+ const fields = [];
105
+ const seenParams = /* @__PURE__ */ new Set();
106
+ for (const rs of routeStates) {
107
+ for (const param of rs.params) {
108
+ if (seenParams.has(param)) continue;
109
+ seenParams.add(param);
110
+ fields.push({
111
+ name: param,
112
+ type: "text",
113
+ required: false,
114
+ default_value: ""
115
+ });
116
+ }
117
+ }
118
+ const routeMetadata = routeStates.map((rs) => ({
119
+ state: rs.name,
120
+ path: rs.path,
121
+ params: rs.params,
122
+ layoutBoundary: rs.layoutBoundary,
123
+ sourceFile: rs.sourceFile
124
+ }));
125
+ return {
126
+ slug,
127
+ name: "Router",
128
+ version: "1.0.0",
129
+ description: "Auto-derived router workflow from file-based routing",
130
+ category: "router",
131
+ fields,
132
+ states,
133
+ transitions,
134
+ roles: [],
135
+ tags: [{ tag_name: "auto-derived" }, { tag_name: "router" }],
136
+ metadata: {
137
+ runtime: "local",
138
+ routes: routeMetadata,
139
+ layoutBoundaries: layoutFiles.map((l) => l.relativePath)
140
+ }
141
+ };
142
+ }
143
+ function findLayoutBoundary(pageRelativePath, layoutFiles) {
144
+ const layoutPaths = layoutFiles.map((l) => l.relativePath);
145
+ const parts = pageRelativePath.split("/");
146
+ for (let i = parts.length - 1; i >= 0; i--) {
147
+ const dir = parts.slice(0, i).join("/");
148
+ const layoutPath = dir ? `${dir}/layout.tsx` : "layout.tsx";
149
+ if (layoutPaths.includes(layoutPath)) {
150
+ return layoutPath;
151
+ }
152
+ }
153
+ return void 0;
154
+ }
155
+
156
+ // src/model-compiler.ts
157
+ import { transformSync } from "@babel/core";
158
+ function extractInterfaceName(source) {
159
+ const match = source.match(/export\s+interface\s+(\w+)/);
160
+ return match ? match[1] : "Unknown";
161
+ }
162
+ function extractWorkflowAnnotation(source) {
163
+ const result = {};
164
+ const workflowMatch = source.match(/@workflow\s+(.+)/);
165
+ if (workflowMatch) {
166
+ const attrs = workflowMatch[1];
167
+ const slugM = attrs.match(/slug="([^"]+)"/);
168
+ if (slugM) result.slug = slugM[1];
169
+ const versionM = attrs.match(/version="([^"]+)"/);
170
+ if (versionM) result.version = versionM[1];
171
+ const categoryM = attrs.match(/category="([^"]+)"/);
172
+ if (categoryM) result.category = categoryM[1];
173
+ }
174
+ const descMatch = source.match(/@description\s+(.+)/);
175
+ if (descMatch) result.description = descMatch[1].trim();
176
+ return result;
177
+ }
178
+ function extractFieldOptionsRaw(source) {
179
+ const result = {};
180
+ const match = source.match(/export\s+const\s+fieldOptions\s*=\s*\{([\s\S]*?)\};/);
181
+ if (!match) return result;
182
+ const body = match[1];
183
+ const fieldRegex = /(\w+)\s*:\s*\{([^}]*)\}/g;
184
+ let fieldMatch;
185
+ while ((fieldMatch = fieldRegex.exec(body)) !== null) {
186
+ const fieldName = fieldMatch[1];
187
+ const optionsBody = fieldMatch[2];
188
+ const opts = {};
189
+ const kvRegex = /(\w+)\s*:\s*(?:'([^']*)'|"([^"]*)"|\[([^\]]*)\]|(\d+(?:\.\d+)?)|(\w+))/g;
190
+ let kvMatch;
191
+ while ((kvMatch = kvRegex.exec(optionsBody)) !== null) {
192
+ const key = kvMatch[1];
193
+ const strVal = kvMatch[2] ?? kvMatch[3];
194
+ const arrVal = kvMatch[4];
195
+ const numVal = kvMatch[5];
196
+ const identVal = kvMatch[6];
197
+ if (strVal !== void 0) {
198
+ opts[key] = strVal;
199
+ } else if (arrVal !== void 0) {
200
+ opts[key] = arrVal.split(",").map((s) => s.trim().replace(/['"]/g, "")).filter(Boolean);
201
+ } else if (numVal !== void 0) {
202
+ opts[key] = Number(numVal);
203
+ } else if (identVal !== void 0) {
204
+ if (identVal === "true") opts[key] = true;
205
+ else if (identVal === "false") opts[key] = false;
206
+ else opts[key] = identVal;
207
+ }
208
+ }
209
+ result[fieldName] = opts;
210
+ }
211
+ return result;
212
+ }
213
+ function compileModel(filename, source, options = {}) {
214
+ const mode = options.mode || "infer";
215
+ const interfaceName = extractInterfaceName(source);
216
+ const annotation = extractWorkflowAnnotation(source);
217
+ const rawFieldOptions = extractFieldOptionsRaw(source);
218
+ const parserPlugins = filename.endsWith(".tsx") ? ["typescript", "jsx"] : ["typescript"];
219
+ const babelResult = transformSync(source, {
220
+ filename,
221
+ plugins: [[babelPlugin, { mode }]],
222
+ parserOpts: { plugins: parserPlugins, attachComment: true }
223
+ });
224
+ const ir = babelResult?.metadata?.mindmatrixIR ?? createEmptyModelIR(interfaceName);
225
+ ir.category = options.categoryOverride || annotation.category || "data";
226
+ if (options.slugOverride) {
227
+ ir.slug = options.slugOverride;
228
+ }
229
+ if (ir.states.length === 0) {
230
+ ir.states.push({
231
+ name: "draft",
232
+ type: "START",
233
+ on_enter: [],
234
+ during: [],
235
+ on_exit: []
236
+ });
237
+ }
238
+ const hasStart = ir.states.some((s) => s.type === "START");
239
+ if (!hasStart && ir.states.length > 0) {
240
+ ir.states[0].type = "START";
241
+ }
242
+ if (!ir.metadata) ir.metadata = {};
243
+ const meta = ir.metadata;
244
+ meta.sourceInterface = interfaceName;
245
+ meta.fieldOptions = rawFieldOptions;
246
+ meta.provenance = {
247
+ frontend: "react-compiler",
248
+ source: "model",
249
+ compiler_version: "2.0.0"
250
+ };
251
+ return {
252
+ ir,
253
+ interfaceName,
254
+ fieldNames: ir.fields.map((f) => f.name),
255
+ transitionNames: ir.transitions.map((t) => t.name),
256
+ stateNames: ir.states.map((s) => s.name),
257
+ hasFieldOptions: Object.keys(rawFieldOptions).length > 0,
258
+ fieldOptions: rawFieldOptions
259
+ };
260
+ }
261
+ function compileModels(files, options = {}) {
262
+ const results = /* @__PURE__ */ new Map();
263
+ for (const [filename, source] of Object.entries(files)) {
264
+ try {
265
+ const compiled = compileModel(filename, source, options);
266
+ results.set(filename, compiled);
267
+ } catch (_err) {
268
+ const iface = extractInterfaceName(source);
269
+ results.set(filename, {
270
+ ir: createEmptyModelIR(iface),
271
+ interfaceName: iface,
272
+ fieldNames: [],
273
+ transitionNames: [],
274
+ stateNames: ["draft"],
275
+ hasFieldOptions: false,
276
+ fieldOptions: {}
277
+ });
278
+ }
279
+ }
280
+ return results;
281
+ }
282
+ function createEmptyModelIR(interfaceName) {
283
+ const slug = interfaceName.replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
284
+ return {
285
+ slug,
286
+ name: interfaceName,
287
+ version: "1.0.0",
288
+ description: "Data model: " + interfaceName,
289
+ category: "data",
290
+ fields: [],
291
+ states: [{
292
+ name: "draft",
293
+ type: "START",
294
+ on_enter: [],
295
+ during: [],
296
+ on_exit: []
297
+ }],
298
+ transitions: [],
299
+ roles: [],
300
+ tags: [{ tag_name: "data" }, { tag_name: "model" }],
301
+ metadata: {
302
+ sourceInterface: interfaceName,
303
+ provenance: {
304
+ frontend: "react-compiler",
305
+ source: "model",
306
+ compiler_version: "2.0.0"
307
+ }
308
+ }
309
+ };
310
+ }
311
+
312
+ // src/route-extractor.ts
313
+ function filePathToUrlPattern(filePath, rootDir) {
314
+ let route = filePath;
315
+ const rootPrefix = rootDir + "/";
316
+ if (route.startsWith(rootPrefix)) {
317
+ route = route.slice(rootPrefix.length);
318
+ }
319
+ route = route.replace(/\.(tsx?|jsx?)$/, "");
320
+ route = route.replace(/\/(page|index)$/, "");
321
+ if (route === "page" || route === "index" || route === "") {
322
+ return "/";
323
+ }
324
+ route = route.replace(/\[([^\]]+)\]/g, ":$1");
325
+ return "/" + route;
326
+ }
327
+ function urlToStateName(urlPath) {
328
+ if (urlPath === "/") return "HOME";
329
+ return urlPath.split("/").filter(Boolean).map((segment) => segment.replace(/^:/, "")).join("_").replace(/([a-z])([A-Z])/g, "$1_$2").replace(/-/g, "_").toUpperCase();
330
+ }
331
+ function extractRouteParams(filePath) {
332
+ const params = [];
333
+ const regex = /\[([^\]]+)\]/g;
334
+ let match;
335
+ while ((match = regex.exec(filePath)) !== null) {
336
+ params.push(match[1]);
337
+ }
338
+ return params;
339
+ }
340
+ function routeDepth(urlPath) {
341
+ if (urlPath === "/") return 0;
342
+ return urlPath.split("/").filter(Boolean).length;
343
+ }
344
+ function isPageFile(filename, pageFileName) {
345
+ if (filename.endsWith("/" + pageFileName)) return true;
346
+ return /\.(tsx|ts|jsx|js)$/.test(filename) && !filename.endsWith(".test.ts") && !filename.endsWith(".test.tsx") && !filename.includes("layout");
347
+ }
348
+ function isLayoutFile(filename, layoutFileName) {
349
+ return filename.endsWith("/" + layoutFileName) || filename.endsWith(layoutFileName);
350
+ }
351
+ function extractRoutes(files, options = {}) {
352
+ const rootDir = options.rootDir || "app";
353
+ const pageFileName = options.pageFileName || "page.tsx";
354
+ const layoutFileName = options.layoutFileName || "layout.tsx";
355
+ const slugPrefix = options.slugPrefix || "app";
356
+ const layouts = [];
357
+ for (const filename of Object.keys(files)) {
358
+ if (isLayoutFile(filename, layoutFileName)) {
359
+ const dir = filename.replace(/\/[^/]+$/, "");
360
+ layouts.push({
361
+ sourceFile: filename,
362
+ directory: dir,
363
+ depth: dir.split("/").filter(Boolean).length
364
+ });
365
+ }
366
+ }
367
+ layouts.sort((a, b) => a.depth - b.depth);
368
+ const routes = [];
369
+ const allParams = /* @__PURE__ */ new Set();
370
+ for (const filename of Object.keys(files)) {
371
+ if (isLayoutFile(filename, layoutFileName)) continue;
372
+ if (!filename.startsWith(rootDir + "/") && !filename.startsWith(rootDir)) continue;
373
+ if (!isPageFile(filename, pageFileName)) continue;
374
+ const urlPath = filePathToUrlPattern(filename, rootDir);
375
+ const stateName = urlToStateName(urlPath);
376
+ const params = extractRouteParams(filename);
377
+ const depth = routeDepth(urlPath);
378
+ const fileDir = filename.replace(/\/[^/]+$/, "");
379
+ let layoutBoundary;
380
+ for (let i = layouts.length - 1; i >= 0; i--) {
381
+ if (fileDir.startsWith(layouts[i].directory)) {
382
+ layoutBoundary = layouts[i].sourceFile;
383
+ break;
384
+ }
385
+ }
386
+ for (const p of params) allParams.add(p);
387
+ routes.push({
388
+ path: urlPath,
389
+ stateName,
390
+ sourceFile: filename,
391
+ params,
392
+ layoutBoundary,
393
+ depth
394
+ });
395
+ }
396
+ routes.sort((a, b) => a.path.localeCompare(b.path));
397
+ const routerIR = buildRouterIR(routes, layouts, Array.from(allParams), slugPrefix);
398
+ return {
399
+ routes,
400
+ layouts,
401
+ routerIR,
402
+ allParams: Array.from(allParams)
403
+ };
404
+ }
405
+ function buildRouterIR(routes, layouts, allParams, slugPrefix) {
406
+ const states = routes.map((route) => ({
407
+ name: route.stateName,
408
+ type: route.path === "/" ? "START" : "REGULAR",
409
+ description: "Route: " + route.path,
410
+ on_enter: [],
411
+ during: [],
412
+ on_exit: []
413
+ }));
414
+ if (states.length > 0 && !states.some((s) => s.type === "START")) {
415
+ states[0].type = "START";
416
+ }
417
+ const transitions = [];
418
+ for (const from of routes) {
419
+ for (const to of routes) {
420
+ if (from.stateName === to.stateName) continue;
421
+ transitions.push({
422
+ name: "nav_" + from.stateName.toLowerCase() + "_to_" + to.stateName.toLowerCase(),
423
+ from: [from.stateName],
424
+ to: to.stateName,
425
+ actions: [],
426
+ conditions: []
427
+ });
428
+ }
429
+ }
430
+ const fields = allParams.map((param) => ({
431
+ name: param,
432
+ type: "text",
433
+ label: param.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase()),
434
+ required: false,
435
+ default_value: ""
436
+ }));
437
+ fields.push({
438
+ name: "current_route",
439
+ type: "text",
440
+ label: "Current Route",
441
+ required: false,
442
+ default_value: "/"
443
+ });
444
+ return {
445
+ slug: slugPrefix + "-router",
446
+ name: "Router",
447
+ version: "1.0.0",
448
+ description: "Auto-generated router from app/ directory structure",
449
+ category: "router",
450
+ fields,
451
+ states,
452
+ transitions,
453
+ roles: [],
454
+ tags: [{ tag_name: "auto-derived" }, { tag_name: "router" }],
455
+ metadata: {
456
+ runtime: "local",
457
+ routes: routes.map((r) => ({
458
+ state: r.stateName,
459
+ path: r.path,
460
+ params: r.params,
461
+ layoutBoundary: r.layoutBoundary,
462
+ sourceFile: r.sourceFile
463
+ })),
464
+ layoutBoundaries: layouts.map((l) => l.sourceFile),
465
+ provenance: {
466
+ frontend: "react-compiler",
467
+ source: "route-extractor",
468
+ compiler_version: "2.0.0"
469
+ }
470
+ }
471
+ };
472
+ }
473
+
474
+ // src/action-compiler.ts
475
+ import { transformSync as transformSync2 } from "@babel/core";
476
+ function extractActionGroup(filename) {
477
+ const base = filename.split("/").pop() || filename;
478
+ return base.replace(/\.server\.(ts|tsx|js|jsx)$/, "");
479
+ }
480
+ function generateEndpoint(blueprintSlug, group, actionName, apiBasePath) {
481
+ return apiBasePath + "/" + blueprintSlug + "/" + group + "/" + actionName;
482
+ }
483
+ function generateActionId(group, actionName) {
484
+ return group + ":" + actionName;
485
+ }
486
+ function extractFunctionBodies(source) {
487
+ const result = /* @__PURE__ */ new Map();
488
+ const funcHeaderRegex = /export\s+(async\s+)?function\s+(\w+)\s*\(/g;
489
+ let headerMatch;
490
+ while ((headerMatch = funcHeaderRegex.exec(source)) !== null) {
491
+ const funcName = headerMatch[2];
492
+ const startIdx = headerMatch.index;
493
+ let braceStart = source.indexOf("{", headerMatch.index + headerMatch[0].length);
494
+ if (braceStart === -1) continue;
495
+ const signatureSlice = source.slice(headerMatch.index + headerMatch[0].length, braceStart);
496
+ const returnTypeMatch = signatureSlice.match(/\)\s*:\s*([^{]+)/);
497
+ const returnType = returnTypeMatch ? returnTypeMatch[1].trim() : void 0;
498
+ let depth = 0;
499
+ let endIdx = braceStart;
500
+ for (let i = braceStart; i < source.length; i++) {
501
+ if (source[i] === "{") depth++;
502
+ else if (source[i] === "}") {
503
+ depth--;
504
+ if (depth === 0) {
505
+ endIdx = i + 1;
506
+ break;
507
+ }
508
+ }
509
+ }
510
+ const fullText = source.slice(startIdx, endIdx);
511
+ result.set(funcName, { body: fullText, returnType });
512
+ }
513
+ return result;
514
+ }
515
+ function extractActionsViaRegex(source) {
516
+ const actions = [];
517
+ const funcRegex = /(?:\/\*\*([\s\S]*?)\*\/\s*)?export\s+(async\s+)?function\s+(\w+)\s*\(([^)]*)\)/g;
518
+ let match;
519
+ while ((match = funcRegex.exec(source)) !== null) {
520
+ const jsdoc = match[1];
521
+ const isAsync = !!match[2];
522
+ const name = match[3];
523
+ const paramsStr = match[4];
524
+ const params = paramsStr.split(",").map((p) => p.trim().split(":")[0].trim().split("?")[0].trim()).filter(Boolean);
525
+ let description;
526
+ if (jsdoc) {
527
+ const lines = jsdoc.split("\n");
528
+ for (const line of lines) {
529
+ const trimmed = line.replace(/^\s*\*\s?/, "").trim();
530
+ if (trimmed && !trimmed.startsWith("@")) {
531
+ description = trimmed;
532
+ break;
533
+ }
534
+ }
535
+ }
536
+ actions.push({ name, async: isAsync, params, description });
537
+ }
538
+ const arrowRegex = /export\s+const\s+(\w+)\s*=\s*(async\s+)?\([^)]*\)/g;
539
+ while ((match = arrowRegex.exec(source)) !== null) {
540
+ const name = match[1];
541
+ const isAsync = !!match[2];
542
+ const arrowParamMatch = source.slice(match.index).match(/\(([^)]*)\)/);
543
+ const params = arrowParamMatch ? arrowParamMatch[1].split(",").map((p) => p.trim().split(":")[0].trim()).filter(Boolean) : [];
544
+ actions.push({ name, async: isAsync, params });
545
+ }
546
+ return actions;
547
+ }
548
+ function compileActions(files, options = {}) {
549
+ const mode = options.mode || "infer";
550
+ const blueprintSlug = options.blueprintSlug || "app";
551
+ const apiBasePath = options.apiBasePath || "/api/v1/actions";
552
+ const allActions = [];
553
+ const byFile = /* @__PURE__ */ new Map();
554
+ const byGroup = /* @__PURE__ */ new Map();
555
+ const errors = [];
556
+ for (const [filename, source] of Object.entries(files)) {
557
+ const group = extractActionGroup(filename);
558
+ const fileActions = [];
559
+ const bodies = extractFunctionBodies(source);
560
+ try {
561
+ const parserPlugins = filename.endsWith(".tsx") ? ["typescript", "jsx"] : ["typescript"];
562
+ const babelResult = transformSync2(source, {
563
+ filename,
564
+ plugins: [[babelPlugin, { mode }]],
565
+ parserOpts: { plugins: parserPlugins, attachComment: true }
566
+ });
567
+ const ir = babelResult?.metadata?.mindmatrixIR ?? null;
568
+ const meta = ir?.metadata;
569
+ const babelActions = meta?.serverActions;
570
+ if (babelActions && babelActions.length > 0) {
571
+ for (const action of babelActions) {
572
+ const bodyInfo = bodies.get(action.name);
573
+ const reg = {
574
+ name: action.name,
575
+ sourceFile: filename,
576
+ async: action.async,
577
+ params: action.params,
578
+ contextType: action.contextType,
579
+ description: action.description,
580
+ body: bodyInfo?.body,
581
+ returnType: bodyInfo?.returnType,
582
+ endpoint: generateEndpoint(blueprintSlug, group, action.name, apiBasePath),
583
+ group,
584
+ actionId: generateActionId(group, action.name)
585
+ };
586
+ fileActions.push(reg);
587
+ }
588
+ } else {
589
+ const regexActions = extractActionsViaRegex(source);
590
+ for (const action of regexActions) {
591
+ const bodyInfo = bodies.get(action.name);
592
+ const reg = {
593
+ name: action.name,
594
+ sourceFile: filename,
595
+ async: action.async,
596
+ params: action.params,
597
+ description: action.description,
598
+ body: bodyInfo?.body,
599
+ returnType: bodyInfo?.returnType,
600
+ endpoint: generateEndpoint(blueprintSlug, group, action.name, apiBasePath),
601
+ group,
602
+ actionId: generateActionId(group, action.name)
603
+ };
604
+ fileActions.push(reg);
605
+ }
606
+ }
607
+ } catch (err) {
608
+ errors.push({ file: filename, message: err.message });
609
+ const regexActions = extractActionsViaRegex(source);
610
+ for (const action of regexActions) {
611
+ const bodyInfo = bodies.get(action.name);
612
+ const reg = {
613
+ name: action.name,
614
+ sourceFile: filename,
615
+ async: action.async,
616
+ params: action.params,
617
+ description: action.description,
618
+ body: bodyInfo?.body,
619
+ returnType: bodyInfo?.returnType,
620
+ endpoint: generateEndpoint(blueprintSlug, group, action.name, apiBasePath),
621
+ group,
622
+ actionId: generateActionId(group, action.name)
623
+ };
624
+ fileActions.push(reg);
625
+ }
626
+ }
627
+ byFile.set(filename, fileActions);
628
+ if (!byGroup.has(group)) byGroup.set(group, []);
629
+ byGroup.get(group).push(...fileActions);
630
+ allActions.push(...fileActions);
631
+ }
632
+ return { actions: allActions, byFile, byGroup, errors };
633
+ }
634
+ function resolveActionReferences(actionNames, registrations) {
635
+ const result = /* @__PURE__ */ new Map();
636
+ const byName = new Map(registrations.map((r) => [r.name, r]));
637
+ for (const name of actionNames) {
638
+ if (byName.has(name)) {
639
+ result.set(name, byName.get(name));
640
+ continue;
641
+ }
642
+ const colonIdx = name.indexOf(":");
643
+ if (colonIdx > 0) {
644
+ const actionName = name.slice(colonIdx + 1);
645
+ if (byName.has(actionName)) {
646
+ result.set(name, byName.get(actionName));
647
+ continue;
648
+ }
649
+ }
650
+ result.set(name, null);
651
+ }
652
+ return result;
653
+ }
654
+
655
+ // src/incremental-compiler.ts
656
+ function hashContent(content) {
657
+ let hash = 5381;
658
+ for (let i = 0; i < content.length; i++) {
659
+ hash = (hash << 5) + hash + content.charCodeAt(i);
660
+ hash |= 0;
661
+ }
662
+ return (hash >>> 0).toString(36);
663
+ }
664
+ function extractImports(source) {
665
+ const imports = [];
666
+ const regex = /import\s+.*?from\s+['"](\.[^'"]+)['"]/g;
667
+ let match;
668
+ while ((match = regex.exec(source)) !== null) {
669
+ imports.push(match[1]);
670
+ }
671
+ return imports;
672
+ }
673
+ function resolveImport(fromFile, importPath, availableFiles) {
674
+ const parts = fromFile.split("/");
675
+ parts.pop();
676
+ const dir = parts.join("/");
677
+ const segments = (dir ? dir + "/" + importPath : importPath).split("/");
678
+ const resolved = [];
679
+ for (const seg of segments) {
680
+ if (seg === ".") continue;
681
+ if (seg === "..") {
682
+ resolved.pop();
683
+ continue;
684
+ }
685
+ resolved.push(seg);
686
+ }
687
+ const basePath = resolved.join("/");
688
+ const extensions = ["", ".ts", ".tsx", ".js", ".jsx"];
689
+ for (const ext of extensions) {
690
+ const candidate = basePath + ext;
691
+ if (availableFiles.includes(candidate)) {
692
+ return candidate;
693
+ }
694
+ }
695
+ for (const ext of [".ts", ".tsx", ".js", ".jsx"]) {
696
+ const candidate = basePath + "/index" + ext;
697
+ if (availableFiles.includes(candidate)) {
698
+ return candidate;
699
+ }
700
+ }
701
+ return null;
702
+ }
703
+ function buildDependencyGraph(files) {
704
+ const availableFiles = Object.keys(files);
705
+ const edges = [];
706
+ const dependents = /* @__PURE__ */ new Map();
707
+ const dependencies = /* @__PURE__ */ new Map();
708
+ for (const filename of availableFiles) {
709
+ dependents.set(filename, /* @__PURE__ */ new Set());
710
+ dependencies.set(filename, /* @__PURE__ */ new Set());
711
+ }
712
+ for (const [filename, source] of Object.entries(files)) {
713
+ const imports = extractImports(source);
714
+ for (const imp of imports) {
715
+ const resolved = resolveImport(filename, imp, availableFiles);
716
+ if (resolved && resolved !== filename) {
717
+ edges.push({ from: filename, to: resolved });
718
+ dependencies.get(filename).add(resolved);
719
+ if (!dependents.has(resolved)) dependents.set(resolved, /* @__PURE__ */ new Set());
720
+ dependents.get(resolved).add(filename);
721
+ }
722
+ }
723
+ }
724
+ return { edges, dependents, dependencies };
725
+ }
726
+ function computeTransitiveDirtySet(directlyChanged, dependents) {
727
+ const dirty = new Set(directlyChanged);
728
+ const queue = [...directlyChanged];
729
+ while (queue.length > 0) {
730
+ const file = queue.shift();
731
+ const deps = dependents.get(file);
732
+ if (!deps) continue;
733
+ for (const dep of deps) {
734
+ if (!dirty.has(dep)) {
735
+ dirty.add(dep);
736
+ queue.push(dep);
737
+ }
738
+ }
739
+ }
740
+ return dirty;
741
+ }
742
+ function topologicalSort(files, dependencies) {
743
+ const inDegree = /* @__PURE__ */ new Map();
744
+ const dependentMap = /* @__PURE__ */ new Map();
745
+ for (const f of files) {
746
+ inDegree.set(f, 0);
747
+ dependentMap.set(f, /* @__PURE__ */ new Set());
748
+ }
749
+ for (const f of files) {
750
+ const deps = dependencies.get(f);
751
+ if (!deps) continue;
752
+ for (const dep of deps) {
753
+ if (files.includes(dep)) {
754
+ inDegree.set(f, (inDegree.get(f) || 0) + 1);
755
+ if (!dependentMap.has(dep)) dependentMap.set(dep, /* @__PURE__ */ new Set());
756
+ dependentMap.get(dep).add(f);
757
+ }
758
+ }
759
+ }
760
+ const queue = [];
761
+ for (const [f, degree] of inDegree) {
762
+ if (degree === 0) queue.push(f);
763
+ }
764
+ const order = [];
765
+ while (queue.length > 0) {
766
+ const f = queue.shift();
767
+ order.push(f);
768
+ for (const dependent of dependentMap.get(f) || []) {
769
+ const newDegree = (inDegree.get(dependent) || 1) - 1;
770
+ inDegree.set(dependent, newDegree);
771
+ if (newDegree === 0) queue.push(dependent);
772
+ }
773
+ }
774
+ for (const f of files) {
775
+ if (!order.includes(f)) {
776
+ order.push(f);
777
+ }
778
+ }
779
+ return order;
780
+ }
781
+ var IncrementalCache = class {
782
+ constructor() {
783
+ this.hashes = /* @__PURE__ */ new Map();
784
+ this.results = /* @__PURE__ */ new Map();
785
+ this.lastStats = {
786
+ totalCached: 0,
787
+ lastRecompiled: 0,
788
+ lastCacheHits: 0,
789
+ lastCompileMs: 0,
790
+ avgPerFileMs: 0,
791
+ cacheHitRate: 0
792
+ };
793
+ }
794
+ /**
795
+ * Determines which files are dirty given current file contents.
796
+ */
797
+ detectDirtyFiles(files, dependents) {
798
+ const currentFiles = new Set(Object.keys(files));
799
+ const contentChanged = [];
800
+ const removed = [];
801
+ const added = [];
802
+ for (const [filename, source] of Object.entries(files)) {
803
+ const hash = hashContent(source);
804
+ const cached = this.hashes.get(filename);
805
+ if (!cached) {
806
+ added.push(filename);
807
+ } else if (cached.hash !== hash) {
808
+ contentChanged.push(filename);
809
+ }
810
+ }
811
+ for (const cached of this.hashes.keys()) {
812
+ if (!currentFiles.has(cached)) {
813
+ removed.push(cached);
814
+ }
815
+ }
816
+ const directlyDirty = /* @__PURE__ */ new Set([...contentChanged, ...added]);
817
+ let dependencyDirty = [];
818
+ if (dependents && directlyDirty.size > 0) {
819
+ const allDirty = computeTransitiveDirtySet(directlyDirty, dependents);
820
+ dependencyDirty = [...allDirty].filter((f) => !directlyDirty.has(f));
821
+ }
822
+ return { contentChanged, dependencyDirty, removed, added };
823
+ }
824
+ /**
825
+ * Updates the cache with a compilation result.
826
+ */
827
+ set(filename, source, result) {
828
+ this.hashes.set(filename, {
829
+ hash: hashContent(source),
830
+ compiledAt: Date.now(),
831
+ size: source.length
832
+ });
833
+ this.results.set(filename, result);
834
+ }
835
+ /**
836
+ * Gets a cached result.
837
+ */
838
+ get(filename) {
839
+ return this.results.get(filename);
840
+ }
841
+ /**
842
+ * Checks if a file is in cache and not dirty.
843
+ */
844
+ has(filename) {
845
+ return this.results.has(filename);
846
+ }
847
+ /**
848
+ * Removes a file from cache.
849
+ */
850
+ delete(filename) {
851
+ this.hashes.delete(filename);
852
+ this.results.delete(filename);
853
+ }
854
+ /**
855
+ * Clears all cached data.
856
+ */
857
+ clear() {
858
+ this.hashes.clear();
859
+ this.results.clear();
860
+ }
861
+ /**
862
+ * Updates stats after a compilation run.
863
+ */
864
+ updateStats(recompiled, cacheHits, compileMs) {
865
+ const total = recompiled + cacheHits;
866
+ this.lastStats = {
867
+ totalCached: this.results.size,
868
+ lastRecompiled: recompiled,
869
+ lastCacheHits: cacheHits,
870
+ lastCompileMs: compileMs,
871
+ avgPerFileMs: recompiled > 0 ? compileMs / recompiled : 0,
872
+ cacheHitRate: total > 0 ? cacheHits / total : 0
873
+ };
874
+ }
875
+ /**
876
+ * Gets compilation statistics.
877
+ */
878
+ getStats() {
879
+ return { ...this.lastStats };
880
+ }
881
+ /**
882
+ * Gets all cached filenames.
883
+ */
884
+ getCachedFiles() {
885
+ return [...this.results.keys()];
886
+ }
887
+ /**
888
+ * Gets all cached results.
889
+ */
890
+ getAllResults() {
891
+ return new Map(this.results);
892
+ }
893
+ };
894
+
895
+ // src/project-compiler.ts
896
+ function parseConfig(source) {
897
+ const config = {};
898
+ const slugMatch = source.match(/slug:\s*['"]([^'"]+)['"]/);
899
+ if (slugMatch) config.slug = slugMatch[1];
900
+ const nameMatch = source.match(/name:\s*['"]([^'"]+)['"]/);
901
+ if (nameMatch) config.name = nameMatch[1];
902
+ const versionMatch = source.match(/version:\s*['"]([^'"]+)['"]/);
903
+ if (versionMatch) config.version = versionMatch[1];
904
+ const descMatch = source.match(/description:\s*['"]([^'"]+)['"]/);
905
+ if (descMatch) config.description = descMatch[1];
906
+ const categoryMatch = source.match(/category:\s*['"]([^'"]+)['"]/);
907
+ if (categoryMatch) config.category = categoryMatch[1];
908
+ const modeMatch = source.match(/mode:\s*['"]([^'"]+)['"]/);
909
+ if (modeMatch && (modeMatch[1] === "strict" || modeMatch[1] === "infer")) {
910
+ config.mode = modeMatch[1];
911
+ }
912
+ return config;
913
+ }
914
+ function isWorkflowFile(filename) {
915
+ return /\.workflow\.(tsx?|jsx?)$/.test(filename);
916
+ }
917
+ function isModelFile(filename) {
918
+ return /models\/.*\.(ts|tsx)$/.test(filename) && !filename.endsWith(".test.ts");
919
+ }
920
+ function isServerActionFile(filename) {
921
+ return /\.server\.(ts|tsx)$/.test(filename);
922
+ }
923
+ function isComponentFile(filename) {
924
+ return /components\/.*\.(tsx?|jsx?)$/.test(filename) && !filename.endsWith(".test.ts") && !filename.endsWith(".test.tsx");
925
+ }
926
+ function isPageFile2(filename) {
927
+ return (/pages\/.*\.(tsx?|jsx?)$/.test(filename) || /app\/.*\.(tsx?|jsx?)$/.test(filename)) && !filename.endsWith(".test.ts") && !filename.endsWith(".test.tsx") && !filename.includes("layout");
928
+ }
929
+ function isAppDirFile(filename) {
930
+ return /^app\//.test(filename);
931
+ }
932
+ function isConfigFile(filename) {
933
+ return /mm\.config\.(ts|tsx|js)$/.test(filename);
934
+ }
935
+ function isCompilableFile(filename) {
936
+ return isWorkflowFile(filename) || isModelFile(filename) || isServerActionFile(filename) || isPageFile2(filename) || isComponentFile(filename);
937
+ }
938
+ function compileFile(filename, source, mode) {
939
+ const errors = [];
940
+ try {
941
+ const parserPlugins = filename.endsWith(".tsx") || filename.endsWith(".jsx") ? ["typescript", "jsx"] : ["typescript"];
942
+ const result = transformSync3(source, {
943
+ filename,
944
+ plugins: [[babelPlugin, { mode }]],
945
+ parserOpts: { plugins: parserPlugins, attachComment: true }
946
+ });
947
+ const ir = result?.metadata?.mindmatrixIR ?? null;
948
+ if (ir?.metadata) {
949
+ const meta = ir.metadata;
950
+ const fileErrors = meta.errors;
951
+ const fileWarnings = meta.warnings;
952
+ if (fileErrors) {
953
+ for (const e of fileErrors) {
954
+ errors.push({
955
+ file: filename,
956
+ message: e.message,
957
+ line: e.line,
958
+ column: e.column,
959
+ endLine: e.line,
960
+ endColumn: e.column !== void 0 ? e.column + 10 : void 0,
961
+ severity: "error"
962
+ });
963
+ }
964
+ }
965
+ if (fileWarnings) {
966
+ for (const w of fileWarnings) {
967
+ errors.push({
968
+ file: filename,
969
+ message: w.message,
970
+ line: w.line,
971
+ column: w.column,
972
+ endLine: w.line,
973
+ endColumn: w.column !== void 0 ? w.column + 10 : void 0,
974
+ severity: "warning"
975
+ });
976
+ }
977
+ }
978
+ }
979
+ return { ir, errors };
980
+ } catch (err) {
981
+ const errMsg = err.message;
982
+ const locMatch = errMsg.match(/\((\d+):(\d+)\)/);
983
+ const line = locMatch ? parseInt(locMatch[1], 10) : void 0;
984
+ const column = locMatch ? parseInt(locMatch[2], 10) : void 0;
985
+ errors.push({
986
+ file: filename,
987
+ message: "Compilation failed: " + errMsg,
988
+ line,
989
+ column,
990
+ endLine: line,
991
+ endColumn: column !== void 0 ? column + 1 : void 0,
992
+ severity: "error"
993
+ });
994
+ return { ir: null, errors };
995
+ }
996
+ }
997
+ function mergeIRs(irs, config) {
998
+ if (irs.length === 0) {
999
+ return createEmptyIR(config);
1000
+ }
1001
+ if (irs.length === 1) {
1002
+ return applyConfig(irs[0], config);
1003
+ }
1004
+ const fieldMap = /* @__PURE__ */ new Map();
1005
+ for (const ir of irs) {
1006
+ for (const field of ir.fields) {
1007
+ if (!fieldMap.has(field.name)) {
1008
+ fieldMap.set(field.name, field);
1009
+ }
1010
+ }
1011
+ }
1012
+ const stateMap = /* @__PURE__ */ new Map();
1013
+ for (const ir of irs) {
1014
+ for (const state of ir.states) {
1015
+ if (stateMap.has(state.name)) {
1016
+ const existing = stateMap.get(state.name);
1017
+ existing.on_enter = [...existing.on_enter, ...state.on_enter];
1018
+ existing.on_exit = [...existing.on_exit, ...state.on_exit];
1019
+ existing.during = [...existing.during, ...state.during];
1020
+ if (state.on_event) {
1021
+ existing.on_event = [...existing.on_event || [], ...state.on_event];
1022
+ }
1023
+ if (state.type === "START") existing.type = "START";
1024
+ else if (state.type === "END" && existing.type === "REGULAR") existing.type = "END";
1025
+ } else {
1026
+ stateMap.set(state.name, { ...state });
1027
+ }
1028
+ }
1029
+ }
1030
+ const transitionMap = /* @__PURE__ */ new Map();
1031
+ for (const ir of irs) {
1032
+ for (const transition of ir.transitions) {
1033
+ if (!transitionMap.has(transition.name)) {
1034
+ transitionMap.set(transition.name, transition);
1035
+ }
1036
+ }
1037
+ }
1038
+ const events = [];
1039
+ for (const ir of irs) {
1040
+ if (ir.on_event) {
1041
+ events.push(...ir.on_event);
1042
+ }
1043
+ }
1044
+ const viewTrees = [];
1045
+ for (const ir of irs) {
1046
+ const views = ir.views;
1047
+ if (views?.default) {
1048
+ viewTrees.push(views.default);
1049
+ }
1050
+ }
1051
+ const extensions = {};
1052
+ for (const ir of irs) {
1053
+ if (ir.extensions) {
1054
+ for (const [key, islands] of Object.entries(ir.extensions)) {
1055
+ if (!extensions[key]) extensions[key] = [];
1056
+ extensions[key].push(...islands);
1057
+ }
1058
+ }
1059
+ }
1060
+ const metadata = {};
1061
+ for (const ir of irs) {
1062
+ if (ir.metadata) {
1063
+ for (const [key, value] of Object.entries(ir.metadata)) {
1064
+ if (key === "errors" || key === "warnings") continue;
1065
+ metadata[key] = value;
1066
+ }
1067
+ }
1068
+ }
1069
+ const roleMap = /* @__PURE__ */ new Map();
1070
+ for (const ir of irs) {
1071
+ for (const role of ir.roles) {
1072
+ if (!roleMap.has(role.name)) {
1073
+ roleMap.set(role.name, role);
1074
+ }
1075
+ }
1076
+ }
1077
+ const base = irs[0];
1078
+ const merged = {
1079
+ slug: base.slug,
1080
+ name: base.name,
1081
+ version: base.version,
1082
+ description: base.description,
1083
+ category: base.category,
1084
+ fields: Array.from(fieldMap.values()),
1085
+ states: Array.from(stateMap.values()),
1086
+ transitions: Array.from(transitionMap.values()),
1087
+ roles: Array.from(roleMap.values()),
1088
+ tags: base.tags,
1089
+ metadata
1090
+ };
1091
+ if (events.length > 0) {
1092
+ merged.on_event = events;
1093
+ }
1094
+ if (Object.keys(extensions).length > 0) {
1095
+ merged.extensions = extensions;
1096
+ }
1097
+ if (viewTrees.length === 1) {
1098
+ merged.views = { default: viewTrees[0] };
1099
+ } else if (viewTrees.length > 1) {
1100
+ const rootView = {
1101
+ id: "project-root",
1102
+ component: "Stack",
1103
+ children: viewTrees
1104
+ };
1105
+ merged.views = { default: rootView };
1106
+ }
1107
+ return applyConfig(merged, config);
1108
+ }
1109
+ function applyConfig(ir, config) {
1110
+ if (config.slug) ir.slug = config.slug;
1111
+ if (config.name) ir.name = config.name;
1112
+ if (config.version) ir.version = config.version;
1113
+ if (config.description !== void 0) ir.description = config.description;
1114
+ if (config.category) ir.category = config.category;
1115
+ if (!ir.metadata) ir.metadata = {};
1116
+ ir.metadata.stable_id = "def-" + ir.slug;
1117
+ ir.metadata.provenance = {
1118
+ frontend: "react-compiler",
1119
+ source: "project",
1120
+ compiler_version: "2.0.0"
1121
+ };
1122
+ return ir;
1123
+ }
1124
+ function createEmptyIR(config) {
1125
+ return {
1126
+ slug: config.slug || "project",
1127
+ name: config.name || "Project",
1128
+ version: config.version || "0.1.0",
1129
+ description: config.description,
1130
+ category: config.category || "workflow",
1131
+ fields: [],
1132
+ states: [{
1133
+ name: "draft",
1134
+ type: "START",
1135
+ on_enter: [],
1136
+ during: [],
1137
+ on_exit: []
1138
+ }],
1139
+ transitions: [],
1140
+ roles: [],
1141
+ tags: [],
1142
+ metadata: {
1143
+ stable_id: "def-" + (config.slug || "project"),
1144
+ provenance: {
1145
+ frontend: "react-compiler",
1146
+ source: "project",
1147
+ compiler_version: "2.0.0"
1148
+ }
1149
+ }
1150
+ };
1151
+ }
1152
+ function resolveImportLinks(files, compilableFiles) {
1153
+ const links = [];
1154
+ for (const filename of compilableFiles) {
1155
+ const source = files[filename];
1156
+ const importRegex = /import\s+(?:type\s+)?(?:\{([^}]+)\}|(\w+))\s+from\s+['"](\.[^'"]+)['"]/g;
1157
+ let match;
1158
+ while ((match = importRegex.exec(source)) !== null) {
1159
+ const namedImports = match[1];
1160
+ const defaultImport = match[2];
1161
+ const importPath = match[3];
1162
+ const resolved = resolveImport(filename, importPath, Object.keys(files));
1163
+ if (!resolved || resolved === filename) continue;
1164
+ let linkType = "unknown";
1165
+ if (isModelFile(resolved)) {
1166
+ linkType = "data-source";
1167
+ } else if (isServerActionFile(resolved)) {
1168
+ linkType = "action";
1169
+ } else if (/components\//.test(resolved)) {
1170
+ linkType = "component";
1171
+ }
1172
+ const symbols = [];
1173
+ if (namedImports) {
1174
+ symbols.push(...namedImports.split(",").map((s) => s.trim().split(" as ")[0].trim()).filter(Boolean));
1175
+ }
1176
+ if (defaultImport) {
1177
+ symbols.push(defaultImport);
1178
+ }
1179
+ links.push({
1180
+ fromFile: filename,
1181
+ toFile: resolved,
1182
+ linkType,
1183
+ symbols
1184
+ });
1185
+ }
1186
+ }
1187
+ return links;
1188
+ }
1189
+ function resolveCompilationOrder(files, compilableFiles) {
1190
+ const { dependencies } = buildDependencyGraph(files);
1191
+ return topologicalSort(compilableFiles, dependencies);
1192
+ }
1193
+ function extractComponentProps(source) {
1194
+ const match = source.match(/function\s+\w+\s*\(\s*\{([^}]+)\}/);
1195
+ if (!match) return [];
1196
+ return match[1].split(",").map((p) => p.trim().split(/[\s=:]/)[0].replace(/^\.{3}/, "").trim()).filter(Boolean);
1197
+ }
1198
+ function buildComposedResult(files, fileIRs, config, errors, warnings, options = {}) {
1199
+ const usePhase2 = options.usePhase2Modules !== false;
1200
+ const workflowIRs = [];
1201
+ const modelIRs = [];
1202
+ const serverActionEntries = [];
1203
+ let modelResults;
1204
+ let actionResult;
1205
+ let routeResult;
1206
+ const componentDefinitions = {};
1207
+ for (const [filename, ir] of Object.entries(fileIRs)) {
1208
+ if (isWorkflowFile(filename)) {
1209
+ workflowIRs.push(ir);
1210
+ } else if (isModelFile(filename)) {
1211
+ if (!ir.category || ir.category === "workflow") {
1212
+ ir.category = "data";
1213
+ }
1214
+ modelIRs.push(ir);
1215
+ } else if (isServerActionFile(filename)) {
1216
+ const meta = ir.metadata;
1217
+ const actions = meta?.serverActions;
1218
+ if (actions) {
1219
+ for (const action of actions) {
1220
+ serverActionEntries.push({
1221
+ name: action.name,
1222
+ sourceFile: filename,
1223
+ async: action.async,
1224
+ params: action.params,
1225
+ description: action.description
1226
+ });
1227
+ }
1228
+ }
1229
+ } else if (isComponentFile(filename)) {
1230
+ const views = ir.views;
1231
+ const experience = views?.default ?? ir.experience;
1232
+ if (experience) {
1233
+ const baseName = filename.split("/").pop()?.replace(/\.(tsx?|jsx?)$/, "") || "Component";
1234
+ const source = files[filename];
1235
+ const props = source ? extractComponentProps(source) : [];
1236
+ componentDefinitions[baseName] = { experience, props };
1237
+ }
1238
+ }
1239
+ }
1240
+ if (usePhase2) {
1241
+ const modelFiles = {};
1242
+ for (const [filename, source] of Object.entries(files)) {
1243
+ if (isModelFile(filename)) {
1244
+ modelFiles[filename] = source;
1245
+ }
1246
+ }
1247
+ if (Object.keys(modelFiles).length > 0) {
1248
+ modelResults = compileModels(modelFiles, { mode: options.mode || "infer" });
1249
+ modelIRs.length = 0;
1250
+ for (const [, result] of modelResults) {
1251
+ modelIRs.push(result.ir);
1252
+ }
1253
+ }
1254
+ const actionFiles = {};
1255
+ for (const [filename, source] of Object.entries(files)) {
1256
+ if (isServerActionFile(filename)) {
1257
+ actionFiles[filename] = source;
1258
+ }
1259
+ }
1260
+ if (Object.keys(actionFiles).length > 0) {
1261
+ actionResult = compileActions(actionFiles, {
1262
+ mode: options.mode || "infer",
1263
+ blueprintSlug: config.slug || "app"
1264
+ });
1265
+ serverActionEntries.length = 0;
1266
+ for (const reg of actionResult.actions) {
1267
+ serverActionEntries.push({
1268
+ name: reg.name,
1269
+ sourceFile: reg.sourceFile,
1270
+ async: reg.async,
1271
+ params: reg.params,
1272
+ description: reg.description,
1273
+ body: reg.body,
1274
+ returnType: reg.returnType
1275
+ });
1276
+ }
1277
+ }
1278
+ const appFiles = {};
1279
+ for (const [filename, source] of Object.entries(files)) {
1280
+ if (isAppDirFile(filename) || isPageFile2(filename)) {
1281
+ appFiles[filename] = source;
1282
+ }
1283
+ }
1284
+ if (Object.keys(appFiles).length > 0) {
1285
+ routeResult = extractRoutes(appFiles, {
1286
+ slugPrefix: config.slug || "app"
1287
+ });
1288
+ }
1289
+ }
1290
+ const childDefinitions = [...workflowIRs, ...modelIRs];
1291
+ let routeTable = [];
1292
+ if (routeResult) {
1293
+ routeTable = routeResult.routes.map((r) => ({
1294
+ path: r.path,
1295
+ stateName: r.stateName,
1296
+ sourceFile: r.sourceFile,
1297
+ params: r.params
1298
+ }));
1299
+ childDefinitions.push(routeResult.routerIR);
1300
+ } else {
1301
+ const pageFiles = [];
1302
+ for (const filename of Object.keys(files)) {
1303
+ if (isPageFile2(filename)) {
1304
+ pageFiles.push({
1305
+ relativePath: filename,
1306
+ absolutePath: filename
1307
+ });
1308
+ const routePath = filename.replace(/^pages\//, "").replace(/^app\//, "").replace(/\.(tsx?|jsx?)$/, "").replace(/\/index$/, "").replace(/\/page$/, "");
1309
+ const stateName = pathToStateName(routePath);
1310
+ const urlPattern = pathToUrlPattern(filename, filename.split("/").pop() || "page.tsx");
1311
+ const params = extractParams(filename);
1312
+ routeTable.push({
1313
+ path: urlPattern,
1314
+ stateName,
1315
+ sourceFile: filename,
1316
+ params
1317
+ });
1318
+ }
1319
+ }
1320
+ if (pageFiles.length > 0) {
1321
+ const routerWorkflow = extractRouterWorkflow(pageFiles, {
1322
+ slug: config.slug ? config.slug + "-router" : "app-router",
1323
+ pageFileName: pageFiles[0]?.relativePath.split("/").pop() || "page.tsx"
1324
+ });
1325
+ childDefinitions.push(routerWorkflow);
1326
+ }
1327
+ }
1328
+ const allIRs = Object.values(fileIRs);
1329
+ const parentIR = mergeIRs(allIRs, config);
1330
+ if (!parentIR.metadata) parentIR.metadata = {};
1331
+ const parentMeta = parentIR.metadata;
1332
+ parentMeta.childSlugs = childDefinitions.map((c) => c.slug);
1333
+ parentMeta.serverActions = serverActionEntries;
1334
+ if (routeTable.length > 0) {
1335
+ parentMeta.routeTable = routeTable;
1336
+ }
1337
+ parentMeta.composition = {
1338
+ workflowCount: workflowIRs.length,
1339
+ modelCount: modelIRs.length,
1340
+ serverActionCount: serverActionEntries.length,
1341
+ routeCount: routeTable.length,
1342
+ componentCount: Object.keys(componentDefinitions).length,
1343
+ totalFiles: Object.keys(files).length
1344
+ };
1345
+ if (Object.keys(componentDefinitions).length > 0) {
1346
+ parentMeta.componentDefinitions = componentDefinitions;
1347
+ }
1348
+ if (actionResult) {
1349
+ parentMeta.actionEndpoints = actionResult.actions.map((a) => ({
1350
+ actionId: a.actionId,
1351
+ endpoint: a.endpoint,
1352
+ group: a.group
1353
+ }));
1354
+ }
1355
+ const compilableFiles = Object.keys(files).filter(isCompilableFile);
1356
+ const importLinks = resolveImportLinks(files, compilableFiles);
1357
+ const pageExperiences = {};
1358
+ for (const [filename, ir] of Object.entries(fileIRs)) {
1359
+ if (isPageFile2(filename)) {
1360
+ const views = ir.views;
1361
+ if (views?.default) {
1362
+ pageExperiences[filename] = views.default;
1363
+ }
1364
+ }
1365
+ }
1366
+ const parentViews = parentIR.views;
1367
+ if (Object.keys(pageExperiences).length > 0) {
1368
+ const pageEntries = Object.entries(pageExperiences);
1369
+ const routeNodes = pageEntries.map(([pagePath, pageTree], i) => {
1370
+ const routePath = "/" + pagePath.replace(/^app\//, "").replace(/\.(tsx?|jsx?)$/, "").replace(/\/index$/, "").replace(/\/page$/, "");
1371
+ return {
1372
+ id: `route-${i}`,
1373
+ component: "Route",
1374
+ config: { path: routePath },
1375
+ children: [pageTree]
1376
+ };
1377
+ });
1378
+ const navLinks = pageEntries.map(([pagePath], i) => {
1379
+ const routePath = "/" + pagePath.replace(/^app\//, "").replace(/\.(tsx?|jsx?)$/, "").replace(/\/index$/, "").replace(/\/page$/, "");
1380
+ const segments = routePath.split("/").filter(Boolean);
1381
+ const label = segments[segments.length - 1]?.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()) || "Home";
1382
+ return {
1383
+ id: `nav-link-${i}`,
1384
+ component: "NavLink",
1385
+ config: { to: routePath, label }
1386
+ };
1387
+ });
1388
+ const firstPagePath = "/" + pageEntries[0][0].replace(/^app\//, "").replace(/\.(tsx?|jsx?)$/, "").replace(/\/index$/, "").replace(/\/page$/, "");
1389
+ routeNodes.unshift({
1390
+ id: "route-index",
1391
+ component: "Route",
1392
+ config: { path: "/", exact: true },
1393
+ children: [pageEntries[0][1]]
1394
+ });
1395
+ const composedExperience = {
1396
+ id: "blueprint-root",
1397
+ component: "Stack",
1398
+ className: "h-full flex flex-col",
1399
+ children: [
1400
+ // Nav bar (always visible, not inside Router so it always renders)
1401
+ {
1402
+ id: "nav-bar",
1403
+ component: "Row",
1404
+ config: { gap: 1 },
1405
+ className: "px-4 py-2 border-b border-border bg-background/95 backdrop-blur-sm sticky top-0 z-10 flex-wrap",
1406
+ children: navLinks
1407
+ },
1408
+ // Router with page routes
1409
+ {
1410
+ id: "page-router",
1411
+ component: "Router",
1412
+ className: "flex-1 min-h-0 overflow-y-auto",
1413
+ children: routeNodes.map((r) => ({
1414
+ ...r,
1415
+ children: r.children?.map((child) => ({
1416
+ ...child,
1417
+ id: child.id || r.id + "-content",
1418
+ component: child.component || "Stack",
1419
+ config: { ...child.config, gap: 4, padding: 4 }
1420
+ }))
1421
+ }))
1422
+ }
1423
+ ]
1424
+ };
1425
+ parentIR.experience = composedExperience;
1426
+ const slug = config.slug || parentIR.slug || "blueprint";
1427
+ parentMeta.blueprint_manifest = {
1428
+ routes: [
1429
+ { path: `${slug}/*`, node: slug, label: config.name || parentIR.name || slug }
1430
+ ],
1431
+ config: {
1432
+ full_bleed: true
1433
+ }
1434
+ };
1435
+ } else if (parentViews?.default) {
1436
+ parentIR.experience = parentViews.default;
1437
+ }
1438
+ for (const childDef of childDefinitions) {
1439
+ for (const [filename, ir] of Object.entries(fileIRs)) {
1440
+ if (ir.slug === childDef.slug || isWorkflowFile(filename) && ir.slug === childDef.slug) {
1441
+ const views = ir.views;
1442
+ if (views?.default) {
1443
+ childDef.experience = views.default;
1444
+ }
1445
+ break;
1446
+ }
1447
+ }
1448
+ }
1449
+ return {
1450
+ ir: parentIR,
1451
+ childDefinitions,
1452
+ fileIRs,
1453
+ routeTable,
1454
+ serverActions: serverActionEntries,
1455
+ errors,
1456
+ warnings,
1457
+ pageExperiences,
1458
+ componentDefinitions,
1459
+ importLinks,
1460
+ modelResults,
1461
+ actionResult,
1462
+ routeResult
1463
+ };
1464
+ }
1465
+ function compileProject(files, options = {}) {
1466
+ const allErrors = [];
1467
+ const allWarnings = [];
1468
+ const fileIRs = {};
1469
+ let config = {};
1470
+ for (const [filename, source] of Object.entries(files)) {
1471
+ if (isConfigFile(filename)) {
1472
+ config = parseConfig(source);
1473
+ break;
1474
+ }
1475
+ }
1476
+ const mode = config.mode || options.mode || "infer";
1477
+ const compilableFiles = Object.keys(files).filter(isCompilableFile);
1478
+ const orderedFiles = resolveCompilationOrder(files, compilableFiles);
1479
+ for (const filename of orderedFiles) {
1480
+ const source = files[filename];
1481
+ const { ir, errors } = compileFile(filename, source, mode);
1482
+ for (const e of errors) {
1483
+ if (e.severity === "error") allErrors.push(e);
1484
+ else allWarnings.push(e);
1485
+ }
1486
+ if (ir) {
1487
+ fileIRs[filename] = ir;
1488
+ }
1489
+ }
1490
+ return buildComposedResult(files, fileIRs, config, allErrors, allWarnings, {
1491
+ usePhase2Modules: options.usePhase2Modules,
1492
+ mode
1493
+ });
1494
+ }
1495
+ var IncrementalProjectCompiler = class {
1496
+ constructor() {
1497
+ this.lastConfig = {};
1498
+ this.cache = new IncrementalCache();
1499
+ }
1500
+ /**
1501
+ * Compile a project incrementally — only recompiles changed files.
1502
+ */
1503
+ compile(files, options = {}) {
1504
+ const startTime = Date.now();
1505
+ const { dependents } = buildDependencyGraph(files);
1506
+ const dirtySet = this.cache.detectDirtyFiles(files, dependents);
1507
+ const allDirty = /* @__PURE__ */ new Set([
1508
+ ...dirtySet.contentChanged,
1509
+ ...dirtySet.dependencyDirty,
1510
+ ...dirtySet.added
1511
+ ]);
1512
+ for (const removed of dirtySet.removed) {
1513
+ this.cache.delete(removed);
1514
+ }
1515
+ if (allDirty.size === 0 && this.cache.getCachedFiles().length > 0) {
1516
+ this.cache.updateStats(0, this.cache.getCachedFiles().length, Date.now() - startTime);
1517
+ return this.rebuildFromCache(files, options);
1518
+ }
1519
+ for (const [filename, source] of Object.entries(files)) {
1520
+ if (isConfigFile(filename)) {
1521
+ if (allDirty.has(filename)) {
1522
+ this.lastConfig = parseConfig(source);
1523
+ }
1524
+ break;
1525
+ }
1526
+ }
1527
+ const mode = this.lastConfig.mode || options.mode || "infer";
1528
+ const compilableFiles = Object.keys(files).filter(isCompilableFile);
1529
+ let recompiled = 0;
1530
+ let cacheHits = 0;
1531
+ for (const filename of compilableFiles) {
1532
+ if (allDirty.has(filename) || !this.cache.has(filename)) {
1533
+ const { ir, errors } = compileFile(filename, files[filename], mode);
1534
+ if (ir) {
1535
+ this.cache.set(filename, files[filename], { ir, errors });
1536
+ } else {
1537
+ this.cache.delete(filename);
1538
+ }
1539
+ recompiled++;
1540
+ } else {
1541
+ cacheHits++;
1542
+ }
1543
+ }
1544
+ for (const cached of this.cache.getCachedFiles()) {
1545
+ if (!compilableFiles.includes(cached)) {
1546
+ this.cache.delete(cached);
1547
+ }
1548
+ }
1549
+ const fileIRs = {};
1550
+ const allErrors = [];
1551
+ const allWarnings = [];
1552
+ for (const cached of this.cache.getCachedFiles()) {
1553
+ const entry = this.cache.get(cached);
1554
+ if (entry) {
1555
+ fileIRs[cached] = entry.ir;
1556
+ for (const e of entry.errors) {
1557
+ if (e.severity === "error") allErrors.push(e);
1558
+ else allWarnings.push(e);
1559
+ }
1560
+ }
1561
+ }
1562
+ this.cache.updateStats(recompiled, cacheHits, Date.now() - startTime);
1563
+ return buildComposedResult(files, fileIRs, this.lastConfig, allErrors, allWarnings, {
1564
+ usePhase2Modules: options.usePhase2Modules,
1565
+ mode
1566
+ });
1567
+ }
1568
+ /**
1569
+ * Rebuild result from cache without recompiling anything.
1570
+ */
1571
+ rebuildFromCache(files, options) {
1572
+ let config = this.lastConfig;
1573
+ if (!config.slug) {
1574
+ for (const [filename, source] of Object.entries(files)) {
1575
+ if (isConfigFile(filename)) {
1576
+ config = parseConfig(source);
1577
+ this.lastConfig = config;
1578
+ break;
1579
+ }
1580
+ }
1581
+ }
1582
+ const fileIRs = {};
1583
+ const allErrors = [];
1584
+ const allWarnings = [];
1585
+ for (const cached of this.cache.getCachedFiles()) {
1586
+ const entry = this.cache.get(cached);
1587
+ if (entry) {
1588
+ fileIRs[cached] = entry.ir;
1589
+ for (const e of entry.errors) {
1590
+ if (e.severity === "error") allErrors.push(e);
1591
+ else allWarnings.push(e);
1592
+ }
1593
+ }
1594
+ }
1595
+ const mode = this.lastConfig.mode || options.mode || "infer";
1596
+ return buildComposedResult(files, fileIRs, config, allErrors, allWarnings, {
1597
+ usePhase2Modules: options.usePhase2Modules,
1598
+ mode
1599
+ });
1600
+ }
1601
+ /** Invalidate a specific file's cache. */
1602
+ invalidate(filename) {
1603
+ this.cache.delete(filename);
1604
+ }
1605
+ /** Invalidate all caches. */
1606
+ invalidateAll() {
1607
+ this.cache.clear();
1608
+ this.lastConfig = {};
1609
+ }
1610
+ /** Check if a file would need recompilation given its current source. */
1611
+ isDirty(filename, source) {
1612
+ const hash = hashContent(source);
1613
+ const cached = this.cache.get(filename);
1614
+ return !cached;
1615
+ }
1616
+ /** Get list of files currently in cache. */
1617
+ getCachedFiles() {
1618
+ return this.cache.getCachedFiles();
1619
+ }
1620
+ /** Get compilation statistics. */
1621
+ getStats() {
1622
+ const stats = this.cache.getStats();
1623
+ return {
1624
+ cachedFiles: stats.totalCached,
1625
+ totalHashes: stats.totalCached,
1626
+ ...stats
1627
+ };
1628
+ }
1629
+ };
1630
+
1631
+ export {
1632
+ compileModel,
1633
+ compileModels,
1634
+ extractRoutes,
1635
+ compileActions,
1636
+ resolveActionReferences,
1637
+ hashContent,
1638
+ extractImports,
1639
+ resolveImport,
1640
+ buildDependencyGraph,
1641
+ computeTransitiveDirtySet,
1642
+ topologicalSort,
1643
+ IncrementalCache,
1644
+ compileProject,
1645
+ IncrementalProjectCompiler
1646
+ };