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

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 (186) hide show
  1. package/dist/{chunk-UBDNXVL2.mjs → chunk-6LAII7OP.mjs} +82 -4
  2. package/dist/{chunk-GVCJJX7E.mjs → chunk-FPAMQXKB.mjs} +14 -18
  3. package/dist/{chunk-NUPJYPFU.mjs → chunk-GMW45YVD.mjs} +68 -1
  4. package/dist/cli/index.js +201 -72
  5. package/dist/cli/index.mjs +55 -8
  6. package/dist/dev-server.js +42 -65
  7. package/dist/dev-server.mjs +1 -1
  8. package/dist/index.js +42 -65
  9. package/dist/index.mjs +1 -1
  10. package/dist/{init-2CRSUGV5.mjs → init-CJCDWI33.mjs} +119 -0
  11. package/package.json +2 -2
  12. package/dist/chunk-26U577GB.mjs +0 -3465
  13. package/dist/chunk-2FBDFAX6.mjs +0 -2362
  14. package/dist/chunk-2L4QSMXG.mjs +0 -175
  15. package/dist/chunk-2REDFOER.mjs +0 -931
  16. package/dist/chunk-3USIFFE4.mjs +0 -2190
  17. package/dist/chunk-45YMGEVT.mjs +0 -186
  18. package/dist/chunk-46YKSHQR.mjs +0 -175
  19. package/dist/chunk-4FN2AISW.mjs +0 -148
  20. package/dist/chunk-4OPI5L7G.mjs +0 -2593
  21. package/dist/chunk-4RYTKOOJ.mjs +0 -186
  22. package/dist/chunk-4XHK6FWL.mjs +0 -2058
  23. package/dist/chunk-52XHYD2V.mjs +0 -214
  24. package/dist/chunk-5FTDWKHH.mjs +0 -244
  25. package/dist/chunk-5GUFFFGL.mjs +0 -148
  26. package/dist/chunk-5RKTOVR5.mjs +0 -244
  27. package/dist/chunk-5VNJ7C6N.mjs +0 -154
  28. package/dist/chunk-5YDMOO4X.mjs +0 -214
  29. package/dist/chunk-64ZWEMLJ.mjs +0 -148
  30. package/dist/chunk-6CQOAAMV.mjs +0 -1803
  31. package/dist/chunk-6SEVAAVT.mjs +0 -3516
  32. package/dist/chunk-6XP4KSWQ.mjs +0 -2190
  33. package/dist/chunk-6YLR5ZDA.mjs +0 -2829
  34. package/dist/chunk-72QWL54I.mjs +0 -175
  35. package/dist/chunk-7B4TRI7C.mjs +0 -4835
  36. package/dist/chunk-7JRAEFRB.mjs +0 -7510
  37. package/dist/chunk-7ZKGHTNB.mjs +0 -4952
  38. package/dist/chunk-AOGY2GK6.mjs +0 -3292
  39. package/dist/chunk-AXXUXRNA.mjs +0 -1434
  40. package/dist/chunk-CHLVKMQW.mjs +0 -175
  41. package/dist/chunk-CKGOZAB7.mjs +0 -939
  42. package/dist/chunk-D34RAZUX.mjs +0 -2223
  43. package/dist/chunk-DE3ZGQAC.mjs +0 -148
  44. package/dist/chunk-DMCY3BBG.mjs +0 -1933
  45. package/dist/chunk-DPIK3PJS.mjs +0 -244
  46. package/dist/chunk-E5IVH4RE.mjs +0 -186
  47. package/dist/chunk-E6FZNUR5.mjs +0 -4953
  48. package/dist/chunk-EJRBDQDP.mjs +0 -2607
  49. package/dist/chunk-ELO4TXJL.mjs +0 -186
  50. package/dist/chunk-EO6SYNCG.mjs +0 -175
  51. package/dist/chunk-EQGA6A6D.mjs +0 -121
  52. package/dist/chunk-EY2CSXYA.mjs +0 -822
  53. package/dist/chunk-FIQ65CDR.mjs +0 -925
  54. package/dist/chunk-FKRO52XH.mjs +0 -3446
  55. package/dist/chunk-FL4YAKU6.mjs +0 -4941
  56. package/dist/chunk-FOZXJFAR.mjs +0 -186
  57. package/dist/chunk-FX6URXWN.mjs +0 -186
  58. package/dist/chunk-FYT47UBU.mjs +0 -5076
  59. package/dist/chunk-G7SMOWOL.mjs +0 -828
  60. package/dist/chunk-GCLGPOJZ.mjs +0 -148
  61. package/dist/chunk-GGB4G5YY.mjs +0 -175
  62. package/dist/chunk-GXB4JOP7.mjs +0 -5072
  63. package/dist/chunk-HFXOUMTD.mjs +0 -175
  64. package/dist/chunk-HLRGCCIL.mjs +0 -4839
  65. package/dist/chunk-HOIUP6IF.mjs +0 -690
  66. package/dist/chunk-HRYR54PT.mjs +0 -175
  67. package/dist/chunk-HWIZ47US.mjs +0 -214
  68. package/dist/chunk-I3AU7GRD.mjs +0 -120
  69. package/dist/chunk-IB7MNPQL.mjs +0 -4953
  70. package/dist/chunk-ICSIHQCG.mjs +0 -148
  71. package/dist/chunk-ILFGMUVD.mjs +0 -1933
  72. package/dist/chunk-IPTX5MJU.mjs +0 -3223
  73. package/dist/chunk-ITGUSH2Z.mjs +0 -2783
  74. package/dist/chunk-IXHBCAMF.mjs +0 -3306
  75. package/dist/chunk-J7JUAHS4.mjs +0 -186
  76. package/dist/chunk-J7TWJ3TM.mjs +0 -2784
  77. package/dist/chunk-JDPLDGVF.mjs +0 -4810
  78. package/dist/chunk-JLA5VNQ3.mjs +0 -186
  79. package/dist/chunk-JQLWFCTM.mjs +0 -214
  80. package/dist/chunk-K53XP2DL.mjs +0 -148
  81. package/dist/chunk-K5HX2SVL.mjs +0 -1902
  82. package/dist/chunk-KFGYOOVS.mjs +0 -214
  83. package/dist/chunk-KFJJCQAL.mjs +0 -148
  84. package/dist/chunk-KFVVOS5N.mjs +0 -925
  85. package/dist/chunk-KJUIIEQE.mjs +0 -186
  86. package/dist/chunk-KNWTHRVQ.mjs +0 -175
  87. package/dist/chunk-KSG4XSZF.mjs +0 -175
  88. package/dist/chunk-L2OZ4CDV.mjs +0 -113
  89. package/dist/chunk-LF5N6DOU.mjs +0 -175
  90. package/dist/chunk-LJQCM2IM.mjs +0 -214
  91. package/dist/chunk-MIZV3TAN.mjs +0 -3293
  92. package/dist/chunk-NKKLQE5V.mjs +0 -148
  93. package/dist/chunk-NOW23XFZ.mjs +0 -186
  94. package/dist/chunk-NRXQKQ74.mjs +0 -148
  95. package/dist/chunk-NTB7OEX2.mjs +0 -2918
  96. package/dist/chunk-NW6555WJ.mjs +0 -186
  97. package/dist/chunk-O4AUS7EU.mjs +0 -148
  98. package/dist/chunk-OMZE6VLQ.mjs +0 -214
  99. package/dist/chunk-OPJKP747.mjs +0 -7506
  100. package/dist/chunk-OWI6XWCD.mjs +0 -3375
  101. package/dist/chunk-P4BR7WVO.mjs +0 -2190
  102. package/dist/chunk-PRUMNNDI.mjs +0 -3192
  103. package/dist/chunk-QQHVYH2X.mjs +0 -244
  104. package/dist/chunk-QTBD5B3F.mjs +0 -148
  105. package/dist/chunk-R57T26RR.mjs +0 -734
  106. package/dist/chunk-S5QLWLLT.mjs +0 -186
  107. package/dist/chunk-SCWGT2FY.mjs +0 -2190
  108. package/dist/chunk-SKSDPPNT.mjs +0 -3788
  109. package/dist/chunk-SMKJUSB3.mjs +0 -2190
  110. package/dist/chunk-SP2YUS33.mjs +0 -186
  111. package/dist/chunk-SU4E6E7B.mjs +0 -3153
  112. package/dist/chunk-SYUUKW5A.mjs +0 -3379
  113. package/dist/chunk-THFYE5ZX.mjs +0 -244
  114. package/dist/chunk-UDDTWG5J.mjs +0 -734
  115. package/dist/chunk-UL2XZEMA.mjs +0 -3128
  116. package/dist/chunk-VCAY2KGM.mjs +0 -175
  117. package/dist/chunk-VLTKQDJ3.mjs +0 -244
  118. package/dist/chunk-WBYMW4NQ.mjs +0 -3450
  119. package/dist/chunk-WECAV6QB.mjs +0 -148
  120. package/dist/chunk-WMKBXUCE.mjs +0 -3228
  121. package/dist/chunk-XAJ5BKKL.mjs +0 -4947
  122. package/dist/chunk-XG2X7AEA.mjs +0 -175
  123. package/dist/chunk-XG7Z23NQ.mjs +0 -148
  124. package/dist/chunk-XMWUHQVV.mjs +0 -939
  125. package/dist/chunk-XWZAOCQ7.mjs +0 -2607
  126. package/dist/chunk-XZNEDRGN.mjs +0 -3876
  127. package/dist/chunk-Y6FXYEAI.mjs +0 -10
  128. package/dist/chunk-Y6MA7ULW.mjs +0 -148
  129. package/dist/chunk-YFS6JMYO.mjs +0 -3342
  130. package/dist/chunk-YMS7Q7LG.mjs +0 -214
  131. package/dist/chunk-Z2G5RZ4H.mjs +0 -186
  132. package/dist/chunk-Z6AIQ4KL.mjs +0 -113
  133. package/dist/chunk-ZA37XTGA.mjs +0 -175
  134. package/dist/chunk-ZE3KCHBM.mjs +0 -2918
  135. package/dist/config-PL24KEWL.mjs +0 -219
  136. package/dist/dev-server-Bs_sz2DG.d.mts +0 -111
  137. package/dist/dev-server-Bs_sz2DG.d.ts +0 -111
  138. package/dist/dev-server-CjoufJ-u.d.mts +0 -109
  139. package/dist/dev-server-CjoufJ-u.d.ts +0 -109
  140. package/dist/dev-server-RmGHIntF.d.mts +0 -113
  141. package/dist/dev-server-RmGHIntF.d.ts +0 -113
  142. package/dist/engine-binary-QQUDACBJ.mjs +0 -455
  143. package/dist/envelope-DD7v0v6E.d.mts +0 -265
  144. package/dist/envelope-DD7v0v6E.d.ts +0 -265
  145. package/dist/envelope-vCVjrHlo.d.mts +0 -265
  146. package/dist/envelope-vCVjrHlo.d.ts +0 -265
  147. package/dist/index-B5gSgvnd.d.mts +0 -44
  148. package/dist/index-B5gSgvnd.d.ts +0 -44
  149. package/dist/index-Bs0MnR54.d.mts +0 -103
  150. package/dist/index-Bs0MnR54.d.ts +0 -103
  151. package/dist/index-DR0nNc_f.d.mts +0 -101
  152. package/dist/index-DR0nNc_f.d.ts +0 -101
  153. package/dist/index-revho_gS.d.mts +0 -104
  154. package/dist/index-revho_gS.d.ts +0 -104
  155. package/dist/init-7FJENUDK.mjs +0 -407
  156. package/dist/init-7JQMAAXS.mjs +0 -363
  157. package/dist/init-DQDX3QK6.mjs +0 -369
  158. package/dist/init-EHO4VQ22.mjs +0 -369
  159. package/dist/init-IXEE2RCF.mjs +0 -340
  160. package/dist/init-UC3FWPIW.mjs +0 -367
  161. package/dist/init-UNSMVKIK.mjs +0 -366
  162. package/dist/init-UNV5XIDE.mjs +0 -367
  163. package/dist/project-compiler-2P4N4DR7.mjs +0 -10
  164. package/dist/project-compiler-D2LCC27O.mjs +0 -10
  165. package/dist/project-compiler-EGJUTAJU.mjs +0 -10
  166. package/dist/project-compiler-EJ3GANJE.mjs +0 -10
  167. package/dist/project-compiler-LOQKVRZJ.mjs +0 -10
  168. package/dist/project-compiler-NNK32MPG.mjs +0 -10
  169. package/dist/project-compiler-OP2VVGJQ.mjs +0 -10
  170. package/dist/project-compiler-RQ6OQKRM.mjs +0 -10
  171. package/dist/project-compiler-VFR6CSDX.mjs +0 -10
  172. package/dist/project-compiler-VWNNCHGO.mjs +0 -10
  173. package/dist/project-compiler-XVAAU4C5.mjs +0 -10
  174. package/dist/project-compiler-YES5FGMD.mjs +0 -10
  175. package/dist/project-compiler-ZKMQDLGU.mjs +0 -10
  176. package/dist/project-decompiler-5GY2KSG4.mjs +0 -7
  177. package/dist/project-decompiler-FLXCEJHS.mjs +0 -7
  178. package/dist/project-decompiler-US7GAVIC.mjs +0 -7
  179. package/dist/project-decompiler-VLPR22QF.mjs +0 -7
  180. package/dist/pull-A2QUHW4K.mjs +0 -109
  181. package/dist/pull-FUS5QYZS.mjs +0 -109
  182. package/dist/pull-JBEQWVPE.mjs +0 -109
  183. package/dist/pull-LD5ENLGY.mjs +0 -109
  184. package/dist/pull-P44LDRWB.mjs +0 -109
  185. package/dist/verify-BYHUKARQ.mjs +0 -1833
  186. package/dist/verify-SEIXUGN4.mjs +0 -1833
