@mmapp/react-compiler 0.1.0-alpha.1 → 0.1.0-alpha.5

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 (265) hide show
  1. package/ATOM-PIPELINE.md +144 -0
  2. package/README.md +88 -40
  3. package/dist/babel/index.js +2814 -277
  4. package/dist/babel/index.mjs +2 -2
  5. package/dist/chunk-3USIFFE4.mjs +2190 -0
  6. package/dist/chunk-45YMGEVT.mjs +186 -0
  7. package/dist/chunk-4FN2AISW.mjs +148 -0
  8. package/dist/chunk-4OPI5L7G.mjs +2593 -0
  9. package/dist/chunk-4RYTKOOJ.mjs +186 -0
  10. package/dist/chunk-52XHYD2V.mjs +214 -0
  11. package/dist/chunk-5GUFFFGL.mjs +148 -0
  12. package/dist/chunk-5RKTOVR5.mjs +244 -0
  13. package/dist/chunk-5YDMOO4X.mjs +214 -0
  14. package/dist/chunk-64ZWEMLJ.mjs +148 -0
  15. package/dist/chunk-6XP4KSWQ.mjs +2190 -0
  16. package/dist/chunk-72QWL54I.mjs +175 -0
  17. package/dist/chunk-7B4TRI7C.mjs +4835 -0
  18. package/dist/chunk-7ZKGHTNB.mjs +4952 -0
  19. package/dist/chunk-CIESM3BP.mjs +33 -0
  20. package/dist/chunk-DE3ZGQAC.mjs +148 -0
  21. package/dist/chunk-DMCY3BBG.mjs +1933 -0
  22. package/dist/chunk-DPIK3PJS.mjs +244 -0
  23. package/dist/chunk-E5IVH4RE.mjs +186 -0
  24. package/dist/chunk-E6FZNUR5.mjs +4953 -0
  25. package/dist/chunk-EJRBDQDP.mjs +2607 -0
  26. package/dist/chunk-ELO4TXJL.mjs +186 -0
  27. package/dist/chunk-EO6SYNCG.mjs +175 -0
  28. package/dist/chunk-FKRO52XH.mjs +3446 -0
  29. package/dist/chunk-FL4YAKU6.mjs +4941 -0
  30. package/dist/chunk-FYT47UBU.mjs +5076 -0
  31. package/dist/chunk-GCLGPOJZ.mjs +148 -0
  32. package/dist/chunk-GXB4JOP7.mjs +5072 -0
  33. package/dist/chunk-HFXOUMTD.mjs +175 -0
  34. package/dist/chunk-HWIZ47US.mjs +214 -0
  35. package/dist/chunk-IB7MNPQL.mjs +4953 -0
  36. package/dist/chunk-ICSIHQCG.mjs +148 -0
  37. package/dist/chunk-J7JUAHS4.mjs +186 -0
  38. package/dist/chunk-JLA5VNQ3.mjs +186 -0
  39. package/dist/chunk-JQLWFCTM.mjs +214 -0
  40. package/dist/chunk-KFJJCQAL.mjs +148 -0
  41. package/dist/chunk-KJUIIEQE.mjs +186 -0
  42. package/dist/chunk-KNWTHRVQ.mjs +175 -0
  43. package/dist/chunk-KSG4XSZF.mjs +175 -0
  44. package/dist/chunk-LF5N6DOU.mjs +175 -0
  45. package/dist/chunk-LJQCM2IM.mjs +214 -0
  46. package/dist/chunk-NTB7OEX2.mjs +2918 -0
  47. package/dist/chunk-NW6555WJ.mjs +186 -0
  48. package/dist/chunk-OMZE6VLQ.mjs +214 -0
  49. package/dist/chunk-OPJKP747.mjs +7506 -0
  50. package/dist/chunk-P4BR7WVO.mjs +2190 -0
  51. package/dist/chunk-QQHVYH2X.mjs +244 -0
  52. package/dist/chunk-S5QLWLLT.mjs +186 -0
  53. package/dist/chunk-SCWGT2FY.mjs +2190 -0
  54. package/dist/chunk-SMKJUSB3.mjs +2190 -0
  55. package/dist/chunk-THFYE5ZX.mjs +244 -0
  56. package/dist/chunk-VCAY2KGM.mjs +175 -0
  57. package/dist/chunk-WBYMW4NQ.mjs +3450 -0
  58. package/dist/chunk-WECAV6QB.mjs +148 -0
  59. package/dist/chunk-WMKBXUCE.mjs +3228 -0
  60. package/dist/chunk-XAJ5BKKL.mjs +4947 -0
  61. package/dist/chunk-XG2X7AEA.mjs +175 -0
  62. package/dist/chunk-XG7Z23NQ.mjs +148 -0
  63. package/dist/chunk-XWZAOCQ7.mjs +2607 -0
  64. package/dist/chunk-Y6MA7ULW.mjs +148 -0
  65. package/dist/chunk-YMS7Q7LG.mjs +214 -0
  66. package/dist/chunk-ZA37XTGA.mjs +175 -0
  67. package/dist/cli/index.js +13189 -6838
  68. package/dist/cli/index.mjs +140 -22
  69. package/dist/codemod/cli.mjs +1 -1
  70. package/dist/codemod/index.mjs +1 -1
  71. package/dist/config-PL24KEWL.mjs +219 -0
  72. package/dist/dev-server-RmGHIntF.d.mts +113 -0
  73. package/dist/dev-server-RmGHIntF.d.ts +113 -0
  74. package/dist/dev-server.d.mts +1 -1
  75. package/dist/dev-server.d.ts +1 -1
  76. package/dist/dev-server.js +4135 -440
  77. package/dist/dev-server.mjs +5 -5
  78. package/dist/envelope.js +2812 -275
  79. package/dist/envelope.mjs +3 -3
  80. package/dist/index.d.mts +161 -2
  81. package/dist/index.d.ts +161 -2
  82. package/dist/index.js +4429 -428
  83. package/dist/index.mjs +217 -9
  84. package/{src/cli/init.ts → dist/init-7JQMAAXS.mjs} +70 -95
  85. package/dist/init-DQDX3QK6.mjs +369 -0
  86. package/dist/init-EHO4VQ22.mjs +369 -0
  87. package/dist/init-UC3FWPIW.mjs +367 -0
  88. package/dist/init-UNSMVKIK.mjs +366 -0
  89. package/dist/init-UNV5XIDE.mjs +367 -0
  90. package/dist/project-compiler-2P4N4DR7.mjs +10 -0
  91. package/dist/project-compiler-D2LCC27O.mjs +10 -0
  92. package/dist/project-compiler-EJ3GANJE.mjs +10 -0
  93. package/dist/project-compiler-LOQKVRZJ.mjs +10 -0
  94. package/dist/project-compiler-OP2VVGJQ.mjs +10 -0
  95. package/dist/project-compiler-RQ6OQKRM.mjs +10 -0
  96. package/dist/project-compiler-VWNNCHGO.mjs +10 -0
  97. package/dist/project-compiler-XVAAU4C5.mjs +10 -0
  98. package/dist/project-compiler-YES5FGMD.mjs +10 -0
  99. package/dist/project-compiler-ZKMQDLGU.mjs +10 -0
  100. package/dist/project-decompiler-FLXCEJHS.mjs +7 -0
  101. package/dist/project-decompiler-US7GAVIC.mjs +7 -0
  102. package/dist/project-decompiler-VLPR22QF.mjs +7 -0
  103. package/dist/pull-FUS5QYZS.mjs +109 -0
  104. package/dist/pull-LD5ENLGY.mjs +109 -0
  105. package/dist/pull-P44LDRWB.mjs +109 -0
  106. package/dist/testing/index.js +2822 -285
  107. package/dist/testing/index.mjs +2 -2
  108. package/dist/verify-SEIXUGN4.mjs +1833 -0
  109. package/dist/vite/index.js +2815 -278
  110. package/dist/vite/index.mjs +3 -3
  111. package/examples/uber-app/app/admin/fleet.tsx +19 -19
  112. package/package.json +16 -6
  113. package/compile-blueprint-chat.mjs +0 -99
  114. package/compile-blueprint-glass-console.mjs +0 -98
  115. package/compile-chat-defs.mjs +0 -92
  116. package/examples/uber-app/tests/payment.test.tsx +0 -129
  117. package/examples/uber-app/tests/ride-flow.test.tsx +0 -123
  118. package/package.json.backup +0 -86
  119. package/scripts/decompile.ts +0 -226
  120. package/scripts/seed-auth.ts +0 -267
  121. package/scripts/seed-uber.ts +0 -248
  122. package/scripts/validate-uber.ts +0 -119
  123. package/seed-blueprint-chat.mjs +0 -444
  124. package/seed-blueprint-glass-console.mjs +0 -445
  125. package/seed-compiled.mjs +0 -318
  126. package/src/RoundTripValidator.ts +0 -400
  127. package/src/__tests__/atom-rendering-coverage.test.ts +0 -680
  128. package/src/__tests__/auth-module-compilation.test.ts +0 -247
  129. package/src/__tests__/auth-template-compilation.test.ts +0 -589
  130. package/src/__tests__/change-extractor.test.ts +0 -142
  131. package/src/__tests__/cli-pull.test.ts +0 -73
  132. package/src/__tests__/cli-test.test.ts +0 -72
  133. package/src/__tests__/component-extractor.test.ts +0 -331
  134. package/src/__tests__/context-extractor.test.ts +0 -145
  135. package/src/__tests__/decompiler.test.ts +0 -718
  136. package/src/__tests__/define-blueprint.test.ts +0 -133
  137. package/src/__tests__/definition-validator.test.ts +0 -519
  138. package/src/__tests__/during-extractor.test.ts +0 -152
  139. package/src/__tests__/effect-extractor.test.ts +0 -107
  140. package/src/__tests__/event-emission.test.ts +0 -127
  141. package/src/__tests__/examples.test.ts +0 -236
  142. package/src/__tests__/full-blueprint-coverage.test.ts +0 -1221
  143. package/src/__tests__/golden-suite.test.ts +0 -403
  144. package/src/__tests__/grammar-island-extractor.test.ts +0 -289
  145. package/src/__tests__/instance-key.test.ts +0 -82
  146. package/src/__tests__/ir-migration.test.ts +0 -255
  147. package/src/__tests__/lock-file.test.ts +0 -117
  148. package/src/__tests__/model-extractor.test.ts +0 -195
  149. package/src/__tests__/model-field-acl.test.ts +0 -237
  150. package/src/__tests__/model-hooks.test.ts +0 -130
  151. package/src/__tests__/model-ref-resolution.test.ts +0 -268
  152. package/src/__tests__/model-roundtrip.test.ts +0 -502
  153. package/src/__tests__/model-runtime.test.ts +0 -112
  154. package/src/__tests__/model-transitions.test.ts +0 -183
  155. package/src/__tests__/nrt-action-trace.test.ts +0 -391
  156. package/src/__tests__/pipeline-hardening.test.ts +0 -413
  157. package/src/__tests__/project-compiler.test.ts +0 -546
  158. package/src/__tests__/project-decompiler.test.ts +0 -343
  159. package/src/__tests__/query-compilation.test.ts +0 -145
  160. package/src/__tests__/round-trip/PLAN.md +0 -158
  161. package/src/__tests__/round-trip/README.md +0 -52
  162. package/src/__tests__/round-trip/RESULTS.md +0 -86
  163. package/src/__tests__/round-trip/fixtures/data-heavy/main.workflow.tsx +0 -55
  164. package/src/__tests__/round-trip/fixtures/data-heavy/mm.config.ts +0 -11
  165. package/src/__tests__/round-trip/fixtures/data-heavy/models/contact.ts +0 -54
  166. package/src/__tests__/round-trip/fixtures/full-workflow/main.workflow.tsx +0 -79
  167. package/src/__tests__/round-trip/fixtures/full-workflow/mm.config.ts +0 -12
  168. package/src/__tests__/round-trip/fixtures/full-workflow/models/order.ts +0 -50
  169. package/src/__tests__/round-trip/fixtures/simple-crud/main.workflow.tsx +0 -25
  170. package/src/__tests__/round-trip/fixtures/simple-crud/mm.config.ts +0 -11
  171. package/src/__tests__/round-trip/fixtures/simple-crud/models/task.ts +0 -32
  172. package/src/__tests__/round-trip/fixtures/view-heavy/main.workflow.tsx +0 -79
  173. package/src/__tests__/round-trip/fixtures/view-heavy/mm.config.ts +0 -10
  174. package/src/__tests__/round-trip/round-trip.test.ts +0 -2598
  175. package/src/__tests__/round-trip-ir.test.ts +0 -300
  176. package/src/__tests__/round-trip.test.ts +0 -1212
  177. package/src/__tests__/route-merging.test.ts +0 -372
  178. package/src/__tests__/router-composition.test.ts +0 -489
  179. package/src/__tests__/router-extractor.test.ts +0 -176
  180. package/src/__tests__/server-action-extractor.test.ts +0 -128
  181. package/src/__tests__/smart-type-inference.test.ts +0 -365
  182. package/src/__tests__/source-envelope.test.ts +0 -284
  183. package/src/__tests__/source-fidelity.test.ts +0 -516
  184. package/src/__tests__/state-extractor.test.ts +0 -115
  185. package/src/__tests__/strict-mode.test.ts +0 -227
  186. package/src/__tests__/transition-effect-extractor.test.ts +0 -119
  187. package/src/__tests__/transition-extractor.test.ts +0 -68
  188. package/src/__tests__/ts-to-expression.test.ts +0 -462
  189. package/src/__tests__/type-generator.test.ts +0 -201
  190. package/src/__tests__/uber-validation.test.ts +0 -502
  191. package/src/action-compiler.ts +0 -361
  192. package/src/babel/emitters/experience-transform.ts +0 -199
  193. package/src/babel/emitters/ir-to-tsx-emitter.ts +0 -110
  194. package/src/babel/emitters/pure-form-emitter.ts +0 -1023
  195. package/src/babel/emitters/runtime-glue-emitter.ts +0 -39
  196. package/src/babel/extractors/change-extractor.ts +0 -199
  197. package/src/babel/extractors/component-extractor.ts +0 -907
  198. package/src/babel/extractors/computed-extractor.ts +0 -262
  199. package/src/babel/extractors/context-extractor.ts +0 -277
  200. package/src/babel/extractors/during-extractor.ts +0 -295
  201. package/src/babel/extractors/effect-extractor.ts +0 -340
  202. package/src/babel/extractors/event-extractor.ts +0 -235
  203. package/src/babel/extractors/grammar-island-extractor.ts +0 -302
  204. package/src/babel/extractors/model-extractor.ts +0 -1018
  205. package/src/babel/extractors/router-extractor.ts +0 -303
  206. package/src/babel/extractors/server-action-extractor.ts +0 -173
  207. package/src/babel/extractors/server-action-hook-extractor.ts +0 -72
  208. package/src/babel/extractors/server-state-extractor.ts +0 -88
  209. package/src/babel/extractors/state-extractor.ts +0 -214
  210. package/src/babel/extractors/transition-effect-extractor.ts +0 -176
  211. package/src/babel/extractors/transition-extractor.ts +0 -143
  212. package/src/babel/index.ts +0 -24
  213. package/src/babel/transpilers/ts-to-expression.ts +0 -674
  214. package/src/babel/visitor.ts +0 -807
  215. package/src/cli/auth.ts +0 -255
  216. package/src/cli/build.ts +0 -288
  217. package/src/cli/deploy.ts +0 -206
  218. package/src/cli/index.ts +0 -328
  219. package/src/cli/installer.ts +0 -261
  220. package/src/cli/lock-file.ts +0 -94
  221. package/src/cli/mmrc.ts +0 -22
  222. package/src/cli/pull.ts +0 -172
  223. package/src/cli/registry-client.ts +0 -175
  224. package/src/cli/test.ts +0 -397
  225. package/src/cli/type-generator.ts +0 -243
  226. package/src/codemod/__tests__/forward.test.ts +0 -239
  227. package/src/codemod/__tests__/reverse.test.ts +0 -145
  228. package/src/codemod/__tests__/round-trip.test.ts +0 -137
  229. package/src/codemod/annotation.ts +0 -97
  230. package/src/codemod/classify.ts +0 -197
  231. package/src/codemod/cli.ts +0 -207
  232. package/src/codemod/control-flow.ts +0 -409
  233. package/src/codemod/forward.ts +0 -244
  234. package/src/codemod/import-manager.ts +0 -171
  235. package/src/codemod/index.ts +0 -120
  236. package/src/codemod/reverse.ts +0 -197
  237. package/src/codemod/rules.ts +0 -174
  238. package/src/codemod/state-transform.ts +0 -126
  239. package/src/decompiler/ast-builder.ts +0 -538
  240. package/src/decompiler/config-generator.ts +0 -151
  241. package/src/decompiler/index.ts +0 -315
  242. package/src/decompiler/project-decompiler.ts +0 -1776
  243. package/src/decompiler/project.ts +0 -862
  244. package/src/decompiler/split-strategy.ts +0 -140
  245. package/src/decompiler/state-emitter.ts +0 -1053
  246. package/src/decompiler/sx-emitter.ts +0 -318
  247. package/src/decompiler/workspace-hydrator.ts +0 -189
  248. package/src/dev-server.ts +0 -238
  249. package/src/envelope/fs-tree.ts +0 -217
  250. package/src/envelope/source-envelope.ts +0 -264
  251. package/src/envelope.ts +0 -315
  252. package/src/incremental-compiler.ts +0 -401
  253. package/src/index.ts +0 -99
  254. package/src/model-compiler.ts +0 -277
  255. package/src/project-compiler.ts +0 -1629
  256. package/src/route-extractor.ts +0 -333
  257. package/src/testing/index.ts +0 -32
  258. package/src/testing/snapshot.ts +0 -252
  259. package/src/testing/test-utils.ts +0 -226
  260. package/src/types.ts +0 -68
  261. package/src/vite/index.ts +0 -288
  262. package/test-compile.mjs +0 -142
  263. package/tsconfig.json +0 -25
  264. package/tsup.config.ts +0 -23
  265. package/vitest.config.ts +0 -9
@@ -1,1023 +0,0 @@
1
- /**
2
- * Workflow Emitter — assembles extracted pieces into IR, engine-compatible, and canonical outputs.
3
- *
4
- * Three output stages:
5
- * 1. emitIR() → IRWorkflowDefinition (the IR cache)
6
- * 2. emitWorkflowDefinition() → engine-compatible JSON (state_type, field_type, action_type)
7
- * 3. emitCanonical() → PureFormWorkflow (canonical tree per 041 protocol)
8
- * 4. emitCompiledOutput() → { canonical, ir } (combined output)
9
- *
10
- * Data flow:
11
- * CompilerState → compilerStateToWorkflow() → ExtractedWorkflow → emitIR() → IRWorkflowDefinition
12
- * → emitWorkflowDefinition() → engine-compatible JSON
13
- * → emitCanonical() → PureFormWorkflow
14
- *
15
- * Critical contract: NOTHING extracted may be silently dropped.
16
- * Every piece of data extracted by the visitor must appear in the output.
17
- */
18
-
19
- import type {
20
- IRWorkflowDefinition,
21
- IRStateDefinition,
22
- IRTransitionDefinition,
23
- IRFieldDefinition,
24
- IRConditionDefinition,
25
- IRDuringAction,
26
- IROnEventSubscription,
27
- IRGrammarIsland,
28
- IRActionDefinition,
29
- IRExperienceNode,
30
- IRDataSource,
31
- PureFormWorkflow,
32
- } from '@mindmatrix/player-core';
33
- import { normalizeCategory } from '@mindmatrix/player-core';
34
- import type { ExtractedWorkflow, CompilerState } from '../../types';
35
- import type { FieldWatcher } from '../extractors/change-extractor';
36
- import type { TransitionEffect } from '../extractors/transition-effect-extractor';
37
- import { inferTransitionStates } from '../extractors/transition-extractor';
38
- import { transformToFrontend } from './experience-transform';
39
-
40
- // =============================================================================
41
- // View normalization (moved from seed-compiled.mjs into compiler)
42
- // =============================================================================
43
-
44
- const PROP_RULES: Record<string, { config?: Record<string, string>; bindings?: Record<string, string> }> = {
45
- Text: {
46
- config: { text: 'value' },
47
- bindings: { text: 'value' },
48
- },
49
- Heading: {
50
- config: { text: 'value' },
51
- bindings: { text: 'value' },
52
- },
53
- Button: {
54
- config: { text: 'label' },
55
- bindings: { text: 'label', onPress: 'onClick' },
56
- },
57
- };
58
-
59
- const COMPONENT_RENAMES: Record<string, string> = {
60
- Heading: 'Text',
61
- };
62
-
63
- const RENAME_EXTRA_CONFIG: Record<string, Record<string, unknown>> = {
64
- Heading: { variant: 'h2' },
65
- };
66
-
67
- /**
68
- * Normalizes an ExperienceNode tree:
69
- * - Renames components (Heading → Text + variant)
70
- * - Remaps prop names (text→value, onPress→onClick)
71
- * - Converts template strings ({field}) → $fn.concat() bindings
72
- * - Rewrites .fire bindings → $action.transition()
73
- * - Rewrites $instance.field → $instance.state_data.field
74
- */
75
- function normalizeViewNode(node: IRExperienceNode, fieldNames: Set<string>): IRExperienceNode {
76
- if (!node || typeof node !== 'object') return node;
77
-
78
- // Rename component if needed
79
- const originalComponent = node.component;
80
- if (originalComponent && COMPONENT_RENAMES[originalComponent]) {
81
- node.component = COMPONENT_RENAMES[originalComponent];
82
- const extra = RENAME_EXTRA_CONFIG[originalComponent];
83
- if (extra) {
84
- node.config = { ...extra, ...(node.config || {}) };
85
- }
86
- }
87
-
88
- // Apply prop rename rules
89
- const rules = PROP_RULES[originalComponent || ''] || PROP_RULES[node.component || ''];
90
- if (rules) {
91
- if (node.config && rules.config) {
92
- for (const [from, to] of Object.entries(rules.config)) {
93
- if (from in node.config && !(to in node.config)) {
94
- node.config[to] = node.config[from];
95
- delete node.config[from];
96
- }
97
- }
98
- }
99
- if (node.bindings && rules.bindings) {
100
- for (const [from, to] of Object.entries(rules.bindings)) {
101
- if (from in node.bindings && !(to in node.bindings)) {
102
- node.bindings[to] = node.bindings[from];
103
- delete node.bindings[from];
104
- }
105
- }
106
- }
107
- }
108
-
109
- // Convert template strings in config to bindings
110
- if (node.config && fieldNames.size > 0) {
111
- for (const [prop, val] of Object.entries(node.config)) {
112
- if (typeof val !== 'string') continue;
113
- const templateRe = /\{\{(\w+)\}\}|\{(\w+)\}/g;
114
- let match;
115
- const refs: Array<{ full: string; field: string; index: number }> = [];
116
- while ((match = templateRe.exec(val)) !== null) {
117
- const field = match[1] || match[2];
118
- if (fieldNames.has(field)) {
119
- refs.push({ full: match[0], field, index: match.index });
120
- }
121
- }
122
- if (refs.length > 0) {
123
- const parts: string[] = [];
124
- let lastEnd = 0;
125
- for (const ref of refs) {
126
- const before = val.slice(lastEnd, ref.index);
127
- if (before) parts.push(`"${before}"`);
128
- parts.push(`$instance.state_data.${ref.field}`);
129
- lastEnd = ref.index + ref.full.length;
130
- }
131
- const trailing = val.slice(lastEnd);
132
- if (trailing) parts.push(`"${trailing}"`);
133
- const expr = `$fn.concat(${parts.join(', ')})`;
134
- if (!node.bindings) node.bindings = {};
135
- node.bindings[prop] = expr;
136
- delete node.config[prop];
137
- }
138
- }
139
- }
140
-
141
- // Rewrite bindings
142
- if (node.bindings) {
143
- for (const [prop, expr] of Object.entries(node.bindings)) {
144
- if (typeof expr !== 'string') continue;
145
-
146
- // .fire bindings → $action.transition("name")
147
- if (expr.endsWith('.fire')) {
148
- const transitionName = expr.slice(0, -5);
149
- node.bindings[prop] = `$action.transition("${transitionName}")`;
150
- continue;
151
- }
152
-
153
- // $instance.fieldName → $instance.state_data.fieldName
154
- if (fieldNames.size > 0 && expr.startsWith('$instance.')) {
155
- const field = expr.slice('$instance.'.length);
156
- if (fieldNames.has(field)) {
157
- node.bindings[prop] = `$instance.state_data.${field}`;
158
- }
159
- }
160
- }
161
- }
162
-
163
- if (node.children && Array.isArray(node.children)) {
164
- node.children = node.children.map(child => normalizeViewNode(child, fieldNames));
165
-
166
- // Fold single Text children into parent config/bindings — only when the
167
- // child Text is "simple" (no style, className, children, or extra config).
168
- // Use PROP_RULES-mapped key so the result is already canonical.
169
- if (node.children.length === 1 && node.children[0].component === 'Text') {
170
- const textChild = node.children[0];
171
- // Only fold when the child Text is truly simple — no style, className,
172
- // children, visible_when, or extra config/binding keys beyond value.
173
- const configKeys = textChild.config ? Object.keys(textChild.config).filter(k => k !== 'value') : [];
174
- const bindingKeys = textChild.bindings ? Object.keys(textChild.bindings).filter(k => k !== 'value') : [];
175
- const isSimple = !textChild.style && !textChild.className && !textChild.children
176
- && !textChild.visible_when && configKeys.length === 0 && bindingKeys.length === 0;
177
- if (isSimple) {
178
- const parentRules = PROP_RULES[node.component || ''];
179
- const configKey = parentRules?.config?.text || 'text';
180
- const bindingKey = parentRules?.bindings?.text || 'text';
181
- if (textChild.config?.value && !textChild.bindings) {
182
- // Static text child: fold into config
183
- if (!node.config) node.config = {};
184
- node.config[configKey] = textChild.config.value;
185
- delete node.children;
186
- } else if (textChild.bindings?.value && !textChild.config?.value) {
187
- // Dynamic text child: fold into bindings
188
- if (!node.bindings) node.bindings = {};
189
- node.bindings[bindingKey] = textChild.bindings.value;
190
- delete node.children;
191
- }
192
- }
193
- }
194
- }
195
-
196
- return node;
197
- }
198
-
199
- // =============================================================================
200
- // Utility functions
201
- // =============================================================================
202
-
203
- /**
204
- * Converts camelCase to snake_case.
205
- */
206
- function toSnakeCase(str: string): string {
207
- return str.replace(/([A-Z])/g, '_$1').toLowerCase().replace(/^_/, '');
208
- }
209
-
210
- /**
211
- * Converts action from IR format (type) to engine format (action_type).
212
- */
213
- function convertAction(action: any): any {
214
- return {
215
- id: action.id,
216
- action_type: action.type,
217
- config: action.config || {},
218
- ...(action.condition && { condition: action.condition }),
219
- };
220
- }
221
-
222
- /**
223
- * Converts an IRDuringAction to engine format.
224
- */
225
- function convertDuringAction(during: IRDuringAction): Record<string, unknown> {
226
- return {
227
- id: during.id,
228
- type: during.type,
229
- ...(during.interval_ms !== undefined && { interval_ms: during.interval_ms }),
230
- ...(during.cron && { cron: during.cron }),
231
- ...(during.delay_ms !== undefined && { delay_ms: during.delay_ms }),
232
- actions: during.actions.map(convertAction),
233
- ...(during.condition && { condition: during.condition }),
234
- };
235
- }
236
-
237
- /**
238
- * Converts an IROnEventSubscription to engine format.
239
- */
240
- function convertOnEvent(sub: IROnEventSubscription): Record<string, unknown> {
241
- return {
242
- match: sub.match,
243
- ...(sub.description && { description: sub.description }),
244
- conditions: sub.conditions || [],
245
- actions: sub.actions.map((a) => ({
246
- type: a.type,
247
- ...(a.field && { field: a.field }),
248
- ...(a.expression && { expression: a.expression }),
249
- ...(a.key && { key: a.key }),
250
- ...(a.message && { message: a.message }),
251
- ...(a.config && { config: a.config }),
252
- ...(a.conditions && a.conditions.length > 0 && { conditions: a.conditions }),
253
- })),
254
- };
255
- }
256
-
257
- // =============================================================================
258
- // IR Emission (renamed from emitPureForm)
259
- // =============================================================================
260
-
261
- /**
262
- * Emits IR from extracted workflow data.
263
- *
264
- * This is the lowered IR output — everything extracted ends up here.
265
- * View tree is normalized and emitted as a top-level `view` field
266
- * (not inside metadata.experience).
267
- */
268
- export function emitIR(extracted: ExtractedWorkflow): IRWorkflowDefinition {
269
- const { slug, name, version, description, category, fields, states, transitions } = extracted;
270
-
271
- // Convert state map to array
272
- const stateArray: IRStateDefinition[] = Array.from(states.values());
273
-
274
- // Ensure at least one START state exists
275
- if (stateArray.length === 0) {
276
- stateArray.push({
277
- name: 'draft',
278
- type: 'START',
279
- on_enter: [],
280
- during: [],
281
- on_exit: [],
282
- });
283
- } else {
284
- const hasStart = stateArray.some((s) => s.type === 'START');
285
- if (!hasStart && stateArray.length > 0) {
286
- stateArray[0].type = 'START';
287
- }
288
- }
289
-
290
- // Only infer from/to for transitions that don't already have explicit values
291
- inferTransitionStates(transitions, states);
292
-
293
- // Validate: every transition references existing states
294
- const stateNames = new Set(stateArray.map((s) => s.name));
295
- for (const transition of transitions) {
296
- if (transition.to && !stateNames.has(transition.to)) {
297
- stateArray.push({
298
- name: transition.to,
299
- type: 'REGULAR',
300
- on_enter: [],
301
- during: [],
302
- on_exit: [],
303
- });
304
- stateNames.add(transition.to);
305
- }
306
- }
307
-
308
- // Normalize view tree (prop renames, binding rewrites, template conversion)
309
- const fieldNames = new Set(fields.map(f => f.name));
310
- let normalizedView: IRExperienceNode | undefined;
311
- if (extracted.experience) {
312
- normalizedView = normalizeViewNode(
313
- JSON.parse(JSON.stringify(extracted.experience)),
314
- fieldNames,
315
- );
316
-
317
- // Attach dataSources from useQuery() extractions to the root view node
318
- const dataSources = extracted.extraMetadata?.dataSources as IRDataSource[] | undefined;
319
- if (dataSources && dataSources.length > 0) {
320
- normalizedView.dataSources = dataSources;
321
- }
322
-
323
- // Attach localDefaults config for $local initialization from useState fields
324
- if (fields.length > 0) {
325
- const localDefaults: Record<string, unknown> = {};
326
- for (const f of fields) {
327
- localDefaults[toSnakeCase(f.name)] = f.default_value ?? null;
328
- }
329
- if (!normalizedView.config) normalizedView.config = {};
330
- normalizedView.config.localDefaults = localDefaults;
331
- }
332
- }
333
-
334
- // Build metadata — include everything extracted EXCEPT experience (now top-level view)
335
- const metadata: Record<string, unknown> = {
336
- stable_id: `def-${slug}`,
337
- provenance: {
338
- frontend: 'react-compiler',
339
- source: `${slug}.workflow.tsx`,
340
- compiler_version: '1.0.0',
341
- },
342
- };
343
- if (extracted.fieldWatchers && extracted.fieldWatchers.length > 0) {
344
- metadata.fieldWatchers = extracted.fieldWatchers;
345
- }
346
- if (extracted.transitionEffects && extracted.transitionEffects.length > 0) {
347
- metadata.transitionEffects = extracted.transitionEffects;
348
- }
349
- // Forward extra metadata from model files (runtime, etc.)
350
- if (extracted.extraMetadata) {
351
- for (const [key, value] of Object.entries(extracted.extraMetadata)) {
352
- metadata[key] = value;
353
- }
354
- }
355
-
356
- // Keep experience in metadata for backward compatibility during migration
357
- if (extracted.experience) {
358
- metadata.experience = extracted.experience;
359
- }
360
-
361
- const ir: IRWorkflowDefinition = {
362
- slug,
363
- name,
364
- version,
365
- description,
366
- category,
367
- fields,
368
- states: stateArray,
369
- transitions,
370
- roles: [],
371
- tags: [],
372
- metadata,
373
- };
374
-
375
- // Attach normalized view as views.default (IR format)
376
- // Also attach frontend-compatible view via transform pass
377
- if (normalizedView) {
378
- (ir as any).views = { default: normalizedView };
379
- (ir as any).frontendViews = { default: transformToFrontend(normalizedView) };
380
- }
381
-
382
- // Emit workflow-level on_event
383
- if (extracted.events && extracted.events.length > 0) {
384
- ir.on_event = extracted.events;
385
- }
386
-
387
- // Emit grammar islands as extensions
388
- if (extracted.grammarIslands && extracted.grammarIslands.length > 0) {
389
- const extensions: Record<string, typeof extracted.grammarIslands> = {};
390
- for (const island of extracted.grammarIslands) {
391
- const key = island.contextTag;
392
- if (!extensions[key]) extensions[key] = [];
393
- extensions[key].push(island);
394
- }
395
- ir.extensions = extensions;
396
- }
397
-
398
- return ir;
399
- }
400
-
401
- /** @deprecated Use emitIR() instead. Kept for backward compatibility. */
402
- export const emitPureForm = emitIR;
403
-
404
- // =============================================================================
405
- // Canonical Tree Emission (per 041 protocol)
406
- // =============================================================================
407
-
408
- /**
409
- * Lifts an IR action into canonical form.
410
- */
411
- function liftAction(action: IRActionDefinition): PureFormWorkflow {
412
- const parts: PureFormWorkflow[] = [];
413
-
414
- if (action.config) {
415
- for (const [key, value] of Object.entries(action.config)) {
416
- parts.push({
417
- slug: key,
418
- category: ['atom'],
419
- parts: [{ slug: String(value), category: ['atom'] }],
420
- });
421
- }
422
- }
423
-
424
- if (action.condition) {
425
- parts.push({
426
- slug: 'condition',
427
- category: ['expression', 'guard'],
428
- parts: [{ slug: action.condition, category: ['binding'] }],
429
- });
430
- }
431
-
432
- return {
433
- slug: action.id,
434
- category: normalizeCategory('expression', 'mutation', action.type),
435
- parts: parts.length > 0 ? parts : undefined,
436
- };
437
- }
438
-
439
- /**
440
- * Lifts an IR during action (schedule) into canonical form.
441
- */
442
- function liftSchedule(during: IRDuringAction): PureFormWorkflow {
443
- const parts: PureFormWorkflow[] = [];
444
-
445
- if (during.interval_ms !== undefined) {
446
- parts.push({
447
- slug: 'every',
448
- category: ['atom'],
449
- parts: [{ slug: String(during.interval_ms), category: ['literal'] }],
450
- });
451
- }
452
-
453
- if (during.cron) {
454
- parts.push({
455
- slug: 'cron',
456
- category: ['atom'],
457
- parts: [{ slug: during.cron, category: ['literal'] }],
458
- });
459
- }
460
-
461
- if (during.delay_ms !== undefined) {
462
- parts.push({
463
- slug: 'delay',
464
- category: ['atom'],
465
- parts: [{ slug: String(during.delay_ms), category: ['literal'] }],
466
- });
467
- }
468
-
469
- // Lift inner actions
470
- for (const action of during.actions) {
471
- parts.push({
472
- slug: 'do',
473
- category: normalizeCategory('expression', 'mutation', action.type),
474
- parts: Object.entries(action.config || {}).map(([key, value]) => ({
475
- slug: key,
476
- category: ['atom'],
477
- parts: [{ slug: String(value), category: ['atom'] }],
478
- })),
479
- });
480
- }
481
-
482
- return {
483
- slug: during.id,
484
- category: normalizeCategory('schedule', during.type),
485
- parts,
486
- };
487
- }
488
-
489
- /**
490
- * Lifts an IR state into canonical form.
491
- */
492
- function liftState(state: IRStateDefinition): PureFormWorkflow {
493
- const parts: PureFormWorkflow[] = [];
494
- const tags: string[] = [];
495
-
496
- if (state.type === 'START') tags.push('start');
497
- if (state.type === 'END') tags.push('end');
498
- if (state.type === 'CANCELLED') tags.push('cancelled');
499
-
500
- // on_enter actions
501
- if (state.on_enter && state.on_enter.length > 0) {
502
- parts.push({
503
- slug: 'on_enter',
504
- category: normalizeCategory('expression', 'sequence'),
505
- parts: state.on_enter.map(liftAction),
506
- });
507
- }
508
-
509
- // on_exit actions
510
- if (state.on_exit && state.on_exit.length > 0) {
511
- parts.push({
512
- slug: 'on_exit',
513
- category: normalizeCategory('expression', 'sequence'),
514
- parts: state.on_exit.map(liftAction),
515
- });
516
- }
517
-
518
- // during actions (schedules)
519
- if (state.during && state.during.length > 0) {
520
- for (const d of state.during) {
521
- parts.push(liftSchedule(d));
522
- }
523
- }
524
-
525
- return {
526
- slug: state.name,
527
- category: normalizeCategory('state', ...tags),
528
- parts: parts.length > 0 ? parts : undefined,
529
- };
530
- }
531
-
532
- /**
533
- * Lifts an IR transition into canonical form.
534
- */
535
- function liftTransition(transition: IRTransitionDefinition): PureFormWorkflow {
536
- const parts: PureFormWorkflow[] = [];
537
-
538
- // from refs
539
- if (transition.from && transition.from.length > 0) {
540
- parts.push({
541
- slug: 'from',
542
- category: ['part'],
543
- parts: transition.from.map((s: string) => ({ slug: s, category: ['ref'] as string[] })),
544
- });
545
- }
546
-
547
- // to ref
548
- if (transition.to) {
549
- parts.push({
550
- slug: 'to',
551
- category: ['part'],
552
- parts: [{ slug: transition.to, category: ['ref'] }],
553
- });
554
- }
555
-
556
- // actions
557
- if (transition.actions && transition.actions.length > 0) {
558
- parts.push({
559
- slug: 'actions',
560
- category: normalizeCategory('expression', 'sequence'),
561
- parts: transition.actions.map(liftAction),
562
- });
563
- }
564
-
565
- // conditions
566
- if (transition.conditions && transition.conditions.length > 0) {
567
- parts.push({
568
- slug: 'conditions',
569
- category: normalizeCategory('expression', 'guard'),
570
- parts: transition.conditions.map((c: IRConditionDefinition, i: number) => ({
571
- slug: `condition_${i}`,
572
- category: normalizeCategory('expression', c.type || 'condition'),
573
- parts: c.expression ? [{ slug: c.expression, category: ['binding'] as string[] }] : undefined,
574
- })),
575
- });
576
- }
577
-
578
- return {
579
- slug: transition.name,
580
- category: ['transition'],
581
- parts,
582
- };
583
- }
584
-
585
- /**
586
- * Lifts an IR field into canonical form.
587
- */
588
- function liftField(field: IRFieldDefinition): PureFormWorkflow {
589
- const parts: PureFormWorkflow[] = [];
590
-
591
- if (field.label) {
592
- parts.push({
593
- slug: 'label',
594
- category: ['atom'],
595
- parts: [{ slug: field.label, category: ['atom'] }],
596
- });
597
- }
598
-
599
- if (field.default_value !== undefined) {
600
- parts.push({
601
- slug: 'default',
602
- category: ['atom'],
603
- parts: [{ slug: String(field.default_value), category: ['literal'] }],
604
- });
605
- }
606
-
607
- if (field.required) {
608
- parts.push({ slug: 'required', category: ['atom'], parts: [{ slug: 'true', category: ['literal'] }] });
609
- }
610
-
611
- if (field.computed) {
612
- parts.push({
613
- slug: 'computed',
614
- category: ['expression'],
615
- parts: [{ slug: field.computed, category: ['binding'] }],
616
- });
617
- }
618
-
619
- return {
620
- slug: field.name,
621
- category: normalizeCategory('field', field.type),
622
- parts: parts.length > 0 ? parts : undefined,
623
- };
624
- }
625
-
626
- /**
627
- * Lifts an ExperienceNode tree into canonical view form.
628
- */
629
- function liftView(node: IRExperienceNode): PureFormWorkflow {
630
- const componentTag = (node.component || 'stack').toLowerCase().replace(/\s+/g, '-');
631
- const parts: PureFormWorkflow[] = [];
632
-
633
- // Config as atom parts
634
- if (node.config) {
635
- for (const [key, value] of Object.entries(node.config)) {
636
- parts.push({
637
- slug: key,
638
- category: ['atom'],
639
- parts: [{ slug: String(value), category: ['atom'] }],
640
- });
641
- }
642
- }
643
-
644
- // Bindings as expression parts
645
- if (node.bindings) {
646
- for (const [key, expr] of Object.entries(node.bindings)) {
647
- if (key === 'onClick' || key === 'onPress') {
648
- // Transition binding
649
- const match = typeof expr === 'string' ? expr.match(/\$action\.transition\("(.+?)"\)/) : null;
650
- if (match) {
651
- parts.push({
652
- slug: key,
653
- category: normalizeCategory('expression', 'effect', 'transition'),
654
- parts: [{ slug: match[1], category: ['ref'] }],
655
- });
656
- } else {
657
- parts.push({
658
- slug: key,
659
- category: normalizeCategory('expression', 'binding'),
660
- parts: [{ slug: String(expr), category: ['binding'] }],
661
- });
662
- }
663
- } else {
664
- parts.push({
665
- slug: key,
666
- category: normalizeCategory('expression', 'binding'),
667
- parts: [{ slug: String(expr), category: ['binding'] }],
668
- });
669
- }
670
- }
671
- }
672
-
673
- // visible_when as guard expression
674
- if (node.visible_when) {
675
- const eqMatch = node.visible_when.match(/\$fn\.eq\((.+?),\s*"(.+?)"\)/);
676
- if (eqMatch) {
677
- parts.push({
678
- slug: 'visible_when',
679
- category: normalizeCategory('expression', 'guard'),
680
- parts: [{
681
- slug: 'body',
682
- category: normalizeCategory('expression', 'eq'),
683
- parts: [
684
- { slug: 'lhs', category: normalizeCategory('expression', 'path'), parts: [{ slug: eqMatch[1], category: ['binding'] }] },
685
- { slug: 'rhs', category: normalizeCategory('expression', 'literal'), parts: [{ slug: eqMatch[2], category: ['literal'] }] },
686
- ],
687
- }],
688
- });
689
- } else {
690
- parts.push({
691
- slug: 'visible_when',
692
- category: normalizeCategory('expression', 'guard'),
693
- parts: [{ slug: node.visible_when, category: ['binding'] }],
694
- });
695
- }
696
- }
697
-
698
- // Recurse children
699
- if (node.children && node.children.length > 0) {
700
- for (const child of node.children) {
701
- parts.push(liftView(child));
702
- }
703
- }
704
-
705
- return {
706
- slug: node.id,
707
- category: normalizeCategory('view', componentTag),
708
- parts: parts.length > 0 ? parts : undefined,
709
- };
710
- }
711
-
712
- /**
713
- * Emits canonical tree from extracted workflow data.
714
- *
715
- * Produces `{ slug, category, parts, metadata }` per 041 protocol.
716
- * This is the TRUTH. The IR is a derivable cache.
717
- */
718
- export function emitCanonical(extracted: ExtractedWorkflow, sourceFilename?: string): PureFormWorkflow {
719
- // First get the IR to reuse its processing (START state inference, transition validation, etc.)
720
- const ir = emitIR(extracted);
721
-
722
- const parts: PureFormWorkflow[] = [];
723
-
724
- // Lift states
725
- for (const state of ir.states) {
726
- parts.push(liftState(state));
727
- }
728
-
729
- // Lift transitions
730
- for (const transition of ir.transitions) {
731
- parts.push(liftTransition(transition));
732
- }
733
-
734
- // Lift fields
735
- for (const field of ir.fields) {
736
- parts.push(liftField(field));
737
- }
738
-
739
- // Lift view tree (from original experience, not normalized IR view)
740
- if (extracted.experience) {
741
- parts.push(liftView(extracted.experience));
742
- }
743
-
744
- // Manifest as meta part
745
- parts.push({
746
- slug: 'manifest',
747
- category: normalizeCategory('meta', 'manifest'),
748
- parts: [
749
- {
750
- slug: 'workflows',
751
- category: ['ref-list'],
752
- parts: [{ slug: ir.slug, category: ['ref'] }],
753
- },
754
- {
755
- slug: 'route',
756
- category: ['route'],
757
- parts: [
758
- { slug: 'path', category: ['atom'], parts: [{ slug: `/${ir.slug}`, category: ['atom'] }] },
759
- { slug: 'label', category: ['atom'], parts: [{ slug: ir.name, category: ['atom'] }] },
760
- ],
761
- },
762
- ],
763
- });
764
-
765
- // Parse category: the user-specified category is the primary.
766
- // Open category set — any string is valid (workflow, data, blueprint, module,
767
- // data-type, view, expression-library, or user-defined categories).
768
- // If the category contains a slash (e.g., "workflow/demo"), split into primary + tag.
769
- const category = extracted.category;
770
- let categoryArray: string[];
771
- if (category.includes('/')) {
772
- const [primary, ...tags] = category.split('/');
773
- categoryArray = normalizeCategory(primary, ...tags);
774
- } else {
775
- categoryArray = [category];
776
- }
777
-
778
- return {
779
- slug: ir.slug,
780
- category: categoryArray,
781
- parts,
782
- metadata: {
783
- stable_id: `def-${ir.slug}`,
784
- provenance: {
785
- frontend: 'react-compiler',
786
- source: sourceFilename || `${ir.slug}.workflow.tsx`,
787
- compiler_version: '1.0.0',
788
- compiled_at: new Date().toISOString(),
789
- },
790
- },
791
- };
792
- }
793
-
794
- /**
795
- * Emits the combined compiled output: canonical tree + lowered IR.
796
- */
797
- export function emitCompiledOutput(extracted: ExtractedWorkflow, sourceFilename?: string): { canonical: PureFormWorkflow; ir: IRWorkflowDefinition } {
798
- return {
799
- canonical: emitCanonical(extracted, sourceFilename),
800
- ir: emitIR(extracted),
801
- };
802
- }
803
-
804
- // =============================================================================
805
- // Text-content folding (lightweight, no renames/rewrites)
806
- // =============================================================================
807
-
808
- /**
809
- * Folds single Text children into parent config/bindings.
810
- * e.g. <Heading>Counter</Heading> → Heading with config.text = "Counter"
811
- * e.g. <Text>{count}</Text> → Text with bindings.text = "$instance.count"
812
- * Does NOT rename components or rewrite bindings — that's normalizeViewNode's job.
813
- */
814
- function foldTextContent(node: IRExperienceNode): IRExperienceNode {
815
- if (!node || typeof node !== 'object') return node;
816
-
817
- if (node.children && Array.isArray(node.children)) {
818
- node.children = node.children.map(child => foldTextContent(child));
819
-
820
- // Fold single Text children into parent — only when truly simple
821
- if (node.children.length === 1 && node.children[0].component === 'Text') {
822
- const textChild = node.children[0];
823
- const configKeys = textChild.config ? Object.keys(textChild.config).filter((k: string) => k !== 'value') : [];
824
- const bindingKeys = textChild.bindings ? Object.keys(textChild.bindings).filter((k: string) => k !== 'value') : [];
825
- const isSimple = !textChild.style && !textChild.className && !textChild.children
826
- && !textChild.visible_when && configKeys.length === 0 && bindingKeys.length === 0;
827
- if (isSimple) {
828
- const parentRules = PROP_RULES[node.component || ''];
829
- const configKey = parentRules?.config?.text || 'text';
830
- const bindingKey = parentRules?.bindings?.text || 'text';
831
- if (textChild.config?.value && !textChild.bindings) {
832
- if (!node.config) node.config = {};
833
- node.config[configKey] = textChild.config.value;
834
- node.children = undefined as any;
835
- } else if (textChild.bindings?.value && !textChild.config?.value) {
836
- if (!node.bindings) node.bindings = {};
837
- node.bindings[bindingKey] = textChild.bindings.value;
838
- node.children = undefined as any;
839
- }
840
- }
841
- }
842
-
843
- // Clean up empty children arrays
844
- if (node.children && node.children.length === 0) {
845
- node.children = undefined as any;
846
- }
847
- }
848
-
849
- // Remove undefined children from serialization
850
- if (!node.children) delete (node as any).children;
851
-
852
- return node;
853
- }
854
-
855
- // =============================================================================
856
- // Engine-compatible Definition Emission
857
- // =============================================================================
858
-
859
- /**
860
- * Emits a LocalWorkflowEngine-compatible WorkflowDefinition.
861
- *
862
- * This converts from the IR format to the engine format:
863
- * - state.type → state.state_type
864
- * - field.type → field.field_type
865
- * - action.type → action.action_type
866
- * - during actions → engine format with action_type
867
- * - on_event → preserved per-state and at workflow level
868
- * - camelCase field names → snake_case
869
- */
870
- export function emitWorkflowDefinition(extracted: ExtractedWorkflow): Record<string, unknown> {
871
- const ir = emitIR(extracted);
872
-
873
- // Convert states: type → state_type, actions type → action_type
874
- const states = ir.states.map((s) => ({
875
- name: s.name,
876
- state_type: s.type,
877
- description: s.description || '',
878
- on_enter: (s.on_enter || []).map(convertAction),
879
- on_exit: (s.on_exit || []).map(convertAction),
880
- during: (s.during || []).map(convertDuringAction),
881
- on_event: (s.on_event || []).map(convertOnEvent),
882
- }));
883
-
884
- // Convert fields: type → field_type, name to snake_case, preserve ACL
885
- const fields = ir.fields.map((f) => ({
886
- name: toSnakeCase(f.name),
887
- field_type: f.type,
888
- label: f.label || f.name.replace(/([A-Z])/g, ' $1').replace(/^./, (c) => c.toUpperCase()),
889
- required: f.required || false,
890
- default_value: f.default_value ?? null,
891
- ...(f.validation && { validation: f.validation }),
892
- ...(f.computed && { computed: f.computed }),
893
- ...(f.computed_deps && { computed_deps: f.computed_deps }),
894
- ...(f.visible_in_states && { visible_in_states: f.visible_in_states }),
895
- ...(f.editable_in_states && { editable_in_states: f.editable_in_states }),
896
- ...(f.visible_to_roles && { visible_to_roles: f.visible_to_roles }),
897
- ...(f.editable_by_roles && { editable_by_roles: f.editable_by_roles }),
898
- ...(f.visible_when && { visible_when: f.visible_when }),
899
- ...(f.editable_when && { editable_when: f.editable_when }),
900
- ...(f.state_home && { state_home: f.state_home }),
901
- }));
902
-
903
- // Convert transitions: add engine-expected extra fields
904
- const transitions = ir.transitions.map((t) => ({
905
- name: t.name,
906
- from: t.from,
907
- to: t.to,
908
- description: t.description || '',
909
- roles: t.roles || [],
910
- auto: t.auto || false,
911
- conditions: t.conditions || [],
912
- actions: (t.actions || []).map(convertAction),
913
- required_fields: t.required_fields || [],
914
- priority: 0,
915
- }));
916
-
917
- // Build state_data from fields
918
- const state_data: Record<string, unknown> = {};
919
- for (const f of fields) {
920
- state_data[f.name] = f.default_value;
921
- }
922
-
923
- // Build workflow-level on_event
924
- const on_event = (ir.on_event || []).map(convertOnEvent);
925
-
926
- // Build views from raw experience (with text-content folding only, no normalization)
927
- let views: Record<string, unknown> | undefined;
928
- if (extracted.experience) {
929
- const viewRoot = foldTextContent(JSON.parse(JSON.stringify(extracted.experience)));
930
-
931
- // Attach dataSources to the engine-compatible view root
932
- const dataSources = extracted.extraMetadata?.dataSources as IRDataSource[] | undefined;
933
- if (dataSources && dataSources.length > 0) {
934
- viewRoot.dataSources = dataSources;
935
- }
936
-
937
- // Attach localDefaults for $local initialization
938
- if (extracted.fields.length > 0) {
939
- const localDefaults: Record<string, unknown> = {};
940
- for (const f of extracted.fields) {
941
- localDefaults[toSnakeCase(f.name)] = f.default_value ?? null;
942
- }
943
- if (!viewRoot.config) viewRoot.config = {};
944
- viewRoot.config.localDefaults = localDefaults;
945
- }
946
-
947
- views = { default: viewRoot };
948
- }
949
-
950
- return {
951
- id: `def-${ir.slug}`,
952
- slug: ir.slug,
953
- name: ir.name,
954
- version: ir.version,
955
- description: ir.description || '',
956
- category: ir.category,
957
- states,
958
- transitions,
959
- fields,
960
- state_data,
961
- roles: [],
962
- child_definitions: [],
963
- tags: ir.tags || [],
964
- metadata: ir.metadata || {},
965
- ...(views && { views }),
966
- ...(on_event.length > 0 && { on_event }),
967
- config: {},
968
- is_immutable: false,
969
- };
970
- }
971
-
972
- // =============================================================================
973
- // Compiler State Conversion
974
- // =============================================================================
975
-
976
- /**
977
- * Converts compiler state to ExtractedWorkflow.
978
- *
979
- * Critical: must transfer ALL extracted data — nothing may be lost.
980
- */
981
- export function compilerStateToWorkflow(state: CompilerState, metadata: {
982
- slug?: string;
983
- name?: string;
984
- version?: string;
985
- description?: string;
986
- category?: string;
987
- [key: string]: unknown;
988
- }): ExtractedWorkflow {
989
- // Extract field watchers and transition effects from metadata
990
- const fieldWatchers = (metadata.fieldWatchers as FieldWatcher[] | undefined) || [];
991
- const transitionEffects = (metadata.transitionEffects as TransitionEffect[] | undefined) || [];
992
-
993
- // Extract grammar islands from metadata
994
- const grammarIslands = (metadata.grammarIslands as IRGrammarIsland[] | undefined) || [];
995
-
996
- // Collect extra metadata — everything that isn't a known key
997
- const knownKeys = new Set(['slug', 'name', 'version', 'description', 'category', 'fieldWatchers', 'transitionEffects', 'grammarIslands', '__modelImports', '__modelImportSlugs', '__slugAutoFallback']);
998
- const extraMetadata: Record<string, unknown> = {};
999
- for (const [key, value] of Object.entries(metadata)) {
1000
- if (!knownKeys.has(key) && value !== undefined) {
1001
- extraMetadata[key] = value;
1002
- }
1003
- }
1004
-
1005
- return {
1006
- slug: metadata.slug || 'workflow',
1007
- name: metadata.name || 'Workflow',
1008
- version: metadata.version || '0.1.0',
1009
- description: metadata.description,
1010
- category: metadata.category || 'workflow',
1011
- fields: state.fields || [],
1012
- states: state.states || new Map(),
1013
- transitions: state.transitions || [],
1014
- events: state.events || [],
1015
- experience: state.experience,
1016
- fieldWatchers: fieldWatchers.length > 0 ? fieldWatchers : undefined,
1017
- transitionEffects: transitionEffects.length > 0 ? transitionEffects : undefined,
1018
- grammarIslands: grammarIslands.length > 0 ? grammarIslands : undefined,
1019
- errors: state.errors,
1020
- warnings: state.warnings,
1021
- extraMetadata: Object.keys(extraMetadata).length > 0 ? extraMetadata : undefined,
1022
- };
1023
- }