@@ -1,4952 +0,0 @@
1
- // src/babel/visitor.ts
2
- import * as t17 from "@babel/types";
3
-
4
- // src/babel/extractors/state-extractor.ts
5
- import * as t from "@babel/types";
6
- var KNOWN_TYPE_REFS = {
7
- Date: "date",
8
- URL: "url",
9
- Record: "json",
10
- Map: "json",
11
- Set: "json"
12
- };
13
- function typeNameToSlug(name) {
14
- return name.replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
15
- }
16
- function resolveSingleType(annotation) {
17
- if (t.isTSNumberKeyword(annotation)) return "number";
18
- if (t.isTSStringKeyword(annotation)) return "text";
19
- if (t.isTSBooleanKeyword(annotation)) return "boolean";
20
- if (t.isTSTypeReference(annotation)) {
21
- const typeName = t.isIdentifier(annotation.typeName) ? annotation.typeName.name : "";
22
- if (typeName === "Array") return "multi_select";
23
- if (typeName && KNOWN_TYPE_REFS[typeName]) return KNOWN_TYPE_REFS[typeName];
24
- if (typeName) return typeNameToSlug(typeName);
25
- }
26
- if (t.isTSArrayType(annotation)) return "multi_select";
27
- if (t.isTSTypeLiteral(annotation) || t.isTSTupleType(annotation)) return "json";
28
- return null;
29
- }
30
- function inferFieldType(typeAnnotation, defaultValue) {
31
- if (typeAnnotation) {
32
- if (t.isTSUnionType(typeAnnotation)) {
33
- const allStringLiterals = typeAnnotation.types.every(
34
- (m) => t.isTSLiteralType(m) && t.isStringLiteral(m.literal)
35
- );
36
- if (allStringLiterals) return "select";
37
- const nonNullMembers = typeAnnotation.types.filter(
38
- (m) => !t.isTSNullKeyword(m) && !t.isTSUndefinedKeyword(m)
39
- );
40
- const allLiteralsExceptNull = nonNullMembers.every(
41
- (m) => t.isTSLiteralType(m) && t.isStringLiteral(m.literal)
42
- );
43
- if (allLiteralsExceptNull && nonNullMembers.length > 0) return "select";
44
- if (nonNullMembers.length === 1) {
45
- const resolved2 = resolveSingleType(nonNullMembers[0]);
46
- if (resolved2) return resolved2;
47
- }
48
- if (nonNullMembers.length > 1) return "json";
49
- }
50
- const resolved = resolveSingleType(typeAnnotation);
51
- if (resolved) return resolved;
52
- }
53
- if (defaultValue) {
54
- if (t.isNumericLiteral(defaultValue)) return "number";
55
- if (t.isStringLiteral(defaultValue)) return "text";
56
- if (t.isBooleanLiteral(defaultValue)) return "boolean";
57
- if (t.isArrayExpression(defaultValue)) return "json";
58
- if (t.isObjectExpression(defaultValue)) return "json";
59
- if (t.isNewExpression(defaultValue) && t.isIdentifier(defaultValue.callee)) {
60
- if (defaultValue.callee.name === "Date") return "date";
61
- }
62
- }
63
- return "text";
64
- }
65
- function extractDefaultValue(arg) {
66
- if (t.isNumericLiteral(arg)) return arg.value;
67
- if (t.isStringLiteral(arg)) return arg.value;
68
- if (t.isBooleanLiteral(arg)) return arg.value;
69
- if (t.isNullLiteral(arg)) return null;
70
- if (t.isArrayExpression(arg)) {
71
- return arg.elements.map(
72
- (el) => el && t.isExpression(el) ? extractDefaultValue(el) : null
73
- );
74
- }
75
- if (t.isObjectExpression(arg)) {
76
- const obj = {};
77
- arg.properties.forEach((prop) => {
78
- if (t.isObjectProperty(prop) && t.isIdentifier(prop.key) && t.isExpression(prop.value)) {
79
- obj[prop.key.name] = extractDefaultValue(prop.value);
80
- }
81
- });
82
- return obj;
83
- }
84
- return void 0;
85
- }
86
- function extractStates(path, state) {
87
- const parent = path.parentPath;
88
- if (!parent.isVariableDeclarator()) return;
89
- const id = parent.node.id;
90
- if (!t.isArrayPattern(id) || id.elements.length < 1) return;
91
- const firstElement = id.elements[0];
92
- if (!t.isIdentifier(firstElement)) return;
93
- const fieldName = firstElement.name;
94
- const args = path.node.arguments;
95
- const defaultValue = args.length > 0 && t.isExpression(args[0]) ? args[0] : null;
96
- let typeAnnotation = null;
97
- if (path.node.typeParameters && t.isTSTypeParameterInstantiation(path.node.typeParameters)) {
98
- const params = path.node.typeParameters.params;
99
- if (params.length > 0) {
100
- typeAnnotation = params[0];
101
- }
102
- }
103
- const fieldType = inferFieldType(typeAnnotation, defaultValue);
104
- const fieldDefaultValue = defaultValue ? extractDefaultValue(defaultValue) : void 0;
105
- const field = {
106
- name: fieldName,
107
- type: fieldType,
108
- default_value: fieldDefaultValue
109
- };
110
- if (fieldType === "select" && typeAnnotation && t.isTSUnionType(typeAnnotation)) {
111
- const options = typeAnnotation.types.filter((m) => t.isTSLiteralType(m) && t.isStringLiteral(m.literal)).map((m) => m.literal.value);
112
- if (options.length > 0) {
113
- field.validation = { options };
114
- }
115
- }
116
- const compilerState = state;
117
- if (!compilerState.fields) compilerState.fields = [];
118
- if (!compilerState.fields.some((f) => f.name === fieldName)) {
119
- compilerState.fields.push(field);
120
- }
121
- }
122
-
123
- // src/babel/extractors/effect-extractor.ts
124
- import * as t2 from "@babel/types";
125
- function analyzeCallbackBody(body, actionCounter) {
126
- const actions = [];
127
- for (const statement of body) {
128
- if (t2.isExpressionStatement(statement)) {
129
- const expr = statement.expression;
130
- if (t2.isCallExpression(expr) && t2.isIdentifier(expr.callee)) {
131
- const calleeName = expr.callee.name;
132
- const args = expr.arguments;
133
- if (calleeName === "setField" && args.length >= 2) {
134
- const field = t2.isStringLiteral(args[0]) ? args[0].value : void 0;
135
- const arg1 = args[1];
136
- if (field !== void 0 && !t2.isArgumentPlaceholder(arg1)) {
137
- const value = extractValue(arg1);
138
- actions.push({
139
- id: `auto_${++actionCounter.value}`,
140
- type: "set_field",
141
- mode: "auto",
142
- config: { field, value }
143
- });
144
- }
145
- } else if (calleeName === "setMemory" && args.length >= 2) {
146
- const key = t2.isStringLiteral(args[0]) ? args[0].value : void 0;
147
- const arg1 = args[1];
148
- if (key !== void 0 && !t2.isArgumentPlaceholder(arg1)) {
149
- const value = extractValue(arg1);
150
- actions.push({
151
- id: `auto_${++actionCounter.value}`,
152
- type: "set_memory",
153
- mode: "auto",
154
- config: { key, value }
155
- });
156
- }
157
- } else if (calleeName.startsWith("set") && args.length >= 1) {
158
- const fieldName = calleeName.slice(3).charAt(0).toLowerCase() + calleeName.slice(4);
159
- const arg0 = args[0];
160
- if (!t2.isArgumentPlaceholder(arg0)) {
161
- const value = extractValue(arg0);
162
- actions.push({
163
- id: `auto_${++actionCounter.value}`,
164
- type: "set_field",
165
- mode: "auto",
166
- config: { field: fieldName, value }
167
- });
168
- }
169
- }
170
- } else if (t2.isCallExpression(expr)) {
171
- const callee = expr.callee;
172
- const args = expr.arguments;
173
- if (t2.isMemberExpression(callee) && t2.isIdentifier(callee.object) && callee.object.name === "console" && t2.isIdentifier(callee.property) && callee.property.name === "log" && args.length > 0) {
174
- const arg0 = args[0];
175
- if (!t2.isArgumentPlaceholder(arg0)) {
176
- const message = extractValue(arg0);
177
- actions.push({
178
- id: `auto_${++actionCounter.value}`,
179
- type: "log_event",
180
- mode: "auto",
181
- config: { message }
182
- });
183
- }
184
- } else {
185
- actions.push({
186
- id: `auto_${++actionCounter.value}`,
187
- type: "custom",
188
- mode: "auto",
189
- config: { expression: generateCode(expr) }
190
- });
191
- }
192
- }
193
- }
194
- }
195
- return actions;
196
- }
197
- function extractValue(node) {
198
- if (t2.isNumericLiteral(node)) return node.value;
199
- if (t2.isStringLiteral(node)) return node.value;
200
- if (t2.isBooleanLiteral(node)) return node.value;
201
- if (t2.isNullLiteral(node)) return null;
202
- if (t2.isArrayExpression(node)) {
203
- return node.elements.map((el) => el && t2.isExpression(el) ? extractValue(el) : null);
204
- }
205
- if (t2.isObjectExpression(node)) {
206
- const obj = {};
207
- node.properties.forEach((prop) => {
208
- if (t2.isObjectProperty(prop) && t2.isIdentifier(prop.key) && t2.isExpression(prop.value)) {
209
- obj[prop.key.name] = extractValue(prop.value);
210
- }
211
- });
212
- return obj;
213
- }
214
- return generateCode(node);
215
- }
216
- function generateCode(node) {
217
- if (t2.isIdentifier(node)) return node.name;
218
- if (t2.isNumericLiteral(node)) return String(node.value);
219
- if (t2.isStringLiteral(node)) return `"${node.value}"`;
220
- if (t2.isBooleanLiteral(node)) return String(node.value);
221
- if (t2.isNullLiteral(node)) return "null";
222
- if (t2.isCallExpression(node) && t2.isMemberExpression(node.callee) && t2.isIdentifier(node.callee.object) && node.callee.object.name === "Date" && t2.isIdentifier(node.callee.property) && node.callee.property.name === "now") {
223
- return "now()";
224
- }
225
- if (t2.isCallExpression(node) && t2.isMemberExpression(node.callee) && t2.isNewExpression(node.callee.object) && t2.isIdentifier(node.callee.object.callee) && node.callee.object.callee.name === "Date" && t2.isIdentifier(node.callee.property) && node.callee.property.name === "toISOString") {
226
- return "now()";
227
- }
228
- if (t2.isBinaryExpression(node)) {
229
- return `(${generateCode(node.left)} ${node.operator} ${generateCode(node.right)})`;
230
- }
231
- if (t2.isLogicalExpression(node)) {
232
- return `(${generateCode(node.left)} ${node.operator} ${generateCode(node.right)})`;
233
- }
234
- if (t2.isConditionalExpression(node)) {
235
- return `(${generateCode(node.test)} ? ${generateCode(node.consequent)} : ${generateCode(node.alternate)})`;
236
- }
237
- if (t2.isUnaryExpression(node) && node.prefix) {
238
- return `${node.operator}${generateCode(node.argument)}`;
239
- }
240
- if (t2.isTemplateLiteral(node)) {
241
- return node.quasis.map((q, i) => {
242
- const raw = q.value.raw;
243
- if (i < node.expressions.length) return raw + "${" + generateCode(node.expressions[i]) + "}";
244
- return raw;
245
- }).join("");
246
- }
247
- if (t2.isMemberExpression(node)) {
248
- const obj = generateCode(node.object);
249
- if (node.computed) {
250
- return `${obj}[${generateCode(node.property)}]`;
251
- }
252
- const prop = t2.isIdentifier(node.property) ? node.property.name : "[property]";
253
- return `${obj}.${prop}`;
254
- }
255
- if (t2.isCallExpression(node)) {
256
- if (t2.isIdentifier(node.callee)) {
257
- const args = node.arguments.map((a) => generateCode(a)).join(", ");
258
- return `${node.callee.name}(${args})`;
259
- }
260
- if (t2.isMemberExpression(node.callee)) {
261
- const obj = generateCode(node.callee.object);
262
- const prop = t2.isIdentifier(node.callee.property) ? node.callee.property.name : "[method]";
263
- const args = node.arguments.map((a) => generateCode(a)).join(", ");
264
- return `${obj}.${prop}(${args})`;
265
- }
266
- }
267
- if (t2.isArrowFunctionExpression(node)) {
268
- if (t2.isExpression(node.body)) {
269
- const params = node.params;
270
- if (params.length === 1 && t2.isIdentifier(params[0])) {
271
- const paramName = params[0].name;
272
- const bodyCode = generateCode(node.body);
273
- return bodyCode.replace(new RegExp(`\\b${paramName}\\b`, "g"), "$prev");
274
- }
275
- }
276
- return "[Function]";
277
- }
278
- if (t2.isFunctionExpression(node)) return "[Function]";
279
- if (t2.isArrayExpression(node)) {
280
- const elements = node.elements.map((el) => el ? generateCode(el) : "undefined").join(", ");
281
- return `[${elements}]`;
282
- }
283
- if (t2.isObjectExpression(node)) {
284
- const props = node.properties.map((p) => {
285
- if (t2.isObjectProperty(p)) {
286
- const key = t2.isIdentifier(p.key) ? p.key.name : t2.isStringLiteral(p.key) ? `"${p.key.value}"` : "[key]";
287
- if (p.shorthand && t2.isIdentifier(p.value)) return key;
288
- return `${key}: ${generateCode(p.value)}`;
289
- }
290
- if (t2.isSpreadElement(p)) return `...${generateCode(p.argument)}`;
291
- return "";
292
- }).filter(Boolean).join(", ");
293
- return `{ ${props} }`;
294
- }
295
- if (t2.isTSAsExpression(node)) return generateCode(node.expression);
296
- if (t2.isTSNonNullExpression(node)) return generateCode(node.expression);
297
- return "[Expression]";
298
- }
299
- function ensureState(states, stateName) {
300
- if (!states.has(stateName)) {
301
- states.set(stateName, {
302
- name: stateName,
303
- type: "REGULAR",
304
- on_enter: [],
305
- during: [],
306
- on_exit: []
307
- });
308
- }
309
- return states.get(stateName);
310
- }
311
- function extractEffects(path, state) {
312
- const callee = path.node.callee;
313
- if (!t2.isIdentifier(callee)) return;
314
- const hookName = callee.name;
315
- const args = path.node.arguments;
316
- if ((hookName === "useOnEnter" || hookName === "useOnExit") && args.length >= 2) {
317
- const stateArg = args[0];
318
- const callbackArg = args[1];
319
- if (!t2.isStringLiteral(stateArg)) return;
320
- const stateName = stateArg.value;
321
- let callbackBody = [];
322
- if (t2.isArrowFunctionExpression(callbackArg) || t2.isFunctionExpression(callbackArg)) {
323
- const body = callbackArg.body;
324
- if (t2.isBlockStatement(body)) {
325
- callbackBody = body.body;
326
- } else if (t2.isExpression(body)) {
327
- callbackBody = [t2.expressionStatement(body)];
328
- }
329
- }
330
- const compilerState = state;
331
- if (!compilerState.states) compilerState.states = /* @__PURE__ */ new Map();
332
- if (!compilerState.actionCounter) compilerState.actionCounter = 0;
333
- const stateDefinition = ensureState(compilerState.states, stateName);
334
- const actions = analyzeCallbackBody(callbackBody, { value: compilerState.actionCounter });
335
- compilerState.actionCounter += actions.length;
336
- if (hookName === "useOnEnter") {
337
- stateDefinition.on_enter.push(...actions);
338
- } else if (hookName === "useOnExit") {
339
- stateDefinition.on_exit.push(...actions);
340
- }
341
- }
342
- }
343
-
344
- // src/babel/extractors/transition-extractor.ts
345
- import * as t3 from "@babel/types";
346
- function extractTransitions(path, state) {
347
- const callee = path.node.callee;
348
- if (!t3.isIdentifier(callee) || callee.name !== "useTransition") return;
349
- const args = path.node.arguments;
350
- if (args.length < 1) return;
351
- const nameArg = args[0];
352
- if (!t3.isStringLiteral(nameArg)) return;
353
- const transitionName = nameArg.value;
354
- const compilerState = state;
355
- if (!compilerState.transitions) compilerState.transitions = [];
356
- const existing = compilerState.transitions.find((tr) => tr.name === transitionName);
357
- if (existing) return;
358
- let from = [];
359
- let to = "";
360
- let roles;
361
- let requiredFields;
362
- let auto;
363
- if (args.length >= 2 && t3.isObjectExpression(args[1])) {
364
- const opts = args[1];
365
- for (const prop of opts.properties) {
366
- if (!t3.isObjectProperty(prop) || !t3.isIdentifier(prop.key)) continue;
367
- if (prop.key.name === "from") {
368
- if (t3.isArrayExpression(prop.value)) {
369
- from = prop.value.elements.filter((el) => t3.isStringLiteral(el)).map((el) => el.value);
370
- } else if (t3.isStringLiteral(prop.value)) {
371
- from = [prop.value.value];
372
- }
373
- } else if (prop.key.name === "to") {
374
- if (t3.isStringLiteral(prop.value)) {
375
- to = prop.value.value;
376
- }
377
- } else if (prop.key.name === "roles") {
378
- if (t3.isArrayExpression(prop.value)) {
379
- roles = prop.value.elements.filter((el) => t3.isStringLiteral(el)).map((el) => el.value);
380
- }
381
- } else if (prop.key.name === "requiredFields") {
382
- if (t3.isArrayExpression(prop.value)) {
383
- requiredFields = prop.value.elements.filter((el) => t3.isStringLiteral(el)).map((el) => el.value);
384
- }
385
- } else if (prop.key.name === "auto") {
386
- if (t3.isBooleanLiteral(prop.value)) {
387
- auto = prop.value.value;
388
- }
389
- }
390
- }
391
- }
392
- const transition = {
393
- name: transitionName,
394
- from,
395
- to,
396
- actions: [],
397
- conditions: [],
398
- ...roles && roles.length > 0 && { roles },
399
- ...requiredFields && requiredFields.length > 0 && { required_fields: requiredFields },
400
- ...auto !== void 0 && { auto }
401
- };
402
- compilerState.transitions.push(transition);
403
- }
404
- function inferTransitionStates(transitions, states) {
405
- const stateArray = Array.from(states.values());
406
- const startStates = stateArray.filter((s) => s.type === "START");
407
- const regularStates = stateArray.filter((s) => s.type === "REGULAR");
408
- const needsInference = transitions.filter((t18) => t18.from.length === 0 || !t18.to);
409
- if (needsInference.length === 0) return;
410
- if (startStates.length === 1 && regularStates.length > 0) {
411
- needsInference.forEach((t18, idx) => {
412
- if (t18.from.length === 0) {
413
- t18.from = [startStates[0].name];
414
- }
415
- if (!t18.to) {
416
- t18.to = regularStates[idx % regularStates.length]?.name || startStates[0].name;
417
- }
418
- });
419
- } else {
420
- const allStateNames = stateArray.map((s) => s.name);
421
- needsInference.forEach((t18, idx) => {
422
- if (t18.from.length === 0 && allStateNames.length > 0) {
423
- t18.from = [allStateNames[0]];
424
- }
425
- if (!t18.to && allStateNames.length > 1) {
426
- t18.to = allStateNames[Math.min(idx + 1, allStateNames.length - 1)];
427
- }
428
- });
429
- }
430
- }
431
-
432
- // src/babel/extractors/event-extractor.ts
433
- import * as t4 from "@babel/types";
434
- function analyzeEventCallback(body) {
435
- const actions = [];
436
- for (const statement of body) {
437
- if (t4.isExpressionStatement(statement)) {
438
- const expr = statement.expression;
439
- if (t4.isCallExpression(expr) && t4.isIdentifier(expr.callee)) {
440
- const calleeName = expr.callee.name;
441
- const args = expr.arguments;
442
- if (calleeName === "setField" && args.length >= 2) {
443
- const field = t4.isStringLiteral(args[0]) ? args[0].value : void 0;
444
- const expression = generateExpression(args[1]);
445
- if (field) {
446
- actions.push({
447
- type: "set_field",
448
- field,
449
- expression
450
- });
451
- }
452
- } else if (calleeName === "setMemory" && args.length >= 2) {
453
- const key = t4.isStringLiteral(args[0]) ? args[0].value : void 0;
454
- const expression = generateExpression(args[1]);
455
- if (key) {
456
- actions.push({
457
- type: "set_memory",
458
- key,
459
- expression
460
- });
461
- }
462
- }
463
- } else if (t4.isCallExpression(expr)) {
464
- const callee = expr.callee;
465
- const args = expr.arguments;
466
- if (t4.isMemberExpression(callee) && t4.isIdentifier(callee.object) && callee.object.name === "console" && t4.isIdentifier(callee.property) && callee.property.name === "log") {
467
- const message = args.length > 0 ? generateExpression(args[0]) : "";
468
- actions.push({
469
- type: "log_event",
470
- message
471
- });
472
- }
473
- }
474
- }
475
- }
476
- return actions;
477
- }
478
- function generateExpression(node) {
479
- if (t4.isStringLiteral(node)) return node.value;
480
- if (t4.isNumericLiteral(node)) return String(node.value);
481
- if (t4.isBooleanLiteral(node)) return String(node.value);
482
- if (t4.isNullLiteral(node)) return "null";
483
- if (t4.isIdentifier(node)) return node.name;
484
- if (t4.isBinaryExpression(node)) {
485
- return `(${generateExpression(node.left)} ${node.operator} ${generateExpression(node.right)})`;
486
- }
487
- if (t4.isLogicalExpression(node)) {
488
- return `(${generateExpression(node.left)} ${node.operator} ${generateExpression(node.right)})`;
489
- }
490
- if (t4.isConditionalExpression(node)) {
491
- return `(${generateExpression(node.test)} ? ${generateExpression(node.consequent)} : ${generateExpression(node.alternate)})`;
492
- }
493
- if (t4.isUnaryExpression(node) && node.prefix) {
494
- return `${node.operator}${generateExpression(node.argument)}`;
495
- }
496
- if (t4.isCallExpression(node) && t4.isIdentifier(node.callee)) {
497
- const args = node.arguments.map((arg) => generateExpression(arg)).join(", ");
498
- return `${node.callee.name}(${args})`;
499
- }
500
- if (t4.isCallExpression(node) && t4.isMemberExpression(node.callee)) {
501
- const obj = generateExpression(node.callee.object);
502
- const prop = t4.isIdentifier(node.callee.property) ? node.callee.property.name : "[method]";
503
- const args = node.arguments.map((arg) => generateExpression(arg)).join(", ");
504
- return `${obj}.${prop}(${args})`;
505
- }
506
- if (t4.isMemberExpression(node)) {
507
- const obj = generateExpression(node.object);
508
- if (node.computed) {
509
- const prop2 = generateExpression(node.property);
510
- return `${obj}[${prop2}]`;
511
- }
512
- const prop = t4.isIdentifier(node.property) ? node.property.name : "[property]";
513
- return `${obj}.${prop}`;
514
- }
515
- if (t4.isTemplateLiteral(node)) {
516
- return node.quasis.map((q, i) => {
517
- const raw = q.value.raw;
518
- if (i < node.expressions.length) return raw + "${" + generateExpression(node.expressions[i]) + "}";
519
- return raw;
520
- }).join("");
521
- }
522
- if (t4.isArrayExpression(node)) {
523
- const elements = node.elements.map((el) => el ? generateExpression(el) : "undefined").join(", ");
524
- return `[${elements}]`;
525
- }
526
- if (t4.isObjectExpression(node)) {
527
- const props = node.properties.map((p) => {
528
- if (t4.isObjectProperty(p)) {
529
- const key = t4.isIdentifier(p.key) ? p.key.name : t4.isStringLiteral(p.key) ? `"${p.key.value}"` : "[key]";
530
- if (p.shorthand && t4.isIdentifier(p.value)) return key;
531
- return `${key}: ${generateExpression(p.value)}`;
532
- }
533
- if (t4.isSpreadElement(p)) return `...${generateExpression(p.argument)}`;
534
- return "";
535
- }).filter(Boolean).join(", ");
536
- return `{ ${props} }`;
537
- }
538
- if (t4.isTSAsExpression(node)) return generateExpression(node.expression);
539
- if (t4.isTSNonNullExpression(node)) return generateExpression(node.expression);
540
- return "[Expression]";
541
- }
542
- function ensureState2(states, stateName) {
543
- if (!states.has(stateName)) {
544
- states.set(stateName, {
545
- name: stateName,
546
- type: "REGULAR",
547
- on_enter: [],
548
- during: [],
549
- on_exit: []
550
- });
551
- }
552
- return states.get(stateName);
553
- }
554
- function extractEvents(path, state) {
555
- const callee = path.node.callee;
556
- if (!t4.isIdentifier(callee) || callee.name !== "useOnEvent") return;
557
- const args = path.node.arguments;
558
- if (args.length < 2) return;
559
- const patternArg = args[0];
560
- const callbackArg = args[1];
561
- const optionsArg = args.length > 2 ? args[2] : null;
562
- if (!t4.isStringLiteral(patternArg)) return;
563
- const pattern = patternArg.value;
564
- let callbackBody = [];
565
- if (t4.isArrowFunctionExpression(callbackArg) || t4.isFunctionExpression(callbackArg)) {
566
- const body = callbackArg.body;
567
- if (t4.isBlockStatement(body)) {
568
- callbackBody = body.body;
569
- } else if (t4.isExpression(body)) {
570
- callbackBody = [t4.expressionStatement(body)];
571
- }
572
- }
573
- let stateName = null;
574
- if (optionsArg && t4.isObjectExpression(optionsArg)) {
575
- const whileProp = optionsArg.properties.find(
576
- (prop) => t4.isObjectProperty(prop) && t4.isIdentifier(prop.key) && prop.key.name === "while"
577
- );
578
- if (whileProp && t4.isObjectProperty(whileProp) && t4.isStringLiteral(whileProp.value)) {
579
- stateName = whileProp.value.value;
580
- }
581
- }
582
- const actions = analyzeEventCallback(callbackBody);
583
- const subscription = {
584
- match: pattern,
585
- conditions: [],
586
- actions
587
- };
588
- const compilerState = state;
589
- if (!compilerState.states) compilerState.states = /* @__PURE__ */ new Map();
590
- if (stateName) {
591
- const stateDefinition = ensureState2(compilerState.states, stateName);
592
- if (!stateDefinition.on_event) stateDefinition.on_event = [];
593
- stateDefinition.on_event.push(subscription);
594
- } else {
595
- if (!compilerState.events) compilerState.events = [];
596
- compilerState.events.push(subscription);
597
- }
598
- }
599
-
600
- // src/babel/extractors/component-extractor.ts
601
- import * as t6 from "@babel/types";
602
-
603
- // src/babel/transpilers/ts-to-expression.ts
604
- import * as t5 from "@babel/types";
605
- function transpileExpression(node, options = {}) {
606
- const ctx = new TranspileContext(options);
607
- const expr = ctx.visit(node);
608
- return { expression: expr, pure: ctx.isPure };
609
- }
610
- function transpileBlock(node, options = {}) {
611
- const ctx = new TranspileContext(options);
612
- const lines = visitStatements(node.body, ctx);
613
- return { expression: lines, pure: ctx.isPure };
614
- }
615
- function visitStatements(stmts, ctx) {
616
- return stmts.map((s) => visitStatement(s, ctx)).join("\n");
617
- }
618
- function visitStatement(stmt, ctx) {
619
- if (t5.isVariableDeclaration(stmt)) {
620
- const keyword = stmt.kind === "const" ? "const" : stmt.kind === "let" ? "let" : "let";
621
- const decls = stmt.declarations.map((d) => {
622
- const init = d.init ? ctx.visit(d.init) : "null";
623
- const lhs = declaratorPattern(d.id);
624
- return `${keyword} ${lhs} = ${init}`;
625
- });
626
- return decls.join(";\n") + ";";
627
- }
628
- if (t5.isIfStatement(stmt)) {
629
- const test = ctx.visit(stmt.test);
630
- const consequent = visitBranchBody(stmt.consequent, ctx);
631
- if (stmt.alternate) {
632
- const alternate = visitBranchBody(stmt.alternate, ctx);
633
- return `if (${test}) ${consequent} else ${alternate}`;
634
- }
635
- return `if (${test}) ${consequent}`;
636
- }
637
- if (t5.isForOfStatement(stmt)) {
638
- const right = ctx.visit(stmt.right);
639
- const varName = forOfPattern(stmt.left);
640
- const body = visitBranchBody(stmt.body, ctx);
641
- return `for (const ${varName} of ${right}) ${body}`;
642
- }
643
- if (t5.isWhileStatement(stmt)) {
644
- const test = ctx.visit(stmt.test);
645
- const body = visitBranchBody(stmt.body, ctx);
646
- return `while (${test}) ${body}`;
647
- }
648
- if (t5.isReturnStatement(stmt)) {
649
- if (!stmt.argument) return "return;";
650
- return `return ${ctx.visit(stmt.argument)};`;
651
- }
652
- if (t5.isExpressionStatement(stmt)) {
653
- return ctx.visit(stmt.expression) + ";";
654
- }
655
- if (t5.isBlockStatement(stmt)) {
656
- const inner = visitStatements(stmt.body, ctx);
657
- return `{
658
- ${indent(inner)}
659
- }`;
660
- }
661
- if (t5.isFunctionDeclaration(stmt) && stmt.id) {
662
- const name = stmt.id.name;
663
- const params = stmt.params.map((p) => t5.isIdentifier(p) ? p.name : "_").join(", ");
664
- const body = visitStatements(stmt.body.body, ctx);
665
- return `function ${name}(${params}) {
666
- ${indent(body)}
667
- }`;
668
- }
669
- return ctx.opaque(`[${stmt.type}]`) + ";";
670
- }
671
- function visitBranchBody(node, ctx) {
672
- if (t5.isBlockStatement(node)) {
673
- const inner2 = visitStatements(node.body, ctx);
674
- return `{
675
- ${indent(inner2)}
676
- }`;
677
- }
678
- const inner = visitStatement(node, ctx);
679
- return `{
680
- ${indent(inner)}
681
- }`;
682
- }
683
- function declaratorPattern(node) {
684
- if (t5.isIdentifier(node)) return node.name;
685
- if (t5.isObjectPattern(node)) {
686
- const props = node.properties.map((p) => {
687
- if (t5.isRestElement(p)) {
688
- return `...${t5.isIdentifier(p.argument) ? p.argument.name : "_"}`;
689
- }
690
- if (t5.isObjectProperty(p)) {
691
- const key = t5.isIdentifier(p.key) ? p.key.name : "_";
692
- const val = t5.isIdentifier(p.value) ? p.value.name : t5.isAssignmentPattern(p.value) && t5.isIdentifier(p.value.left) ? p.value.left.name : "_";
693
- return key === val ? key : `${key}: ${val}`;
694
- }
695
- return "_";
696
- });
697
- return `{ ${props.join(", ")} }`;
698
- }
699
- if (t5.isArrayPattern(node)) {
700
- const elems = node.elements.map(
701
- (e) => e === null ? "" : t5.isIdentifier(e) ? e.name : "_"
702
- );
703
- return `[${elems.join(", ")}]`;
704
- }
705
- return "_";
706
- }
707
- function forOfPattern(left) {
708
- if (t5.isVariableDeclaration(left)) {
709
- const d = left.declarations[0];
710
- if (d) return declaratorPattern(d.id);
711
- }
712
- if (t5.isIdentifier(left)) return left.name;
713
- return "_";
714
- }
715
- function indent(code) {
716
- return code.split("\n").map((l) => " " + l).join("\n");
717
- }
718
- var TranspileContext = class {
719
- constructor(options) {
720
- this.isPure = true;
721
- this.localFieldMap = options.localFieldMap ?? /* @__PURE__ */ new Map();
722
- this.derivedVarMap = options.derivedVarMap ?? /* @__PURE__ */ new Map();
723
- this.setterToFieldMap = options.setterToFieldMap ?? /* @__PURE__ */ new Map();
724
- }
725
- /**
726
- * Emit an opaque JS fallback, marking the result as impure.
727
- */
728
- opaque(jsCode) {
729
- this.isPure = false;
730
- return `$expr(${jsCode})`;
731
- }
732
- /**
733
- * Visit an AST node and produce an mm-compute expression string.
734
- */
735
- visit(node) {
736
- if (t5.isStringLiteral(node)) return `"${node.value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
737
- if (t5.isNumericLiteral(node)) return String(node.value);
738
- if (t5.isBooleanLiteral(node)) return String(node.value);
739
- if (t5.isNullLiteral(node)) return "null";
740
- if (t5.isIdentifier(node)) {
741
- const snakeName = this.localFieldMap.get(node.name);
742
- if (snakeName) return `$local.${snakeName}`;
743
- const derivedInit = this.derivedVarMap.get(node.name);
744
- if (derivedInit) return `(${this.visit(derivedInit)})`;
745
- if (node.name === "undefined") return "null";
746
- if (node.name === "NaN") return "null";
747
- if (node.name === "Infinity") return "null";
748
- return node.name;
749
- }
750
- if (t5.isTSAsExpression(node)) return this.visit(node.expression);
751
- if (t5.isTSNonNullExpression(node)) return this.visit(node.expression);
752
- if (t5.isTSTypeAssertion(node)) return this.visit(node.expression);
753
- if (t5.isParenthesizedExpression(node)) return `(${this.visit(node.expression)})`;
754
- if (t5.isUnaryExpression(node) && node.prefix) {
755
- return this.visitUnary(node);
756
- }
757
- if (t5.isBinaryExpression(node)) {
758
- return this.visitBinary(node);
759
- }
760
- if (t5.isLogicalExpression(node)) {
761
- return this.visitLogical(node);
762
- }
763
- if (t5.isConditionalExpression(node)) {
764
- return `if(${this.visit(node.test)}, ${this.visit(node.consequent)}, ${this.visit(node.alternate)})`;
765
- }
766
- if (t5.isMemberExpression(node) || t5.isOptionalMemberExpression(node)) {
767
- return this.visitMember(node);
768
- }
769
- if (t5.isCallExpression(node) || t5.isOptionalCallExpression(node)) {
770
- return this.visitCall(node);
771
- }
772
- if (t5.isTemplateLiteral(node)) {
773
- return this.visitTemplateLiteral(node);
774
- }
775
- if (t5.isArrayExpression(node)) {
776
- const elements = node.elements.map((el) => {
777
- if (el === null) return "null";
778
- if (t5.isSpreadElement(el)) return this.opaque(`...${this.visit(el.argument)}`);
779
- return t5.isExpression(el) ? this.visit(el) : "null";
780
- });
781
- return `[${elements.join(", ")}]`;
782
- }
783
- if (t5.isObjectExpression(node)) {
784
- return this.visitObject(node);
785
- }
786
- if (t5.isArrowFunctionExpression(node)) {
787
- return this.visitArrow(node);
788
- }
789
- if (t5.isNewExpression(node)) {
790
- return this.visitNew(node);
791
- }
792
- if (t5.isAssignmentExpression(node) && node.operator === "=" && t5.isIdentifier(node.left)) {
793
- return `${node.left.name} = ${this.visit(node.right)}`;
794
- }
795
- return this.opaque(fallbackGenerate(node));
796
- }
797
- // ---------------------------------------------------------------------------
798
- // Unary
799
- // ---------------------------------------------------------------------------
800
- visitUnary(node) {
801
- if (node.operator === "!") {
802
- return `not(${this.visit(node.argument)})`;
803
- }
804
- if (node.operator === "-") {
805
- if (t5.isNumericLiteral(node.argument)) return String(-node.argument.value);
806
- return `(0 - ${this.visit(node.argument)})`;
807
- }
808
- if (node.operator === "typeof") {
809
- return `typeof(${this.visit(node.argument)})`;
810
- }
811
- return this.opaque(`${node.operator}${fallbackGenerate(node.argument)}`);
812
- }
813
- // ---------------------------------------------------------------------------
814
- // Binary
815
- // ---------------------------------------------------------------------------
816
- visitBinary(node) {
817
- const left = this.visit(node.left);
818
- const right = this.visit(node.right);
819
- switch (node.operator) {
820
- case "===":
821
- return `(${left} == ${right})`;
822
- case "!==":
823
- return `(${left} != ${right})`;
824
- case "==":
825
- return `(${left} == ${right})`;
826
- case "!=":
827
- return `(${left} != ${right})`;
828
- case "<":
829
- return `(${left} < ${right})`;
830
- case ">":
831
- return `(${left} > ${right})`;
832
- case "<=":
833
- return `(${left} <= ${right})`;
834
- case ">=":
835
- return `(${left} >= ${right})`;
836
- case "+":
837
- return `(${left} + ${right})`;
838
- case "-":
839
- return `(${left} - ${right})`;
840
- case "*":
841
- return `(${left} * ${right})`;
842
- case "/":
843
- return `(${left} / ${right})`;
844
- case "%":
845
- return `(${left} % ${right})`;
846
- default:
847
- return this.opaque(`(${left} ${node.operator} ${right})`);
848
- }
849
- }
850
- // ---------------------------------------------------------------------------
851
- // Logical
852
- // ---------------------------------------------------------------------------
853
- visitLogical(node) {
854
- const left = this.visit(node.left);
855
- const right = this.visit(node.right);
856
- switch (node.operator) {
857
- case "&&":
858
- return `(${left} && ${right})`;
859
- case "||":
860
- return `(${left} || ${right})`;
861
- case "??":
862
- return `coalesce(${left}, ${right})`;
863
- default:
864
- return this.opaque(`(${left} ${node.operator} ${right})`);
865
- }
866
- }
867
- // ---------------------------------------------------------------------------
868
- // Member expression
869
- // ---------------------------------------------------------------------------
870
- visitMember(node) {
871
- const isOptional = node.optional === true;
872
- if (!node.computed && t5.isIdentifier(node.property) && node.property.name === "length") {
873
- const obj2 = this.visit(node.object);
874
- if (isOptional) {
875
- return `if(${obj2} != null, length(${obj2}), null)`;
876
- }
877
- return `length(${obj2})`;
878
- }
879
- const obj = this.visit(node.object);
880
- if (node.computed) {
881
- const prop2 = t5.isExpression(node.property) ? this.visit(node.property) : "0";
882
- if (isOptional) {
883
- return `if(${obj} != null, get(${obj}, ${prop2}), null)`;
884
- }
885
- return `${obj}[${prop2}]`;
886
- }
887
- const prop = t5.isIdentifier(node.property) ? node.property.name : "[property]";
888
- if (isOptional) {
889
- return `if(${obj} != null, ${obj}.${prop}, null)`;
890
- }
891
- return `${obj}.${prop}`;
892
- }
893
- // ---------------------------------------------------------------------------
894
- // Call expression
895
- // ---------------------------------------------------------------------------
896
- visitCall(node) {
897
- if (t5.isIdentifier(node.callee)) {
898
- const setterField = this.setterToFieldMap.get(node.callee.name);
899
- if (setterField) {
900
- return this.visitSetterCall(node, setterField);
901
- }
902
- const args = this.visitArgs(node.arguments);
903
- return `${node.callee.name}(${args})`;
904
- }
905
- if (t5.isMemberExpression(node.callee) || t5.isOptionalMemberExpression(node.callee)) {
906
- const methodName = t5.isIdentifier(node.callee.property) ? node.callee.property.name : null;
907
- if (!methodName) {
908
- return this.opaque(fallbackGenerate(node));
909
- }
910
- if (t5.isIdentifier(node.callee.object) && node.callee.object.name === "Math") {
911
- return this.visitMathCall(methodName, node.arguments);
912
- }
913
- if (t5.isIdentifier(node.callee.object) && node.callee.object.name === "JSON") {
914
- return this.visitJsonCall(methodName, node.arguments);
915
- }
916
- if (t5.isIdentifier(node.callee.object) && node.callee.object.name === "Date") {
917
- if (methodName === "now") return "now_ms()";
918
- }
919
- const obj = this.visit(node.callee.object);
920
- return this.visitMethodCall(obj, methodName, node.arguments);
921
- }
922
- return this.opaque(fallbackGenerate(node));
923
- }
924
- // ---------------------------------------------------------------------------
925
- // Method call transpilation (obj.method(args))
926
- // ---------------------------------------------------------------------------
927
- visitMethodCall(obj, method, args) {
928
- switch (method) {
929
- // --- String methods ---
930
- case "toLowerCase":
931
- return `lower(${obj})`;
932
- case "toUpperCase":
933
- return `upper(${obj})`;
934
- case "trim":
935
- return `trim(${obj})`;
936
- case "startsWith": {
937
- const [arg] = this.visitArgsList(args);
938
- return `starts_with(${obj}, ${arg})`;
939
- }
940
- case "endsWith": {
941
- const [arg] = this.visitArgsList(args);
942
- return `ends_with(${obj}, ${arg})`;
943
- }
944
- case "includes": {
945
- const [arg] = this.visitArgsList(args);
946
- return `contains(${obj}, ${arg})`;
947
- }
948
- case "split": {
949
- const [sep] = this.visitArgsList(args);
950
- return `split(${obj}, ${sep})`;
951
- }
952
- case "join": {
953
- const [sep] = this.visitArgsList(args);
954
- return `join(${obj}, ${sep})`;
955
- }
956
- case "replace": {
957
- const visited = this.visitArgsList(args);
958
- return `replace(${obj}, ${visited[0]}, ${visited[1]})`;
959
- }
960
- case "substring":
961
- case "slice": {
962
- const visited = this.visitArgsList(args);
963
- if (visited.length === 1) return `substring(${obj}, ${visited[0]})`;
964
- return `substring(${obj}, ${visited[0]}, ${visited[1]})`;
965
- }
966
- case "charAt": {
967
- const [idx] = this.visitArgsList(args);
968
- return `substring(${obj}, ${idx}, (${idx} + 1))`;
969
- }
970
- case "indexOf": {
971
- const [arg] = this.visitArgsList(args);
972
- return `indexof(${obj}, ${arg})`;
973
- }
974
- case "toString":
975
- return `to_string(${obj})`;
976
- case "toISOString":
977
- return "now()";
978
- case "concat": {
979
- const visited = this.visitArgsList(args);
980
- return `concat(${obj}, ${visited.join(", ")})`;
981
- }
982
- // --- Array higher-order methods ---
983
- case "filter":
984
- return this.visitArrayHigherOrder("filter", obj, args);
985
- case "map":
986
- return this.visitArrayHigherOrder("map", obj, args);
987
- case "find":
988
- return this.visitArrayHigherOrder("find", obj, args);
989
- case "reduce":
990
- return this.visitArrayReduce(obj, args);
991
- case "some":
992
- return this.visitArrayHigherOrder("some", obj, args);
993
- case "every":
994
- return this.visitArrayHigherOrder("every", obj, args);
995
- // --- Array push: arr.push(item) → arr = concat(arr, [item]) ---
996
- case "push": {
997
- const [item] = this.visitArgsList(args);
998
- return `${obj} = concat(${obj}, [${item}])`;
999
- }
1000
- // --- Array mutation-free methods ---
1001
- case "reverse":
1002
- return `reverse(${obj})`;
1003
- case "sort":
1004
- return `sort(${obj})`;
1005
- case "flat":
1006
- return `flat(${obj})`;
1007
- // --- JSON methods on values ---
1008
- case "stringify":
1009
- return `to_string(${obj})`;
1010
- default:
1011
- return this.opaque(`${obj}.${method}(${this.visitArgs(args)})`);
1012
- }
1013
- }
1014
- // ---------------------------------------------------------------------------
1015
- // Array higher-order method transpilation
1016
- // ---------------------------------------------------------------------------
1017
- visitArrayHigherOrder(fn, obj, args) {
1018
- const firstArg = args[0];
1019
- if (!firstArg || !t5.isExpression(firstArg)) {
1020
- return this.opaque(`${obj}.${fn}()`);
1021
- }
1022
- if (t5.isArrowFunctionExpression(firstArg) && t5.isExpression(firstArg.body)) {
1023
- const paramName = firstArg.params.length > 0 && t5.isIdentifier(firstArg.params[0]) ? firstArg.params[0].name : "_";
1024
- const lambdaBody = this.visit(firstArg.body);
1025
- return `${fn}(${obj}, ${paramName} => ${lambdaBody})`;
1026
- }
1027
- const argStr = this.visit(firstArg);
1028
- return `${fn}(${obj}, ${argStr})`;
1029
- }
1030
- visitArrayReduce(obj, args) {
1031
- const [callbackArg, initArg] = args;
1032
- if (!callbackArg || !t5.isExpression(callbackArg)) {
1033
- return this.opaque(`${obj}.reduce()`);
1034
- }
1035
- if (t5.isArrowFunctionExpression(callbackArg) && t5.isExpression(callbackArg.body)) {
1036
- const params = callbackArg.params;
1037
- const accName = params.length > 0 && t5.isIdentifier(params[0]) ? params[0].name : "acc";
1038
- const itemName = params.length > 1 && t5.isIdentifier(params[1]) ? params[1].name : "x";
1039
- const lambdaBody = this.visit(callbackArg.body);
1040
- const initStr = initArg && t5.isExpression(initArg) ? this.visit(initArg) : "0";
1041
- return `reduce(${obj}, (${accName}, ${itemName}) => ${lambdaBody}, ${initStr})`;
1042
- }
1043
- return this.opaque(fallbackGenerate({ type: "CallExpression" }));
1044
- }
1045
- // ---------------------------------------------------------------------------
1046
- // Math.* methods
1047
- // ---------------------------------------------------------------------------
1048
- visitMathCall(method, args) {
1049
- const visited = this.visitArgsList(args);
1050
- switch (method) {
1051
- case "max":
1052
- return `max(${visited.join(", ")})`;
1053
- case "min":
1054
- return `min(${visited.join(", ")})`;
1055
- case "round":
1056
- return `round(${visited.join(", ")})`;
1057
- case "floor":
1058
- return `floor(${visited.join(", ")})`;
1059
- case "ceil":
1060
- return `ceil(${visited.join(", ")})`;
1061
- case "abs":
1062
- return `abs(${visited.join(", ")})`;
1063
- case "pow":
1064
- return `power(${visited.join(", ")})`;
1065
- case "sqrt":
1066
- return `sqrt(${visited.join(", ")})`;
1067
- case "log":
1068
- return `log(${visited.join(", ")})`;
1069
- case "log10":
1070
- return `log10(${visited.join(", ")})`;
1071
- case "sign":
1072
- return `sign(${visited.join(", ")})`;
1073
- default:
1074
- return this.opaque(`Math.${method}(${visited.join(", ")})`);
1075
- }
1076
- }
1077
- // ---------------------------------------------------------------------------
1078
- // JSON.* methods
1079
- // ---------------------------------------------------------------------------
1080
- visitJsonCall(method, args) {
1081
- const visited = this.visitArgsList(args);
1082
- switch (method) {
1083
- case "stringify":
1084
- return `to_string(${visited[0]})`;
1085
- case "parse":
1086
- return `from_json(${visited[0]})`;
1087
- default:
1088
- return this.opaque(`JSON.${method}(${visited.join(", ")})`);
1089
- }
1090
- }
1091
- // ---------------------------------------------------------------------------
1092
- // Template literals
1093
- // ---------------------------------------------------------------------------
1094
- visitTemplateLiteral(node) {
1095
- const parts = [];
1096
- for (let i = 0; i < node.quasis.length; i++) {
1097
- const raw = node.quasis[i].value.cooked ?? node.quasis[i].value.raw;
1098
- if (raw) {
1099
- parts.push(`"${raw.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`);
1100
- }
1101
- if (i < node.expressions.length) {
1102
- const exprStr = this.visit(node.expressions[i]);
1103
- parts.push(`to_string(${exprStr})`);
1104
- }
1105
- }
1106
- const nonEmpty = parts.filter((p) => p !== '""');
1107
- if (nonEmpty.length === 0) return '""';
1108
- if (nonEmpty.length === 1) return nonEmpty[0];
1109
- return `concat(${nonEmpty.join(", ")})`;
1110
- }
1111
- // ---------------------------------------------------------------------------
1112
- // Object expression
1113
- // ---------------------------------------------------------------------------
1114
- visitObject(node) {
1115
- const props = node.properties.map((prop) => {
1116
- if (t5.isSpreadElement(prop)) {
1117
- return this.opaque(`...${this.visit(prop.argument)}`);
1118
- }
1119
- if (t5.isObjectProperty(prop)) {
1120
- const key = t5.isIdentifier(prop.key) ? `"${prop.key.name}"` : t5.isStringLiteral(prop.key) ? `"${prop.key.value}"` : t5.isNumericLiteral(prop.key) ? `"${prop.key.value}"` : '"[key]"';
1121
- const value = t5.isExpression(prop.value) ? this.visit(prop.value) : "null";
1122
- return `${key}: ${value}`;
1123
- }
1124
- return this.opaque("[method]");
1125
- });
1126
- return `{${props.join(", ")}}`;
1127
- }
1128
- // ---------------------------------------------------------------------------
1129
- // Arrow function (lambda)
1130
- // ---------------------------------------------------------------------------
1131
- visitArrow(node) {
1132
- if (t5.isExpression(node.body)) {
1133
- const params = node.params.map((p) => {
1134
- if (t5.isIdentifier(p)) return p.name;
1135
- return "_";
1136
- }).join(", ");
1137
- const body = this.visit(node.body);
1138
- if (node.params.length === 1) return `${params} => ${body}`;
1139
- return `(${params}) => ${body}`;
1140
- }
1141
- return this.opaque(fallbackGenerate(node));
1142
- }
1143
- // ---------------------------------------------------------------------------
1144
- // new expressions
1145
- // ---------------------------------------------------------------------------
1146
- visitNew(node) {
1147
- if (t5.isIdentifier(node.callee) && node.callee.name === "Date" && node.arguments.length === 0) {
1148
- return "now()";
1149
- }
1150
- return this.opaque(fallbackGenerate(node));
1151
- }
1152
- // ---------------------------------------------------------------------------
1153
- // setState setter calls
1154
- // ---------------------------------------------------------------------------
1155
- visitSetterCall(node, fieldName) {
1156
- if (node.arguments.length >= 1) {
1157
- const arg = node.arguments[0];
1158
- if ((t5.isArrowFunctionExpression(arg) || t5.isFunctionExpression(arg)) && arg.params.length >= 1 && t5.isIdentifier(arg.params[0])) {
1159
- const paramName = arg.params[0].name;
1160
- const bodyExpr = t5.isExpression(arg.body) ? this.visit(arg.body) : "null";
1161
- const resolved = bodyExpr.replace(
1162
- new RegExp(`(?<![.$\\w])${paramName}(?![\\w])`, "g"),
1163
- `$local.${fieldName}`
1164
- );
1165
- return `$action.setLocal("${fieldName}")(${resolved})`;
1166
- }
1167
- const argStr = t5.isExpression(arg) ? this.visit(arg) : "null";
1168
- return `$action.setLocal("${fieldName}")(${argStr})`;
1169
- }
1170
- return `$action.setLocal("${fieldName}")`;
1171
- }
1172
- // ---------------------------------------------------------------------------
1173
- // Argument helpers
1174
- // ---------------------------------------------------------------------------
1175
- visitArgs(args) {
1176
- return args.map((a) => {
1177
- if (t5.isExpression(a)) return this.visit(a);
1178
- if (t5.isSpreadElement(a)) return this.opaque(`...${this.visit(a.argument)}`);
1179
- return "null";
1180
- }).join(", ");
1181
- }
1182
- visitArgsList(args) {
1183
- return args.map((a) => {
1184
- if (t5.isExpression(a)) return this.visit(a);
1185
- if (t5.isSpreadElement(a)) return this.opaque(`...${this.visit(a.argument)}`);
1186
- return "null";
1187
- });
1188
- }
1189
- };
1190
- function fallbackGenerate(node) {
1191
- if (t5.isIdentifier(node)) return node.name;
1192
- if (t5.isStringLiteral(node)) return `"${node.value.replace(/"/g, '\\"')}"`;
1193
- if (t5.isNumericLiteral(node)) return String(node.value);
1194
- if (t5.isBooleanLiteral(node)) return String(node.value);
1195
- if (t5.isNullLiteral(node)) return "null";
1196
- return `[${node.type}]`;
1197
- }
1198
-
1199
- // src/babel/extractors/component-extractor.ts
1200
- var nodeIdCounter = 0;
1201
- var localFieldMap = /* @__PURE__ */ new Map();
1202
- var setterToFieldMap = /* @__PURE__ */ new Map();
1203
- var derivedVarMap = /* @__PURE__ */ new Map();
1204
- function toSnakeCase(str) {
1205
- return str.replace(/([A-Z])/g, "_$1").toLowerCase().replace(/^_/, "");
1206
- }
1207
- var STATIC_EVAL_FAIL = Symbol("STATIC_EVAL_FAIL");
1208
- function tryStaticEval(node) {
1209
- if (t6.isStringLiteral(node)) return node.value;
1210
- if (t6.isNumericLiteral(node)) return node.value;
1211
- if (t6.isBooleanLiteral(node)) return node.value;
1212
- if (t6.isNullLiteral(node)) return null;
1213
- if (t6.isIdentifier(node) && node.name === "undefined") return void 0;
1214
- if (t6.isUnaryExpression(node) && node.operator === "-" && t6.isNumericLiteral(node.argument)) {
1215
- return -node.argument.value;
1216
- }
1217
- if (t6.isArrayExpression(node)) {
1218
- const result = [];
1219
- for (const el of node.elements) {
1220
- if (el === null) {
1221
- result.push(null);
1222
- continue;
1223
- }
1224
- if (t6.isSpreadElement(el)) return STATIC_EVAL_FAIL;
1225
- const val = tryStaticEval(el);
1226
- if (val === STATIC_EVAL_FAIL) return STATIC_EVAL_FAIL;
1227
- result.push(val);
1228
- }
1229
- return result;
1230
- }
1231
- if (t6.isObjectExpression(node)) {
1232
- const result = {};
1233
- for (const prop of node.properties) {
1234
- if (t6.isSpreadElement(prop) || t6.isObjectMethod(prop)) return STATIC_EVAL_FAIL;
1235
- if (!t6.isObjectProperty(prop)) return STATIC_EVAL_FAIL;
1236
- let key;
1237
- if (t6.isIdentifier(prop.key)) key = prop.key.name;
1238
- else if (t6.isStringLiteral(prop.key)) key = prop.key.value;
1239
- else if (t6.isNumericLiteral(prop.key)) key = String(prop.key.value);
1240
- else return STATIC_EVAL_FAIL;
1241
- if (!t6.isExpression(prop.value)) return STATIC_EVAL_FAIL;
1242
- const val = tryStaticEval(prop.value);
1243
- if (val === STATIC_EVAL_FAIL) return STATIC_EVAL_FAIL;
1244
- result[key] = val;
1245
- }
1246
- return result;
1247
- }
1248
- if (t6.isTemplateLiteral(node) && node.expressions.length === 0) {
1249
- return node.quasis[0].value.cooked ?? node.quasis[0].value.raw;
1250
- }
1251
- return STATIC_EVAL_FAIL;
1252
- }
1253
- function initLocalFieldMaps(fields) {
1254
- localFieldMap.clear();
1255
- setterToFieldMap.clear();
1256
- for (const field of fields) {
1257
- const camelName = field.name;
1258
- const snakeName = toSnakeCase(camelName);
1259
- localFieldMap.set(camelName, snakeName);
1260
- const setterName = "set" + camelName.charAt(0).toUpperCase() + camelName.slice(1);
1261
- setterToFieldMap.set(setterName, snakeName);
1262
- }
1263
- }
1264
- function registerDerivedVar(name, init) {
1265
- derivedVarMap.set(name, init);
1266
- }
1267
- function resetNodeIdCounter() {
1268
- nodeIdCounter = 0;
1269
- derivedVarMap.clear();
1270
- }
1271
- function jsxToExperienceNode(node) {
1272
- if (t6.isJSXFragment(node)) {
1273
- return {
1274
- id: `fragment_${++nodeIdCounter}`,
1275
- children: extractChildren(node.children)
1276
- };
1277
- }
1278
- const element = node.openingElement;
1279
- const componentName = resolveComponentName(element.name);
1280
- const id = generateNodeId(componentName);
1281
- const config = {};
1282
- const bindings = {};
1283
- let visibleWhen;
1284
- let layout;
1285
- let slot;
1286
- let className;
1287
- let displayName;
1288
- const layoutMap = {
1289
- Stack: "stack",
1290
- Row: "row",
1291
- Grid: "grid",
1292
- Tabs: "tabs",
1293
- Column: "column"
1294
- };
1295
- if (layoutMap[componentName]) {
1296
- layout = layoutMap[componentName];
1297
- }
1298
- for (const attr of element.attributes) {
1299
- if (t6.isJSXAttribute(attr) && t6.isJSXIdentifier(attr.name)) {
1300
- const attrName = attr.name.name;
1301
- const attrValue = attr.value;
1302
- if (attrName === "visible_when" && t6.isStringLiteral(attrValue)) {
1303
- visibleWhen = attrValue.value;
1304
- } else if (attrName === "data-slot" && t6.isStringLiteral(attrValue)) {
1305
- slot = attrValue.value;
1306
- } else if (attrName === "className" && t6.isStringLiteral(attrValue)) {
1307
- className = attrValue.value;
1308
- } else if (attrName === "displayName" && t6.isStringLiteral(attrValue)) {
1309
- displayName = attrValue.value;
1310
- } else if (t6.isJSXExpressionContainer(attrValue)) {
1311
- const expr = attrValue.expression;
1312
- if (t6.isJSXEmptyExpression(expr)) continue;
1313
- if (t6.isNumericLiteral(expr)) {
1314
- config[attrName] = expr.value;
1315
- } else if (t6.isBooleanLiteral(expr)) {
1316
- config[attrName] = expr.value;
1317
- } else if (t6.isStringLiteral(expr)) {
1318
- if (expr.value.includes("$instance") || expr.value.includes("$local") || /^[a-zA-Z_]+\(/.test(expr.value)) {
1319
- bindings[attrName] = expr.value;
1320
- } else {
1321
- config[attrName] = expr.value;
1322
- }
1323
- } else if (t6.isIdentifier(expr)) {
1324
- const snakeName = localFieldMap.get(expr.name);
1325
- bindings[attrName] = snakeName ? `$local.${snakeName}` : `$instance.${expr.name}`;
1326
- } else if (isEventHandlerProp(attrName) && (t6.isArrowFunctionExpression(expr) || t6.isFunctionExpression(expr))) {
1327
- const decomposed = decomposeHandlerToSeq(expr);
1328
- if (decomposed) {
1329
- bindings[attrName] = decomposed;
1330
- } else {
1331
- bindings[attrName] = `$expr(${generateExpression2(expr)})`;
1332
- }
1333
- } else if (t6.isExpression(expr)) {
1334
- const staticVal = tryStaticEval(expr);
1335
- if (staticVal !== STATIC_EVAL_FAIL) {
1336
- config[attrName] = staticVal;
1337
- } else {
1338
- bindings[attrName] = generateExpression2(expr);
1339
- }
1340
- }
1341
- } else if (t6.isStringLiteral(attrValue)) {
1342
- config[attrName] = attrValue.value;
1343
- } else if (attrValue === null) {
1344
- config[attrName] = true;
1345
- }
1346
- } else if (t6.isJSXSpreadAttribute(attr)) {
1347
- if (t6.isIdentifier(attr.argument)) {
1348
- bindings["..." + attr.argument.name] = `$instance.${attr.argument.name}`;
1349
- }
1350
- }
1351
- }
1352
- const children = extractChildren(node.children);
1353
- const experienceNode = {
1354
- id,
1355
- ...displayName && { displayName },
1356
- component: componentName,
1357
- ...slot && { slot },
1358
- ...layout && { layout },
1359
- ...className && { className },
1360
- ...Object.keys(bindings).length > 0 && { bindings },
1361
- ...Object.keys(config).length > 0 && { config },
1362
- ...visibleWhen && { visible_when: visibleWhen },
1363
- ...children.length > 0 && { children }
1364
- };
1365
- return experienceNode;
1366
- }
1367
- function resolveComponentName(name) {
1368
- if (t6.isJSXIdentifier(name)) return name.name;
1369
- if (t6.isJSXMemberExpression(name)) {
1370
- const obj = resolveComponentName(name.object);
1371
- return `${obj}.${name.property.name}`;
1372
- }
1373
- if (t6.isJSXNamespacedName(name)) {
1374
- return `${name.namespace.name}:${name.name.name}`;
1375
- }
1376
- return "div";
1377
- }
1378
- function extractChildren(children) {
1379
- const nodes = [];
1380
- for (const child of children) {
1381
- if (t6.isJSXElement(child)) {
1382
- nodes.push(jsxToExperienceNode(child));
1383
- } else if (t6.isJSXFragment(child)) {
1384
- nodes.push(jsxToExperienceNode(child));
1385
- } else if (t6.isJSXText(child)) {
1386
- const text = child.value.trim();
1387
- if (text) {
1388
- nodes.push({
1389
- id: `text_${++nodeIdCounter}`,
1390
- component: "Text",
1391
- config: { value: text }
1392
- });
1393
- }
1394
- } else if (t6.isJSXExpressionContainer(child)) {
1395
- const expr = child.expression;
1396
- if (t6.isJSXEmptyExpression(expr)) continue;
1397
- if (t6.isConditionalExpression(expr)) {
1398
- const condExpr = generateExpression2(expr.test);
1399
- if (t6.isJSXElement(expr.consequent) || t6.isJSXFragment(expr.consequent)) {
1400
- const consequent = jsxToExperienceNode(expr.consequent);
1401
- consequent.visible_when = condExpr;
1402
- nodes.push(consequent);
1403
- }
1404
- if (t6.isJSXElement(expr.alternate) || t6.isJSXFragment(expr.alternate)) {
1405
- const alternate = jsxToExperienceNode(expr.alternate);
1406
- alternate.visible_when = `not(${condExpr})`;
1407
- nodes.push(alternate);
1408
- }
1409
- } else if (t6.isLogicalExpression(expr) && expr.operator === "&&") {
1410
- const condExpr = generateExpression2(expr.left);
1411
- if (t6.isJSXElement(expr.right) || t6.isJSXFragment(expr.right)) {
1412
- const element = jsxToExperienceNode(expr.right);
1413
- element.visible_when = condExpr;
1414
- nodes.push(element);
1415
- }
1416
- } else if (t6.isCallExpression(expr) && t6.isMemberExpression(expr.callee) && t6.isIdentifier(expr.callee.property) && expr.callee.property.name === "map" && expr.arguments.length > 0) {
1417
- const listSource = generateExpression2(expr.callee.object);
1418
- const mapFn = expr.arguments[0];
1419
- let itemTemplate = null;
1420
- let itemAlias = "item";
1421
- if (t6.isArrowFunctionExpression(mapFn) || t6.isFunctionExpression(mapFn)) {
1422
- if (mapFn.params.length > 0 && t6.isIdentifier(mapFn.params[0])) {
1423
- itemAlias = mapFn.params[0].name;
1424
- }
1425
- const body = mapFn.body;
1426
- if (t6.isJSXElement(body) || t6.isJSXFragment(body)) {
1427
- itemTemplate = jsxToExperienceNode(body);
1428
- } else if (t6.isBlockStatement(body)) {
1429
- for (const stmt of body.body) {
1430
- if (t6.isReturnStatement(stmt) && stmt.argument) {
1431
- if (t6.isJSXElement(stmt.argument) || t6.isJSXFragment(stmt.argument)) {
1432
- itemTemplate = jsxToExperienceNode(stmt.argument);
1433
- }
1434
- break;
1435
- }
1436
- }
1437
- }
1438
- }
1439
- nodes.push({
1440
- id: `each_${++nodeIdCounter}`,
1441
- component: "Each",
1442
- bindings: { items: listSource.startsWith("$") ? listSource : `$instance.${listSource}` },
1443
- config: { as: itemAlias },
1444
- ...itemTemplate ? { children: [itemTemplate] } : {}
1445
- });
1446
- } else if ((t6.isArrowFunctionExpression(expr) || t6.isFunctionExpression(expr)) && extractJSXFromCallback(expr)) {
1447
- const jsxNode = extractJSXFromCallback(expr);
1448
- nodes.push(jsxToExperienceNode(jsxNode));
1449
- } else if (t6.isStringLiteral(expr)) {
1450
- nodes.push({
1451
- id: `text_${++nodeIdCounter}`,
1452
- component: "Text",
1453
- config: { value: expr.value }
1454
- });
1455
- } else if (t6.isIdentifier(expr)) {
1456
- const snakeName = localFieldMap.get(expr.name);
1457
- const bindingPath = snakeName ? `$local.${snakeName}` : `$instance.${expr.name}`;
1458
- nodes.push({
1459
- id: `text_${++nodeIdCounter}`,
1460
- component: "Text",
1461
- bindings: { value: bindingPath }
1462
- });
1463
- } else if (t6.isExpression(expr)) {
1464
- const exprStr = generateExpression2(expr);
1465
- if (exprStr !== "[Expression]") {
1466
- nodes.push({
1467
- id: `text_${++nodeIdCounter}`,
1468
- component: "Text",
1469
- bindings: { value: exprStr }
1470
- });
1471
- }
1472
- }
1473
- }
1474
- }
1475
- return nodes;
1476
- }
1477
- function generateNodeId(componentName) {
1478
- const id = componentName.replace(/\./g, "-").replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
1479
- return `${id}_${++nodeIdCounter}`;
1480
- }
1481
- function generateExpression2(node) {
1482
- if (t6.isIdentifier(node)) {
1483
- const snakeName = localFieldMap.get(node.name);
1484
- if (snakeName) return `$local.${snakeName}`;
1485
- const derivedInit = derivedVarMap.get(node.name);
1486
- if (derivedInit) return `(${generateExpression2(derivedInit)})`;
1487
- return node.name;
1488
- }
1489
- if (t6.isStringLiteral(node)) return `"${node.value.replace(/"/g, '\\"')}"`;
1490
- if (t6.isNumericLiteral(node)) return String(node.value);
1491
- if (t6.isBooleanLiteral(node)) return String(node.value);
1492
- if (t6.isNullLiteral(node)) return "null";
1493
- if (t6.isMemberExpression(node) || t6.isOptionalMemberExpression(node)) {
1494
- const obj = t6.isExpression(node.object) ? generateExpression2(node.object) : "[object]";
1495
- const optional = node.optional ? "?." : ".";
1496
- if (node.computed) {
1497
- const prop2 = t6.isExpression(node.property) ? generateExpression2(node.property) : "0";
1498
- return `${obj}[${prop2}]`;
1499
- }
1500
- const prop = t6.isIdentifier(node.property) ? node.property.name : "[property]";
1501
- return `${obj}${optional}${prop}`;
1502
- }
1503
- if (t6.isBinaryExpression(node)) {
1504
- return `(${generateExpression2(node.left)} ${node.operator} ${generateExpression2(node.right)})`;
1505
- }
1506
- if (t6.isLogicalExpression(node)) {
1507
- return `(${generateExpression2(node.left)} ${node.operator} ${generateExpression2(node.right)})`;
1508
- }
1509
- if (t6.isConditionalExpression(node)) {
1510
- return `(${generateExpression2(node.test)} ? ${generateExpression2(node.consequent)} : ${generateExpression2(node.alternate)})`;
1511
- }
1512
- if (t6.isUnaryExpression(node) && node.prefix) {
1513
- const space = node.operator === "typeof" || node.operator === "void" || node.operator === "delete" ? " " : "";
1514
- return `${node.operator}${space}${generateExpression2(node.argument)}`;
1515
- }
1516
- if (t6.isCallExpression(node) || t6.isOptionalCallExpression(node)) {
1517
- if (t6.isIdentifier(node.callee)) {
1518
- const setterFieldName = setterToFieldMap.get(node.callee.name);
1519
- if (setterFieldName) {
1520
- if (node.arguments.length >= 1) {
1521
- const arg = node.arguments[0];
1522
- if ((t6.isArrowFunctionExpression(arg) || t6.isFunctionExpression(arg)) && arg.params.length >= 1 && t6.isIdentifier(arg.params[0])) {
1523
- const paramName = arg.params[0].name;
1524
- const bodyExpr = t6.isExpression(arg.body) ? generateExpression2(arg.body) : "undefined";
1525
- const resolved = bodyExpr.replace(
1526
- new RegExp(`(?<![.$\\w])${paramName}(?![\\w])`, "g"),
1527
- `$local.${setterFieldName}`
1528
- );
1529
- return `$action.setLocal("${setterFieldName}")(${resolved})`;
1530
- }
1531
- const argStr = t6.isExpression(arg) ? generateExpression2(arg) : "undefined";
1532
- return `$action.setLocal("${setterFieldName}")(${argStr})`;
1533
- }
1534
- return `$action.setLocal("${setterFieldName}")`;
1535
- }
1536
- const args = node.arguments.map((a) => t6.isExpression(a) ? generateExpression2(a) : t6.isSpreadElement(a) ? `...${generateExpression2(a.argument)}` : "undefined").join(", ");
1537
- return `${node.callee.name}(${args})`;
1538
- }
1539
- if (t6.isMemberExpression(node.callee) || t6.isOptionalMemberExpression(node.callee)) {
1540
- const mmResult = transpileExpression(node, {
1541
- localFieldMap,
1542
- derivedVarMap,
1543
- setterToFieldMap
1544
- });
1545
- if (mmResult.pure) return mmResult.expression;
1546
- const obj = generateExpression2(node.callee.object);
1547
- const optional = node.callee.optional ? "?." : ".";
1548
- const prop = t6.isIdentifier(node.callee.property) ? node.callee.property.name : "[method]";
1549
- const args = node.arguments.map((a) => t6.isExpression(a) ? generateExpression2(a) : t6.isSpreadElement(a) ? `...${generateExpression2(a.argument)}` : "undefined").join(", ");
1550
- return `${obj}${optional}${prop}(${args})`;
1551
- }
1552
- if (t6.isExpression(node.callee)) {
1553
- const callee = generateExpression2(node.callee);
1554
- const args = node.arguments.map((a) => t6.isExpression(a) ? generateExpression2(a) : "undefined").join(", ");
1555
- return `(${callee})(${args})`;
1556
- }
1557
- }
1558
- if (t6.isTemplateLiteral(node)) {
1559
- const parts = node.quasis.map((q, i) => {
1560
- const raw = q.value.raw;
1561
- if (i < node.expressions.length) {
1562
- return raw + "${" + generateExpression2(node.expressions[i]) + "}";
1563
- }
1564
- return raw;
1565
- }).join("");
1566
- return "`" + parts + "`";
1567
- }
1568
- if (t6.isArrowFunctionExpression(node)) {
1569
- const params = node.params.map((p) => {
1570
- if (t6.isIdentifier(p)) return p.name;
1571
- if (t6.isRestElement(p) && t6.isIdentifier(p.argument)) return `...${p.argument.name}`;
1572
- if (t6.isAssignmentPattern(p) && t6.isIdentifier(p.left)) {
1573
- return `${p.left.name} = ${t6.isExpression(p.right) ? generateExpression2(p.right) : "undefined"}`;
1574
- }
1575
- return "_";
1576
- }).join(", ");
1577
- if (t6.isExpression(node.body)) {
1578
- return `(${params}) => ${generateExpression2(node.body)}`;
1579
- }
1580
- if (t6.isBlockStatement(node.body)) {
1581
- const bodyStr = generateBlockStatement(node.body);
1582
- return `(${params}) => { ${bodyStr} }`;
1583
- }
1584
- }
1585
- if (t6.isArrayExpression(node)) {
1586
- const elements = node.elements.map((el) => {
1587
- if (el === null) return "undefined";
1588
- if (t6.isSpreadElement(el)) return `...${generateExpression2(el.argument)}`;
1589
- return t6.isExpression(el) ? generateExpression2(el) : "undefined";
1590
- }).join(", ");
1591
- return `[${elements}]`;
1592
- }
1593
- if (t6.isObjectExpression(node)) {
1594
- const props = node.properties.map((prop) => {
1595
- if (t6.isSpreadElement(prop)) return `...${generateExpression2(prop.argument)}`;
1596
- if (t6.isObjectProperty(prop)) {
1597
- const key = t6.isIdentifier(prop.key) ? prop.key.name : t6.isStringLiteral(prop.key) ? `"${prop.key.value}"` : t6.isNumericLiteral(prop.key) ? String(prop.key.value) : "[key]";
1598
- if (prop.shorthand && t6.isIdentifier(prop.value)) return key;
1599
- const value = t6.isExpression(prop.value) ? generateExpression2(prop.value) : "undefined";
1600
- return `${key}: ${value}`;
1601
- }
1602
- if (t6.isObjectMethod(prop)) {
1603
- const key = t6.isIdentifier(prop.key) ? prop.key.name : "[method]";
1604
- const params = prop.params.map((p) => t6.isIdentifier(p) ? p.name : "_").join(", ");
1605
- const bodyStr = generateBlockStatement(prop.body);
1606
- return `${key}(${params}) { ${bodyStr} }`;
1607
- }
1608
- return "";
1609
- }).filter(Boolean).join(", ");
1610
- return `{ ${props} }`;
1611
- }
1612
- if (t6.isParenthesizedExpression(node)) {
1613
- return `(${generateExpression2(node.expression)})`;
1614
- }
1615
- if (t6.isTSAsExpression(node)) return generateExpression2(node.expression);
1616
- if (t6.isTSNonNullExpression(node)) return generateExpression2(node.expression);
1617
- if (t6.isTSTypeAssertion(node)) return generateExpression2(node.expression);
1618
- if (t6.isSequenceExpression(node)) {
1619
- return `(${node.expressions.map(generateExpression2).join(", ")})`;
1620
- }
1621
- if (t6.isAssignmentExpression(node)) {
1622
- const left = t6.isExpression(node.left) ? generateExpression2(node.left) : "[target]";
1623
- return `(${left} ${node.operator} ${generateExpression2(node.right)})`;
1624
- }
1625
- if (t6.isUpdateExpression(node)) {
1626
- const arg = generateExpression2(node.argument);
1627
- return node.prefix ? `${node.operator}${arg}` : `${arg}${node.operator}`;
1628
- }
1629
- if (t6.isTaggedTemplateExpression(node)) {
1630
- return generateExpression2(node.quasi);
1631
- }
1632
- if (t6.isSpreadElement(node)) {
1633
- return `...${generateExpression2(node.argument)}`;
1634
- }
1635
- if (t6.isYieldExpression(node)) {
1636
- return node.argument ? `yield ${generateExpression2(node.argument)}` : "yield";
1637
- }
1638
- if (t6.isAwaitExpression(node)) {
1639
- return `await ${generateExpression2(node.argument)}`;
1640
- }
1641
- if (t6.isNewExpression(node)) {
1642
- const callee = t6.isExpression(node.callee) ? generateExpression2(node.callee) : "Object";
1643
- const args = node.arguments.map((a) => t6.isExpression(a) ? generateExpression2(a) : "undefined").join(", ");
1644
- return `new ${callee}(${args})`;
1645
- }
1646
- if (t6.isThisExpression(node)) return "this";
1647
- console.warn(`[component-extractor] Unhandled expression type: ${node.type}`);
1648
- return "[Expression]";
1649
- }
1650
- function generateBlockStatement(block) {
1651
- return block.body.map((stmt) => {
1652
- if (t6.isReturnStatement(stmt)) {
1653
- return stmt.argument ? `return ${generateExpression2(stmt.argument)};` : "return;";
1654
- }
1655
- if (t6.isExpressionStatement(stmt)) {
1656
- return `${generateExpression2(stmt.expression)};`;
1657
- }
1658
- if (t6.isVariableDeclaration(stmt)) {
1659
- const decls = stmt.declarations.map((d) => {
1660
- const id = t6.isIdentifier(d.id) ? d.id.name : "_";
1661
- const init = d.init && t6.isExpression(d.init) ? generateExpression2(d.init) : "undefined";
1662
- return `${id} = ${init}`;
1663
- }).join(", ");
1664
- return `${stmt.kind} ${decls};`;
1665
- }
1666
- if (t6.isIfStatement(stmt)) {
1667
- const test = generateExpression2(stmt.test);
1668
- const consequent = t6.isBlockStatement(stmt.consequent) ? `{ ${generateBlockStatement(stmt.consequent)} }` : t6.isExpressionStatement(stmt.consequent) ? `{ ${generateExpression2(stmt.consequent.expression)}; }` : "{}";
1669
- const alternate = stmt.alternate ? t6.isBlockStatement(stmt.alternate) ? ` else { ${generateBlockStatement(stmt.alternate)} }` : t6.isIfStatement(stmt.alternate) ? ` else ${generateBlockStatement(t6.blockStatement([stmt.alternate]))}` : "" : "";
1670
- return `if (${test}) ${consequent}${alternate}`;
1671
- }
1672
- return "/* [Statement] */";
1673
- }).join(" ");
1674
- }
1675
- function extractJSXFromCallback(node) {
1676
- const body = node.body;
1677
- if (t6.isJSXElement(body) || t6.isJSXFragment(body)) {
1678
- return body;
1679
- }
1680
- if (t6.isParenthesizedExpression(body)) {
1681
- const inner = body.expression;
1682
- if (t6.isJSXElement(inner) || t6.isJSXFragment(inner)) {
1683
- return inner;
1684
- }
1685
- }
1686
- if (t6.isBlockStatement(body)) {
1687
- for (const stmt of body.body) {
1688
- if (t6.isReturnStatement(stmt) && stmt.argument) {
1689
- if (t6.isJSXElement(stmt.argument) || t6.isJSXFragment(stmt.argument)) {
1690
- return stmt.argument;
1691
- }
1692
- if (t6.isParenthesizedExpression(stmt.argument)) {
1693
- const inner = stmt.argument.expression;
1694
- if (t6.isJSXElement(inner) || t6.isJSXFragment(inner)) {
1695
- return inner;
1696
- }
1697
- }
1698
- }
1699
- }
1700
- }
1701
- return null;
1702
- }
1703
- function isEventHandlerProp(name) {
1704
- return /^on[A-Z]/.test(name);
1705
- }
1706
- function expressionToActionAtom(expr) {
1707
- if (t6.isCallExpression(expr) || t6.isOptionalCallExpression(expr)) {
1708
- if (t6.isIdentifier(expr.callee)) {
1709
- const setterFieldName = setterToFieldMap.get(expr.callee.name);
1710
- if (setterFieldName && expr.arguments.length >= 1) {
1711
- const arg = expr.arguments[0];
1712
- if ((t6.isArrowFunctionExpression(arg) || t6.isFunctionExpression(arg)) && arg.params.length >= 1 && t6.isIdentifier(arg.params[0])) {
1713
- const paramName = arg.params[0].name;
1714
- const bodyExpr = t6.isExpression(arg.body) ? generateExpression2(arg.body) : "undefined";
1715
- const resolved = bodyExpr.replace(
1716
- new RegExp(`(?<![.$\\w])${paramName}(?![\\w])`, "g"),
1717
- `$local.${setterFieldName}`
1718
- );
1719
- return `$action.setLocal("${setterFieldName}", ${resolved})`;
1720
- }
1721
- const argStr = t6.isExpression(arg) ? generateExpression2(arg) : "undefined";
1722
- return `$action.setLocal("${setterFieldName}", ${argStr})`;
1723
- }
1724
- return null;
1725
- }
1726
- if (t6.isMemberExpression(expr.callee) || t6.isOptionalMemberExpression(expr.callee)) {
1727
- const generated = generateExpression2(expr);
1728
- if (generated.startsWith("$action.")) return generated;
1729
- }
1730
- return null;
1731
- }
1732
- return null;
1733
- }
1734
- function statementToAction(stmt) {
1735
- if (t6.isExpressionStatement(stmt)) {
1736
- return expressionToActionAtom(stmt.expression);
1737
- }
1738
- if (t6.isIfStatement(stmt)) {
1739
- const condition = generateExpression2(stmt.test);
1740
- let thenAction = null;
1741
- if (t6.isBlockStatement(stmt.consequent)) {
1742
- const actions = stmt.consequent.body.map((s) => statementToAction(s)).filter(Boolean);
1743
- if (actions.length === 0 || actions.length !== stmt.consequent.body.length) return null;
1744
- thenAction = actions.length === 1 ? actions[0] : `$action.seq(${actions.join(", ")})`;
1745
- } else if (t6.isExpressionStatement(stmt.consequent)) {
1746
- thenAction = expressionToActionAtom(stmt.consequent.expression);
1747
- }
1748
- if (!thenAction) return null;
1749
- let elseAction = null;
1750
- if (stmt.alternate) {
1751
- if (t6.isBlockStatement(stmt.alternate)) {
1752
- const actions = stmt.alternate.body.map((s) => statementToAction(s)).filter(Boolean);
1753
- if (actions.length !== stmt.alternate.body.length) return null;
1754
- elseAction = actions.length === 1 ? actions[0] : `$action.seq(${actions.join(", ")})`;
1755
- } else if (t6.isIfStatement(stmt.alternate)) {
1756
- elseAction = statementToAction(stmt.alternate);
1757
- } else if (t6.isExpressionStatement(stmt.alternate)) {
1758
- elseAction = expressionToActionAtom(stmt.alternate.expression);
1759
- }
1760
- if (!elseAction) return null;
1761
- }
1762
- return elseAction ? `$action.when(${condition}, ${thenAction}, ${elseAction})` : `$action.when(${condition}, ${thenAction})`;
1763
- }
1764
- return null;
1765
- }
1766
- function decomposeHandlerToSeq(node) {
1767
- if (t6.isArrowFunctionExpression(node) && t6.isExpression(node.body)) {
1768
- return expressionToActionAtom(node.body);
1769
- }
1770
- const body = node.body;
1771
- if (!t6.isBlockStatement(body)) return null;
1772
- const actions = [];
1773
- for (const stmt of body.body) {
1774
- const action = statementToAction(stmt);
1775
- if (!action) return null;
1776
- actions.push(action);
1777
- }
1778
- if (actions.length === 0) return null;
1779
- if (actions.length === 1) return actions[0];
1780
- return `$action.seq(${actions.join(", ")})`;
1781
- }
1782
- function extractComponents(path, state) {
1783
- const arg = path.node.argument;
1784
- if (!arg) return;
1785
- const compilerState = state;
1786
- if (compilerState.fields && compilerState.fields.length > 0) {
1787
- initLocalFieldMaps(compilerState.fields);
1788
- }
1789
- let experienceNode = null;
1790
- if (t6.isJSXElement(arg)) {
1791
- experienceNode = jsxToExperienceNode(arg);
1792
- } else if (t6.isJSXFragment(arg)) {
1793
- experienceNode = jsxToExperienceNode(arg);
1794
- }
1795
- if (experienceNode) {
1796
- compilerState.experience = experienceNode;
1797
- }
1798
- }
1799
-
1800
- // src/babel/extractors/during-extractor.ts
1801
- import * as t7 from "@babel/types";
1802
- var duringIdCounter = 0;
1803
- function resetDuringIdCounter() {
1804
- duringIdCounter = 0;
1805
- }
1806
- function analyzeCallbackBody2(body, actionCounter) {
1807
- const actions = [];
1808
- for (const statement of body) {
1809
- if (!t7.isExpressionStatement(statement)) continue;
1810
- const expr = statement.expression;
1811
- if (t7.isCallExpression(expr) && t7.isIdentifier(expr.callee)) {
1812
- const calleeName = expr.callee.name;
1813
- const args = expr.arguments;
1814
- if (calleeName === "setField" && args.length >= 2) {
1815
- const field = t7.isStringLiteral(args[0]) ? args[0].value : void 0;
1816
- const arg1 = args[1];
1817
- if (field !== void 0 && !t7.isArgumentPlaceholder(arg1)) {
1818
- actions.push({
1819
- id: `auto_${++actionCounter.value}`,
1820
- type: "set_field",
1821
- mode: "auto",
1822
- config: { field, value: extractValue2(arg1) }
1823
- });
1824
- }
1825
- } else if (calleeName === "setMemory" && args.length >= 2) {
1826
- const key = t7.isStringLiteral(args[0]) ? args[0].value : void 0;
1827
- const arg1 = args[1];
1828
- if (key !== void 0 && !t7.isArgumentPlaceholder(arg1)) {
1829
- actions.push({
1830
- id: `auto_${++actionCounter.value}`,
1831
- type: "set_memory",
1832
- mode: "auto",
1833
- config: { key, value: extractValue2(arg1) }
1834
- });
1835
- }
1836
- } else if (calleeName.startsWith("set") && calleeName.length > 3 && args.length >= 1) {
1837
- const fieldName = calleeName.slice(3, 4).toLowerCase() + calleeName.slice(4);
1838
- const arg0 = args[0];
1839
- if (!t7.isArgumentPlaceholder(arg0)) {
1840
- actions.push({
1841
- id: `auto_${++actionCounter.value}`,
1842
- type: "set_field",
1843
- mode: "auto",
1844
- config: { field: fieldName, value: extractValue2(arg0) }
1845
- });
1846
- }
1847
- }
1848
- } else if (t7.isCallExpression(expr)) {
1849
- const callee = expr.callee;
1850
- if (t7.isMemberExpression(callee) && t7.isIdentifier(callee.object) && callee.object.name === "console" && t7.isIdentifier(callee.property) && callee.property.name === "log" && expr.arguments.length > 0) {
1851
- const arg0 = expr.arguments[0];
1852
- if (!t7.isArgumentPlaceholder(arg0)) {
1853
- actions.push({
1854
- id: `auto_${++actionCounter.value}`,
1855
- type: "log_event",
1856
- mode: "auto",
1857
- config: { message: extractValue2(arg0) }
1858
- });
1859
- }
1860
- } else {
1861
- actions.push({
1862
- id: `auto_${++actionCounter.value}`,
1863
- type: "custom",
1864
- mode: "auto",
1865
- config: { expression: generateCode2(expr) }
1866
- });
1867
- }
1868
- }
1869
- }
1870
- return actions;
1871
- }
1872
- function extractValue2(node) {
1873
- if (t7.isNumericLiteral(node)) return node.value;
1874
- if (t7.isStringLiteral(node)) return node.value;
1875
- if (t7.isBooleanLiteral(node)) return node.value;
1876
- if (t7.isNullLiteral(node)) return null;
1877
- if (t7.isArrayExpression(node)) {
1878
- return node.elements.map((el) => el && t7.isExpression(el) ? extractValue2(el) : null);
1879
- }
1880
- if (t7.isObjectExpression(node)) {
1881
- const obj = {};
1882
- node.properties.forEach((prop) => {
1883
- if (t7.isObjectProperty(prop) && t7.isIdentifier(prop.key) && t7.isExpression(prop.value)) {
1884
- obj[prop.key.name] = extractValue2(prop.value);
1885
- }
1886
- });
1887
- return obj;
1888
- }
1889
- return generateCode2(node);
1890
- }
1891
- function generateCode2(node) {
1892
- if (t7.isIdentifier(node)) return node.name;
1893
- if (t7.isNumericLiteral(node)) return String(node.value);
1894
- if (t7.isStringLiteral(node)) return `"${node.value}"`;
1895
- if (t7.isBooleanLiteral(node)) return String(node.value);
1896
- if (t7.isNullLiteral(node)) return "null";
1897
- if (t7.isBinaryExpression(node)) {
1898
- return `(${generateCode2(node.left)} ${node.operator} ${generateCode2(node.right)})`;
1899
- }
1900
- if (t7.isLogicalExpression(node)) {
1901
- return `(${generateCode2(node.left)} ${node.operator} ${generateCode2(node.right)})`;
1902
- }
1903
- if (t7.isConditionalExpression(node)) {
1904
- return `(${generateCode2(node.test)} ? ${generateCode2(node.consequent)} : ${generateCode2(node.alternate)})`;
1905
- }
1906
- if (t7.isUnaryExpression(node) && node.prefix) {
1907
- return `${node.operator}${generateCode2(node.argument)}`;
1908
- }
1909
- if (t7.isCallExpression(node) && t7.isMemberExpression(node.callee) && t7.isIdentifier(node.callee.object) && node.callee.object.name === "Date" && t7.isIdentifier(node.callee.property) && node.callee.property.name === "now") {
1910
- return "now()";
1911
- }
1912
- if (t7.isMemberExpression(node)) {
1913
- const obj = generateCode2(node.object);
1914
- if (node.computed) {
1915
- return `${obj}[${generateCode2(node.property)}]`;
1916
- }
1917
- const prop = t7.isIdentifier(node.property) ? node.property.name : "[property]";
1918
- return `${obj}.${prop}`;
1919
- }
1920
- if (t7.isCallExpression(node)) {
1921
- if (t7.isIdentifier(node.callee)) {
1922
- const args = node.arguments.map((a) => generateCode2(a)).join(", ");
1923
- return `${node.callee.name}(${args})`;
1924
- }
1925
- if (t7.isMemberExpression(node.callee)) {
1926
- const obj = generateCode2(node.callee.object);
1927
- const prop = t7.isIdentifier(node.callee.property) ? node.callee.property.name : "[method]";
1928
- const args = node.arguments.map((a) => generateCode2(a)).join(", ");
1929
- return `${obj}.${prop}(${args})`;
1930
- }
1931
- }
1932
- if (t7.isArrowFunctionExpression(node) || t7.isFunctionExpression(node)) {
1933
- if (t7.isArrowFunctionExpression(node) && t7.isExpression(node.body)) {
1934
- const params = node.params;
1935
- if (params.length === 1 && t7.isIdentifier(params[0])) {
1936
- const paramName = params[0].name;
1937
- const bodyCode = generateCode2(node.body);
1938
- return bodyCode.replace(new RegExp(`\\b${paramName}\\b`, "g"), "$prev");
1939
- }
1940
- }
1941
- return "[Function]";
1942
- }
1943
- if (t7.isTemplateLiteral(node)) {
1944
- return node.quasis.map((q, i) => {
1945
- const raw = q.value.raw;
1946
- if (i < node.expressions.length) return raw + "${" + generateCode2(node.expressions[i]) + "}";
1947
- return raw;
1948
- }).join("");
1949
- }
1950
- if (t7.isArrayExpression(node)) {
1951
- const elements = node.elements.map((el) => el ? generateCode2(el) : "undefined").join(", ");
1952
- return `[${elements}]`;
1953
- }
1954
- if (t7.isObjectExpression(node)) {
1955
- const props = node.properties.map((p) => {
1956
- if (t7.isObjectProperty(p)) {
1957
- const key = t7.isIdentifier(p.key) ? p.key.name : t7.isStringLiteral(p.key) ? `"${p.key.value}"` : "[key]";
1958
- if (p.shorthand && t7.isIdentifier(p.value)) return key;
1959
- return `${key}: ${generateCode2(p.value)}`;
1960
- }
1961
- if (t7.isSpreadElement(p)) return `...${generateCode2(p.argument)}`;
1962
- return "";
1963
- }).filter(Boolean).join(", ");
1964
- return `{ ${props} }`;
1965
- }
1966
- if (t7.isTSAsExpression(node)) return generateCode2(node.expression);
1967
- if (t7.isTSNonNullExpression(node)) return generateCode2(node.expression);
1968
- return "[Expression]";
1969
- }
1970
- function ensureState3(states, stateName) {
1971
- if (!states.has(stateName)) {
1972
- states.set(stateName, {
1973
- name: stateName,
1974
- type: "REGULAR",
1975
- on_enter: [],
1976
- during: [],
1977
- on_exit: []
1978
- });
1979
- }
1980
- return states.get(stateName);
1981
- }
1982
- function extractDuring(path, state) {
1983
- const callee = path.node.callee;
1984
- if (!t7.isIdentifier(callee) || callee.name !== "useWhileIn") return;
1985
- const args = path.node.arguments;
1986
- if (args.length < 3) return;
1987
- const stateArg = args[0];
1988
- const intervalArg = args[1];
1989
- const callbackArg = args[2];
1990
- if (!t7.isStringLiteral(stateArg)) return;
1991
- const stateName = stateArg.value;
1992
- let intervalMs = 1e3;
1993
- if (t7.isNumericLiteral(intervalArg)) {
1994
- intervalMs = intervalArg.value;
1995
- }
1996
- let callbackBody = [];
1997
- if (t7.isArrowFunctionExpression(callbackArg) || t7.isFunctionExpression(callbackArg)) {
1998
- const body = callbackArg.body;
1999
- if (t7.isBlockStatement(body)) {
2000
- callbackBody = body.body;
2001
- } else if (t7.isExpression(body)) {
2002
- callbackBody = [t7.expressionStatement(body)];
2003
- }
2004
- }
2005
- const compilerState = state;
2006
- if (!compilerState.states) compilerState.states = /* @__PURE__ */ new Map();
2007
- if (!compilerState.actionCounter) compilerState.actionCounter = 0;
2008
- const stateDefinition = ensureState3(compilerState.states, stateName);
2009
- const actions = analyzeCallbackBody2(callbackBody, { value: compilerState.actionCounter });
2010
- compilerState.actionCounter += actions.length;
2011
- const duringAction = {
2012
- id: `during_${++duringIdCounter}`,
2013
- type: "interval",
2014
- interval_ms: intervalMs,
2015
- actions
2016
- };
2017
- stateDefinition.during.push(duringAction);
2018
- }
2019
-
2020
- // src/babel/extractors/change-extractor.ts
2021
- import * as t8 from "@babel/types";
2022
- var watcherIdCounter = 0;
2023
- function resetWatcherIdCounter() {
2024
- watcherIdCounter = 0;
2025
- }
2026
- function analyzeCallbackBody3(body, actionCounter) {
2027
- const actions = [];
2028
- for (const statement of body) {
2029
- if (!t8.isExpressionStatement(statement)) continue;
2030
- const expr = statement.expression;
2031
- if (t8.isCallExpression(expr) && t8.isIdentifier(expr.callee)) {
2032
- const calleeName = expr.callee.name;
2033
- const args = expr.arguments;
2034
- if (calleeName === "setField" && args.length >= 2) {
2035
- const field = t8.isStringLiteral(args[0]) ? args[0].value : void 0;
2036
- if (field !== void 0) {
2037
- actions.push({
2038
- id: `auto_${++actionCounter.value}`,
2039
- type: "set_field",
2040
- mode: "auto",
2041
- config: { field, value: extractValue3(args[1]) }
2042
- });
2043
- }
2044
- } else if (calleeName === "setMemory" && args.length >= 2) {
2045
- const key = t8.isStringLiteral(args[0]) ? args[0].value : void 0;
2046
- if (key !== void 0) {
2047
- actions.push({
2048
- id: `auto_${++actionCounter.value}`,
2049
- type: "set_memory",
2050
- mode: "auto",
2051
- config: { key, value: extractValue3(args[1]) }
2052
- });
2053
- }
2054
- } else if (calleeName.startsWith("set") && calleeName.length > 3 && args.length >= 1) {
2055
- const fieldName = calleeName.slice(3, 4).toLowerCase() + calleeName.slice(4);
2056
- actions.push({
2057
- id: `auto_${++actionCounter.value}`,
2058
- type: "set_field",
2059
- mode: "auto",
2060
- config: { field: fieldName, value: extractValue3(args[0]) }
2061
- });
2062
- }
2063
- } else if (t8.isCallExpression(expr)) {
2064
- const callee = expr.callee;
2065
- if (t8.isMemberExpression(callee) && t8.isIdentifier(callee.object) && callee.object.name === "console" && t8.isIdentifier(callee.property) && callee.property.name === "log" && expr.arguments.length > 0) {
2066
- actions.push({
2067
- id: `auto_${++actionCounter.value}`,
2068
- type: "log_event",
2069
- mode: "auto",
2070
- config: { message: extractValue3(expr.arguments[0]) }
2071
- });
2072
- }
2073
- }
2074
- }
2075
- return actions;
2076
- }
2077
- function extractValue3(node) {
2078
- if (t8.isNumericLiteral(node)) return node.value;
2079
- if (t8.isStringLiteral(node)) return node.value;
2080
- if (t8.isBooleanLiteral(node)) return node.value;
2081
- if (t8.isNullLiteral(node)) return null;
2082
- if (t8.isIdentifier(node)) return node.name;
2083
- if (t8.isTemplateLiteral(node)) {
2084
- return node.quasis.map((q, i) => {
2085
- const raw = q.value.raw;
2086
- if (i < node.expressions.length) {
2087
- const expr = node.expressions[i];
2088
- return raw + "${" + (t8.isIdentifier(expr) ? expr.name : "[expr]") + "}";
2089
- }
2090
- return raw;
2091
- }).join("");
2092
- }
2093
- if (t8.isArrayExpression(node)) {
2094
- return node.elements.map((el) => el && t8.isExpression(el) ? extractValue3(el) : null);
2095
- }
2096
- if (t8.isObjectExpression(node)) {
2097
- const obj = {};
2098
- node.properties.forEach((prop) => {
2099
- if (t8.isObjectProperty(prop) && t8.isIdentifier(prop.key) && t8.isExpression(prop.value)) {
2100
- obj[prop.key.name] = extractValue3(prop.value);
2101
- }
2102
- });
2103
- return obj;
2104
- }
2105
- if (t8.isMemberExpression(node)) {
2106
- const obj = t8.isIdentifier(node.object) ? node.object.name : "[object]";
2107
- const prop = t8.isIdentifier(node.property) ? node.property.name : "[property]";
2108
- return `${obj}.${prop}`;
2109
- }
2110
- if (t8.isConditionalExpression(node)) {
2111
- return `(${extractValue3(node.test)} ? ${extractValue3(node.consequent)} : ${extractValue3(node.alternate)})`;
2112
- }
2113
- if (t8.isBinaryExpression(node)) {
2114
- return `(${extractValue3(node.left)} ${node.operator} ${extractValue3(node.right)})`;
2115
- }
2116
- if (t8.isLogicalExpression(node)) {
2117
- return `(${extractValue3(node.left)} ${node.operator} ${extractValue3(node.right)})`;
2118
- }
2119
- if (t8.isTSAsExpression(node)) return extractValue3(node.expression);
2120
- if (t8.isTSNonNullExpression(node)) return extractValue3(node.expression);
2121
- return "[Expression]";
2122
- }
2123
- function extractChangeWatcher(path, state) {
2124
- const callee = path.node.callee;
2125
- if (!t8.isIdentifier(callee) || callee.name !== "useOnChange") return;
2126
- const args = path.node.arguments;
2127
- if (args.length < 2) return;
2128
- const fieldArg = args[0];
2129
- const callbackArg = args[1];
2130
- if (!t8.isStringLiteral(fieldArg)) return;
2131
- const field = fieldArg.value;
2132
- let callbackBody = [];
2133
- if (t8.isArrowFunctionExpression(callbackArg) || t8.isFunctionExpression(callbackArg)) {
2134
- const body = callbackArg.body;
2135
- if (t8.isBlockStatement(body)) {
2136
- callbackBody = body.body;
2137
- } else if (t8.isExpression(body)) {
2138
- callbackBody = [t8.expressionStatement(body)];
2139
- }
2140
- }
2141
- const compilerState = state;
2142
- if (!compilerState.actionCounter) compilerState.actionCounter = 0;
2143
- const actions = analyzeCallbackBody3(callbackBody, { value: compilerState.actionCounter });
2144
- compilerState.actionCounter += actions.length;
2145
- const watcher = {
2146
- id: `watcher_${++watcherIdCounter}`,
2147
- field,
2148
- actions
2149
- };
2150
- if (!compilerState.metadata) compilerState.metadata = {};
2151
- const meta = compilerState.metadata;
2152
- if (!meta.fieldWatchers) meta.fieldWatchers = [];
2153
- meta.fieldWatchers.push(watcher);
2154
- }
2155
-
2156
- // src/babel/extractors/computed-extractor.ts
2157
- import * as t9 from "@babel/types";
2158
- function expressionToString(node) {
2159
- if (t9.isIdentifier(node)) return node.name;
2160
- if (t9.isNumericLiteral(node)) return String(node.value);
2161
- if (t9.isStringLiteral(node)) return `"${node.value}"`;
2162
- if (t9.isBooleanLiteral(node)) return String(node.value);
2163
- if (t9.isNullLiteral(node)) return "null";
2164
- if (t9.isTemplateLiteral(node)) {
2165
- return node.quasis.map((q, i) => {
2166
- const raw = q.value.raw;
2167
- if (i < node.expressions.length) {
2168
- const expr = node.expressions[i];
2169
- return raw + "${" + expressionToString(expr) + "}";
2170
- }
2171
- return raw;
2172
- }).join("");
2173
- }
2174
- if (t9.isBinaryExpression(node)) {
2175
- return `${expressionToString(node.left)} ${node.operator} ${expressionToString(node.right)}`;
2176
- }
2177
- if (t9.isLogicalExpression(node)) {
2178
- return `${expressionToString(node.left)} ${node.operator} ${expressionToString(node.right)}`;
2179
- }
2180
- if (t9.isConditionalExpression(node)) {
2181
- return `${expressionToString(node.test)} ? ${expressionToString(node.consequent)} : ${expressionToString(node.alternate)}`;
2182
- }
2183
- if (t9.isMemberExpression(node) && !node.computed) {
2184
- return `${expressionToString(node.object)}.${expressionToString(node.property)}`;
2185
- }
2186
- if (t9.isCallExpression(node)) {
2187
- const callee = expressionToString(node.callee);
2188
- const args = node.arguments.map((a) => expressionToString(a)).join(", ");
2189
- return `${callee}(${args})`;
2190
- }
2191
- if (t9.isUnaryExpression(node)) {
2192
- return `${node.operator}${expressionToString(node.argument)}`;
2193
- }
2194
- if (t9.isParenthesizedExpression(node)) {
2195
- return `(${expressionToString(node.expression)})`;
2196
- }
2197
- return "[Expression]";
2198
- }
2199
- function inferComputedType(body) {
2200
- if (t9.isNumericLiteral(body) || t9.isBinaryExpression(body)) return "number";
2201
- if (t9.isStringLiteral(body) || t9.isTemplateLiteral(body)) return "text";
2202
- if (t9.isBooleanLiteral(body) || t9.isLogicalExpression(body)) return "boolean";
2203
- if (t9.isArrayExpression(body)) return "json";
2204
- if (t9.isObjectExpression(body)) return "json";
2205
- return "text";
2206
- }
2207
- function extractStringArray(node) {
2208
- if (!t9.isArrayExpression(node)) return [];
2209
- return node.elements.filter((el) => t9.isStringLiteral(el)).map((el) => el.value);
2210
- }
2211
- function extractComputed(path, state) {
2212
- const callee = path.node.callee;
2213
- if (!t9.isIdentifier(callee) || callee.name !== "useComputed") return;
2214
- const args = path.node.arguments;
2215
- if (args.length < 2) return;
2216
- const nameArg = args[0];
2217
- if (!t9.isStringLiteral(nameArg)) return;
2218
- const fieldName = nameArg.value;
2219
- const computeArg = args[1];
2220
- if (!t9.isArrowFunctionExpression(computeArg) && !t9.isFunctionExpression(computeArg)) return;
2221
- let expression;
2222
- let returnType = "text";
2223
- if (t9.isExpression(computeArg.body) && !t9.isBlockStatement(computeArg.body)) {
2224
- expression = expressionToString(computeArg.body);
2225
- returnType = inferComputedType(computeArg.body);
2226
- } else if (t9.isBlockStatement(computeArg.body)) {
2227
- const returnStmt = computeArg.body.body.find(
2228
- (s) => t9.isReturnStatement(s)
2229
- );
2230
- if (returnStmt?.argument) {
2231
- expression = expressionToString(returnStmt.argument);
2232
- returnType = inferComputedType(returnStmt.argument);
2233
- } else {
2234
- expression = "[Expression]";
2235
- }
2236
- } else {
2237
- expression = "[Expression]";
2238
- }
2239
- let mode = "read-time";
2240
- let deps = [];
2241
- let staleness;
2242
- let rlsStalenessOk;
2243
- let explicitType;
2244
- if (args.length >= 3 && t9.isObjectExpression(args[2])) {
2245
- const optObj = args[2];
2246
- for (const prop of optObj.properties) {
2247
- if (!t9.isObjectProperty(prop) || !t9.isIdentifier(prop.key)) continue;
2248
- switch (prop.key.name) {
2249
- case "mode":
2250
- if (t9.isStringLiteral(prop.value)) {
2251
- const modeVal = prop.value.value;
2252
- if (modeVal === "read-time" || modeVal === "transaction-maintained" || modeVal === "async-materialized") {
2253
- mode = modeVal;
2254
- }
2255
- }
2256
- break;
2257
- case "deps":
2258
- deps = extractStringArray(prop.value);
2259
- break;
2260
- case "staleness":
2261
- if (t9.isStringLiteral(prop.value)) {
2262
- staleness = prop.value.value;
2263
- }
2264
- break;
2265
- case "rlsStalenessOk":
2266
- if (t9.isBooleanLiteral(prop.value)) {
2267
- rlsStalenessOk = prop.value.value;
2268
- }
2269
- break;
2270
- case "type":
2271
- if (t9.isStringLiteral(prop.value)) {
2272
- explicitType = prop.value.value;
2273
- }
2274
- break;
2275
- }
2276
- }
2277
- }
2278
- let varName = fieldName;
2279
- const parent = path.parentPath;
2280
- if (parent?.isVariableDeclarator() && t9.isIdentifier(parent.node.id)) {
2281
- varName = parent.node.id.name;
2282
- }
2283
- const compilerState = state;
2284
- const fieldDef = {
2285
- name: fieldName,
2286
- type: explicitType || returnType,
2287
- computed: expression,
2288
- computed_deps: deps.length > 0 ? deps : void 0
2289
- };
2290
- fieldDef.computed_mode = mode;
2291
- if (staleness !== void 0) {
2292
- fieldDef.computed_staleness = staleness;
2293
- }
2294
- if (rlsStalenessOk !== void 0) {
2295
- fieldDef.rls_staleness_tolerance = rlsStalenessOk;
2296
- }
2297
- compilerState.fields.push(fieldDef);
2298
- if (!compilerState.metadata) compilerState.metadata = {};
2299
- const meta = compilerState.metadata;
2300
- if (!meta.computedFields) meta.computedFields = [];
2301
- meta.computedFields.push({
2302
- name: fieldName,
2303
- varName,
2304
- expression,
2305
- deps,
2306
- mode,
2307
- type: explicitType || returnType,
2308
- staleness,
2309
- rlsStalenessOk
2310
- });
2311
- }
2312
-
2313
- // src/babel/extractors/transition-effect-extractor.ts
2314
- import * as t10 from "@babel/types";
2315
- var transitionEffectIdCounter = 0;
2316
- function resetTransitionEffectIdCounter() {
2317
- transitionEffectIdCounter = 0;
2318
- }
2319
- function analyzeCallbackBody4(body, actionCounter) {
2320
- const actions = [];
2321
- for (const statement of body) {
2322
- if (!t10.isExpressionStatement(statement)) continue;
2323
- const expr = statement.expression;
2324
- if (t10.isCallExpression(expr) && t10.isIdentifier(expr.callee)) {
2325
- const calleeName = expr.callee.name;
2326
- const args = expr.arguments;
2327
- if (calleeName === "setField" && args.length >= 2) {
2328
- const field = t10.isStringLiteral(args[0]) ? args[0].value : void 0;
2329
- if (field !== void 0) {
2330
- actions.push({
2331
- id: `auto_${++actionCounter.value}`,
2332
- type: "set_field",
2333
- mode: "auto",
2334
- config: { field, value: extractValue4(args[1]) }
2335
- });
2336
- }
2337
- } else if (calleeName === "setMemory" && args.length >= 2) {
2338
- const key = t10.isStringLiteral(args[0]) ? args[0].value : void 0;
2339
- if (key !== void 0) {
2340
- actions.push({
2341
- id: `auto_${++actionCounter.value}`,
2342
- type: "set_memory",
2343
- mode: "auto",
2344
- config: { key, value: extractValue4(args[1]) }
2345
- });
2346
- }
2347
- } else if (calleeName.startsWith("set") && calleeName.length > 3 && args.length >= 1) {
2348
- const fieldName = calleeName.slice(3, 4).toLowerCase() + calleeName.slice(4);
2349
- actions.push({
2350
- id: `auto_${++actionCounter.value}`,
2351
- type: "set_field",
2352
- mode: "auto",
2353
- config: { field: fieldName, value: extractValue4(args[0]) }
2354
- });
2355
- }
2356
- } else if (t10.isCallExpression(expr)) {
2357
- const callee = expr.callee;
2358
- if (t10.isMemberExpression(callee) && t10.isIdentifier(callee.object) && callee.object.name === "console" && t10.isIdentifier(callee.property) && callee.property.name === "log" && expr.arguments.length > 0) {
2359
- actions.push({
2360
- id: `auto_${++actionCounter.value}`,
2361
- type: "log_event",
2362
- mode: "auto",
2363
- config: { message: extractValue4(expr.arguments[0]) }
2364
- });
2365
- }
2366
- }
2367
- }
2368
- return actions;
2369
- }
2370
- function extractValue4(node) {
2371
- if (t10.isNumericLiteral(node)) return node.value;
2372
- if (t10.isStringLiteral(node)) return node.value;
2373
- if (t10.isBooleanLiteral(node)) return node.value;
2374
- if (t10.isNullLiteral(node)) return null;
2375
- if (t10.isIdentifier(node)) return node.name;
2376
- if (t10.isArrayExpression(node)) {
2377
- return node.elements.map((el) => el && t10.isExpression(el) ? extractValue4(el) : null);
2378
- }
2379
- if (t10.isObjectExpression(node)) {
2380
- const obj = {};
2381
- node.properties.forEach((prop) => {
2382
- if (t10.isObjectProperty(prop) && t10.isIdentifier(prop.key) && t10.isExpression(prop.value)) {
2383
- obj[prop.key.name] = extractValue4(prop.value);
2384
- }
2385
- });
2386
- return obj;
2387
- }
2388
- if (t10.isMemberExpression(node)) {
2389
- const obj = t10.isIdentifier(node.object) ? node.object.name : "[object]";
2390
- const prop = t10.isIdentifier(node.property) ? node.property.name : "[property]";
2391
- return `${obj}.${prop}`;
2392
- }
2393
- if (t10.isConditionalExpression(node)) {
2394
- return `(${extractValue4(node.test)} ? ${extractValue4(node.consequent)} : ${extractValue4(node.alternate)})`;
2395
- }
2396
- if (t10.isTSAsExpression(node)) return extractValue4(node.expression);
2397
- if (t10.isTSNonNullExpression(node)) return extractValue4(node.expression);
2398
- return "[Expression]";
2399
- }
2400
- function extractTransitionEffect(path, state) {
2401
- const callee = path.node.callee;
2402
- if (!t10.isIdentifier(callee) || callee.name !== "useOnTransition") return;
2403
- const args = path.node.arguments;
2404
- if (args.length < 1) return;
2405
- const callbackArg = args[0];
2406
- let callbackBody = [];
2407
- if (t10.isArrowFunctionExpression(callbackArg) || t10.isFunctionExpression(callbackArg)) {
2408
- const body = callbackArg.body;
2409
- if (t10.isBlockStatement(body)) {
2410
- callbackBody = body.body;
2411
- } else if (t10.isExpression(body)) {
2412
- callbackBody = [t10.expressionStatement(body)];
2413
- }
2414
- }
2415
- const compilerState = state;
2416
- if (!compilerState.actionCounter) compilerState.actionCounter = 0;
2417
- const actions = analyzeCallbackBody4(callbackBody, { value: compilerState.actionCounter });
2418
- compilerState.actionCounter += actions.length;
2419
- const effect = {
2420
- id: `transition_effect_${++transitionEffectIdCounter}`,
2421
- actions
2422
- };
2423
- if (!compilerState.metadata) compilerState.metadata = {};
2424
- const meta = compilerState.metadata;
2425
- if (!meta.transitionEffects) meta.transitionEffects = [];
2426
- meta.transitionEffects.push(effect);
2427
- }
2428
-
2429
- // src/babel/extractors/model-extractor.ts
2430
- import * as t11 from "@babel/types";
2431
- function tsTypeToFieldType(typeAnnotation) {
2432
- if (!typeAnnotation) return "text";
2433
- const annotation = typeAnnotation.typeAnnotation;
2434
- return resolveType(annotation);
2435
- }
2436
- var KNOWN_TYPE_REFS2 = {
2437
- Date: "datetime",
2438
- Record: "json",
2439
- Map: "json",
2440
- Set: "json",
2441
- URL: "url"
2442
- };
2443
- function typeNameToSlug2(name) {
2444
- return name.replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
2445
- }
2446
- function resolveType(annotation) {
2447
- if (t11.isTSStringKeyword(annotation)) return "text";
2448
- if (t11.isTSNumberKeyword(annotation)) return "number";
2449
- if (t11.isTSBooleanKeyword(annotation)) return "boolean";
2450
- if (t11.isTSTypeReference(annotation) && t11.isIdentifier(annotation.typeName)) {
2451
- const typeName = annotation.typeName.name;
2452
- if (KNOWN_TYPE_REFS2[typeName]) return KNOWN_TYPE_REFS2[typeName];
2453
- if (typeName === "Array") return "multi_select";
2454
- return typeNameToSlug2(typeName);
2455
- }
2456
- if (t11.isTSArrayType(annotation)) {
2457
- return "multi_select";
2458
- }
2459
- if (t11.isTSUnionType(annotation)) {
2460
- const allLiterals = annotation.types.every(
2461
- (t22) => t11.isTSLiteralType(t22) && (t11.isStringLiteral(t22.literal) || t11.isNumericLiteral(t22.literal))
2462
- );
2463
- if (allLiterals) return "select";
2464
- return "text";
2465
- }
2466
- if (t11.isTSLiteralType(annotation) && t11.isStringLiteral(annotation.literal)) return "text";
2467
- if (t11.isTSLiteralType(annotation) && t11.isNumericLiteral(annotation.literal)) return "number";
2468
- return "text";
2469
- }
2470
- function extractUnionOptions(annotation) {
2471
- if (!t11.isTSUnionType(annotation)) return void 0;
2472
- const options = [];
2473
- for (const member of annotation.types) {
2474
- if (t11.isTSLiteralType(member) && t11.isStringLiteral(member.literal)) {
2475
- options.push(member.literal.value);
2476
- }
2477
- }
2478
- return options.length > 0 ? options : void 0;
2479
- }
2480
- function extractDefaultValue2(fieldType) {
2481
- switch (fieldType) {
2482
- case "text":
2483
- return "";
2484
- case "rich_text":
2485
- return "";
2486
- case "number":
2487
- return 0;
2488
- case "boolean":
2489
- return false;
2490
- case "date":
2491
- return null;
2492
- case "datetime":
2493
- return null;
2494
- case "select":
2495
- return "";
2496
- case "multi_select":
2497
- return [];
2498
- case "url":
2499
- return "";
2500
- case "json":
2501
- return {};
2502
- // Custom Element-based field types (email, currency, etc.) default to null
2503
- default:
2504
- return null;
2505
- }
2506
- }
2507
- function extractFieldsFromInterface(declaration) {
2508
- const fields = [];
2509
- for (const member of declaration.body.body) {
2510
- if (!t11.isTSPropertySignature(member)) continue;
2511
- if (!t11.isIdentifier(member.key)) continue;
2512
- const name = member.key.name;
2513
- const required = !member.optional;
2514
- const typeAnno = member.typeAnnotation;
2515
- const fieldType = tsTypeToFieldType(typeAnno);
2516
- const field = {
2517
- name,
2518
- type: fieldType,
2519
- label: name.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase()),
2520
- required,
2521
- default_value: extractDefaultValue2(fieldType)
2522
- };
2523
- if (typeAnno) {
2524
- const options = extractUnionOptions(typeAnno.typeAnnotation);
2525
- if (options) {
2526
- field.validation = { options };
2527
- }
2528
- }
2529
- fields.push(field);
2530
- }
2531
- return fields;
2532
- }
2533
- function extractTransitionsFromObject(init, actionCounter) {
2534
- const transitions = [];
2535
- for (const prop of init.properties) {
2536
- if (!t11.isObjectProperty(prop)) continue;
2537
- if (!t11.isIdentifier(prop.key) && !t11.isStringLiteral(prop.key)) continue;
2538
- if (!t11.isObjectExpression(prop.value)) continue;
2539
- const name = t11.isIdentifier(prop.key) ? prop.key.name : prop.key.value;
2540
- const config = extractObjectLiteral(prop.value);
2541
- let from = [];
2542
- if (typeof config.from === "string") {
2543
- from = [config.from];
2544
- } else if (Array.isArray(config.from)) {
2545
- from = config.from.map(String);
2546
- }
2547
- const to = String(config.to || "");
2548
- const conditions = [];
2549
- if (config.guard) {
2550
- conditions.push(parseGuardExpression(config.guard));
2551
- }
2552
- if (config.conditions && Array.isArray(config.conditions)) {
2553
- for (const cond of config.conditions) {
2554
- conditions.push(cond);
2555
- }
2556
- }
2557
- const actions = [];
2558
- if (config.actions && Array.isArray(config.actions)) {
2559
- for (const action of config.actions) {
2560
- if (typeof action === "object" && action !== null) {
2561
- actions.push({
2562
- id: `auto_${++actionCounter.value}`,
2563
- type: action.type || "custom",
2564
- mode: "auto",
2565
- config: action
2566
- });
2567
- }
2568
- }
2569
- }
2570
- transitions.push({
2571
- name,
2572
- from,
2573
- to,
2574
- description: config.description,
2575
- conditions: conditions.length > 0 ? conditions : void 0,
2576
- actions,
2577
- roles: config.roles,
2578
- auto: config.auto,
2579
- required_fields: config.required_fields
2580
- });
2581
- }
2582
- return transitions;
2583
- }
2584
- function parseGuardExpression(guard) {
2585
- const simpleMatch = guard.match(
2586
- /^(\$?\w+(?:\.\w+)*)\s*(not_in|is_set|is_empty|contains|>=|<=|!=|==|>|<|in)\s*(.+)?$/
2587
- );
2588
- if (simpleMatch) {
2589
- const [, field, op, rawValue] = simpleMatch;
2590
- const operatorMap = {
2591
- "==": "eq",
2592
- "!=": "ne",
2593
- ">": "gt",
2594
- ">=": "gte",
2595
- "<": "lt",
2596
- "<=": "lte",
2597
- "in": "in",
2598
- "not_in": "not_in",
2599
- "contains": "contains",
2600
- "is_set": "is_set",
2601
- "is_empty": "is_empty"
2602
- };
2603
- const operator = operatorMap[op];
2604
- if (operator) {
2605
- let value = rawValue?.trim();
2606
- if (value === void 0 || value === "") {
2607
- return { field, operator };
2608
- }
2609
- if (typeof value === "string") {
2610
- if (value.startsWith('"') && value.endsWith('"')) {
2611
- value = value.slice(1, -1);
2612
- } else if (value.startsWith("'") && value.endsWith("'")) {
2613
- value = value.slice(1, -1);
2614
- } else if (value === "true") {
2615
- value = true;
2616
- } else if (value === "false") {
2617
- value = false;
2618
- } else if (value === "null") {
2619
- value = null;
2620
- } else if (!isNaN(Number(value))) {
2621
- value = Number(value);
2622
- }
2623
- }
2624
- return { field, operator, value };
2625
- }
2626
- }
2627
- return { expression: guard };
2628
- }
2629
- function extractHooksFromObject(init, states, actionCounter) {
2630
- for (const prop of init.properties) {
2631
- if (!t11.isObjectProperty(prop)) continue;
2632
- if (!t11.isIdentifier(prop.key) && !t11.isStringLiteral(prop.key)) continue;
2633
- const hookName = t11.isIdentifier(prop.key) ? prop.key.name : prop.key.value;
2634
- const hookConfig = t11.isObjectExpression(prop.value) ? extractObjectLiteral(prop.value) : {};
2635
- const enterMatch = hookName.match(/^on_enter_(.+)$/);
2636
- const exitMatch = hookName.match(/^on_exit_(.+)$/);
2637
- if (!enterMatch && !exitMatch) continue;
2638
- const stateName = enterMatch ? enterMatch[1] : exitMatch[1];
2639
- const phase = enterMatch ? "on_enter" : "on_exit";
2640
- if (!states.has(stateName)) {
2641
- states.set(stateName, {
2642
- name: stateName,
2643
- type: "REGULAR",
2644
- on_enter: [],
2645
- during: [],
2646
- on_exit: []
2647
- });
2648
- }
2649
- const state = states.get(stateName);
2650
- if (hookConfig.emit && typeof hookConfig.emit === "string") {
2651
- const action = {
2652
- id: `auto_${++actionCounter.value}`,
2653
- type: "emit_event",
2654
- mode: "auto",
2655
- config: { event: hookConfig.emit }
2656
- };
2657
- state[phase].push(action);
2658
- }
2659
- if (hookConfig.actions && Array.isArray(hookConfig.actions)) {
2660
- for (const handler of hookConfig.actions) {
2661
- if (typeof handler === "string") {
2662
- const action = {
2663
- id: `auto_${++actionCounter.value}`,
2664
- type: "server_action",
2665
- mode: "auto",
2666
- config: { handler }
2667
- };
2668
- state[phase].push(action);
2669
- }
2670
- }
2671
- }
2672
- }
2673
- }
2674
- function applyFieldOptions(fields, init) {
2675
- const options = extractObjectLiteral(init);
2676
- for (const [fieldName, opts] of Object.entries(options)) {
2677
- const field = fields.find((f) => f.name === fieldName);
2678
- if (!field) continue;
2679
- if (opts.scope || opts.persistence || opts.sync) {
2680
- field.state_home = {
2681
- scope: opts.scope || "instance",
2682
- persistence: opts.persistence || "durable",
2683
- sync: opts.sync || "none"
2684
- };
2685
- }
2686
- if (opts.computed && typeof opts.computed === "string") {
2687
- field.computed = opts.computed;
2688
- }
2689
- if (opts.computed_deps && Array.isArray(opts.computed_deps)) {
2690
- field.computed_deps = opts.computed_deps.map(String);
2691
- }
2692
- if (opts.visible_in_states && Array.isArray(opts.visible_in_states)) {
2693
- field.visible_in_states = opts.visible_in_states.map(String);
2694
- }
2695
- if (opts.editable_in_states && Array.isArray(opts.editable_in_states)) {
2696
- field.editable_in_states = opts.editable_in_states.map(String);
2697
- }
2698
- if (opts.visible_to_roles && Array.isArray(opts.visible_to_roles)) {
2699
- field.visible_to_roles = opts.visible_to_roles.map(String);
2700
- }
2701
- if (opts.editable_by_roles && Array.isArray(opts.editable_by_roles)) {
2702
- field.editable_by_roles = opts.editable_by_roles.map(String);
2703
- }
2704
- if (opts.visible_when && typeof opts.visible_when === "string") {
2705
- field.visible_when = opts.visible_when;
2706
- }
2707
- if (opts.editable_when && typeof opts.editable_when === "string") {
2708
- field.editable_when = opts.editable_when;
2709
- }
2710
- if (opts.validation && typeof opts.validation === "object") {
2711
- const val = opts.validation;
2712
- const validation = field.validation || {};
2713
- if (val.min !== void 0) validation.min = Number(val.min);
2714
- if (val.max !== void 0) validation.max = Number(val.max);
2715
- if (val.minLength !== void 0) validation.minLength = Number(val.minLength);
2716
- if (val.maxLength !== void 0) validation.maxLength = Number(val.maxLength);
2717
- if (val.options && Array.isArray(val.options)) {
2718
- validation.options = val.options.map(String);
2719
- }
2720
- if (val.rules && Array.isArray(val.rules)) {
2721
- validation.rules = val.rules.map((r) => ({
2722
- expression: String(r.expression || ""),
2723
- message: String(r.message || ""),
2724
- severity: r.severity === "warning" ? "warning" : "error"
2725
- }));
2726
- }
2727
- field.validation = validation;
2728
- }
2729
- }
2730
- }
2731
- function extractObjectLiteral(node) {
2732
- const obj = {};
2733
- for (const prop of node.properties) {
2734
- if (!t11.isObjectProperty(prop)) continue;
2735
- const key = t11.isIdentifier(prop.key) ? prop.key.name : t11.isStringLiteral(prop.key) ? prop.key.value : null;
2736
- if (!key) continue;
2737
- obj[key] = extractNodeValue(prop.value);
2738
- }
2739
- return obj;
2740
- }
2741
- function extractNodeValue(node) {
2742
- if (t11.isStringLiteral(node)) return node.value;
2743
- if (t11.isNumericLiteral(node)) return node.value;
2744
- if (t11.isBooleanLiteral(node)) return node.value;
2745
- if (t11.isNullLiteral(node)) return null;
2746
- if (t11.isArrayExpression(node)) {
2747
- return node.elements.map((el) => {
2748
- if (!el) return null;
2749
- if (t11.isSpreadElement(el)) return "[Spread]";
2750
- return extractNodeValue(el);
2751
- });
2752
- }
2753
- if (t11.isObjectExpression(node)) {
2754
- return extractObjectLiteral(node);
2755
- }
2756
- if (t11.isTemplateLiteral(node)) {
2757
- return node.quasis.map((q) => q.value.raw).join("${}");
2758
- }
2759
- if (t11.isIdentifier(node)) {
2760
- if (node.name === "undefined") return void 0;
2761
- return node.name;
2762
- }
2763
- if (t11.isConditionalExpression(node)) {
2764
- return `(${extractNodeValue(node.test)} ? ${extractNodeValue(node.consequent)} : ${extractNodeValue(node.alternate)})`;
2765
- }
2766
- if (t11.isBinaryExpression(node)) {
2767
- return `(${extractNodeValue(node.left)} ${node.operator} ${extractNodeValue(node.right)})`;
2768
- }
2769
- if (t11.isLogicalExpression(node)) {
2770
- return `(${extractNodeValue(node.left)} ${node.operator} ${extractNodeValue(node.right)})`;
2771
- }
2772
- if (t11.isMemberExpression(node)) {
2773
- const obj = t11.isIdentifier(node.object) ? node.object.name : "[object]";
2774
- const prop = t11.isIdentifier(node.property) ? node.property.name : "[property]";
2775
- return `${obj}.${prop}`;
2776
- }
2777
- if (t11.isTSAsExpression(node)) return extractNodeValue(node.expression);
2778
- if (t11.isTSNonNullExpression(node)) return extractNodeValue(node.expression);
2779
- return "[Expression]";
2780
- }
2781
- function isModelFile(path, filename) {
2782
- if (filename && /\/models\//.test(filename)) return true;
2783
- let hasInterface = false;
2784
- let hasTransitions = false;
2785
- let hasDefineModel = false;
2786
- for (const node of path.node.body) {
2787
- if (t11.isExportDefaultDeclaration(node)) {
2788
- const decl = node.declaration;
2789
- if (t11.isCallExpression(decl) && t11.isIdentifier(decl.callee) && decl.callee.name === "defineModel") {
2790
- hasDefineModel = true;
2791
- }
2792
- }
2793
- if (t11.isExportNamedDeclaration(node)) {
2794
- if (t11.isTSInterfaceDeclaration(node.declaration)) {
2795
- hasInterface = true;
2796
- }
2797
- if (t11.isVariableDeclaration(node.declaration)) {
2798
- for (const decl of node.declaration.declarations) {
2799
- if (t11.isIdentifier(decl.id) && decl.id.name === "transitions") {
2800
- hasTransitions = true;
2801
- }
2802
- }
2803
- }
2804
- }
2805
- }
2806
- return hasDefineModel || hasInterface && hasTransitions;
2807
- }
2808
- function modelTypeToIRType(modelType) {
2809
- switch (modelType) {
2810
- case "string":
2811
- return "text";
2812
- case "number":
2813
- return "number";
2814
- case "boolean":
2815
- return "boolean";
2816
- case "date":
2817
- return "date";
2818
- case "array":
2819
- return "multi_select";
2820
- case "json":
2821
- return "json";
2822
- case "file":
2823
- return "file";
2824
- case "relation":
2825
- return "relation";
2826
- default:
2827
- return modelType;
2828
- }
2829
- }
2830
- function modelStateTypeToIR(type) {
2831
- if (type === "initial") return "START";
2832
- if (type === "final") return "END";
2833
- return "REGULAR";
2834
- }
2835
- function extractDefineModelCall(programPath, compilerState, actionCounter) {
2836
- for (const node of programPath.node.body) {
2837
- if (!t11.isExportDefaultDeclaration(node)) continue;
2838
- const decl = node.declaration;
2839
- if (!t11.isCallExpression(decl)) continue;
2840
- if (!t11.isIdentifier(decl.callee) || decl.callee.name !== "defineModel") continue;
2841
- if (decl.arguments.length === 0 || !t11.isObjectExpression(decl.arguments[0])) continue;
2842
- const config = extractObjectLiteral(decl.arguments[0]);
2843
- if (config.slug) compilerState.metadata.slug = String(config.slug);
2844
- if (config.version) compilerState.metadata.version = String(config.version);
2845
- if (config.category) {
2846
- if (Array.isArray(config.category)) {
2847
- compilerState.metadata.category = String(config.category[0]);
2848
- compilerState.metadata.categoryArray = config.category;
2849
- } else {
2850
- compilerState.metadata.category = String(config.category);
2851
- }
2852
- }
2853
- if (config.description) compilerState.metadata.description = String(config.description);
2854
- if (config.fields && typeof config.fields === "object" && !Array.isArray(config.fields)) {
2855
- const fieldsObj = config.fields;
2856
- for (const [name, fieldConfig] of Object.entries(fieldsObj)) {
2857
- const irType = modelTypeToIRType(String(fieldConfig.type || "text"));
2858
- const field = {
2859
- name,
2860
- type: irType,
2861
- required: fieldConfig.required === true,
2862
- default_value: fieldConfig.default !== void 0 ? fieldConfig.default : extractDefaultValue2(irType)
2863
- };
2864
- if (fieldConfig.enum && Array.isArray(fieldConfig.enum)) {
2865
- field.validation = { options: fieldConfig.enum.map(String) };
2866
- }
2867
- compilerState.fields.push(field);
2868
- }
2869
- }
2870
- if (config.states && typeof config.states === "object" && !Array.isArray(config.states)) {
2871
- const statesObj = config.states;
2872
- for (const [name, stateConfig] of Object.entries(statesObj)) {
2873
- const stateType = modelStateTypeToIR(stateConfig.type);
2874
- if (!compilerState.states.has(name)) {
2875
- compilerState.states.set(name, {
2876
- name,
2877
- type: stateType,
2878
- description: stateConfig.description,
2879
- on_enter: [],
2880
- during: [],
2881
- on_exit: []
2882
- });
2883
- } else {
2884
- compilerState.states.get(name).type = stateType;
2885
- }
2886
- }
2887
- }
2888
- if (config.transitions && typeof config.transitions === "object" && !Array.isArray(config.transitions)) {
2889
- const transObj = config.transitions;
2890
- for (const [name, transConfig] of Object.entries(transObj)) {
2891
- let from = [];
2892
- if (typeof transConfig.from === "string") {
2893
- from = [transConfig.from];
2894
- } else if (Array.isArray(transConfig.from)) {
2895
- from = transConfig.from.map(String);
2896
- }
2897
- const to = String(transConfig.to || "");
2898
- for (const f of from) {
2899
- if (!compilerState.states.has(f)) {
2900
- compilerState.states.set(f, {
2901
- name: f,
2902
- type: "REGULAR",
2903
- on_enter: [],
2904
- during: [],
2905
- on_exit: []
2906
- });
2907
- }
2908
- }
2909
- if (to && !compilerState.states.has(to)) {
2910
- compilerState.states.set(to, {
2911
- name: to,
2912
- type: "REGULAR",
2913
- on_enter: [],
2914
- during: [],
2915
- on_exit: []
2916
- });
2917
- }
2918
- const conditions = [];
2919
- if (transConfig.guard) {
2920
- conditions.push(parseGuardExpression(String(transConfig.guard)));
2921
- }
2922
- compilerState.transitions.push({
2923
- name,
2924
- from,
2925
- to,
2926
- description: transConfig.description,
2927
- conditions: conditions.length > 0 ? conditions : void 0,
2928
- actions: [],
2929
- roles: transConfig.roles,
2930
- auto: transConfig.auto,
2931
- required_fields: transConfig.required_fields
2932
- });
2933
- }
2934
- }
2935
- if (config.roles && typeof config.roles === "object" && !Array.isArray(config.roles)) {
2936
- const rolesObj = config.roles;
2937
- if (!compilerState.metadata.roles) compilerState.metadata.roles = {};
2938
- for (const [roleName, roleConfig] of Object.entries(rolesObj)) {
2939
- compilerState.metadata.roles[roleName] = {
2940
- description: roleConfig.description,
2941
- permissions: roleConfig.permissions
2942
- };
2943
- }
2944
- }
2945
- if (config.metadata && typeof config.metadata === "object") {
2946
- compilerState.metadata.modelMetadata = config.metadata;
2947
- }
2948
- return true;
2949
- }
2950
- return false;
2951
- }
2952
- function extractModelFile(path, state) {
2953
- const compilerState = state;
2954
- if (!compilerState.actionCounter) compilerState.actionCounter = 0;
2955
- const actionCounter = { value: compilerState.actionCounter };
2956
- const foundDefineModel = extractDefineModelCall(path, compilerState, actionCounter);
2957
- if (foundDefineModel) {
2958
- for (const node of path.node.body) {
2959
- if (t11.isExportNamedDeclaration(node) && t11.isTSInterfaceDeclaration(node.declaration)) {
2960
- const interfaceFields = extractFieldsFromInterface(node.declaration);
2961
- for (const iField of interfaceFields) {
2962
- const existing = compilerState.fields.find((f) => f.name === iField.name);
2963
- if (existing) {
2964
- if (iField.required) existing.required = true;
2965
- }
2966
- }
2967
- if (!compilerState.metadata.name) {
2968
- compilerState.metadata.name = node.declaration.id.name;
2969
- }
2970
- }
2971
- }
2972
- compilerState.actionCounter = actionCounter.value;
2973
- return;
2974
- }
2975
- let interfaceName = "";
2976
- for (const node of path.node.body) {
2977
- if (!t11.isExportNamedDeclaration(node)) continue;
2978
- const declaration = node.declaration;
2979
- if (t11.isTSInterfaceDeclaration(declaration)) {
2980
- interfaceName = declaration.id.name;
2981
- const fields = extractFieldsFromInterface(declaration);
2982
- compilerState.fields.push(...fields);
2983
- for (const field of fields) {
2984
- if (field.validation?.options && field.validation.options.length > 0) {
2985
- for (const option of field.validation.options) {
2986
- if (!compilerState.states.has(option)) {
2987
- compilerState.states.set(option, {
2988
- name: option,
2989
- type: "REGULAR",
2990
- on_enter: [],
2991
- during: [],
2992
- on_exit: []
2993
- });
2994
- }
2995
- }
2996
- const firstState = compilerState.states.get(field.validation.options[0]);
2997
- if (firstState) firstState.type = "START";
2998
- break;
2999
- }
3000
- }
3001
- if (!compilerState.metadata.name) {
3002
- compilerState.metadata.name = interfaceName;
3003
- }
3004
- }
3005
- if (t11.isVariableDeclaration(declaration)) {
3006
- for (const decl of declaration.declarations) {
3007
- if (!t11.isIdentifier(decl.id) || !decl.init) continue;
3008
- const varName = decl.id.name;
3009
- if (varName === "transitions" && t11.isObjectExpression(decl.init)) {
3010
- const transitions = extractTransitionsFromObject(decl.init, actionCounter);
3011
- compilerState.transitions.push(...transitions);
3012
- for (const trans of transitions) {
3013
- for (const fromState of trans.from) {
3014
- if (!compilerState.states.has(fromState)) {
3015
- compilerState.states.set(fromState, {
3016
- name: fromState,
3017
- type: "REGULAR",
3018
- on_enter: [],
3019
- during: [],
3020
- on_exit: []
3021
- });
3022
- }
3023
- }
3024
- if (trans.to && !compilerState.states.has(trans.to)) {
3025
- compilerState.states.set(trans.to, {
3026
- name: trans.to,
3027
- type: "REGULAR",
3028
- on_enter: [],
3029
- during: [],
3030
- on_exit: []
3031
- });
3032
- }
3033
- }
3034
- }
3035
- if (varName === "states") {
3036
- const arrExpr = t11.isTSAsExpression(decl.init) ? decl.init.expression : decl.init;
3037
- if (t11.isArrayExpression(arrExpr)) {
3038
- for (const el of arrExpr.elements) {
3039
- if (!t11.isObjectExpression(el)) continue;
3040
- let stateName = "";
3041
- let stateType = "REGULAR";
3042
- let stateDesc = "";
3043
- for (const prop of el.properties) {
3044
- if (!t11.isObjectProperty(prop) || !t11.isIdentifier(prop.key)) continue;
3045
- if (prop.key.name === "name" && t11.isStringLiteral(prop.value)) {
3046
- stateName = prop.value.value;
3047
- } else if (prop.key.name === "type") {
3048
- const val = t11.isTSAsExpression(prop.value) ? prop.value.expression : prop.value;
3049
- if (t11.isStringLiteral(val)) stateType = val.value;
3050
- } else if (prop.key.name === "description" && t11.isStringLiteral(prop.value)) {
3051
- stateDesc = prop.value.value;
3052
- }
3053
- }
3054
- if (stateName && !compilerState.states.has(stateName)) {
3055
- compilerState.states.set(stateName, {
3056
- name: stateName,
3057
- type: stateType,
3058
- description: stateDesc || void 0,
3059
- on_enter: [],
3060
- during: [],
3061
- on_exit: []
3062
- });
3063
- } else if (stateName) {
3064
- compilerState.states.get(stateName).type = stateType;
3065
- }
3066
- }
3067
- }
3068
- }
3069
- if (varName === "endStates" && t11.isArrayExpression(decl.init)) {
3070
- for (const el of decl.init.elements) {
3071
- if (t11.isStringLiteral(el)) {
3072
- if (!compilerState.states.has(el.value)) {
3073
- compilerState.states.set(el.value, {
3074
- name: el.value,
3075
- type: "END",
3076
- on_enter: [],
3077
- during: [],
3078
- on_exit: []
3079
- });
3080
- } else {
3081
- compilerState.states.get(el.value).type = "END";
3082
- }
3083
- }
3084
- }
3085
- }
3086
- if (varName === "cancelledStates" && t11.isArrayExpression(decl.init)) {
3087
- for (const el of decl.init.elements) {
3088
- if (t11.isStringLiteral(el)) {
3089
- if (!compilerState.states.has(el.value)) {
3090
- compilerState.states.set(el.value, {
3091
- name: el.value,
3092
- type: "CANCELLED",
3093
- on_enter: [],
3094
- during: [],
3095
- on_exit: []
3096
- });
3097
- } else {
3098
- compilerState.states.get(el.value).type = "CANCELLED";
3099
- }
3100
- }
3101
- }
3102
- }
3103
- if (varName === "hooks" && t11.isObjectExpression(decl.init)) {
3104
- extractHooksFromObject(decl.init, compilerState.states, actionCounter);
3105
- }
3106
- if (varName === "runtime" && t11.isStringLiteral(decl.init)) {
3107
- compilerState.metadata.runtime = decl.init.value;
3108
- }
3109
- if (varName === "fieldOptions" && t11.isObjectExpression(decl.init)) {
3110
- applyFieldOptions(compilerState.fields, decl.init);
3111
- }
3112
- }
3113
- }
3114
- }
3115
- compilerState.actionCounter = actionCounter.value;
3116
- if (interfaceName && compilerState.metadata.__slugAutoFallback) {
3117
- compilerState.metadata.slug = interfaceName.replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
3118
- delete compilerState.metadata.__slugAutoFallback;
3119
- }
3120
- }
3121
-
3122
- // src/babel/extractors/server-action-extractor.ts
3123
- import * as t12 from "@babel/types";
3124
- function isServerActionFile(filename) {
3125
- if (!filename) return false;
3126
- return /\.server\.(ts|tsx|js|jsx)$/.test(filename);
3127
- }
3128
- function extractServerActions(path, state) {
3129
- const compilerState = state;
3130
- const serverActions = [];
3131
- for (const node of path.node.body) {
3132
- if (t12.isExportNamedDeclaration(node)) {
3133
- const decl = node.declaration;
3134
- if (t12.isFunctionDeclaration(decl) && decl.id) {
3135
- const action = extractFunctionAction(decl);
3136
- if (action) {
3137
- const comments = node.leadingComments || decl.leadingComments || [];
3138
- action.description = extractDescription(comments);
3139
- serverActions.push(action);
3140
- }
3141
- }
3142
- if (t12.isVariableDeclaration(decl)) {
3143
- for (const varDecl of decl.declarations) {
3144
- if (!t12.isIdentifier(varDecl.id)) continue;
3145
- const init = varDecl.init;
3146
- if (t12.isArrowFunctionExpression(init) || t12.isFunctionExpression(init)) {
3147
- const action = {
3148
- name: varDecl.id.name,
3149
- async: init.async || false,
3150
- params: init.params.filter((p) => t12.isIdentifier(p)).map((p) => p.name)
3151
- };
3152
- if (init.params.length > 0) {
3153
- const firstParam = init.params[0];
3154
- if (t12.isIdentifier(firstParam) && firstParam.typeAnnotation) {
3155
- action.contextType = extractTypeName(firstParam.typeAnnotation);
3156
- }
3157
- }
3158
- serverActions.push(action);
3159
- }
3160
- }
3161
- }
3162
- }
3163
- }
3164
- if (serverActions.length > 0) {
3165
- if (!compilerState.metadata) compilerState.metadata = {};
3166
- compilerState.metadata.serverActions = serverActions;
3167
- }
3168
- }
3169
- function extractFunctionAction(decl) {
3170
- if (!decl.id) return null;
3171
- const action = {
3172
- name: decl.id.name,
3173
- async: decl.async || false,
3174
- params: decl.params.filter((p) => t12.isIdentifier(p)).map((p) => p.name)
3175
- };
3176
- if (decl.params.length > 0) {
3177
- const firstParam = decl.params[0];
3178
- if (t12.isIdentifier(firstParam) && firstParam.typeAnnotation) {
3179
- action.contextType = extractTypeName(firstParam.typeAnnotation);
3180
- }
3181
- }
3182
- return action;
3183
- }
3184
- function extractTypeName(annotation) {
3185
- if (t12.isTSTypeAnnotation(annotation)) {
3186
- const typeNode = annotation.typeAnnotation;
3187
- if (t12.isTSTypeReference(typeNode) && t12.isIdentifier(typeNode.typeName)) {
3188
- return typeNode.typeName.name;
3189
- }
3190
- }
3191
- return void 0;
3192
- }
3193
- function extractDescription(comments) {
3194
- for (const comment of comments) {
3195
- if (comment.type !== "CommentBlock") continue;
3196
- const lines = comment.value.split("\n");
3197
- for (const line of lines) {
3198
- const trimmed = line.replace(/^\s*\*\s?/, "").trim();
3199
- if (trimmed && !trimmed.startsWith("@")) {
3200
- return trimmed;
3201
- }
3202
- }
3203
- }
3204
- return void 0;
3205
- }
3206
-
3207
- // src/babel/extractors/server-action-hook-extractor.ts
3208
- import * as t13 from "@babel/types";
3209
- function extractServerActionHook(path, state) {
3210
- const args = path.node.arguments;
3211
- if (args.length < 1) return;
3212
- const nameArg = args[0];
3213
- if (!t13.isStringLiteral(nameArg)) return;
3214
- const compilerState = state;
3215
- const entry = {
3216
- name: nameArg.value
3217
- };
3218
- if (args.length > 1 && t13.isObjectExpression(args[1])) {
3219
- for (const prop of args[1].properties) {
3220
- if (!t13.isObjectProperty(prop) || !t13.isIdentifier(prop.key)) continue;
3221
- if (prop.key.name === "instanceId" && t13.isStringLiteral(prop.value)) {
3222
- entry.staticInstanceId = prop.value.value;
3223
- }
3224
- }
3225
- }
3226
- const parent = path.parentPath;
3227
- if (parent?.isVariableDeclarator() && t13.isIdentifier(parent.node.id)) {
3228
- entry.variableName = parent.node.id.name;
3229
- }
3230
- if (!compilerState.metadata) compilerState.metadata = {};
3231
- const meta = compilerState.metadata;
3232
- if (!meta.serverActionHooks) meta.serverActionHooks = [];
3233
- meta.serverActionHooks.push(entry);
3234
- }
3235
-
3236
- // src/babel/extractors/server-state-extractor.ts
3237
- import * as t14 from "@babel/types";
3238
- function extractServerState(path, state) {
3239
- const args = path.node.arguments;
3240
- if (args.length < 1) return;
3241
- const compilerState = state;
3242
- const entry = {};
3243
- const instanceArg = args[0];
3244
- if (t14.isStringLiteral(instanceArg)) {
3245
- entry.staticInstanceId = instanceArg.value;
3246
- }
3247
- if (args.length > 1 && t14.isObjectExpression(args[1])) {
3248
- for (const prop of args[1].properties) {
3249
- if (!t14.isObjectProperty(prop) || !t14.isIdentifier(prop.key)) continue;
3250
- if (prop.key.name === "enabled" && t14.isBooleanLiteral(prop.value)) {
3251
- if (!prop.value.value) entry.disabled = true;
3252
- }
3253
- }
3254
- }
3255
- const parent = path.parentPath;
3256
- if (parent?.isVariableDeclarator()) {
3257
- if (t14.isIdentifier(parent.node.id)) {
3258
- entry.variableName = parent.node.id.name;
3259
- } else if (t14.isObjectPattern(parent.node.id)) {
3260
- const props = parent.node.id.properties.filter((p) => t14.isObjectProperty(p) && t14.isIdentifier(p.key)).map((p) => p.key.name);
3261
- if (props.length > 0) {
3262
- entry.variableName = props.join(", ");
3263
- }
3264
- }
3265
- }
3266
- if (!compilerState.metadata) compilerState.metadata = {};
3267
- const meta = compilerState.metadata;
3268
- if (!meta.serverStateSubscriptions) meta.serverStateSubscriptions = [];
3269
- meta.serverStateSubscriptions.push(entry);
3270
- meta.requiresSSE = true;
3271
- }
3272
-
3273
- // src/babel/extractors/grammar-island-extractor.ts
3274
- import * as t15 from "@babel/types";
3275
- var GRAMMAR_TAGS = /* @__PURE__ */ new Set(["cedar", "sql", "cron", "dmn", "graphql", "jsonpath"]);
3276
- function parseCedar(source) {
3277
- const policies = [];
3278
- const policyRegex = /(permit|forbid)\s*\(([^)]*)\)(?:\s*when\s*\{([^}]*)\})?/g;
3279
- let match;
3280
- while ((match = policyRegex.exec(source)) !== null) {
3281
- const [, effect, scope, condition] = match;
3282
- const parts = scope.split(",").map((s) => s.trim());
3283
- const policy = {
3284
- effect,
3285
- conditions: []
3286
- };
3287
- for (const part of parts) {
3288
- if (part.startsWith("principal")) {
3289
- policy.principal = part;
3290
- } else if (part.startsWith("action")) {
3291
- policy.action = part;
3292
- } else if (part.startsWith("resource")) {
3293
- policy.resource = part;
3294
- }
3295
- }
3296
- if (condition) {
3297
- policy.conditions.push(condition.trim());
3298
- }
3299
- policies.push(policy);
3300
- }
3301
- return { policies };
3302
- }
3303
- function parseCron(source) {
3304
- const trimmed = source.trim();
3305
- const parts = trimmed.split(/\s+/);
3306
- const valid = parts.length === 5;
3307
- return {
3308
- expression: trimmed,
3309
- fields: {
3310
- minute: parts[0] || "*",
3311
- hour: parts[1] || "*",
3312
- dayOfMonth: parts[2] || "*",
3313
- month: parts[3] || "*",
3314
- dayOfWeek: parts[4] || "*"
3315
- },
3316
- valid
3317
- };
3318
- }
3319
- function parseDmn(source) {
3320
- const lines = source.split("\n").map((l) => l.trim()).filter((l) => l.length > 0);
3321
- const rules = [];
3322
- const headers = [];
3323
- let hitPolicy = "first";
3324
- if (lines.length === 0) return { hitPolicy, rules, headers };
3325
- const headerLine = lines[0];
3326
- const headerCells = headerLine.split("|").map((c) => c.trim()).filter((c) => c.length > 0);
3327
- headers.push(...headerCells);
3328
- const outputStartIndex = headers.length - 1;
3329
- let dataStart = 1;
3330
- if (lines.length > 1 && /^[|\s-]+$/.test(lines[1])) {
3331
- dataStart = 2;
3332
- }
3333
- const hitPolicyMatch = source.match(/@hitPolicy\s*=\s*"?(\w+)"?/);
3334
- if (hitPolicyMatch) {
3335
- hitPolicy = hitPolicyMatch[1];
3336
- }
3337
- for (let i = dataStart; i < lines.length; i++) {
3338
- const cells = lines[i].split("|").map((c) => c.trim()).filter((c) => c.length > 0);
3339
- if (cells.length < headers.length) continue;
3340
- const inputs = {};
3341
- const output = {};
3342
- for (let j = 0; j < headers.length; j++) {
3343
- if (j >= outputStartIndex) {
3344
- output[headers[j]] = cells[j];
3345
- } else {
3346
- inputs[headers[j]] = cells[j];
3347
- }
3348
- }
3349
- rules.push({ inputs, output });
3350
- }
3351
- return { hitPolicy, rules, headers };
3352
- }
3353
- function extractGrammarIsland(path, state, slug) {
3354
- const tag = path.node.tag;
3355
- if (!t15.isIdentifier(tag)) return;
3356
- const tagName = tag.name;
3357
- if (!GRAMMAR_TAGS.has(tagName)) return;
3358
- const compilerState = state;
3359
- const quasi = path.node.quasi;
3360
- let rawSource = "";
3361
- for (let i = 0; i < quasi.quasis.length; i++) {
3362
- rawSource += quasi.quasis[i].value.raw;
3363
- if (i < quasi.expressions.length) {
3364
- const expr = quasi.expressions[i];
3365
- if (t15.isIdentifier(expr)) {
3366
- rawSource += `\${${expr.name}}`;
3367
- } else {
3368
- rawSource += `\${expr_${i}}`;
3369
- }
3370
- }
3371
- }
3372
- rawSource = rawSource.trim();
3373
- let parsed = void 0;
3374
- switch (tagName) {
3375
- case "cedar":
3376
- parsed = parseCedar(rawSource);
3377
- break;
3378
- case "cron":
3379
- parsed = parseCron(rawSource);
3380
- break;
3381
- case "dmn":
3382
- parsed = parseDmn(rawSource);
3383
- break;
3384
- case "sql":
3385
- parsed = { query: rawSource };
3386
- break;
3387
- case "graphql":
3388
- parsed = { query: rawSource };
3389
- break;
3390
- case "jsonpath":
3391
- parsed = { expression: rawSource };
3392
- break;
3393
- }
3394
- const island = {
3395
- slug,
3396
- contextTag: tagName,
3397
- rawSource,
3398
- parsed
3399
- };
3400
- if (!compilerState.metadata) compilerState.metadata = {};
3401
- const meta = compilerState.metadata;
3402
- if (!meta.grammarIslands) meta.grammarIslands = [];
3403
- meta.grammarIslands.push(island);
3404
- }
3405
- function extractGrammarIslands(path, state) {
3406
- path.traverse({
3407
- TaggedTemplateExpression(templatePath) {
3408
- const tag = templatePath.node.tag;
3409
- if (!t15.isIdentifier(tag) || !GRAMMAR_TAGS.has(tag.name)) return;
3410
- let slug = "unnamed";
3411
- const parent = templatePath.parentPath;
3412
- if (parent && parent.isVariableDeclarator() && t15.isIdentifier(parent.node.id)) {
3413
- slug = parent.node.id.name;
3414
- }
3415
- if (parent && parent.isObjectProperty() && t15.isIdentifier(parent.node.key)) {
3416
- slug = parent.node.key.name;
3417
- }
3418
- if (parent && parent.isObjectProperty() && t15.isStringLiteral(parent.node.key)) {
3419
- slug = parent.node.key.value;
3420
- }
3421
- extractGrammarIsland(templatePath, state, slug);
3422
- }
3423
- });
3424
- }
3425
-
3426
- // src/babel/extractors/context-extractor.ts
3427
- import * as t16 from "@babel/types";
3428
- function hasContextCreation(path) {
3429
- let found = false;
3430
- path.traverse({
3431
- CallExpression(callPath) {
3432
- if (t16.isIdentifier(callPath.node.callee, { name: "createContext" })) {
3433
- found = true;
3434
- callPath.stop();
3435
- }
3436
- }
3437
- });
3438
- return found;
3439
- }
3440
- function extractContextWorkflows(path, state) {
3441
- const compilerState = state;
3442
- const contextWorkflows = [];
3443
- const contextNames = /* @__PURE__ */ new Map();
3444
- path.traverse({
3445
- // Detect: const XContext = createContext(...)
3446
- VariableDeclarator(declPath) {
3447
- const init = declPath.node.init;
3448
- if (!init || !t16.isCallExpression(init)) return;
3449
- if (!t16.isIdentifier(init.callee, { name: "createContext" })) return;
3450
- if (!t16.isIdentifier(declPath.node.id)) return;
3451
- const contextName = declPath.node.id.name;
3452
- contextNames.set(contextName, contextName);
3453
- const workflow = {
3454
- name: contextName,
3455
- fields: [],
3456
- reducerActions: []
3457
- };
3458
- const typeParams = init.typeParameters;
3459
- if (typeParams && t16.isTSTypeParameterInstantiation(typeParams)) {
3460
- const typeArg = typeParams.params[0];
3461
- if (t16.isTSTypeReference(typeArg) && t16.isIdentifier(typeArg.typeName)) {
3462
- const interfaceName = typeArg.typeName.name;
3463
- extractFieldsFromInterface2(path, interfaceName, workflow);
3464
- }
3465
- }
3466
- if (init.arguments.length > 0 && t16.isObjectExpression(init.arguments[0])) {
3467
- workflow.initialState = extractObjectLiteral2(init.arguments[0]);
3468
- }
3469
- contextWorkflows.push(workflow);
3470
- },
3471
- // Detect useReducer(reducer, initialState) and extract reducer cases
3472
- CallExpression(callPath) {
3473
- if (!t16.isIdentifier(callPath.node.callee, { name: "useReducer" })) return;
3474
- const args = callPath.node.arguments;
3475
- if (args.length < 1) return;
3476
- const reducerArg = args[0];
3477
- if (!t16.isIdentifier(reducerArg)) return;
3478
- const reducerName = reducerArg.name;
3479
- const actions = extractReducerActions(path, reducerName);
3480
- if (contextWorkflows.length > 0) {
3481
- const lastWorkflow = contextWorkflows[contextWorkflows.length - 1];
3482
- lastWorkflow.reducerActions = actions;
3483
- lastWorkflow.reducerName = reducerName;
3484
- }
3485
- }
3486
- });
3487
- if (contextWorkflows.length > 0) {
3488
- if (!compilerState.metadata) compilerState.metadata = {};
3489
- const meta = compilerState.metadata;
3490
- meta.contextWorkflows = contextWorkflows;
3491
- }
3492
- }
3493
- function extractFieldsFromInterface2(path, interfaceName, workflow) {
3494
- path.traverse({
3495
- TSInterfaceDeclaration(ifacePath) {
3496
- if (!t16.isIdentifier(ifacePath.node.id, { name: interfaceName })) return;
3497
- for (const prop of ifacePath.node.body.body) {
3498
- if (!t16.isTSPropertySignature(prop)) continue;
3499
- if (!t16.isIdentifier(prop.key)) continue;
3500
- const field = {
3501
- name: prop.key.name,
3502
- type: extractTSType(prop.typeAnnotation),
3503
- optional: prop.optional || false
3504
- };
3505
- workflow.fields.push(field);
3506
- }
3507
- }
3508
- });
3509
- }
3510
- function extractTSType(annotation) {
3511
- if (!annotation || !t16.isTSTypeAnnotation(annotation)) return "unknown";
3512
- const typeNode = annotation.typeAnnotation;
3513
- if (t16.isTSStringKeyword(typeNode)) return "string";
3514
- if (t16.isTSNumberKeyword(typeNode)) return "number";
3515
- if (t16.isTSBooleanKeyword(typeNode)) return "boolean";
3516
- if (t16.isTSArrayType(typeNode)) return `${extractTSTypeNode(typeNode.elementType)}[]`;
3517
- if (t16.isTSTypeReference(typeNode) && t16.isIdentifier(typeNode.typeName)) return typeNode.typeName.name;
3518
- return "unknown";
3519
- }
3520
- function extractTSTypeNode(node) {
3521
- if (t16.isTSStringKeyword(node)) return "string";
3522
- if (t16.isTSNumberKeyword(node)) return "number";
3523
- if (t16.isTSBooleanKeyword(node)) return "boolean";
3524
- if (t16.isTSTypeReference(node) && t16.isIdentifier(node.typeName)) return node.typeName.name;
3525
- return "unknown";
3526
- }
3527
- function extractReducerActions(path, reducerName) {
3528
- const actions = [];
3529
- path.traverse({
3530
- FunctionDeclaration(funcPath) {
3531
- if (!funcPath.node.id || funcPath.node.id.name !== reducerName) return;
3532
- funcPath.traverse({
3533
- SwitchStatement(switchPath) {
3534
- for (const switchCase of switchPath.node.cases) {
3535
- if (!switchCase.test) continue;
3536
- if (t16.isStringLiteral(switchCase.test)) {
3537
- actions.push({
3538
- type: switchCase.test.value
3539
- });
3540
- }
3541
- }
3542
- }
3543
- });
3544
- }
3545
- });
3546
- return actions;
3547
- }
3548
- function extractObjectLiteral2(obj) {
3549
- const result = {};
3550
- for (const prop of obj.properties) {
3551
- if (!t16.isObjectProperty(prop) || !t16.isIdentifier(prop.key)) continue;
3552
- if (t16.isStringLiteral(prop.value)) result[prop.key.name] = prop.value.value;
3553
- else if (t16.isNumericLiteral(prop.value)) result[prop.key.name] = prop.value.value;
3554
- else if (t16.isBooleanLiteral(prop.value)) result[prop.key.name] = prop.value.value;
3555
- else if (t16.isNullLiteral(prop.value)) result[prop.key.name] = null;
3556
- else if (t16.isArrayExpression(prop.value)) result[prop.key.name] = [];
3557
- else if (t16.isObjectExpression(prop.value)) result[prop.key.name] = extractObjectLiteral2(prop.value);
3558
- }
3559
- return result;
3560
- }
3561
-
3562
- // src/babel/emitters/pure-form-emitter.ts
3563
- import { normalizeCategory } from "@mindmatrix/player-core";
3564
-
3565
- // src/babel/emitters/experience-transform.ts
3566
- function transformToFrontend(node) {
3567
- const result = {
3568
- id: node.id
3569
- };
3570
- if (node.displayName) {
3571
- result.displayName = node.displayName;
3572
- } else if (node.config?.displayName && typeof node.config.displayName === "string") {
3573
- result.displayName = node.config.displayName;
3574
- }
3575
- if (node.experienceId) result.experienceId = node.experienceId;
3576
- if (node.component) result.component = node.component;
3577
- if (node.slot) {
3578
- result.slot = node.slot;
3579
- } else if (node.config?.slot && typeof node.config.slot === "string") {
3580
- result.slot = node.config.slot;
3581
- }
3582
- if (node.className) {
3583
- result.className = node.className;
3584
- } else if (node.config?.className && typeof node.config.className === "string") {
3585
- result.className = node.config.className;
3586
- }
3587
- if (node.style) result.style = node.style;
3588
- if (node.overrides) result.overrides = node.overrides;
3589
- if (node.layout) result.layout = node.layout;
3590
- if (node.dataScope) result.dataScope = node.dataScope;
3591
- if (node.bindings) result.bindings = node.bindings;
3592
- if (node.visible_when) result.visible_when = node.visible_when;
3593
- if (node.config) {
3594
- const cleaned = { ...node.config };
3595
- delete cleaned.slot;
3596
- delete cleaned.className;
3597
- delete cleaned.displayName;
3598
- if (Object.keys(cleaned).length > 0) {
3599
- result.config = cleaned;
3600
- }
3601
- }
3602
- if (node.dataSources && node.dataSources.length > 0) {
3603
- result.dataSources = node.dataSources.map(transformDataSource);
3604
- }
3605
- if (node.children && node.children.length > 0) {
3606
- result.children = node.children.map(transformToFrontend);
3607
- }
3608
- return result;
3609
- }
3610
- function transformDataSource(ds) {
3611
- const d = ds;
3612
- switch (ds.type) {
3613
- case "workflow":
3614
- return {
3615
- type: "workflow",
3616
- name: ds.name,
3617
- slug: ds.slug,
3618
- query: ds.query,
3619
- ...d.instanceId && { instanceId: d.instanceId },
3620
- ...d.entity !== void 0 && { entity: d.entity },
3621
- ...ds.paginated !== void 0 && { paginated: ds.paginated },
3622
- ...ds.pageSize !== void 0 && { pageSize: ds.pageSize },
3623
- ...d.filter && { filter: d.filter },
3624
- ...d.filters && { filters: d.filters },
3625
- ...ds.sort && { sort: ds.sort },
3626
- ...d.search && { search: d.search },
3627
- ...ds.searchFields && { searchFields: ds.searchFields },
3628
- ...ds.facets && { facets: ds.facets },
3629
- ...d.range && { range: d.range },
3630
- ...d.aggregate && { aggregate: d.aggregate },
3631
- ...ds.groupBy && { groupBy: ds.groupBy },
3632
- ...ds.parentInstanceId && { parentInstanceId: ds.parentInstanceId },
3633
- ...d.autoStart !== void 0 && { autoStart: d.autoStart },
3634
- ...d.initialData && { initialData: d.initialData },
3635
- ...d.includeDefinition !== void 0 && { includeDefinition: d.includeDefinition }
3636
- };
3637
- case "api":
3638
- return {
3639
- type: "api",
3640
- name: ds.name,
3641
- endpoint: ds.endpoint,
3642
- ...d.method && { method: d.method },
3643
- ...d.mapping && { mapping: d.mapping },
3644
- ...d.staleTime !== void 0 && { staleTime: d.staleTime }
3645
- };
3646
- case "ref":
3647
- return {
3648
- type: "ref",
3649
- name: ds.name,
3650
- expression: ds.expression
3651
- };
3652
- case "static":
3653
- return {
3654
- type: "static",
3655
- name: ds.name,
3656
- data: ds.data
3657
- };
3658
- }
3659
- }
3660
-
3661
- // src/babel/emitters/pure-form-emitter.ts
3662
- var PROP_RULES = {
3663
- Text: {
3664
- config: { text: "value" },
3665
- bindings: { text: "value" }
3666
- },
3667
- Heading: {
3668
- config: { text: "value" },
3669
- bindings: { text: "value" }
3670
- },
3671
- Button: {
3672
- config: { text: "label" },
3673
- bindings: { text: "label", onPress: "onClick" }
3674
- }
3675
- };
3676
- var COMPONENT_RENAMES = {
3677
- Heading: "Text"
3678
- };
3679
- var RENAME_EXTRA_CONFIG = {
3680
- Heading: { variant: "h2" }
3681
- };
3682
- function normalizeViewNode(node, fieldNames) {
3683
- if (!node || typeof node !== "object") return node;
3684
- const originalComponent = node.component;
3685
- if (originalComponent && COMPONENT_RENAMES[originalComponent]) {
3686
- node.component = COMPONENT_RENAMES[originalComponent];
3687
- const extra = RENAME_EXTRA_CONFIG[originalComponent];
3688
- if (extra) {
3689
- node.config = { ...extra, ...node.config || {} };
3690
- }
3691
- }
3692
- const rules = PROP_RULES[originalComponent || ""] || PROP_RULES[node.component || ""];
3693
- if (rules) {
3694
- if (node.config && rules.config) {
3695
- for (const [from, to] of Object.entries(rules.config)) {
3696
- if (from in node.config && !(to in node.config)) {
3697
- node.config[to] = node.config[from];
3698
- delete node.config[from];
3699
- }
3700
- }
3701
- }
3702
- if (node.bindings && rules.bindings) {
3703
- for (const [from, to] of Object.entries(rules.bindings)) {
3704
- if (from in node.bindings && !(to in node.bindings)) {
3705
- node.bindings[to] = node.bindings[from];
3706
- delete node.bindings[from];
3707
- }
3708
- }
3709
- }
3710
- }
3711
- if (node.config && fieldNames.size > 0) {
3712
- for (const [prop, val] of Object.entries(node.config)) {
3713
- if (typeof val !== "string") continue;
3714
- const templateRe = /\{\{(\w+)\}\}|\{(\w+)\}/g;
3715
- let match;
3716
- const refs = [];
3717
- while ((match = templateRe.exec(val)) !== null) {
3718
- const field = match[1] || match[2];
3719
- if (fieldNames.has(field)) {
3720
- refs.push({ full: match[0], field, index: match.index });
3721
- }
3722
- }
3723
- if (refs.length > 0) {
3724
- const parts = [];
3725
- let lastEnd = 0;
3726
- for (const ref of refs) {
3727
- const before = val.slice(lastEnd, ref.index);
3728
- if (before) parts.push(`"${before}"`);
3729
- parts.push(`$instance.state_data.${ref.field}`);
3730
- lastEnd = ref.index + ref.full.length;
3731
- }
3732
- const trailing = val.slice(lastEnd);
3733
- if (trailing) parts.push(`"${trailing}"`);
3734
- const expr = `$fn.concat(${parts.join(", ")})`;
3735
- if (!node.bindings) node.bindings = {};
3736
- node.bindings[prop] = expr;
3737
- delete node.config[prop];
3738
- }
3739
- }
3740
- }
3741
- if (node.bindings) {
3742
- for (const [prop, expr] of Object.entries(node.bindings)) {
3743
- if (typeof expr !== "string") continue;
3744
- if (expr.endsWith(".fire")) {
3745
- const transitionName = expr.slice(0, -5);
3746
- node.bindings[prop] = `$action.transition("${transitionName}")`;
3747
- continue;
3748
- }
3749
- if (fieldNames.size > 0 && expr.startsWith("$instance.")) {
3750
- const field = expr.slice("$instance.".length);
3751
- if (fieldNames.has(field)) {
3752
- node.bindings[prop] = `$instance.state_data.${field}`;
3753
- }
3754
- }
3755
- }
3756
- }
3757
- if (node.children && Array.isArray(node.children)) {
3758
- node.children = node.children.map((child) => normalizeViewNode(child, fieldNames));
3759
- if (node.children.length === 1 && node.children[0].component === "Text") {
3760
- const textChild = node.children[0];
3761
- const configKeys = textChild.config ? Object.keys(textChild.config).filter((k) => k !== "value") : [];
3762
- const bindingKeys = textChild.bindings ? Object.keys(textChild.bindings).filter((k) => k !== "value") : [];
3763
- const isSimple = !textChild.style && !textChild.className && !textChild.children && !textChild.visible_when && configKeys.length === 0 && bindingKeys.length === 0;
3764
- if (isSimple) {
3765
- const parentRules = PROP_RULES[node.component || ""];
3766
- const configKey = parentRules?.config?.text || "text";
3767
- const bindingKey = parentRules?.bindings?.text || "text";
3768
- if (textChild.config?.value && !textChild.bindings) {
3769
- if (!node.config) node.config = {};
3770
- node.config[configKey] = textChild.config.value;
3771
- delete node.children;
3772
- } else if (textChild.bindings?.value && !textChild.config?.value) {
3773
- if (!node.bindings) node.bindings = {};
3774
- node.bindings[bindingKey] = textChild.bindings.value;
3775
- delete node.children;
3776
- }
3777
- }
3778
- }
3779
- }
3780
- return node;
3781
- }
3782
- function toSnakeCase2(str) {
3783
- return str.replace(/([A-Z])/g, "_$1").toLowerCase().replace(/^_/, "");
3784
- }
3785
- function convertAction(action) {
3786
- return {
3787
- id: action.id,
3788
- action_type: action.type,
3789
- config: action.config || {},
3790
- ...action.condition && { condition: action.condition }
3791
- };
3792
- }
3793
- function convertDuringAction(during) {
3794
- return {
3795
- id: during.id,
3796
- type: during.type,
3797
- ...during.interval_ms !== void 0 && { interval_ms: during.interval_ms },
3798
- ...during.cron && { cron: during.cron },
3799
- ...during.delay_ms !== void 0 && { delay_ms: during.delay_ms },
3800
- actions: during.actions.map(convertAction),
3801
- ...during.condition && { condition: during.condition }
3802
- };
3803
- }
3804
- function convertOnEvent(sub) {
3805
- return {
3806
- match: sub.match,
3807
- ...sub.description && { description: sub.description },
3808
- conditions: sub.conditions || [],
3809
- actions: sub.actions.map((a) => ({
3810
- type: a.type,
3811
- ...a.field && { field: a.field },
3812
- ...a.expression && { expression: a.expression },
3813
- ...a.key && { key: a.key },
3814
- ...a.message && { message: a.message },
3815
- ...a.config && { config: a.config },
3816
- ...a.conditions && a.conditions.length > 0 && { conditions: a.conditions }
3817
- }))
3818
- };
3819
- }
3820
- function emitIR(extracted) {
3821
- const { slug, name, version, description, category, fields, states, transitions } = extracted;
3822
- const stateArray = Array.from(states.values());
3823
- if (stateArray.length === 0) {
3824
- stateArray.push({
3825
- name: "draft",
3826
- type: "START",
3827
- on_enter: [],
3828
- during: [],
3829
- on_exit: []
3830
- });
3831
- } else {
3832
- const hasStart = stateArray.some((s) => s.type === "START");
3833
- if (!hasStart && stateArray.length > 0) {
3834
- stateArray[0].type = "START";
3835
- }
3836
- }
3837
- inferTransitionStates(transitions, states);
3838
- const stateNames = new Set(stateArray.map((s) => s.name));
3839
- for (const transition of transitions) {
3840
- if (transition.to && !stateNames.has(transition.to)) {
3841
- stateArray.push({
3842
- name: transition.to,
3843
- type: "REGULAR",
3844
- on_enter: [],
3845
- during: [],
3846
- on_exit: []
3847
- });
3848
- stateNames.add(transition.to);
3849
- }
3850
- }
3851
- const fieldNames = new Set(fields.map((f) => f.name));
3852
- let normalizedView;
3853
- if (extracted.experience) {
3854
- normalizedView = normalizeViewNode(
3855
- JSON.parse(JSON.stringify(extracted.experience)),
3856
- fieldNames
3857
- );
3858
- const dataSources = extracted.extraMetadata?.dataSources;
3859
- if (dataSources && dataSources.length > 0) {
3860
- normalizedView.dataSources = dataSources;
3861
- }
3862
- if (fields.length > 0) {
3863
- const localDefaults = {};
3864
- for (const f of fields) {
3865
- localDefaults[toSnakeCase2(f.name)] = f.default_value ?? null;
3866
- }
3867
- if (!normalizedView.config) normalizedView.config = {};
3868
- normalizedView.config.localDefaults = localDefaults;
3869
- }
3870
- }
3871
- const metadata = {
3872
- stable_id: `def-${slug}`,
3873
- provenance: {
3874
- frontend: "react-compiler",
3875
- source: `${slug}.workflow.tsx`,
3876
- compiler_version: "1.0.0"
3877
- }
3878
- };
3879
- if (extracted.fieldWatchers && extracted.fieldWatchers.length > 0) {
3880
- metadata.fieldWatchers = extracted.fieldWatchers;
3881
- }
3882
- if (extracted.transitionEffects && extracted.transitionEffects.length > 0) {
3883
- metadata.transitionEffects = extracted.transitionEffects;
3884
- }
3885
- if (extracted.extraMetadata) {
3886
- for (const [key, value] of Object.entries(extracted.extraMetadata)) {
3887
- metadata[key] = value;
3888
- }
3889
- }
3890
- if (extracted.experience) {
3891
- metadata.experience = extracted.experience;
3892
- }
3893
- const ir = {
3894
- slug,
3895
- name,
3896
- version,
3897
- description,
3898
- category,
3899
- fields,
3900
- states: stateArray,
3901
- transitions,
3902
- roles: [],
3903
- tags: [],
3904
- metadata
3905
- };
3906
- if (normalizedView) {
3907
- ir.views = { default: normalizedView };
3908
- ir.frontendViews = { default: transformToFrontend(normalizedView) };
3909
- }
3910
- if (extracted.events && extracted.events.length > 0) {
3911
- ir.on_event = extracted.events;
3912
- }
3913
- if (extracted.grammarIslands && extracted.grammarIslands.length > 0) {
3914
- const extensions = {};
3915
- for (const island of extracted.grammarIslands) {
3916
- const key = island.contextTag;
3917
- if (!extensions[key]) extensions[key] = [];
3918
- extensions[key].push(island);
3919
- }
3920
- ir.extensions = extensions;
3921
- }
3922
- return ir;
3923
- }
3924
- var emitPureForm = emitIR;
3925
- function liftAction(action) {
3926
- const parts = [];
3927
- if (action.config) {
3928
- for (const [key, value] of Object.entries(action.config)) {
3929
- parts.push({
3930
- slug: key,
3931
- category: ["atom"],
3932
- parts: [{ slug: String(value), category: ["atom"] }]
3933
- });
3934
- }
3935
- }
3936
- if (action.condition) {
3937
- parts.push({
3938
- slug: "condition",
3939
- category: ["expression", "guard"],
3940
- parts: [{ slug: action.condition, category: ["binding"] }]
3941
- });
3942
- }
3943
- return {
3944
- slug: action.id,
3945
- category: normalizeCategory("expression", "mutation", action.type),
3946
- parts: parts.length > 0 ? parts : void 0
3947
- };
3948
- }
3949
- function liftSchedule(during) {
3950
- const parts = [];
3951
- if (during.interval_ms !== void 0) {
3952
- parts.push({
3953
- slug: "every",
3954
- category: ["atom"],
3955
- parts: [{ slug: String(during.interval_ms), category: ["literal"] }]
3956
- });
3957
- }
3958
- if (during.cron) {
3959
- parts.push({
3960
- slug: "cron",
3961
- category: ["atom"],
3962
- parts: [{ slug: during.cron, category: ["literal"] }]
3963
- });
3964
- }
3965
- if (during.delay_ms !== void 0) {
3966
- parts.push({
3967
- slug: "delay",
3968
- category: ["atom"],
3969
- parts: [{ slug: String(during.delay_ms), category: ["literal"] }]
3970
- });
3971
- }
3972
- for (const action of during.actions) {
3973
- parts.push({
3974
- slug: "do",
3975
- category: normalizeCategory("expression", "mutation", action.type),
3976
- parts: Object.entries(action.config || {}).map(([key, value]) => ({
3977
- slug: key,
3978
- category: ["atom"],
3979
- parts: [{ slug: String(value), category: ["atom"] }]
3980
- }))
3981
- });
3982
- }
3983
- return {
3984
- slug: during.id,
3985
- category: normalizeCategory("schedule", during.type),
3986
- parts
3987
- };
3988
- }
3989
- function liftState(state) {
3990
- const parts = [];
3991
- const tags = [];
3992
- if (state.type === "START") tags.push("start");
3993
- if (state.type === "END") tags.push("end");
3994
- if (state.type === "CANCELLED") tags.push("cancelled");
3995
- if (state.on_enter && state.on_enter.length > 0) {
3996
- parts.push({
3997
- slug: "on_enter",
3998
- category: normalizeCategory("expression", "sequence"),
3999
- parts: state.on_enter.map(liftAction)
4000
- });
4001
- }
4002
- if (state.on_exit && state.on_exit.length > 0) {
4003
- parts.push({
4004
- slug: "on_exit",
4005
- category: normalizeCategory("expression", "sequence"),
4006
- parts: state.on_exit.map(liftAction)
4007
- });
4008
- }
4009
- if (state.during && state.during.length > 0) {
4010
- for (const d of state.during) {
4011
- parts.push(liftSchedule(d));
4012
- }
4013
- }
4014
- return {
4015
- slug: state.name,
4016
- category: normalizeCategory("state", ...tags),
4017
- parts: parts.length > 0 ? parts : void 0
4018
- };
4019
- }
4020
- function liftTransition(transition) {
4021
- const parts = [];
4022
- if (transition.from && transition.from.length > 0) {
4023
- parts.push({
4024
- slug: "from",
4025
- category: ["part"],
4026
- parts: transition.from.map((s) => ({ slug: s, category: ["ref"] }))
4027
- });
4028
- }
4029
- if (transition.to) {
4030
- parts.push({
4031
- slug: "to",
4032
- category: ["part"],
4033
- parts: [{ slug: transition.to, category: ["ref"] }]
4034
- });
4035
- }
4036
- if (transition.actions && transition.actions.length > 0) {
4037
- parts.push({
4038
- slug: "actions",
4039
- category: normalizeCategory("expression", "sequence"),
4040
- parts: transition.actions.map(liftAction)
4041
- });
4042
- }
4043
- if (transition.conditions && transition.conditions.length > 0) {
4044
- parts.push({
4045
- slug: "conditions",
4046
- category: normalizeCategory("expression", "guard"),
4047
- parts: transition.conditions.map((c, i) => ({
4048
- slug: `condition_${i}`,
4049
- category: normalizeCategory("expression", c.type || "condition"),
4050
- parts: c.expression ? [{ slug: c.expression, category: ["binding"] }] : void 0
4051
- }))
4052
- });
4053
- }
4054
- return {
4055
- slug: transition.name,
4056
- category: ["transition"],
4057
- parts
4058
- };
4059
- }
4060
- function liftField(field) {
4061
- const parts = [];
4062
- if (field.label) {
4063
- parts.push({
4064
- slug: "label",
4065
- category: ["atom"],
4066
- parts: [{ slug: field.label, category: ["atom"] }]
4067
- });
4068
- }
4069
- if (field.default_value !== void 0) {
4070
- parts.push({
4071
- slug: "default",
4072
- category: ["atom"],
4073
- parts: [{ slug: String(field.default_value), category: ["literal"] }]
4074
- });
4075
- }
4076
- if (field.required) {
4077
- parts.push({ slug: "required", category: ["atom"], parts: [{ slug: "true", category: ["literal"] }] });
4078
- }
4079
- if (field.computed) {
4080
- parts.push({
4081
- slug: "computed",
4082
- category: ["expression"],
4083
- parts: [{ slug: field.computed, category: ["binding"] }]
4084
- });
4085
- }
4086
- return {
4087
- slug: field.name,
4088
- category: normalizeCategory("field", field.type),
4089
- parts: parts.length > 0 ? parts : void 0
4090
- };
4091
- }
4092
- function liftView(node) {
4093
- const componentTag = (node.component || "stack").toLowerCase().replace(/\s+/g, "-");
4094
- const parts = [];
4095
- if (node.config) {
4096
- for (const [key, value] of Object.entries(node.config)) {
4097
- parts.push({
4098
- slug: key,
4099
- category: ["atom"],
4100
- parts: [{ slug: String(value), category: ["atom"] }]
4101
- });
4102
- }
4103
- }
4104
- if (node.bindings) {
4105
- for (const [key, expr] of Object.entries(node.bindings)) {
4106
- if (key === "onClick" || key === "onPress") {
4107
- const match = typeof expr === "string" ? expr.match(/\$action\.transition\("(.+?)"\)/) : null;
4108
- if (match) {
4109
- parts.push({
4110
- slug: key,
4111
- category: normalizeCategory("expression", "effect", "transition"),
4112
- parts: [{ slug: match[1], category: ["ref"] }]
4113
- });
4114
- } else {
4115
- parts.push({
4116
- slug: key,
4117
- category: normalizeCategory("expression", "binding"),
4118
- parts: [{ slug: String(expr), category: ["binding"] }]
4119
- });
4120
- }
4121
- } else {
4122
- parts.push({
4123
- slug: key,
4124
- category: normalizeCategory("expression", "binding"),
4125
- parts: [{ slug: String(expr), category: ["binding"] }]
4126
- });
4127
- }
4128
- }
4129
- }
4130
- if (node.visible_when) {
4131
- const eqMatch = node.visible_when.match(/\$fn\.eq\((.+?),\s*"(.+?)"\)/);
4132
- if (eqMatch) {
4133
- parts.push({
4134
- slug: "visible_when",
4135
- category: normalizeCategory("expression", "guard"),
4136
- parts: [{
4137
- slug: "body",
4138
- category: normalizeCategory("expression", "eq"),
4139
- parts: [
4140
- { slug: "lhs", category: normalizeCategory("expression", "path"), parts: [{ slug: eqMatch[1], category: ["binding"] }] },
4141
- { slug: "rhs", category: normalizeCategory("expression", "literal"), parts: [{ slug: eqMatch[2], category: ["literal"] }] }
4142
- ]
4143
- }]
4144
- });
4145
- } else {
4146
- parts.push({
4147
- slug: "visible_when",
4148
- category: normalizeCategory("expression", "guard"),
4149
- parts: [{ slug: node.visible_when, category: ["binding"] }]
4150
- });
4151
- }
4152
- }
4153
- if (node.children && node.children.length > 0) {
4154
- for (const child of node.children) {
4155
- parts.push(liftView(child));
4156
- }
4157
- }
4158
- return {
4159
- slug: node.id,
4160
- category: normalizeCategory("view", componentTag),
4161
- parts: parts.length > 0 ? parts : void 0
4162
- };
4163
- }
4164
- function emitCanonical(extracted, sourceFilename) {
4165
- const ir = emitIR(extracted);
4166
- const parts = [];
4167
- for (const state of ir.states) {
4168
- parts.push(liftState(state));
4169
- }
4170
- for (const transition of ir.transitions) {
4171
- parts.push(liftTransition(transition));
4172
- }
4173
- for (const field of ir.fields) {
4174
- parts.push(liftField(field));
4175
- }
4176
- if (extracted.experience) {
4177
- parts.push(liftView(extracted.experience));
4178
- }
4179
- parts.push({
4180
- slug: "manifest",
4181
- category: normalizeCategory("meta", "manifest"),
4182
- parts: [
4183
- {
4184
- slug: "workflows",
4185
- category: ["ref-list"],
4186
- parts: [{ slug: ir.slug, category: ["ref"] }]
4187
- },
4188
- {
4189
- slug: "route",
4190
- category: ["route"],
4191
- parts: [
4192
- { slug: "path", category: ["atom"], parts: [{ slug: `/${ir.slug}`, category: ["atom"] }] },
4193
- { slug: "label", category: ["atom"], parts: [{ slug: ir.name, category: ["atom"] }] }
4194
- ]
4195
- }
4196
- ]
4197
- });
4198
- const category = extracted.category;
4199
- let categoryArray;
4200
- if (category.includes("/")) {
4201
- const [primary, ...tags] = category.split("/");
4202
- categoryArray = normalizeCategory(primary, ...tags);
4203
- } else {
4204
- categoryArray = [category];
4205
- }
4206
- return {
4207
- slug: ir.slug,
4208
- category: categoryArray,
4209
- parts,
4210
- metadata: {
4211
- stable_id: `def-${ir.slug}`,
4212
- provenance: {
4213
- frontend: "react-compiler",
4214
- source: sourceFilename || `${ir.slug}.workflow.tsx`,
4215
- compiler_version: "1.0.0",
4216
- compiled_at: (/* @__PURE__ */ new Date()).toISOString()
4217
- }
4218
- }
4219
- };
4220
- }
4221
- function emitCompiledOutput(extracted, sourceFilename) {
4222
- return {
4223
- canonical: emitCanonical(extracted, sourceFilename),
4224
- ir: emitIR(extracted)
4225
- };
4226
- }
4227
- function foldTextContent(node) {
4228
- if (!node || typeof node !== "object") return node;
4229
- if (node.children && Array.isArray(node.children)) {
4230
- node.children = node.children.map((child) => foldTextContent(child));
4231
- if (node.children.length === 1 && node.children[0].component === "Text") {
4232
- const textChild = node.children[0];
4233
- const configKeys = textChild.config ? Object.keys(textChild.config).filter((k) => k !== "value") : [];
4234
- const bindingKeys = textChild.bindings ? Object.keys(textChild.bindings).filter((k) => k !== "value") : [];
4235
- const isSimple = !textChild.style && !textChild.className && !textChild.children && !textChild.visible_when && configKeys.length === 0 && bindingKeys.length === 0;
4236
- if (isSimple) {
4237
- const parentRules = PROP_RULES[node.component || ""];
4238
- const configKey = parentRules?.config?.text || "text";
4239
- const bindingKey = parentRules?.bindings?.text || "text";
4240
- if (textChild.config?.value && !textChild.bindings) {
4241
- if (!node.config) node.config = {};
4242
- node.config[configKey] = textChild.config.value;
4243
- node.children = void 0;
4244
- } else if (textChild.bindings?.value && !textChild.config?.value) {
4245
- if (!node.bindings) node.bindings = {};
4246
- node.bindings[bindingKey] = textChild.bindings.value;
4247
- node.children = void 0;
4248
- }
4249
- }
4250
- }
4251
- if (node.children && node.children.length === 0) {
4252
- node.children = void 0;
4253
- }
4254
- }
4255
- if (!node.children) delete node.children;
4256
- return node;
4257
- }
4258
- function emitWorkflowDefinition(extracted) {
4259
- const ir = emitIR(extracted);
4260
- const states = ir.states.map((s) => ({
4261
- name: s.name,
4262
- state_type: s.type,
4263
- description: s.description || "",
4264
- on_enter: (s.on_enter || []).map(convertAction),
4265
- on_exit: (s.on_exit || []).map(convertAction),
4266
- during: (s.during || []).map(convertDuringAction),
4267
- on_event: (s.on_event || []).map(convertOnEvent)
4268
- }));
4269
- const fields = ir.fields.map((f) => ({
4270
- name: toSnakeCase2(f.name),
4271
- field_type: f.type,
4272
- label: f.label || f.name.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase()),
4273
- required: f.required || false,
4274
- default_value: f.default_value ?? null,
4275
- ...f.validation && { validation: f.validation },
4276
- ...f.computed && { computed: f.computed },
4277
- ...f.computed_deps && { computed_deps: f.computed_deps },
4278
- ...f.visible_in_states && { visible_in_states: f.visible_in_states },
4279
- ...f.editable_in_states && { editable_in_states: f.editable_in_states },
4280
- ...f.visible_to_roles && { visible_to_roles: f.visible_to_roles },
4281
- ...f.editable_by_roles && { editable_by_roles: f.editable_by_roles },
4282
- ...f.visible_when && { visible_when: f.visible_when },
4283
- ...f.editable_when && { editable_when: f.editable_when },
4284
- ...f.state_home && { state_home: f.state_home }
4285
- }));
4286
- const transitions = ir.transitions.map((t18) => ({
4287
- name: t18.name,
4288
- from: t18.from,
4289
- to: t18.to,
4290
- description: t18.description || "",
4291
- roles: t18.roles || [],
4292
- auto: t18.auto || false,
4293
- conditions: t18.conditions || [],
4294
- actions: (t18.actions || []).map(convertAction),
4295
- required_fields: t18.required_fields || [],
4296
- priority: 0
4297
- }));
4298
- const state_data = {};
4299
- for (const f of fields) {
4300
- state_data[f.name] = f.default_value;
4301
- }
4302
- const on_event = (ir.on_event || []).map(convertOnEvent);
4303
- let views;
4304
- if (extracted.experience) {
4305
- const viewRoot = foldTextContent(JSON.parse(JSON.stringify(extracted.experience)));
4306
- const dataSources = extracted.extraMetadata?.dataSources;
4307
- if (dataSources && dataSources.length > 0) {
4308
- viewRoot.dataSources = dataSources;
4309
- }
4310
- if (extracted.fields.length > 0) {
4311
- const localDefaults = {};
4312
- for (const f of extracted.fields) {
4313
- localDefaults[toSnakeCase2(f.name)] = f.default_value ?? null;
4314
- }
4315
- if (!viewRoot.config) viewRoot.config = {};
4316
- viewRoot.config.localDefaults = localDefaults;
4317
- }
4318
- views = { default: viewRoot };
4319
- }
4320
- return {
4321
- id: `def-${ir.slug}`,
4322
- slug: ir.slug,
4323
- name: ir.name,
4324
- version: ir.version,
4325
- description: ir.description || "",
4326
- category: ir.category,
4327
- states,
4328
- transitions,
4329
- fields,
4330
- state_data,
4331
- roles: [],
4332
- child_definitions: [],
4333
- tags: ir.tags || [],
4334
- metadata: ir.metadata || {},
4335
- ...views && { views },
4336
- ...on_event.length > 0 && { on_event },
4337
- config: {},
4338
- is_immutable: false
4339
- };
4340
- }
4341
- function compilerStateToWorkflow(state, metadata) {
4342
- const fieldWatchers = metadata.fieldWatchers || [];
4343
- const transitionEffects = metadata.transitionEffects || [];
4344
- const grammarIslands = metadata.grammarIslands || [];
4345
- const knownKeys = /* @__PURE__ */ new Set(["slug", "name", "version", "description", "category", "fieldWatchers", "transitionEffects", "grammarIslands", "__modelImports", "__modelImportSlugs", "__slugAutoFallback"]);
4346
- const extraMetadata = {};
4347
- for (const [key, value] of Object.entries(metadata)) {
4348
- if (!knownKeys.has(key) && value !== void 0) {
4349
- extraMetadata[key] = value;
4350
- }
4351
- }
4352
- return {
4353
- slug: metadata.slug || "workflow",
4354
- name: metadata.name || "Workflow",
4355
- version: metadata.version || "0.1.0",
4356
- description: metadata.description,
4357
- category: metadata.category || "workflow",
4358
- fields: state.fields || [],
4359
- states: state.states || /* @__PURE__ */ new Map(),
4360
- transitions: state.transitions || [],
4361
- events: state.events || [],
4362
- experience: state.experience,
4363
- fieldWatchers: fieldWatchers.length > 0 ? fieldWatchers : void 0,
4364
- transitionEffects: transitionEffects.length > 0 ? transitionEffects : void 0,
4365
- grammarIslands: grammarIslands.length > 0 ? grammarIslands : void 0,
4366
- errors: state.errors,
4367
- warnings: state.warnings,
4368
- extraMetadata: Object.keys(extraMetadata).length > 0 ? extraMetadata : void 0
4369
- };
4370
- }
4371
-
4372
- // src/babel/visitor.ts
4373
- function resolveSlugArg(args, state) {
4374
- if (args.length < 1) return null;
4375
- const slugArg = args[0];
4376
- if (t17.isStringLiteral(slugArg)) return slugArg.value;
4377
- if (t17.isIdentifier(slugArg)) {
4378
- const compilerState = state;
4379
- const meta = compilerState.metadata;
4380
- const resolvedSlugs = meta.__modelImportSlugs;
4381
- if (resolvedSlugs?.[slugArg.name]) return resolvedSlugs[slugArg.name];
4382
- const importSources = meta.__modelImports;
4383
- if (importSources?.[slugArg.name]) {
4384
- const importPath = importSources[slugArg.name];
4385
- const filename = importPath.split("/").pop() || "";
4386
- return filename.replace(/\.(ts|tsx|js|jsx)$/, "").replace(/\.model$/, "").replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
4387
- }
4388
- }
4389
- return null;
4390
- }
4391
- function extractQueryDataSource(path, state) {
4392
- const args = path.node.arguments;
4393
- if (args.length < 1) return;
4394
- const slug = resolveSlugArg(args, state);
4395
- if (!slug) return;
4396
- const compilerState = state;
4397
- const dataSource = {
4398
- type: "workflow",
4399
- name: slug,
4400
- slug,
4401
- query: "list"
4402
- };
4403
- if (args.length > 1 && t17.isObjectExpression(args[1])) {
4404
- for (const prop of args[1].properties) {
4405
- if (!t17.isObjectProperty(prop) || !t17.isIdentifier(prop.key)) continue;
4406
- const key = prop.key.name;
4407
- const val = prop.value;
4408
- switch (key) {
4409
- case "limit":
4410
- if (t17.isNumericLiteral(val)) {
4411
- dataSource.pageSize = val.value;
4412
- dataSource.paginated = true;
4413
- }
4414
- break;
4415
- case "orderBy":
4416
- if (t17.isStringLiteral(val)) {
4417
- dataSource.sort = val.value;
4418
- }
4419
- break;
4420
- case "order":
4421
- if (t17.isStringLiteral(val) && dataSource.sort) {
4422
- dataSource.sort = `${dataSource.sort}:${val.value}`;
4423
- }
4424
- break;
4425
- case "search":
4426
- if (t17.isStringLiteral(val)) {
4427
- dataSource.search = val.value;
4428
- }
4429
- break;
4430
- case "searchFields":
4431
- if (t17.isArrayExpression(val)) {
4432
- dataSource.searchFields = val.elements.filter((el) => t17.isStringLiteral(el)).map((el) => el.value);
4433
- }
4434
- break;
4435
- case "filter":
4436
- if (t17.isObjectExpression(val)) {
4437
- const filter = {};
4438
- for (const fp of val.properties) {
4439
- if (t17.isObjectProperty(fp) && t17.isIdentifier(fp.key) && t17.isStringLiteral(fp.value)) {
4440
- filter[fp.key.name] = fp.value.value;
4441
- }
4442
- }
4443
- if (Object.keys(filter).length > 0) {
4444
- dataSource.filter = filter;
4445
- }
4446
- }
4447
- break;
4448
- case "state":
4449
- if (t17.isStringLiteral(val)) {
4450
- if (!dataSource.filter) dataSource.filter = {};
4451
- dataSource.filter.current_state = val.value;
4452
- }
4453
- break;
4454
- case "groupBy":
4455
- if (t17.isStringLiteral(val)) {
4456
- dataSource.groupBy = val.value;
4457
- }
4458
- break;
4459
- case "facets":
4460
- if (t17.isArrayExpression(val)) {
4461
- dataSource.facets = val.elements.filter((el) => t17.isStringLiteral(el)).map((el) => el.value);
4462
- }
4463
- break;
4464
- }
4465
- }
4466
- }
4467
- if (!compilerState.metadata) compilerState.metadata = {};
4468
- const meta = compilerState.metadata;
4469
- if (!meta.dataSources) meta.dataSources = [];
4470
- meta.dataSources.push(dataSource);
4471
- }
4472
- function extractMutationDataSource(path, state) {
4473
- const args = path.node.arguments;
4474
- if (args.length < 1) return;
4475
- const slug = resolveSlugArg(args, state);
4476
- if (!slug) return;
4477
- const compilerState = state;
4478
- if (!compilerState.metadata) compilerState.metadata = {};
4479
- const meta = compilerState.metadata;
4480
- if (!meta.mutationTargets) meta.mutationTargets = [];
4481
- meta.mutationTargets.push(slug);
4482
- }
4483
- function extractDuringAction(path, state) {
4484
- const args = path.node.arguments;
4485
- if (args.length < 1 || !t17.isObjectExpression(args[0])) return;
4486
- const compilerState = state;
4487
- const config = args[0];
4488
- let stateName;
4489
- let intervalMs = 1e3;
4490
- for (const prop of config.properties) {
4491
- if (!t17.isObjectProperty(prop) || !t17.isIdentifier(prop.key)) continue;
4492
- if (prop.key.name === "state" && t17.isStringLiteral(prop.value)) {
4493
- stateName = prop.value.value;
4494
- }
4495
- if (prop.key.name === "intervalMs" && t17.isNumericLiteral(prop.value)) {
4496
- intervalMs = prop.value.value;
4497
- }
4498
- }
4499
- if (!stateName) return;
4500
- if (!compilerState.states.has(stateName)) {
4501
- compilerState.states.set(stateName, {
4502
- name: stateName,
4503
- type: "REGULAR",
4504
- on_enter: [],
4505
- during: [],
4506
- on_exit: []
4507
- });
4508
- }
4509
- const stateEntry = compilerState.states.get(stateName);
4510
- if (!stateEntry.during) stateEntry.during = [];
4511
- compilerState.actionCounter++;
4512
- stateEntry.during.push({
4513
- id: `during_${compilerState.actionCounter}`,
4514
- type: "interval",
4515
- interval_ms: intervalMs,
4516
- actions: []
4517
- });
4518
- }
4519
- function extractRoleDependency(path, state) {
4520
- const args = path.node.arguments;
4521
- if (args.length < 1 || !t17.isStringLiteral(args[0])) return;
4522
- const compilerState = state;
4523
- if (!compilerState.metadata) compilerState.metadata = {};
4524
- const meta = compilerState.metadata;
4525
- if (!meta.roleDependencies) meta.roleDependencies = [];
4526
- const roles = meta.roleDependencies;
4527
- const role = args[0].value;
4528
- if (!roles.includes(role)) roles.push(role);
4529
- }
4530
- function extractViewDependency(path, state) {
4531
- const args = path.node.arguments;
4532
- if (args.length < 1 || !t17.isStringLiteral(args[0])) return;
4533
- const compilerState = state;
4534
- if (!compilerState.metadata) compilerState.metadata = {};
4535
- const meta = compilerState.metadata;
4536
- if (!meta.viewDependencies) meta.viewDependencies = [];
4537
- const views = meta.viewDependencies;
4538
- const slug = args[0].value;
4539
- if (!views.includes(slug)) views.push(slug);
4540
- }
4541
- function extractParamsUsage(_path, state) {
4542
- const compilerState = state;
4543
- if (!compilerState.metadata) compilerState.metadata = {};
4544
- const meta = compilerState.metadata;
4545
- meta.acceptsParams = true;
4546
- }
4547
- function extractLibraryDependency(path, state) {
4548
- const args = path.node.arguments;
4549
- if (args.length < 1 || !t17.isStringLiteral(args[0])) return;
4550
- const compilerState = state;
4551
- if (!compilerState.metadata) compilerState.metadata = {};
4552
- const meta = compilerState.metadata;
4553
- if (!meta.libraryDependencies) meta.libraryDependencies = [];
4554
- const libs = meta.libraryDependencies;
4555
- const slug = args[0].value;
4556
- if (!libs.includes(slug)) libs.push(slug);
4557
- }
4558
- var STRICT_BANNED_HOOKS = {
4559
- useEffect: "STRICT_USE_EFFECT",
4560
- useLayoutEffect: "STRICT_USE_LAYOUT_EFFECT",
4561
- useRef: "STRICT_USE_REF",
4562
- useMemo: "STRICT_USE_MEMO",
4563
- useCallback: "STRICT_USE_CALLBACK"
4564
- };
4565
- function extractMetadataFromComments(comments, metadata) {
4566
- for (const comment of comments) {
4567
- if (comment.type !== "CommentBlock") continue;
4568
- const lines = comment.value.split("\n");
4569
- for (const line of lines) {
4570
- const workflowMatch = line.match(/@workflow\s+(.+)/);
4571
- if (workflowMatch) {
4572
- const rest = workflowMatch[1].trim();
4573
- const kvRegex = /(\w+)="([^"]+)"/g;
4574
- let kvMatch;
4575
- let hasKV = false;
4576
- while ((kvMatch = kvRegex.exec(rest)) !== null) {
4577
- hasKV = true;
4578
- const [, key, val] = kvMatch;
4579
- if (key === "slug") metadata.slug = val;
4580
- else if (key === "version") metadata.version = val;
4581
- else if (key === "category") metadata.category = val;
4582
- else if (key === "description") metadata.description = val;
4583
- }
4584
- if (!hasKV) {
4585
- metadata.slug = rest;
4586
- }
4587
- continue;
4588
- }
4589
- const match = line.match(/@(\w+)\s+(.+)/);
4590
- if (match) {
4591
- const [, tag, value] = match;
4592
- if (tag === "version") metadata.version = value.trim();
4593
- if (tag === "category") metadata.category = value.trim();
4594
- if (tag === "description") metadata.description = value.trim();
4595
- }
4596
- }
4597
- }
4598
- }
4599
- function createVisitor(options = {}) {
4600
- const mode = options.mode;
4601
- return {
4602
- Program: {
4603
- // Initialize compiler state at program entry
4604
- enter(_path, state) {
4605
- resetNodeIdCounter();
4606
- resetDuringIdCounter();
4607
- resetWatcherIdCounter();
4608
- resetTransitionEffectIdCounter();
4609
- const compilerState = {
4610
- fields: [],
4611
- states: /* @__PURE__ */ new Map(),
4612
- transitions: [],
4613
- events: [],
4614
- actionCounter: 0,
4615
- metadata: {},
4616
- errors: [],
4617
- warnings: []
4618
- };
4619
- const program = _path.node;
4620
- const leadingComments = program.leadingComments || [];
4621
- extractMetadataFromComments(leadingComments, compilerState.metadata);
4622
- if (program.body.length > 0) {
4623
- const firstStmt = program.body[0];
4624
- if (firstStmt.leadingComments) {
4625
- extractMetadataFromComments(firstStmt.leadingComments, compilerState.metadata);
4626
- }
4627
- }
4628
- const exportDeclaration = program.body.find(
4629
- (node) => t17.isExportNamedDeclaration(node) || t17.isExportDefaultDeclaration(node)
4630
- );
4631
- if (exportDeclaration) {
4632
- if (exportDeclaration.leadingComments) {
4633
- extractMetadataFromComments(exportDeclaration.leadingComments, compilerState.metadata);
4634
- }
4635
- if (t17.isExportNamedDeclaration(exportDeclaration)) {
4636
- const declaration = exportDeclaration.declaration;
4637
- if (t17.isFunctionDeclaration(declaration)) {
4638
- if (declaration.id) {
4639
- compilerState.metadata.name = declaration.id.name;
4640
- }
4641
- if (declaration.leadingComments) {
4642
- extractMetadataFromComments(declaration.leadingComments, compilerState.metadata);
4643
- }
4644
- }
4645
- } else if (t17.isExportDefaultDeclaration(exportDeclaration)) {
4646
- const declaration = exportDeclaration.declaration;
4647
- if (t17.isFunctionDeclaration(declaration)) {
4648
- if (declaration.id) {
4649
- compilerState.metadata.name = declaration.id.name;
4650
- }
4651
- if (declaration.leadingComments) {
4652
- extractMetadataFromComments(declaration.leadingComments, compilerState.metadata);
4653
- }
4654
- } else if (t17.isIdentifier(declaration)) {
4655
- compilerState.metadata.name = declaration.name;
4656
- }
4657
- }
4658
- }
4659
- if (!compilerState.metadata.slug && state.filename) {
4660
- const fileName = state.filename.split("/").pop() || "";
4661
- compilerState.metadata.slug = fileName.replace(/\.workflow\.(tsx?|jsx?)$/, "").replace(/\.(tsx?|jsx?)$/, "").replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
4662
- compilerState.metadata.__slugAutoFallback = true;
4663
- }
4664
- Object.assign(state, compilerState);
4665
- if (isModelFile(_path, state.filename)) {
4666
- extractModelFile(_path, state);
4667
- state.__isModelFile = true;
4668
- if (!compilerState.metadata.category) {
4669
- compilerState.metadata.category = "data";
4670
- }
4671
- }
4672
- extractGrammarIslands(_path, state);
4673
- if (hasContextCreation(_path)) {
4674
- extractContextWorkflows(_path, state);
4675
- }
4676
- if (isServerActionFile(state.filename)) {
4677
- extractServerActions(_path, state);
4678
- state.__isServerActionFile = true;
4679
- }
4680
- },
4681
- // After all extraction, emit Pure Form JSON
4682
- exit(_path, state) {
4683
- const compilerState = state;
4684
- const extracted = compilerStateToWorkflow(compilerState, compilerState.metadata);
4685
- const ir = emitIR(extracted);
4686
- const definition = emitWorkflowDefinition(extracted);
4687
- const canonical = emitCanonical(extracted, state.filename);
4688
- if (compilerState.errors && compilerState.errors.length > 0) {
4689
- if (!ir.metadata) ir.metadata = {};
4690
- ir.metadata.errors = compilerState.errors;
4691
- }
4692
- if (compilerState.warnings && compilerState.warnings.length > 0) {
4693
- if (!ir.metadata) ir.metadata = {};
4694
- ir.metadata.warnings = compilerState.warnings;
4695
- }
4696
- if (!state.file.metadata) state.file.metadata = {};
4697
- state.file.metadata.mindmatrixIR = ir;
4698
- state.file.metadata.mindmatrixDefinition = definition;
4699
- state.file.metadata.mindmatrixCanonical = canonical;
4700
- }
4701
- },
4702
- // Extract metadata from function declarations with JSDoc
4703
- FunctionDeclaration(path, state) {
4704
- const comments = path.node.leadingComments || [];
4705
- const compilerState = state;
4706
- extractMetadataFromComments(comments, compilerState.metadata);
4707
- },
4708
- // Main hook extraction dispatcher
4709
- CallExpression(path, state) {
4710
- const callee = path.node.callee;
4711
- if (!t17.isIdentifier(callee)) return;
4712
- const compilerState = state;
4713
- const hookName = callee.name;
4714
- if (mode === "strict" && STRICT_BANNED_HOOKS[hookName]) {
4715
- const error = {
4716
- code: STRICT_BANNED_HOOKS[hookName],
4717
- message: `${hookName}() is not allowed in strict mode. Use @mindmatrix/react effect hooks instead.`,
4718
- line: path.node.loc?.start.line,
4719
- column: path.node.loc?.start.column,
4720
- severity: "error"
4721
- };
4722
- if (!compilerState.errors) compilerState.errors = [];
4723
- compilerState.errors.push(error);
4724
- return;
4725
- }
4726
- if (mode === "infer" && hookName === "useEffect") {
4727
- const warning = {
4728
- code: "INFER_RAW_JSX",
4729
- message: `useEffect() found in infer mode \u2014 component will be treated as an opaque [raw jsx] grammar island.`,
4730
- line: path.node.loc?.start.line,
4731
- column: path.node.loc?.start.column,
4732
- severity: "warning"
4733
- };
4734
- if (!compilerState.warnings) compilerState.warnings = [];
4735
- compilerState.warnings.push(warning);
4736
- return;
4737
- }
4738
- switch (hookName) {
4739
- case "useState":
4740
- extractStates(path, state);
4741
- break;
4742
- case "useOnEnter":
4743
- case "useOnExit":
4744
- extractEffects(path, state);
4745
- break;
4746
- case "useTransition":
4747
- extractTransitions(path, state);
4748
- break;
4749
- case "useOnEvent":
4750
- extractEvents(path, state);
4751
- break;
4752
- case "useWhileIn":
4753
- extractDuring(path, state);
4754
- break;
4755
- case "useOnChange":
4756
- extractChangeWatcher(path, state);
4757
- break;
4758
- case "useComputed":
4759
- extractComputed(path, state);
4760
- break;
4761
- case "useOnTransition":
4762
- extractTransitionEffect(path, state);
4763
- break;
4764
- case "useQuery":
4765
- extractQueryDataSource(path, state);
4766
- break;
4767
- case "useMutation":
4768
- extractMutationDataSource(path, state);
4769
- break;
4770
- case "useDuringAction":
4771
- extractDuringAction(path, state);
4772
- break;
4773
- case "useRole":
4774
- extractRoleDependency(path, state);
4775
- break;
4776
- case "useView":
4777
- extractViewDependency(path, state);
4778
- break;
4779
- case "useParams":
4780
- extractParamsUsage(path, state);
4781
- break;
4782
- case "useExpressionLibrary":
4783
- extractLibraryDependency(path, state);
4784
- break;
4785
- case "useServerAction":
4786
- extractServerActionHook(path, state);
4787
- break;
4788
- case "useServerState":
4789
- extractServerState(path, state);
4790
- break;
4791
- }
4792
- },
4793
- // Track imports: model imports for useQuery(modelRef) resolution + strict mode validation
4794
- ImportDeclaration(path, state) {
4795
- const compilerState = state;
4796
- const source = path.node.source.value;
4797
- if (source.match(/\/models\/|\.model(?:\.[tj]sx?)?$/)) {
4798
- if (!compilerState.metadata) compilerState.metadata = {};
4799
- const meta = compilerState.metadata;
4800
- if (!meta.__modelImports) meta.__modelImports = {};
4801
- const imports = meta.__modelImports;
4802
- for (const specifier of path.node.specifiers) {
4803
- if (t17.isImportDefaultSpecifier(specifier) || t17.isImportSpecifier(specifier)) {
4804
- imports[specifier.local.name] = source;
4805
- }
4806
- }
4807
- }
4808
- if (mode !== "strict") return;
4809
- if (source.startsWith("@mindmatrix/") || source.startsWith("@mmapp/") || source === "react" || source.startsWith("react/") || source.startsWith(".") || source.startsWith("/")) {
4810
- return;
4811
- }
4812
- const error = {
4813
- code: "STRICT_FORBIDDEN_IMPORT",
4814
- message: `Import from '${source}' is not allowed in strict mode. Only @mindmatrix/* and relative imports are permitted.`,
4815
- line: path.node.loc?.start.line,
4816
- column: path.node.loc?.start.column,
4817
- severity: "error"
4818
- };
4819
- if (!compilerState.errors) compilerState.errors = [];
4820
- compilerState.errors.push(error);
4821
- },
4822
- // Track derived/computed variable declarations for expression inlining.
4823
- //
4824
- // Three cases:
4825
- // 1. `const hasContent = expr` → registerDerivedVar (inline the expression)
4826
- // 2. `const users = useQuery(...)` → registerDerivedVar as $instance.{slug}
4827
- // (data source results are available on $instance by their slug)
4828
- // 3. `const sendMsg = useMutation(...)` → registerDerivedVar as $action.transition
4829
- // (mutation results are action callbacks)
4830
- // 4. `const memo = useMemo(() => expr, [])` → registerDerivedVar with body expr
4831
- VariableDeclarator(path, state) {
4832
- const compilerState = state;
4833
- if (!compilerState.metadata) return;
4834
- const id = path.node.id;
4835
- const init = path.node.init;
4836
- if (t17.isArrayPattern(id)) return;
4837
- if (!t17.isIdentifier(id) || !init || !t17.isExpression(init)) return;
4838
- const parentFn = path.getFunctionParent();
4839
- if (!parentFn) return;
4840
- const parentNode = parentFn.parentPath;
4841
- const isExportedDirectly = parentNode?.isExportDefaultDeclaration() || parentNode?.isExportNamedDeclaration();
4842
- let isExportedByName = false;
4843
- if (!isExportedDirectly && parentNode?.isVariableDeclarator()) {
4844
- const varId = parentNode.node.id;
4845
- if (t17.isIdentifier(varId)) {
4846
- isExportedByName = varId.name === compilerState.metadata?.name;
4847
- }
4848
- }
4849
- if (!isExportedDirectly && !isExportedByName) return;
4850
- if (t17.isCallExpression(init) && t17.isIdentifier(init.callee)) {
4851
- const callee = init.callee.name;
4852
- if (callee === "useQuery") {
4853
- registerDerivedVar(id.name, t17.optionalMemberExpression(
4854
- t17.identifier("$instance"),
4855
- t17.identifier(id.name),
4856
- false,
4857
- // computed
4858
- true
4859
- // optional
4860
- ));
4861
- return;
4862
- }
4863
- if (callee === "useMutation") {
4864
- registerDerivedVar(id.name, t17.memberExpression(
4865
- t17.identifier("$action"),
4866
- t17.identifier("transition")
4867
- ));
4868
- return;
4869
- }
4870
- if (callee === "useServerAction") {
4871
- registerDerivedVar(id.name, t17.memberExpression(
4872
- t17.identifier("$action"),
4873
- t17.identifier("serverAction")
4874
- ));
4875
- return;
4876
- }
4877
- if (callee === "useServerState") {
4878
- registerDerivedVar(id.name, t17.optionalMemberExpression(
4879
- t17.identifier("$instance"),
4880
- t17.identifier("serverState"),
4881
- false,
4882
- true
4883
- ));
4884
- return;
4885
- }
4886
- if (callee === "useMemo" && init.arguments.length >= 1) {
4887
- const callback = init.arguments[0];
4888
- if (t17.isArrowFunctionExpression(callback)) {
4889
- if (t17.isExpression(callback.body)) {
4890
- registerDerivedVar(id.name, callback.body);
4891
- } else if (t17.isBlockStatement(callback.body)) {
4892
- const retStmt = callback.body.body.find((s) => t17.isReturnStatement(s));
4893
- if (retStmt?.argument && t17.isExpression(retStmt.argument)) {
4894
- registerDerivedVar(id.name, retStmt.argument);
4895
- }
4896
- }
4897
- }
4898
- return;
4899
- }
4900
- if (callee.startsWith("use")) return;
4901
- }
4902
- registerDerivedVar(id.name, init);
4903
- },
4904
- // Extract JSX from function component return.
4905
- // Only extract from the exported component function's direct return,
4906
- // not from nested callbacks (Each render functions, helper components, etc.).
4907
- ReturnStatement(path, state) {
4908
- if (!t17.isJSXElement(path.node.argument) && !t17.isJSXFragment(path.node.argument)) return;
4909
- const parentFn = path.getFunctionParent();
4910
- if (!parentFn) return;
4911
- const parentNode = parentFn.parentPath;
4912
- const isExportedDirectly = parentNode?.isExportDefaultDeclaration() || parentNode?.isExportNamedDeclaration();
4913
- let isExportedByName = false;
4914
- if (!isExportedDirectly && parentNode?.isVariableDeclarator()) {
4915
- const varId = parentNode.node.id;
4916
- if (t17.isIdentifier(varId)) {
4917
- isExportedByName = varId.name === state.metadata?.name;
4918
- }
4919
- }
4920
- if (isExportedDirectly || isExportedByName) {
4921
- extractComponents(path, state);
4922
- }
4923
- }
4924
- };
4925
- }
4926
-
4927
- // src/babel/index.ts
4928
- function babelPlugin(api, options = {}) {
4929
- api.assertVersion(7);
4930
- return {
4931
- name: "mindmatrix-react",
4932
- visitor: createVisitor(options)
4933
- };
4934
- }
4935
-
4936
- export {
4937
- extractStates,
4938
- extractEffects,
4939
- extractTransitions,
4940
- extractEvents,
4941
- transpileBlock,
4942
- extractComponents,
4943
- extractComputed,
4944
- transformToFrontend,
4945
- emitIR,
4946
- emitPureForm,
4947
- emitCanonical,
4948
- emitCompiledOutput,
4949
- compilerStateToWorkflow,
4950
- createVisitor,
4951
- babelPlugin
4952
- };