@flipova/foundation 1.9.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +64 -1
  3. package/dist/{chunk-3PYMFFVP.mjs → chunk-32VWREEH.mjs} +2289 -7
  4. package/dist/chunk-32VWREEH.mjs.map +1 -0
  5. package/dist/{chunk-5ZDSYOFL.js → chunk-3RJREGCN.js} +2604 -309
  6. package/dist/chunk-3RJREGCN.js.map +1 -0
  7. package/dist/{chunk-MWRMHYW2.js → chunk-D4QJYQOK.js} +17 -17
  8. package/dist/{chunk-MWRMHYW2.js.map → chunk-D4QJYQOK.js.map} +1 -1
  9. package/dist/{chunk-GZPFYWMA.mjs → chunk-IKVONTJC.mjs} +10 -3
  10. package/dist/chunk-IKVONTJC.mjs.map +1 -0
  11. package/dist/{chunk-RRZSROIT.mjs → chunk-RRV2Q4SS.mjs} +3 -3
  12. package/dist/{chunk-RRZSROIT.mjs.map → chunk-RRV2Q4SS.mjs.map} +1 -1
  13. package/dist/chunk-RUZBEFDO.js +669 -0
  14. package/dist/{chunk-T7V6TILB.js.map → chunk-RUZBEFDO.js.map} +1 -1
  15. package/dist/{chunk-45NSZH5Z.js → chunk-UBZMVSIN.js} +10 -2
  16. package/dist/chunk-UBZMVSIN.js.map +1 -0
  17. package/dist/{chunk-SYHGZT2M.mjs → chunk-YTD4AWV2.mjs} +4 -4
  18. package/dist/{chunk-SYHGZT2M.mjs.map → chunk-YTD4AWV2.mjs.map} +1 -1
  19. package/dist/config/index.js +6 -6
  20. package/dist/config/index.mjs +1 -1
  21. package/dist/index.d.mts +1 -2
  22. package/dist/index.d.ts +1 -2
  23. package/dist/index.js +200 -201
  24. package/dist/index.mjs +4 -5
  25. package/dist/layout/index.d.mts +192 -3
  26. package/dist/layout/index.d.ts +192 -3
  27. package/dist/layout/index.js +159 -160
  28. package/dist/layout/index.mjs +1 -2
  29. package/dist/studio-v2/cli/index.js +96 -0
  30. package/dist/theme/index.js +14 -14
  31. package/dist/theme/index.mjs +1 -1
  32. package/dist/tokens/index.js +14 -14
  33. package/dist/tokens/index.mjs +1 -1
  34. package/dist/web/index.js +3639 -363
  35. package/dist/web/index.js.map +1 -1
  36. package/dist/web/index.mjs +3463 -61
  37. package/dist/web/index.mjs.map +1 -1
  38. package/package.json +15 -8
  39. package/studio-v2/apps/web/CHANGELOG.md +7 -0
  40. package/studio-v2/apps/web/LICENSE +21 -0
  41. package/studio-v2/apps/web/README.md +56 -0
  42. package/studio-v2/apps/web/dist/+not-found.html +793 -0
  43. package/studio-v2/apps/web/dist/_expo/.routes.json +3 -0
  44. package/studio-v2/apps/web/dist/_expo/static/css/global-a4717de456877faacb88ee482aa99653.css +1 -0
  45. package/{studio/app/dist/_expo/static/js/web/entry-77f601f6b9353e7b6e3b18cdbe63ac99.js → studio-v2/apps/web/dist/_expo/static/js/web/entry-5d96588cc8f2ee5c00754cef9ac6481d.js} +3707 -17257
  46. package/studio-v2/apps/web/dist/_expo/static/js/web/index-470f33f64d8c4f7b8d8da2632b2959c2.js +4 -0
  47. package/{studio/app/dist/_expo/static/js/web/index-ac88f7a39991e452f0b4323da9aa4367.js → studio-v2/apps/web/dist/_expo/static/js/web/index-f7fcd21ae9d8dacf4c88ea5796614af0.js} +3 -3
  48. package/studio-v2/apps/web/dist/_sitemap.html +793 -0
  49. package/studio-v2/apps/web/dist/assets/___node_modules/@react-navigation/drawer/lib/module/views/assets/toggle-drawer-icon.ae74bb20586a731af545e6b00fe14a09.png +0 -0
  50. package/studio-v2/apps/web/dist/assets/___node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png +0 -0
  51. package/studio-v2/apps/web/dist/assets/___node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png +0 -0
  52. package/studio-v2/apps/web/dist/assets/___node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png +0 -0
  53. package/studio-v2/apps/web/dist/assets/___node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png +0 -0
  54. package/studio-v2/apps/web/dist/assets/___node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png +0 -0
  55. package/studio-v2/apps/web/dist/assets/___node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png +0 -0
  56. package/studio-v2/apps/web/dist/assets/___node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png +0 -0
  57. package/studio-v2/apps/web/dist/assets/___node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png +0 -0
  58. package/studio-v2/apps/web/dist/assets/___node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png +0 -0
  59. package/studio-v2/apps/web/dist/assets/___node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png +0 -0
  60. package/studio-v2/apps/web/dist/assets/___node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png +0 -0
  61. package/studio-v2/apps/web/dist/index.html +793 -0
  62. package/dist/chunk-3PYMFFVP.mjs.map +0 -1
  63. package/dist/chunk-45NSZH5Z.js.map +0 -1
  64. package/dist/chunk-4QTEZKXE.mjs +0 -2287
  65. package/dist/chunk-4QTEZKXE.mjs.map +0 -1
  66. package/dist/chunk-5ZDSYOFL.js.map +0 -1
  67. package/dist/chunk-BJTO5JO5.mjs +0 -10
  68. package/dist/chunk-BJTO5JO5.mjs.map +0 -1
  69. package/dist/chunk-DGUM43GV.js +0 -12
  70. package/dist/chunk-DGUM43GV.js.map +0 -1
  71. package/dist/chunk-ECBM426M.mjs +0 -2647
  72. package/dist/chunk-ECBM426M.mjs.map +0 -1
  73. package/dist/chunk-EIWDEXBO.js +0 -2690
  74. package/dist/chunk-EIWDEXBO.js.map +0 -1
  75. package/dist/chunk-FLEEJX7L.js +0 -2301
  76. package/dist/chunk-FLEEJX7L.js.map +0 -1
  77. package/dist/chunk-GZPFYWMA.mjs.map +0 -1
  78. package/dist/chunk-T7V6TILB.js +0 -669
  79. package/dist/primitives-DVX2q5St.d.mts +0 -195
  80. package/dist/primitives-nj-4at-g.d.ts +0 -195
  81. package/dist/studio/cli/index.d.mts +0 -1
  82. package/dist/studio/cli/index.d.ts +0 -1
  83. package/dist/studio/cli/index.js +0 -42
  84. package/dist/studio/cli/index.js.map +0 -1
  85. package/dist/studio/cli/index.mjs +0 -35
  86. package/dist/studio/cli/index.mjs.map +0 -1
  87. package/dist/studio/index.d.mts +0 -441
  88. package/dist/studio/index.d.ts +0 -441
  89. package/dist/studio/index.js +0 -84
  90. package/dist/studio/index.js.map +0 -1
  91. package/dist/studio/index.mjs +0 -3
  92. package/dist/studio/index.mjs.map +0 -1
  93. package/dist/web/index.d.mts +0 -778
  94. package/dist/web/index.d.ts +0 -778
  95. package/studio/README.md +0 -154
  96. package/studio/app/dist/_expo/static/js/web/index-9587ee2e3c02826ac2da47e86fefe882.js +0 -4
  97. package/studio/app/dist/index.html +0 -37
  98. package/studio/app/dist/metadata.json +0 -1
  99. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/AntDesign.3f78af31cca60105799838a1a7a59fbd.ttf +0 -0
  100. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/Entypo.31b5ffea3daddc69dd01a1f3d6cf63c5.ttf +0 -0
  101. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/EvilIcons.140c53a7643ea949007aa9a282153849.ttf +0 -0
  102. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/Feather.ca4b48e04dc1ce10bfbddb262c8b835f.ttf +0 -0
  103. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/FontAwesome.b06871f281fee6b241d60582ae9369b9.ttf +0 -0
  104. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/FontAwesome5_Brands.3b89dd103490708d19a95adcae52210e.ttf +0 -0
  105. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/FontAwesome5_Regular.1f77739ca9ff2188b539c36f30ffa2be.ttf +0 -0
  106. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/FontAwesome5_Solid.605ed7926cf39a2ad5ec2d1f9d391d3d.ttf +0 -0
  107. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/FontAwesome6_Brands.56c8d80832e37783f12c05db7c8849e2.ttf +0 -0
  108. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/FontAwesome6_Regular.370dd5af19f8364907b6e2c41f45dbbf.ttf +0 -0
  109. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/FontAwesome6_Solid.adec7d6f310bc577f05e8fe06a5daccf.ttf +0 -0
  110. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/Fontisto.b49ae8ab2dbccb02c4d11caaacf09eab.ttf +0 -0
  111. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/Foundation.e20945d7c929279ef7a6f1db184a4470.ttf +0 -0
  112. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/Ionicons.b4eb097d35f44ed943676fd56f6bdc51.ttf +0 -0
  113. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/MaterialCommunityIcons.6e435534bd35da5fef04168860a9b8fa.ttf +0 -0
  114. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/MaterialIcons.4e85bc9ebe07e0340c9c4fc2f6c38908.ttf +0 -0
  115. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/Octicons.871378c6eab492a3e689a9385dc45a12.ttf +0 -0
  116. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/SimpleLineIcons.d2285965fe34b05465047401b8595dd0.ttf +0 -0
  117. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/Zocial.1681f34aaca71b8dfb70756bca331eb2.ttf +0 -0
  118. /package/{studio/app/dist/assets/__node_modules/expo-router/assets/react-navigation/elements → studio-v2/apps/web/dist/assets/___node_modules/@react-navigation/elements/lib/module/assets}/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png +0 -0
  119. /package/{studio/app/dist/assets/__node_modules/expo-router/assets/react-navigation/elements → studio-v2/apps/web/dist/assets/___node_modules/@react-navigation/elements/lib/module/assets}/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png +0 -0
  120. /package/{studio/app/dist/assets/__node_modules/expo-router/assets/react-navigation/elements → studio-v2/apps/web/dist/assets/___node_modules/@react-navigation/elements/lib/module/assets}/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png +0 -0
  121. /package/{studio/app/dist/assets/__node_modules/expo-router/assets/react-navigation/elements → studio-v2/apps/web/dist/assets/___node_modules/@react-navigation/elements/lib/module/assets}/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png +0 -0
  122. /package/{studio/app/dist/assets/__node_modules/expo-router/assets/react-navigation/elements → studio-v2/apps/web/dist/assets/___node_modules/@react-navigation/elements/lib/module/assets}/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png +0 -0
  123. /package/{studio/app/dist/assets/__node_modules/expo-router/assets/react-navigation/elements → studio-v2/apps/web/dist/assets/___node_modules/@react-navigation/elements/lib/module/assets}/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png +0 -0
  124. /package/{studio/app/dist/assets/__node_modules/expo-router/assets/react-navigation/elements → studio-v2/apps/web/dist/assets/___node_modules/@react-navigation/elements/lib/module/assets}/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png +0 -0
  125. /package/{studio/app/dist/assets/__node_modules/expo-router/assets/react-navigation/elements → studio-v2/apps/web/dist/assets/___node_modules/@react-navigation/elements/lib/module/assets}/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png +0 -0
  126. /package/{studio/app/dist/assets/__node_modules/expo-router/assets/react-navigation/elements → studio-v2/apps/web/dist/assets/___node_modules/@react-navigation/elements/lib/module/assets}/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png +0 -0
  127. /package/{studio/app/dist/assets/__node_modules/expo-router/assets/react-navigation/elements → studio-v2/apps/web/dist/assets/___node_modules/@react-navigation/elements/lib/module/assets}/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png +0 -0
  128. /package/{studio/app/dist/assets/__node_modules/expo-router/assets/react-navigation/elements → studio-v2/apps/web/dist/assets/___node_modules/@react-navigation/elements/lib/module/assets}/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png +0 -0
  129. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png +0 -0
  130. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png +0 -0
  131. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png +0 -0
  132. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png +0 -0
  133. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png +0 -0
  134. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png +0 -0
  135. /package/{studio/app/dist/assets/__node_modules → studio-v2/apps/web/dist/assets/___node_modules}/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png +0 -0
@@ -1,2647 +0,0 @@
1
- import { getLayoutMeta, primitiveRegistry, blockRegistry, componentRegistry, layoutRegistry } from './chunk-4QTEZKXE.mjs';
2
- import * as fs2 from 'fs';
3
- import fs2__default from 'fs';
4
- import * as path2 from 'path';
5
- import path2__default from 'path';
6
- import express, { Router } from 'express';
7
- import { WebSocketServer, WebSocket } from 'ws';
8
- import http from 'http';
9
-
10
- // studio/engine/tree/operations.ts
11
- var counter = 0;
12
- function generateId() {
13
- return `node_${Date.now()}_${++counter}`;
14
- }
15
- function createNode(kind, registryId, props = {}, variant) {
16
- return {
17
- id: generateId(),
18
- kind,
19
- registryId,
20
- props,
21
- variant,
22
- children: []
23
- };
24
- }
25
- function findNode(root, nodeId) {
26
- if (root.id === nodeId) return root;
27
- for (const child of root.children) {
28
- const found = findNode(child, nodeId);
29
- if (found) return found;
30
- }
31
- return null;
32
- }
33
- function findParent(root, nodeId) {
34
- for (const child of root.children) {
35
- if (child.id === nodeId) return root;
36
- const found = findParent(child, nodeId);
37
- if (found) return found;
38
- }
39
- return null;
40
- }
41
- function insertChild(root, parentId, node, index) {
42
- if (root.id === parentId) {
43
- const children = [...root.children];
44
- if (index !== void 0) {
45
- children.splice(index, 0, node);
46
- } else {
47
- children.push(node);
48
- }
49
- return { ...root, children };
50
- }
51
- return {
52
- ...root,
53
- children: root.children.map((child) => insertChild(child, parentId, node, index))
54
- };
55
- }
56
- function removeNode(root, nodeId) {
57
- return {
58
- ...root,
59
- children: root.children.filter((child) => child.id !== nodeId).map((child) => removeNode(child, nodeId))
60
- };
61
- }
62
- function updateProps(root, nodeId, props) {
63
- if (root.id === nodeId) {
64
- return { ...root, props: { ...root.props, ...props } };
65
- }
66
- return {
67
- ...root,
68
- children: root.children.map((child) => updateProps(child, nodeId, props))
69
- };
70
- }
71
- function moveNode(root, nodeId, newParentId, index) {
72
- const node = findNode(root, nodeId);
73
- if (!node) return root;
74
- const withoutNode = removeNode(root, nodeId);
75
- return insertChild(withoutNode, newParentId, node, index);
76
- }
77
- function pageNameToRoute(name) {
78
- return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
79
- }
80
- function pageNameToComponent(name) {
81
- return name.replace(/[^a-zA-Z0-9 ]/g, " ").split(/\s+/).filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("") + "Screen";
82
- }
83
- function renamePage(project, pageId, newName) {
84
- const page = project.pages.find((p) => p.id === pageId);
85
- if (!page) throw new Error(`Page not found: ${pageId}`);
86
- const oldRoute = page.route;
87
- const newRoute = pageNameToRoute(newName);
88
- const updatedPages = project.pages.map(
89
- (p) => p.id === pageId ? { ...p, name: newName, route: newRoute } : p
90
- );
91
- const updatedScreens = project.navigation.screens.map(
92
- (s) => s.pageId === pageId ? { ...s, name: newName } : s
93
- );
94
- return {
95
- project: {
96
- ...project,
97
- pages: updatedPages,
98
- navigation: { ...project.navigation, screens: updatedScreens }
99
- },
100
- oldRoute
101
- };
102
- }
103
- function createPage(name, layoutId = "RootLayout") {
104
- return {
105
- id: generateId(),
106
- name,
107
- route: pageNameToRoute(name),
108
- root: createNode("layout", layoutId),
109
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
110
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
111
- };
112
- }
113
- function findRepeatAncestor(root, nodeId, ancestors = []) {
114
- if (root.id === nodeId) {
115
- return ancestors.find((a) => !!a.repeatBinding) || null;
116
- }
117
- for (const child of root.children) {
118
- const found = findRepeatAncestor(child, nodeId, [...ancestors, root]);
119
- if (found !== null) return found;
120
- }
121
- return null;
122
- }
123
- function collectQueryRefs(node) {
124
- const refs = /* @__PURE__ */ new Set();
125
- const addRef = (expr) => {
126
- if (expr?.startsWith("$query.")) refs.add(expr.slice(7).split(".")[0]);
127
- };
128
- const walk = (n) => {
129
- if (n.bindings) Object.values(n.bindings).forEach(addRef);
130
- addRef(n.repeatBinding?.source);
131
- addRef(n.conditionalRender?.expression);
132
- if (n.events) {
133
- for (const actions of Object.values(n.events)) {
134
- for (const a of actions) {
135
- if (a.type === "callApi" && a.payload?.queryName) ;
136
- }
137
- }
138
- }
139
- n.children.forEach(walk);
140
- };
141
- walk(node);
142
- return refs;
143
- }
144
- function collectStateRefs(node) {
145
- const refs = /* @__PURE__ */ new Set();
146
- const addRef = (expr) => {
147
- if (expr?.startsWith("$state.")) refs.add(expr.slice(7).split(".")[0]);
148
- };
149
- const walk = (n) => {
150
- if (n.bindings) Object.values(n.bindings).forEach(addRef);
151
- addRef(n.conditionalRender?.expression);
152
- n.children.forEach(walk);
153
- };
154
- walk(node);
155
- return refs;
156
- }
157
- function extractItemFields(data) {
158
- if (!data) return [];
159
- const sample = Array.isArray(data) ? data[0] : data;
160
- if (!sample || typeof sample !== "object") return [];
161
- return Object.entries(sample).map(([key, val]) => ({
162
- key,
163
- type: typeof val === "object" && val !== null ? Array.isArray(val) ? "array" : "object" : typeof val,
164
- preview: typeof val === "string" ? val.slice(0, 20) : typeof val === "number" ? String(val) : typeof val
165
- }));
166
- }
167
-
168
- // studio/engine/codegen/naming.ts
169
- function nameToSlug(name) {
170
- return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
171
- }
172
- function slugToComponent(slug) {
173
- return slug.split("-").filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("") + "Screen";
174
- }
175
- function deriveScreenNames(pageNameOrRoute, route) {
176
- const fileName = route ? route : nameToSlug(pageNameOrRoute);
177
- const componentName = slugToComponent(fileName);
178
- const hookName = `use${componentName}`;
179
- return {
180
- fileName,
181
- componentName,
182
- hookName,
183
- hookFileName: `${componentName}.hook.ts`,
184
- screenFileName: `${fileName}.tsx`
185
- };
186
- }
187
- function capitalize(s) {
188
- return s.charAt(0).toUpperCase() + s.slice(1);
189
- }
190
- function normalizeQueryName(raw) {
191
- const parts = raw.replace(/[^a-zA-Z0-9]+/g, " ").trim().split(" ").filter(Boolean);
192
- if (parts.length === 0) return "query";
193
- return parts.map((p, i) => i === 0 ? p.charAt(0).toLowerCase() + p.slice(1) : capitalize(p)).join("");
194
- }
195
-
196
- // studio/engine/tree/expressions.ts
197
- function resolveForCodegen(expr, ctx) {
198
- if (!expr) return expr;
199
- if (expr.startsWith("$state.")) return expr.slice(7);
200
- if (expr.startsWith("$global.")) return `globalState.${expr.slice(8)}`;
201
- if (expr.startsWith("$node.")) {
202
- const rest = expr.slice(6);
203
- const dotIdx = rest.indexOf(".");
204
- if (dotIdx > 0) {
205
- const propName = rest.slice(dotIdx + 1);
206
- return propName;
207
- }
208
- return `/* node prop: ${rest} */`;
209
- }
210
- if (expr.startsWith("$query.")) return expr.slice(7);
211
- if (expr.startsWith("$const.")) return `CONSTANTS.${expr.slice(7)}`;
212
- if (expr.startsWith("$env.")) return `process.env.${expr.slice(5)}`;
213
- if (expr.startsWith("$theme.")) return `theme.${expr.slice(7)}`;
214
- if (expr.startsWith("$device.width")) return "Dimensions.get('window').width";
215
- if (expr.startsWith("$device.height")) return "Dimensions.get('window').height";
216
- if (expr.startsWith("$device.platform")) return "Platform.OS";
217
- if (expr.startsWith("$device.isIOS")) return "Platform.OS === 'ios'";
218
- if (expr.startsWith("$device.isAndroid")) return "Platform.OS === 'android'";
219
- if (expr.startsWith("$date.now")) return "Date.now()";
220
- if (expr.startsWith("$date.today")) return "new Date().toISOString().split('T')[0]";
221
- if (expr.startsWith("$date.timestamp")) return "Math.floor(Date.now() / 1000)";
222
- if (expr.startsWith("$nav.currentRoute")) return "/* current route */";
223
- if (expr.startsWith("$nav.params")) return "/* route params */";
224
- if (expr.startsWith("$nav.goBack")) return "router.back()";
225
- if (expr.startsWith("$")) return expr.slice(1);
226
- if (expr.startsWith("item.")) return expr;
227
- if (ctx?.itemVar && !expr.includes("(") && !expr.includes(" ")) {
228
- return `${ctx.itemVar}.${expr}`;
229
- }
230
- return expr;
231
- }
232
- function resolveForResponse(expr, ctx) {
233
- const errVar = ctx?.errorVar || "_err";
234
- if (expr === "$response") return "_res";
235
- if (expr.startsWith("$response.")) return "_res." + expr.slice(10);
236
- if (expr === "$error" || expr === "$response.error") return errVar;
237
- if (expr.startsWith("$error.")) return errVar + "." + expr.slice(7);
238
- return resolveForCodegen(expr);
239
- }
240
-
241
- // studio/app/src/renderer/slotConfig.ts
242
- function deriveSlotConfig(slots) {
243
- if (!slots || slots.length === 0) {
244
- return { mode: "children" };
245
- }
246
- const hasExplicitKind = slots.some((s) => s.kind !== void 0);
247
- if (hasExplicitKind) {
248
- const primaryItems = slots.find((s) => s.kind === "items");
249
- const namedArraySlots = slots.filter((s) => s.kind === "named-array");
250
- const namedSlots2 = slots.filter((s) => s.kind === "named");
251
- const childrenSlot = slots.find((s) => s.kind === "children");
252
- if (primaryItems) {
253
- return {
254
- mode: "items",
255
- itemsProp: primaryItems.name,
256
- secondaryArraySlots: namedArraySlots.map((s) => ({ prop: s.name, label: s.label }))
257
- };
258
- }
259
- if (childrenSlot && namedSlots2.length === 0) {
260
- return { mode: "children" };
261
- }
262
- return {
263
- mode: "named",
264
- slots: slots.filter((s) => s.kind === "named" || s.kind === "named-array").map((s, i) => ({ prop: s.name, label: s.label, fallbackIndex: i }))
265
- };
266
- }
267
- if (slots.length === 1 && slots[0].name === "children" && !slots[0].array) {
268
- return { mode: "children" };
269
- }
270
- if (slots.length === 1 && slots[0].array) {
271
- return { mode: "items", itemsProp: slots[0].name };
272
- }
273
- const allArray = slots.every((s) => s.array);
274
- if (allArray && slots.length > 1) {
275
- const [primary, ...secondary] = slots;
276
- return {
277
- mode: "items",
278
- itemsProp: primary.name,
279
- secondaryArraySlots: secondary.map((s) => ({ prop: s.name, label: s.label }))
280
- };
281
- }
282
- const namedSlots = slots.filter((s) => s.name !== "children");
283
- if (namedSlots.length > 0) {
284
- return {
285
- mode: "named",
286
- slots: slots.map((s, i) => ({ prop: s.name, label: s.label, fallbackIndex: i }))
287
- };
288
- }
289
- return { mode: "children" };
290
- }
291
-
292
- // studio/engine/codegen/generator.ts
293
- var COMPONENT_SOURCE = "@flipova/foundation";
294
- function addImport(c, source, name) {
295
- if (!c.imports.has(source)) c.imports.set(source, /* @__PURE__ */ new Set());
296
- c.imports.get(source).add(name);
297
- }
298
- function collectImports(node, c) {
299
- if (node.kind !== "text" && node.kind !== "slot") {
300
- addImport(c, COMPONENT_SOURCE, node.registryId);
301
- }
302
- for (const v of Object.values(node.props)) {
303
- if (typeof v === "string" && v.startsWith("$")) {
304
- const [group] = v.slice(1).split(".");
305
- const tokenMap = {
306
- spacing: "spacing",
307
- radii: "radii",
308
- shadow: "shadows",
309
- fontSize: "fontSizes",
310
- fontWeight: "fontWeights",
311
- lineHeight: "lineHeights",
312
- opacity: "opacity",
313
- duration: "durations",
314
- zIndex: "zIndices",
315
- color: "colors"
316
- };
317
- if (group === "theme") addImport(c, COMPONENT_SOURCE, "useTheme");
318
- else if (tokenMap[group]) addImport(c, "@flipova/foundation/tokens", tokenMap[group]);
319
- }
320
- }
321
- if (node.events) {
322
- for (const actions of Object.values(node.events)) {
323
- for (const a of actions) {
324
- collectActionImport(a, c);
325
- }
326
- }
327
- }
328
- if (node.animation?.preset !== "none") {
329
- addImport(c, "react-native", "Animated");
330
- addImport(c, "react", "useEffect");
331
- addImport(c, "react", "useRef");
332
- }
333
- for (const child of node.children) collectImports(child, c);
334
- }
335
- function collectActionImport(a, c) {
336
- const p = a.payload;
337
- switch (a.type) {
338
- case "navigate":
339
- addImport(c, "expo-router", "useRouter");
340
- break;
341
- case "alert":
342
- addImport(c, "react-native", "Alert");
343
- break;
344
- case "toast":
345
- addImport(c, "react-native", "Alert");
346
- break;
347
- case "share":
348
- addImport(c, "react-native", "Share");
349
- break;
350
- case "haptics":
351
- addImport(c, "expo-haptics", "* as Haptics");
352
- break;
353
- case "openURL":
354
- addImport(c, "react-native", "Linking");
355
- break;
356
- case "clipboard":
357
- addImport(c, "expo-clipboard", "* as Clipboard");
358
- break;
359
- case "sendSMS":
360
- addImport(c, "expo-sms", "* as SMS");
361
- break;
362
- case "biometrics":
363
- addImport(c, "expo-local-authentication", "* as LocalAuthentication");
364
- break;
365
- case "getLocation":
366
- addImport(c, "expo-location", "* as Location");
367
- break;
368
- // Recursive: collect imports from nested actions
369
- case "conditional":
370
- if (Array.isArray(p.then)) p.then.forEach((a2) => collectActionImport(a2, c));
371
- if (Array.isArray(p.else)) p.else.forEach((a2) => collectActionImport(a2, c));
372
- break;
373
- case "loop":
374
- if (Array.isArray(p.body)) p.body.forEach((a2) => collectActionImport(a2, c));
375
- break;
376
- case "parallel":
377
- if (Array.isArray(p.lanes)) p.lanes.forEach((lane) => lane.forEach((a2) => collectActionImport(a2, c)));
378
- break;
379
- }
380
- }
381
- function resolveResponseExpr(expr, errorVar) {
382
- return resolveForResponse(expr, { errorVar });
383
- }
384
- function renderActionWithResponse(action, errorVar, stateKeys) {
385
- const san = (s) => s.replace(/[^a-zA-Z0-9_]/g, "");
386
- const p = action.payload;
387
- const resResp = (v) => resolveResponseExpr(v, errorVar);
388
- const resolveVal = (val) => {
389
- if (!val) return JSON.stringify(val);
390
- if (val.startsWith("$")) return resResp(val);
391
- return JSON.stringify(val);
392
- };
393
- switch (action.type) {
394
- case "setState": {
395
- const key = san(String(p.key || "value"));
396
- if (!key) return "";
397
- const val = String(p.value ?? "");
398
- const resolved = val.startsWith("$node.") ? resolveNodeForCodegen(val, stateKeys) : resolveVal(val);
399
- return `set${capitalize(key)}(${resolved});`;
400
- }
401
- case "navigate": {
402
- const screen = String(p.screen || "");
403
- return screen.startsWith("$") ? `router.push(${resResp(screen)});` : `router.push("/${screen}");`;
404
- }
405
- case "alert":
406
- return `Alert.alert(${resolveVal(String(p.title || ""))}, ${resolveVal(String(p.message || ""))});`;
407
- case "consoleLog": {
408
- const msg = String(p.message || "log");
409
- return `console.log(${resolveVal(msg)});`;
410
- }
411
- default:
412
- return renderAction(action, stateKeys);
413
- }
414
- }
415
- function renderAction(action, stateKeys, itemVar) {
416
- const san = (s) => s.replace(/[^a-zA-Z0-9_]/g, "");
417
- const p = action.payload;
418
- const res = (expr) => resolveExpression(expr, itemVar, stateKeys);
419
- const resolveVal = (val) => {
420
- if (!val) return JSON.stringify(val);
421
- if (val.startsWith("$")) return res(val);
422
- if (/^(true|false|null|undefined|\d)/.test(val)) return val;
423
- if (itemVar && /^[a-zA-Z_][a-zA-Z0-9_.]*$/.test(val)) return `${itemVar}.${val}`;
424
- return JSON.stringify(val);
425
- };
426
- switch (action.type) {
427
- case "navigate": {
428
- const screen = String(action.payload.screen || "");
429
- return screen.startsWith("$") ? `router.push(${res(screen)});` : `router.push("/${screen}");`;
430
- }
431
- case "setState": {
432
- const key = san(String(action.payload.key || "value"));
433
- if (!key) return "";
434
- const val = String(action.payload.value ?? "");
435
- const resolved = val.startsWith("$node.") ? resolveNodeForCodegen(val, stateKeys) : resolveVal(val);
436
- return `set${capitalize(key)}(${resolved});`;
437
- }
438
- case "alert":
439
- return `Alert.alert(${resolveVal(String(action.payload.title || ""))}, ${resolveVal(String(action.payload.message || ""))});`;
440
- case "toast": {
441
- const msg = resolveVal(String(p.message || ""));
442
- const variant = String(p.variant || "info");
443
- return `Alert.alert(${JSON.stringify(capitalize(variant))}, ${msg});`;
444
- }
445
- case "openModal": {
446
- const name = san(String(action.payload.name || "dialog"));
447
- return `setShow${capitalize(name)}(true);`;
448
- }
449
- case "closeModal": {
450
- const name = san(String(action.payload.name || "dialog"));
451
- return `setShow${capitalize(name)}(false);`;
452
- }
453
- case "callApi": {
454
- const p2 = action.payload;
455
- const qName = normalizeQueryName(String(p2.queryName || "fetchData").replace(/[^a-zA-Z0-9_]/g, ""));
456
- const refetchFn = `refetch${capitalize(qName)}`;
457
- const bodyEntries = p2.body ? Object.entries(p2.body) : [];
458
- const hasBody = bodyEntries.length > 0;
459
- const storeAs = p2.storeResponseAs ? String(p2.storeResponseAs).replace(/[^a-zA-Z0-9_]/g, "") : null;
460
- const hasOnSuccess = Array.isArray(p2.onSuccess) && p2.onSuccess.length > 0;
461
- const hasOnError = Array.isArray(p2.onError) && p2.onError.length > 0;
462
- if (!hasBody && !storeAs && !hasOnSuccess && !hasOnError) {
463
- return `await ${refetchFn}();`;
464
- }
465
- const bodyArg = hasBody ? `{ ${bodyEntries.map(([k, v]) => {
466
- const expr = String(v);
467
- return expr.startsWith("$node.") ? `${k}: ${resolveNodeForCodegen(expr, stateKeys)}` : `${k}: ${res(expr)}`;
468
- }).join(", ")} }` : void 0;
469
- const lines = [];
470
- lines.push(`try {`);
471
- lines.push(` const _res = await ${refetchFn}(${bodyArg ? bodyArg : ""});`);
472
- if (storeAs) {
473
- lines.push(` set${capitalize(storeAs)}(_res);`);
474
- }
475
- if (hasOnSuccess) {
476
- for (const a of p2.onSuccess) {
477
- const rendered = renderActionWithResponse(a, void 0, stateKeys);
478
- if (rendered) lines.push(` ${rendered}`);
479
- }
480
- }
481
- lines.push(`} catch (_err: any) {`);
482
- if (hasOnError) {
483
- for (const a of p2.onError) {
484
- const rendered = renderActionWithResponse(a, "_err", stateKeys);
485
- if (rendered) lines.push(` ${rendered}`);
486
- }
487
- } else {
488
- lines.push(` console.error("${qName} failed:", _err);`);
489
- }
490
- lines.push(`}`);
491
- return lines.join("\n ");
492
- }
493
- case "consoleLog": {
494
- const msg = String(action.payload.message || "log");
495
- return `console.log(${resolveVal(msg)});`;
496
- }
497
- case "playSound":
498
- return `/* play sound: ${action.payload.uri || ""} */`;
499
- case "haptics":
500
- return `Haptics.impactAsync(Haptics.ImpactFeedbackStyle.${action.payload.style || "Medium"});`;
501
- case "share":
502
- return `Share.share({ message: ${JSON.stringify(action.payload.message || "")} });`;
503
- case "sendSMS":
504
- return `SMS.sendSMSAsync([${JSON.stringify(action.payload.number || "")}], ${JSON.stringify(action.payload.message || "")});`;
505
- case "biometrics":
506
- return `LocalAuthentication.authenticateAsync();`;
507
- case "getLocation":
508
- return `Location.getCurrentPositionAsync({});`;
509
- case "clipboard":
510
- return `Clipboard.setStringAsync(${JSON.stringify(action.payload.text || "")});`;
511
- case "openURL": {
512
- const url = String(action.payload.url || "");
513
- return `if (isSafeUrl(${JSON.stringify(url)})) Linking.openURL(${JSON.stringify(url)});`;
514
- }
515
- case "callCustomFn": {
516
- const p2 = action.payload;
517
- const fnId = String(p2.fnId || "").replace(/[^a-zA-Z0-9_]/g, "");
518
- const hookName = `use${capitalize(fnId)}`;
519
- const params = p2.params || {};
520
- const paramEntries = Object.entries(params);
521
- const hasParams = paramEntries.length > 0;
522
- const storeAs = p2.storeResultAs ? String(p2.storeResultAs).replace(/[^a-zA-Z0-9_]/g, "") : null;
523
- const lines = [];
524
- lines.push(`const _${fnId}Result = await ${hookName}().execute(${hasParams ? paramEntries.map(([k, v]) => res(String(v))).join(", ") : ""});`);
525
- if (storeAs) {
526
- lines.push(`set${capitalize(storeAs)}(_${fnId}Result);`);
527
- }
528
- return lines.join("\n ");
529
- }
530
- case "custom":
531
- return String(p.code || "");
532
- case "setGlobalState": {
533
- const key = (p.key || "").replace(/[^a-zA-Z0-9_]/g, "");
534
- if (!key) return "";
535
- return `setGlobal${capitalize(key)}(${resolveVal(String(p.value ?? ""))});`;
536
- }
537
- case "resetState": {
538
- const key = (p.key || "").replace(/[^a-zA-Z0-9_]/g, "");
539
- if (!key) return "";
540
- const def = p.defaultValue;
541
- return `set${capitalize(key)}(${def !== void 0 ? JSON.stringify(def) : "null"});`;
542
- }
543
- case "mergeState": {
544
- const key = (p.key || "").replace(/[^a-zA-Z0-9_]/g, "");
545
- if (!key) return "";
546
- const val = String(p.value ?? "{}");
547
- const resolved = val.startsWith("$") ? res(val) : itemVar && /^[a-zA-Z_][a-zA-Z0-9_.]*$/.test(val) ? `${itemVar}.${val}` : val;
548
- return `set${capitalize(key)}(prev => ({ ...prev, ...${resolved} }));`;
549
- }
550
- case "toggleState": {
551
- const key = (p.key || "").replace(/[^a-zA-Z0-9_]/g, "");
552
- if (!key) return "";
553
- return `set${capitalize(key)}(prev => !prev);`;
554
- }
555
- case "incrementState": {
556
- const key = (p.key || "").replace(/[^a-zA-Z0-9_]/g, "");
557
- if (!key) return "";
558
- const by = Number(p.by ?? 1);
559
- const min = p.min !== void 0 ? Number(p.min) : null;
560
- const max = p.max !== void 0 ? Number(p.max) : null;
561
- let expr = `prev + ${by}`;
562
- if (min !== null && max !== null) expr = `Math.min(Math.max(${expr}, ${min}), ${max})`;
563
- else if (min !== null) expr = `Math.max(${expr}, ${min})`;
564
- else if (max !== null) expr = `Math.min(${expr}, ${max})`;
565
- return `set${capitalize(key)}(prev => ${expr});`;
566
- }
567
- case "delay": {
568
- const ms = Number(p.ms ?? 500);
569
- return `await new Promise(r => setTimeout(r, ${ms}));`;
570
- }
571
- case "conditional": {
572
- const cond = p.condition ? res(String(p.condition)) : "false";
573
- const thenActions = Array.isArray(p.then) ? p.then : [];
574
- const elseActions = Array.isArray(p.else) ? p.else : [];
575
- const thenCode = thenActions.map((a) => renderAction(a, stateKeys, itemVar)).filter(Boolean).map((l) => ` ${l}`).join("\n");
576
- const elseCode = elseActions.map((a) => renderAction(a, stateKeys, itemVar)).filter(Boolean).map((l) => ` ${l}`).join("\n");
577
- const lines = [`if (${cond}) {`, thenCode || " // no actions"];
578
- if (elseCode) {
579
- lines.push("} else {");
580
- lines.push(elseCode);
581
- }
582
- lines.push("}");
583
- return lines.join("\n");
584
- }
585
- case "transform": {
586
- if (!p.storeAs || !p.source) return "";
587
- const key = String(p.storeAs).replace(/[^a-zA-Z0-9_]/g, "");
588
- const src = res(String(p.source));
589
- const steps = Array.isArray(p.steps) ? p.steps : [];
590
- let expr = src;
591
- for (const step of steps) {
592
- const arg = step.arg ? res(String(step.arg)) : void 0;
593
- const arg2 = step.arg2 ? res(String(step.arg2)) : void 0;
594
- const field = step.field ? JSON.stringify(step.field) : void 0;
595
- switch (step.op) {
596
- case "filter":
597
- expr = `(${expr}).filter(item => ${arg || "true"})`;
598
- break;
599
- case "map":
600
- expr = `(${expr}).map(item => ${arg || "item"})`;
601
- break;
602
- case "sort":
603
- expr = field ? `[...(${expr})].sort((a,b) => a[${field}] > b[${field}] ? 1 : -1)` : `[...(${expr})].sort()`;
604
- break;
605
- case "reverse":
606
- expr = `[...(${expr})].reverse()`;
607
- break;
608
- case "slice":
609
- expr = `(${expr}).slice(${arg || 0}${arg2 ? `, ${arg2}` : ""})`;
610
- break;
611
- case "flatten":
612
- expr = `(${expr}).flat()`;
613
- break;
614
- case "unique":
615
- expr = `[...new Set(${expr})]`;
616
- break;
617
- case "count":
618
- expr = `(${expr}).length`;
619
- break;
620
- case "first":
621
- expr = `(${expr})[0]`;
622
- break;
623
- case "last":
624
- expr = `(${expr}).at(-1)`;
625
- break;
626
- case "join":
627
- expr = `(${expr}).join(${arg || '","'})`;
628
- break;
629
- case "sum":
630
- expr = field ? `(${expr}).reduce((s,i) => s + Number(i[${field}]), 0)` : `(${expr}).reduce((s,i) => s + Number(i), 0)`;
631
- break;
632
- case "uppercase":
633
- expr = `String(${expr}).toUpperCase()`;
634
- break;
635
- case "lowercase":
636
- expr = `String(${expr}).toLowerCase()`;
637
- break;
638
- case "trim":
639
- expr = `String(${expr}).trim()`;
640
- break;
641
- case "split":
642
- expr = `String(${expr}).split(${arg || '","'})`;
643
- break;
644
- case "replace":
645
- expr = `String(${expr}).replace(new RegExp(${arg || '""'}, 'g'), ${arg2 || '""'})`;
646
- break;
647
- case "add":
648
- expr = `Number(${expr}) + Number(${arg || 0})`;
649
- break;
650
- case "subtract":
651
- expr = `Number(${expr}) - Number(${arg || 0})`;
652
- break;
653
- case "multiply":
654
- expr = `Number(${expr}) * Number(${arg || 1})`;
655
- break;
656
- case "divide":
657
- expr = `Number(${arg || 1}) !== 0 ? Number(${expr}) / Number(${arg || 1}) : 0`;
658
- break;
659
- case "abs":
660
- expr = `Math.abs(Number(${expr}))`;
661
- break;
662
- case "floor":
663
- expr = `Math.floor(Number(${expr}))`;
664
- break;
665
- case "ceil":
666
- expr = `Math.ceil(Number(${expr}))`;
667
- break;
668
- case "round":
669
- expr = `Math.round(Number(${expr}))`;
670
- break;
671
- case "not":
672
- expr = `!(${expr})`;
673
- break;
674
- case "stringify":
675
- expr = `JSON.stringify(${expr})`;
676
- break;
677
- case "parse":
678
- expr = `JSON.parse(String(${expr}))`;
679
- break;
680
- case "get":
681
- expr = field ? `(${expr})?.[${field}]` : expr;
682
- break;
683
- case "set":
684
- expr = field && arg ? `{ ...(${expr}), [${field}]: ${arg} }` : expr;
685
- break;
686
- case "keys":
687
- expr = `Object.keys(${expr})`;
688
- break;
689
- case "values":
690
- expr = `Object.values(${expr})`;
691
- break;
692
- }
693
- }
694
- return `set${capitalize(key)}(${expr});`;
695
- }
696
- case "compute": {
697
- if (!p.storeAs || !p.expression) return "";
698
- const key = String(p.storeAs).replace(/[^a-zA-Z0-9_]/g, "");
699
- const expr = String(p.expression).replace(/\$state\.([a-zA-Z0-9_]+)/g, "$1").replace(/\$global\.([a-zA-Z0-9_]+)/g, "global_$1");
700
- return `set${capitalize(key)}(${expr});`;
701
- }
702
- case "loop": {
703
- if (!p.source) return "";
704
- const src = res(String(p.source));
705
- const loopItemVar = String(p.itemVar || "item").replace(/[^a-zA-Z0-9_]/g, "");
706
- const body = Array.isArray(p.body) ? p.body : [];
707
- const bodyCode = body.map((a) => renderAction(a, stateKeys, loopItemVar)).filter(Boolean).map((l) => ` ${l}`).join("\n");
708
- return `for (const ${loopItemVar} of (${src} || [])) {
709
- ${bodyCode || " // no actions"}
710
- }`;
711
- }
712
- case "parallel": {
713
- const lanes = Array.isArray(p.lanes) ? p.lanes : [];
714
- if (!lanes.length) return "";
715
- const laneCode = lanes.map((lane) => {
716
- const code = lane.map((a) => renderAction(a, stateKeys, itemVar)).filter(Boolean).join("; ");
717
- const needsAsync = lane.some(isAsyncAction);
718
- const asyncKw = needsAsync ? "async " : "";
719
- return `Promise.resolve().then(${asyncKw}() => { ${code} })`;
720
- });
721
- const join2 = p.join;
722
- const joinMode = join2?.mode || "all";
723
- const raceOrAll = joinMode === "all" ? `Promise.all` : `Promise.race`;
724
- const onCompleteCode = (join2?.onComplete || []).map((a) => renderAction(a, stateKeys, itemVar)).filter(Boolean).join("; ");
725
- const onTimeoutCode = (join2?.onTimeout || []).map((a) => renderAction(a, stateKeys, itemVar)).filter(Boolean).join("; ");
726
- const lines = [];
727
- if (join2?.timeoutMs !== void 0) {
728
- lines.push(`const _timeout = new Promise<void>((_, rej) => setTimeout(() => rej(new Error('timeout')), ${join2.timeoutMs}));`);
729
- lines.push(`try {`);
730
- lines.push(` await Promise.race([${raceOrAll}([${laneCode.join(", ")}]), _timeout]);`);
731
- if (onCompleteCode) lines.push(` ${onCompleteCode}`);
732
- lines.push(`} catch (_e: any) {`);
733
- lines.push(` if (_e?.message === 'timeout') { ${onTimeoutCode || "/* timeout */"} }`);
734
- lines.push(`}`);
735
- } else {
736
- lines.push(`await ${raceOrAll}([${laneCode.join(", ")}]);`);
737
- if (onCompleteCode) lines.push(onCompleteCode);
738
- }
739
- return lines.join("\n ");
740
- }
741
- default:
742
- return "";
743
- }
744
- }
745
- function resolveNodeForCodegen(expr, stateKeys) {
746
- if (!expr.startsWith("$node.")) return expr;
747
- const parts = expr.slice(6).split(".");
748
- if (parts.length < 2) return `/* $node non r\xE9solu: ${expr} */`;
749
- const propName = parts[1];
750
- if (stateKeys && stateKeys.has(propName)) {
751
- return propName;
752
- }
753
- return `/* $node non r\xE9solu: ${expr} */`;
754
- }
755
- function resolveExpression(expr, itemVar, stateKeys) {
756
- if (expr.startsWith("$node.")) {
757
- return resolveNodeForCodegen(expr, stateKeys);
758
- }
759
- return resolveForCodegen(expr, { itemVar });
760
- }
761
- function hasActionType(node, type) {
762
- if (node.events) {
763
- for (const actions of Object.values(node.events)) {
764
- for (const a of actions) {
765
- if (a.type === type) return true;
766
- if (a.type === "parallel") {
767
- const lanes = Array.isArray(a.payload.lanes) ? a.payload.lanes : [];
768
- if (lanes.some((lane) => lane.some((la) => la.type === type))) return true;
769
- }
770
- }
771
- }
772
- }
773
- return node.children.some((c) => hasActionType(c, type));
774
- }
775
- function collectHookRNImports(node) {
776
- const rn = /* @__PURE__ */ new Set();
777
- const walk = (n) => {
778
- if (n.events) {
779
- for (const actions of Object.values(n.events)) {
780
- for (const a of actions) {
781
- collectActionRNImport(a, rn);
782
- }
783
- }
784
- }
785
- for (const c of n.children) walk(c);
786
- };
787
- walk(node);
788
- return rn;
789
- }
790
- function collectActionRNImport(a, rn) {
791
- const p = a.payload;
792
- switch (a.type) {
793
- case "alert":
794
- case "toast":
795
- rn.add("Alert");
796
- break;
797
- case "share":
798
- rn.add("Share");
799
- break;
800
- case "openURL":
801
- rn.add("Linking");
802
- break;
803
- case "conditional":
804
- if (Array.isArray(p.then)) p.then.forEach((a2) => collectActionRNImport(a2, rn));
805
- if (Array.isArray(p.else)) p.else.forEach((a2) => collectActionRNImport(a2, rn));
806
- break;
807
- case "loop":
808
- if (Array.isArray(p.body)) p.body.forEach((a2) => collectActionRNImport(a2, rn));
809
- break;
810
- case "parallel":
811
- if (Array.isArray(p.lanes)) p.lanes.forEach((lane) => lane.forEach((a2) => collectActionRNImport(a2, rn)));
812
- if (p.join?.onComplete) p.join.onComplete.forEach((a2) => collectActionRNImport(a2, rn));
813
- if (p.join?.onTimeout) p.join.onTimeout.forEach((a2) => collectActionRNImport(a2, rn));
814
- break;
815
- }
816
- }
817
- function hasNavigateAction(node) {
818
- return hasActionType(node, "navigate");
819
- }
820
- function collectApiCalls(node, out, queries) {
821
- if (node.events) {
822
- for (const actions of Object.values(node.events)) {
823
- for (const a of actions) {
824
- if (a.type === "callApi" && a.payload.queryName) {
825
- const raw = String(a.payload.queryName);
826
- const query = queries?.find((q) => q.id === raw || q.name === raw);
827
- const name = normalizeQueryName(query ? query.name : raw);
828
- if (name && !out.has(name)) out.set(name, { autoFetch: false });
829
- }
830
- }
831
- }
832
- }
833
- if (node.repeatBinding?.source?.startsWith("$query.")) {
834
- const varName = node.repeatBinding.source.slice(7);
835
- const baseName = varName.endsWith("Data") ? varName.slice(0, -4) : varName;
836
- const query = queries?.find((q) => normalizeQueryName(q.name) === baseName || q.name === baseName);
837
- const name = query ? normalizeQueryName(query.name) : baseName;
838
- if (name) out.set(name, { autoFetch: true });
839
- }
840
- if (node.bindings) {
841
- for (const expr of Object.values(node.bindings)) {
842
- if (expr?.startsWith("$query.")) {
843
- const varName = expr.slice(7).split(".")[0];
844
- const baseName = varName.endsWith("Data") ? varName.slice(0, -4) : varName;
845
- const query = queries?.find((q) => normalizeQueryName(q.name) === baseName);
846
- const name = query ? normalizeQueryName(query.name) : baseName;
847
- if (name && !out.has(name)) out.set(name, { autoFetch: false });
848
- }
849
- }
850
- }
851
- if (node.bindings) {
852
- for (const expr of Object.values(node.bindings)) {
853
- if (expr?.startsWith("$state.")) {
854
- const alias = expr.slice(7).split(".")[0];
855
- const query = queries?.find((q) => q.alias === alias);
856
- if (query) {
857
- const name = normalizeQueryName(query.name);
858
- if (name && !out.has(name)) out.set(name, { autoFetch: query.autoFetch ?? false });
859
- }
860
- }
861
- }
862
- }
863
- if (node.repeatBinding?.source?.startsWith("$state.")) {
864
- const alias = node.repeatBinding.source.slice(7).split(".")[0];
865
- const query = queries?.find((q) => q.alias === alias);
866
- if (query) {
867
- const name = normalizeQueryName(query.name);
868
- if (name) out.set(name, { autoFetch: true });
869
- }
870
- }
871
- if (node.conditionalRender?.expression?.startsWith("$query.")) {
872
- const varName = node.conditionalRender.expression.slice(7).split(".")[0];
873
- const baseName = varName.endsWith("Data") ? varName.slice(0, -4) : varName;
874
- if (baseName && !out.has(baseName)) out.set(baseName, { autoFetch: false });
875
- }
876
- for (const c of node.children) collectApiCalls(c, out, queries);
877
- }
878
- function collectStyles(node, map) {
879
- const styles = node.styles;
880
- if (styles) {
881
- const filtered = Object.fromEntries(Object.entries(styles).filter(([, v]) => v != null));
882
- if (Object.keys(filtered).length > 0) map.set(node.id, filtered);
883
- }
884
- for (const c of node.children) collectStyles(c, map);
885
- }
886
- function collectStateKeys(node, pageState, out, queries) {
887
- for (const ps of pageState) {
888
- out.set(ps.name, { type: ps.type, default: stateDefaultLiteral(ps) });
889
- }
890
- if (queries) {
891
- for (const q of queries) {
892
- if (q.alias && !out.has(q.alias)) {
893
- const isArrayResponse = q.method === "GET";
894
- out.set(q.alias, {
895
- type: isArrayResponse ? "any[]" : "any",
896
- default: isArrayResponse ? "[]" : "null"
897
- });
898
- }
899
- }
900
- }
901
- const walk = (n) => {
902
- if (n.events) {
903
- for (const actions of Object.values(n.events)) {
904
- for (const a of actions) {
905
- const p = a.payload;
906
- if (a.type === "setState" && p.key) {
907
- const key = String(p.key).replace(/[^a-zA-Z0-9_]/g, "");
908
- if (key && !out.has(key)) out.set(key, { type: "any", default: "null" });
909
- }
910
- if ((a.type === "openModal" || a.type === "closeModal") && p.name) {
911
- const name = String(p.name).replace(/[^a-zA-Z0-9_]/g, "");
912
- if (name) {
913
- const showKey = `show${capitalize(name)}`;
914
- if (!out.has(showKey)) out.set(showKey, { type: "boolean", default: "false" });
915
- }
916
- }
917
- if (a.type === "callApi" && p.storeResponseAs) {
918
- const key = String(p.storeResponseAs).replace(/[^a-zA-Z0-9_]/g, "");
919
- if (key && !out.has(key)) out.set(key, { type: "any", default: "null" });
920
- }
921
- if ((a.type === "transform" || a.type === "compute") && p.storeAs) {
922
- const key = String(p.storeAs).replace(/[^a-zA-Z0-9_]/g, "");
923
- if (key && !out.has(key)) out.set(key, { type: "any", default: "null" });
924
- }
925
- if (["incrementState", "toggleState", "mergeState", "resetState"].includes(a.type) && p.key) {
926
- const key = String(p.key).replace(/[^a-zA-Z0-9_]/g, "");
927
- if (key && !out.has(key)) out.set(key, { type: "any", default: "null" });
928
- }
929
- if (a.type === "parallel") {
930
- const lanes = Array.isArray(p.lanes) ? p.lanes : [];
931
- const join2 = p.join;
932
- const walkActions = (acts) => acts.forEach((la) => {
933
- const lp = la.payload;
934
- if (la.type === "setState" && lp.key) {
935
- const k = String(lp.key).replace(/[^a-zA-Z0-9_]/g, "");
936
- if (k && !out.has(k)) out.set(k, { type: "any", default: "null" });
937
- }
938
- });
939
- lanes.forEach((lane) => walkActions(lane));
940
- if (join2?.onComplete) walkActions(join2.onComplete);
941
- if (join2?.onTimeout) walkActions(join2.onTimeout);
942
- }
943
- if (a.type === "conditional") {
944
- const walkBranch = (acts) => acts.forEach((ba) => {
945
- const bp = ba.payload;
946
- if (ba.type === "setState" && bp.key) {
947
- const k = String(bp.key).replace(/[^a-zA-Z0-9_]/g, "");
948
- if (k && !out.has(k)) out.set(k, { type: "any", default: "null" });
949
- }
950
- });
951
- if (Array.isArray(p.then)) walkBranch(p.then);
952
- if (Array.isArray(p.else)) walkBranch(p.else);
953
- }
954
- }
955
- }
956
- }
957
- for (const c of n.children) walk(c);
958
- };
959
- walk(node);
960
- }
961
- function stateDefaultLiteral(ps) {
962
- if (ps.default != null) return JSON.stringify(ps.default);
963
- switch (ps.type) {
964
- case "string":
965
- return '""';
966
- case "number":
967
- return "0";
968
- case "boolean":
969
- return "false";
970
- case "object":
971
- return "{}";
972
- case "array":
973
- return "[]";
974
- default:
975
- return "null";
976
- }
977
- }
978
- function getHandlerName(node, eventName) {
979
- const comp = node.registryId.replace(/[^a-zA-Z0-9]/g, "");
980
- const ev = eventName.replace(/^on/, "");
981
- return `handle${comp}${capitalize(ev)}`;
982
- }
983
- function isAsyncAction(a) {
984
- const p = a.payload;
985
- const type = a.type;
986
- if (["callApi", "callCustomFn", "delay", "loop", "parallel"].includes(type)) return true;
987
- if (type === "conditional") {
988
- const thenAsync = Array.isArray(p.then) && p.then.some(isAsyncAction);
989
- const elseAsync = Array.isArray(p.else) && p.else.some(isAsyncAction);
990
- return thenAsync || elseAsync;
991
- }
992
- return false;
993
- }
994
- function collectHandlers(node, out, deps, stateKeys, itemVar) {
995
- if (node.events) {
996
- for (const [ev, actions] of Object.entries(node.events)) {
997
- if (actions.length > 0) {
998
- const name = getHandlerName(node, ev);
999
- const body = actions.map((a) => ` ${renderAction(a, stateKeys, itemVar)}`).filter(Boolean);
1000
- const needsAsync = actions.some(isAsyncAction);
1001
- if (needsAsync && body.length > 0 && !body[0].includes("__async__")) {
1002
- body.unshift(" // __async__");
1003
- }
1004
- out.set(name, { body, itemVar });
1005
- }
1006
- }
1007
- }
1008
- const childItemVar = node.repeatBinding ? node.repeatBinding.itemVar || deriveItemVar(node.repeatBinding.source) : itemVar;
1009
- for (const c of node.children) collectHandlers(c, out, deps, stateKeys, childItemVar);
1010
- }
1011
- function serializeProp(key, value) {
1012
- if (typeof value === "string") {
1013
- if (value.startsWith("$")) {
1014
- const [group, token] = value.slice(1).split(".");
1015
- const tokenMap = {
1016
- spacing: "spacing",
1017
- radii: "radii",
1018
- shadow: "shadows",
1019
- fontSize: "fontSizes",
1020
- fontWeight: "fontWeights",
1021
- lineHeight: "lineHeights",
1022
- opacity: "opacity",
1023
- duration: "durations",
1024
- zIndex: "zIndices",
1025
- color: "colors"
1026
- };
1027
- if (group === "theme") return `${key}={theme.${token}}`;
1028
- if (tokenMap[group]) return `${key}={${tokenMap[group]}[${JSON.stringify(token)}]}`;
1029
- const resolved = resolveForCodegen(value);
1030
- return `${key}={${resolved}}`;
1031
- }
1032
- return `${key}="${value}"`;
1033
- }
1034
- if (typeof value === "number") return `${key}={${value}}`;
1035
- if (typeof value === "boolean") return value ? key : `${key}={false}`;
1036
- if (Array.isArray(value)) return `${key}={${JSON.stringify(value)}}`;
1037
- if (typeof value === "object" && value !== null) return `${key}={${JSON.stringify(value)}}`;
1038
- return "";
1039
- }
1040
- function deriveItemVar(source) {
1041
- const raw = source.replace(/^\$query\./, "").replace(/^\$state\./, "").replace(/Data$/, "");
1042
- const name = raw.replace(/^get/, "").replace(/[^a-zA-Z0-9]/g, "");
1043
- if (!name) return "item";
1044
- const lower = name.charAt(0).toLowerCase() + name.slice(1);
1045
- if (lower.endsWith("ies")) return lower.slice(0, -3) + "y";
1046
- if (lower.endsWith("s") && lower.length > 2) return lower.slice(0, -1);
1047
- return lower;
1048
- }
1049
- function buildSecondaryArraySlotProps(namedSlotChildren, slotCfg, indent, pad, handlerMap, styleMap, itemVar, stateKeys, node) {
1050
- if (!slotCfg.secondaryArraySlots?.length) return "";
1051
- const parts = [];
1052
- for (const secondarySlot of slotCfg.secondaryArraySlots) {
1053
- const slotChildren = namedSlotChildren.filter((c) => c.slotName === secondarySlot.prop);
1054
- const slotBinding = node?.slotBindings?.[secondarySlot.prop];
1055
- if (slotBinding && slotBinding.mode !== "static" && slotBinding.source) {
1056
- const { source, keyProp = "id", itemVar: explicitVar } = slotBinding;
1057
- const loopVar = explicitVar || deriveItemVar(source);
1058
- const keyExpr = `${loopVar}.${keyProp}`;
1059
- const resolvedSource = resolveExpression(source);
1060
- const templateChild = slotChildren[0];
1061
- if (templateChild) {
1062
- const childJsx = renderNode(templateChild, indent + 2, handlerMap, styleMap, loopVar, stateKeys, keyExpr);
1063
- parts.push(` ${secondarySlot.prop}={${resolvedSource}.map((${loopVar}) => (
1064
- ${childJsx}
1065
- ${pad}))}`);
1066
- } else {
1067
- parts.push(` ${secondarySlot.prop}={[]}`);
1068
- }
1069
- } else if (slotChildren.length === 0) {
1070
- parts.push(` ${secondarySlot.prop}={[]}`);
1071
- } else {
1072
- const renderedItems = slotChildren.map((c) => renderNode(c, indent + 2, handlerMap, styleMap, itemVar, stateKeys)).join(",\n");
1073
- parts.push(` ${secondarySlot.prop}={[
1074
- ${renderedItems}
1075
- ${pad}]}`);
1076
- }
1077
- }
1078
- return parts.join("");
1079
- }
1080
- function renderNode(node, indent, handlerMap, styleMap, itemVar, stateKeys, keyExpr) {
1081
- const pad = " ".repeat(indent);
1082
- if (node.kind === "text") return `${pad}<Text>${node.props.text ?? ""}</Text>`;
1083
- const tag = node.registryId;
1084
- const mergedProps = { ...node.props };
1085
- if (node.bindings) {
1086
- for (const [k, expr] of Object.entries(node.bindings)) {
1087
- if (expr) mergedProps[k] = `__BIND__${expr}`;
1088
- }
1089
- }
1090
- const propsArr = Object.entries(mergedProps).filter(([, v]) => v !== void 0).map(([k, v]) => {
1091
- if (typeof v === "string" && v.startsWith("__BIND__")) {
1092
- const expr = v.slice(8);
1093
- const resolved = expr.startsWith("$node.") ? resolveNodeForCodegen(expr, stateKeys) : resolveExpression(expr, itemVar);
1094
- return `${k}={${resolved}}`;
1095
- }
1096
- return serializeProp(k, v);
1097
- }).filter(Boolean);
1098
- if (keyExpr) propsArr.unshift(`key={${keyExpr}}`);
1099
- if (node.events) {
1100
- for (const [ev, actions] of Object.entries(node.events)) {
1101
- if (actions.length > 0) {
1102
- const handlerName = getHandlerName(node, ev);
1103
- if (itemVar) {
1104
- propsArr.push(`${ev}={() => ${handlerName}(${itemVar})}`);
1105
- } else {
1106
- propsArr.push(`${ev}={${handlerName}}`);
1107
- }
1108
- }
1109
- }
1110
- }
1111
- const layoutMeta = getLayoutMeta(node.registryId);
1112
- const slotCfg = deriveSlotConfig(layoutMeta?.slots);
1113
- const isItemsMode = slotCfg.mode === "items";
1114
- const itemsPropName = slotCfg.itemsProp ?? "items";
1115
- const arraySlotPropNames = /* @__PURE__ */ new Set();
1116
- if (isItemsMode) {
1117
- arraySlotPropNames.add(itemsPropName);
1118
- for (const s of slotCfg.secondaryArraySlots ?? []) arraySlotPropNames.add(s.prop);
1119
- }
1120
- const namedSlotChildren = node.children.filter((c) => {
1121
- if (!c.slotName || c.slotName === "children") return false;
1122
- if (isItemsMode && c.slotName === itemsPropName) return false;
1123
- return true;
1124
- });
1125
- const jsxChildren = node.children.filter(
1126
- (c) => !c.slotName || c.slotName === "children" || isItemsMode && c.slotName === itemsPropName
1127
- );
1128
- for (const sc of namedSlotChildren) {
1129
- if (isItemsMode && slotCfg.secondaryArraySlots?.some((s) => s.prop === sc.slotName)) {
1130
- continue;
1131
- }
1132
- const slotDef = layoutMeta?.slots?.find((s) => s.name === sc.slotName);
1133
- const isNamedArray = slotDef?.kind === "named-array" || slotDef?.kind === void 0 && slotDef?.array === true;
1134
- if (isNamedArray) {
1135
- continue;
1136
- }
1137
- propsArr.push(`${sc.slotName}={(
1138
- ${renderNode(sc, indent + 1, handlerMap, styleMap, itemVar, stateKeys)}
1139
- ${pad})}`);
1140
- }
1141
- if (!isItemsMode) {
1142
- const namedArraySlotNames = new Set(
1143
- (layoutMeta?.slots ?? []).filter((s) => s.kind === "named-array" || s.kind === void 0 && s.array === true).map((s) => s.name)
1144
- );
1145
- for (const slotName of namedArraySlotNames) {
1146
- const slotChildren = namedSlotChildren.filter((c) => c.slotName === slotName);
1147
- const slotBinding = node.slotBindings?.[slotName];
1148
- if (slotBinding && slotBinding.mode !== "static" && slotBinding.source) {
1149
- const { source, keyProp = "id", itemVar: explicitVar } = slotBinding;
1150
- const loopVar = explicitVar || deriveItemVar(source);
1151
- const keyExpr2 = `${loopVar}.${keyProp}`;
1152
- const resolvedSource = resolveExpression(source);
1153
- if (slotBinding.mode === "template" && slotChildren.length > 0) {
1154
- const templateChild = slotChildren[0];
1155
- const childJsx = renderNode(templateChild, indent + 2, handlerMap, styleMap, loopVar, stateKeys, keyExpr2);
1156
- propsArr.push(`${slotName}={${resolvedSource}.map((${loopVar}) => (
1157
- ${childJsx}
1158
- ${pad}))}`);
1159
- } else if (slotBinding.mode === "data" && slotChildren.length > 0) {
1160
- const templateChild = slotChildren[0];
1161
- const childJsx = renderNode(templateChild, indent + 2, handlerMap, styleMap, loopVar, stateKeys, keyExpr2);
1162
- propsArr.push(`${slotName}={${resolvedSource}.map((${loopVar}) => (
1163
- ${childJsx}
1164
- ${pad}))}`);
1165
- } else {
1166
- if (slotChildren.length === 0) {
1167
- propsArr.push(`${slotName}={[]}`);
1168
- } else {
1169
- const renderedItems = slotChildren.map((c) => renderNode(c, indent + 2, handlerMap, styleMap, itemVar, stateKeys)).join(",\n");
1170
- propsArr.push(`${slotName}={[
1171
- ${renderedItems}
1172
- ${pad}]}`);
1173
- }
1174
- }
1175
- } else {
1176
- if (slotChildren.length === 0) {
1177
- propsArr.push(`${slotName}={[]}`);
1178
- } else {
1179
- const renderedItems = slotChildren.map((c) => renderNode(c, indent + 2, handlerMap, styleMap, itemVar, stateKeys)).join(",\n");
1180
- propsArr.push(`${slotName}={[
1181
- ${renderedItems}
1182
- ${pad}]}`);
1183
- }
1184
- }
1185
- }
1186
- }
1187
- const filteredPropsArr = isItemsMode ? propsArr.filter((p) => !arraySlotPropNames.has(p.split("=")[0].split("{")[0].trim())) : propsArr;
1188
- const propsStr = filteredPropsArr.join(" ");
1189
- const styleKey = styleMap?.has(node.id) ? `s_${node.id.replace(/[^a-zA-Z0-9]/g, "_")}` : null;
1190
- const styleStr = styleKey ? ` style={styles.${styleKey}}` : "";
1191
- const opening = propsStr ? `${tag} ${propsStr}${styleStr}` : `${tag}${styleStr}`;
1192
- let jsx;
1193
- if (jsxChildren.length === 0) {
1194
- if (isItemsMode) {
1195
- const secondaryProps = buildSecondaryArraySlotProps(namedSlotChildren, slotCfg, indent, pad, handlerMap, styleMap, itemVar, stateKeys, node);
1196
- jsx = `${pad}<${opening} ${itemsPropName}={[]}${secondaryProps} />`;
1197
- } else {
1198
- jsx = `${pad}<${opening} />`;
1199
- }
1200
- } else {
1201
- if (node.repeatBinding) {
1202
- const { source, keyProp = "id" } = node.repeatBinding;
1203
- const loopVar = node.repeatBinding.itemVar || deriveItemVar(source);
1204
- const keyExpr2 = `${loopVar}.${keyProp}`;
1205
- const resolvedSource = resolveExpression(source);
1206
- const mappedChildren = jsxChildren.map((child, idx) => {
1207
- return renderNode(child, indent + 2, handlerMap, styleMap, loopVar, stateKeys, idx === 0 ? keyExpr2 : void 0);
1208
- }).join("\n");
1209
- const childrenStr = `${pad} {${resolvedSource}.map((${loopVar}) => (
1210
- ${mappedChildren}
1211
- ${pad} ))}`;
1212
- if (isItemsMode) {
1213
- const mapExpr = `{${resolvedSource}.map((${loopVar}) => (
1214
- ${mappedChildren}
1215
- ${pad}))}`;
1216
- const secondaryProps = buildSecondaryArraySlotProps(namedSlotChildren, slotCfg, indent, pad, handlerMap, styleMap, itemVar, stateKeys, node);
1217
- const openingWithItems = `${opening} ${itemsPropName}=${mapExpr}${secondaryProps}`;
1218
- jsx = `${pad}<${openingWithItems} />`;
1219
- } else {
1220
- jsx = `${pad}<${opening}>
1221
- ${childrenStr}
1222
- ${pad}</${tag}>`;
1223
- }
1224
- } else {
1225
- if (isItemsMode) {
1226
- const templateChild = jsxChildren.length === 1 ? jsxChildren[0] : null;
1227
- if (templateChild?.repeatBinding) {
1228
- const { source, keyProp = "id" } = templateChild.repeatBinding;
1229
- const loopVar = templateChild.repeatBinding.itemVar || deriveItemVar(source);
1230
- const keyExpr2 = `${loopVar}.${keyProp}`;
1231
- const resolvedSource = resolveExpression(source);
1232
- const childJsx = renderNode(templateChild, indent + 2, handlerMap, styleMap, loopVar, stateKeys, keyExpr2);
1233
- const mapExpr = `{${resolvedSource}.map((${loopVar}) => (
1234
- ${childJsx}
1235
- ${pad}))}`;
1236
- const secondaryProps = buildSecondaryArraySlotProps(namedSlotChildren, slotCfg, indent, pad, handlerMap, styleMap, itemVar, stateKeys, node);
1237
- jsx = `${pad}<${opening} ${itemsPropName}=${mapExpr}${secondaryProps} />`;
1238
- } else {
1239
- const renderedItems = jsxChildren.map((c) => renderNode(c, indent + 2, handlerMap, styleMap, itemVar, stateKeys)).join(",\n");
1240
- const itemsExpr = `{[
1241
- ${renderedItems}
1242
- ${pad}]}`;
1243
- const secondaryProps = buildSecondaryArraySlotProps(namedSlotChildren, slotCfg, indent, pad, handlerMap, styleMap, itemVar, stateKeys, node);
1244
- jsx = `${pad}<${opening} ${itemsPropName}=${itemsExpr}${secondaryProps} />`;
1245
- }
1246
- } else {
1247
- const childrenStr = jsxChildren.map((c) => renderNode(c, indent + 1, handlerMap, styleMap, itemVar, stateKeys)).join("\n");
1248
- jsx = `${pad}<${opening}>
1249
- ${childrenStr}
1250
- ${pad}</${tag}>`;
1251
- }
1252
- }
1253
- }
1254
- if (node.conditionalRender) {
1255
- const { expression, mode } = node.conditionalRender;
1256
- const expr = expression.startsWith("$node.") ? resolveNodeForCodegen(expression, stateKeys) : resolveExpression(expression, itemVar);
1257
- jsx = mode === "show" ? `${pad}{${expr} && (
1258
- ${jsx}
1259
- ${pad})}` : `${pad}{!${expr} && (
1260
- ${jsx}
1261
- ${pad})}`;
1262
- }
1263
- return jsx;
1264
- }
1265
- function renderImports(c) {
1266
- const lines = [`import React from "react";`];
1267
- for (const [source, names] of c.imports) {
1268
- const sorted = Array.from(names).sort();
1269
- const stars = sorted.filter((n) => n.startsWith("* as "));
1270
- const named = sorted.filter((n) => !n.startsWith("* as "));
1271
- for (const s of stars) lines.push(`import ${s} from "${source}";`);
1272
- if (named.length > 0) lines.push(`import { ${named.join(", ")} } from "${source}";`);
1273
- }
1274
- return lines.join("\n");
1275
- }
1276
- function generatePageCode(page, queries) {
1277
- const { componentName, hookName } = deriveScreenNames(page.name);
1278
- const collector = { imports: /* @__PURE__ */ new Map() };
1279
- collectImports(page.root, collector);
1280
- const stateKeys = /* @__PURE__ */ new Map();
1281
- collectStateKeys(page.root, page.state || [], stateKeys, queries);
1282
- const apiCalls = /* @__PURE__ */ new Map();
1283
- collectApiCalls(page.root, apiCalls, queries);
1284
- const handlers = /* @__PURE__ */ new Map();
1285
- collectHandlers(page.root, handlers, { needsRouter: hasNavigateAction(page.root), apiCalls: new Set(apiCalls.keys()) }, stateKeys);
1286
- const styleMap = /* @__PURE__ */ new Map();
1287
- collectStyles(page.root, styleMap);
1288
- const useStyleSheet = styleMap.size > 0;
1289
- if (useStyleSheet) addImport(collector, "react-native", "StyleSheet");
1290
- const body = renderNode(page.root, 2, handlers, useStyleSheet ? styleMap : void 0, void 0, stateKeys);
1291
- let styleBlock = "";
1292
- if (useStyleSheet) {
1293
- const entries = Array.from(styleMap.entries()).map(([id, styles]) => {
1294
- const key = `s_${id.replace(/[^a-zA-Z0-9]/g, "_")}`;
1295
- const parts = Object.entries(styles).map(
1296
- ([k, v]) => typeof v === "string" ? `${k}: ${JSON.stringify(v)}` : `${k}: ${v}`
1297
- );
1298
- return ` ${key}: { ${parts.join(", ")} }`;
1299
- });
1300
- styleBlock = `
1301
- const styles = StyleSheet.create({
1302
- ${entries.join(",\n")}
1303
- });
1304
- `;
1305
- }
1306
- const destructured = [
1307
- ...stateKeys.keys(),
1308
- ...Array.from(apiCalls.keys()).flatMap((q) => [`${q}Data`, `${q}Loading`, `${q}Error`, `refetch${capitalize(q)}`]),
1309
- ...handlers.keys()
1310
- ].join(", ");
1311
- return `${renderImports(collector)}
1312
- import { ${hookName} } from "./${componentName}.hook";
1313
-
1314
- export default function ${componentName}() {
1315
- const { ${destructured} } = ${hookName}();
1316
-
1317
- return (
1318
- ${body}
1319
- );
1320
- }
1321
- ${styleBlock}`;
1322
- }
1323
- function checkUsesGlobal(node) {
1324
- const check = (expr) => expr?.startsWith("$global.");
1325
- if (node.bindings && Object.values(node.bindings).some(check)) return true;
1326
- if (check(node.conditionalRender?.expression)) return true;
1327
- if (check(node.repeatBinding?.source)) return true;
1328
- if (node.events) {
1329
- for (const acts of Object.values(node.events)) {
1330
- for (const a of acts) {
1331
- if (a.type === "setState" && check(String(a.payload.value || ""))) return true;
1332
- if (a.type === "callApi" && a.payload.body) {
1333
- for (const v of Object.values(a.payload.body)) {
1334
- if (check(v)) return true;
1335
- }
1336
- }
1337
- }
1338
- }
1339
- }
1340
- return node.children.some(checkUsesGlobal);
1341
- }
1342
- function generatePageHook(page, queries, hookDir) {
1343
- const { hookName } = deriveScreenNames(page.name, page.route);
1344
- const needsRouter = hasNavigateAction(page.root);
1345
- const usesGlobal = checkUsesGlobal(page.root);
1346
- const stateKeys = /* @__PURE__ */ new Map();
1347
- collectStateKeys(page.root, page.state || [], stateKeys, queries);
1348
- const apiCalls = /* @__PURE__ */ new Map();
1349
- collectApiCalls(page.root, apiCalls, queries);
1350
- const handlers = /* @__PURE__ */ new Map();
1351
- collectHandlers(page.root, handlers, { apiCalls: new Set(apiCalls.keys()) }, stateKeys);
1352
- const depth = hookDir ? hookDir.split("/").filter(Boolean).length : 1;
1353
- const relativeToControllers = "../".repeat(depth) + "controllers";
1354
- const relativeToProviders = "../".repeat(depth) + "app/providers";
1355
- const handlerDeps = (body) => {
1356
- const deps = [];
1357
- if (needsRouter && body.some((l) => l.includes("router."))) deps.push("router");
1358
- for (const qName of apiCalls.keys()) {
1359
- if (body.some((l) => l.includes(`refetch${capitalize(qName)}`))) deps.push(`refetch${capitalize(qName)}`);
1360
- }
1361
- if (usesGlobal) deps.push("globalState");
1362
- return deps.join(", ");
1363
- };
1364
- const needsEffect = Array.from(apiCalls.values()).some((v) => v.autoFetch) || Array.from(apiCalls.entries()).some(([qName]) => {
1365
- const query = queries?.find((q) => normalizeQueryName(q.name) === qName);
1366
- return query?.alias && stateKeys.has(query.alias);
1367
- });
1368
- const reactHooks = ["useState", "useCallback"];
1369
- if (needsEffect) reactHooks.push("useEffect");
1370
- const imports = [`import { ${reactHooks.join(", ")} } from "react";`];
1371
- if (needsRouter) imports.push(`import { useRouter } from "expo-router";`);
1372
- if (usesGlobal) imports.push(`import { useGlobalState } from "${relativeToProviders}/GlobalStateProvider";`);
1373
- const rnImports = collectHookRNImports(page.root);
1374
- if (rnImports.size > 0) {
1375
- imports.push(`import { ${[...rnImports].sort().join(", ")} } from "react-native";`);
1376
- }
1377
- for (const qName of apiCalls.keys()) {
1378
- imports.push(`import { use${capitalize(qName)} } from "${relativeToControllers}/${qName}.controller";`);
1379
- }
1380
- const stateLines = Array.from(stateKeys.entries()).map(
1381
- ([k, v]) => ` const [${k}, set${capitalize(k)}] = useState<${v.type === "any" ? "any" : v.type}>(${v.default});`
1382
- );
1383
- const queryLines = Array.from(apiCalls.entries()).map(([qName]) => {
1384
- return ` const { data: ${qName}Data, loading: ${qName}Loading, error: ${qName}Error, refetch: refetch${capitalize(qName)} } = use${capitalize(qName)}();`;
1385
- });
1386
- const autoFetchEffects = Array.from(apiCalls.entries()).filter(([, { autoFetch }]) => autoFetch).map(([qName]) => ` useEffect(() => { refetch${capitalize(qName)}(); }, []);`);
1387
- const dataSyncEffects = Array.from(apiCalls.entries()).filter(([qName]) => {
1388
- const query = queries?.find((q) => normalizeQueryName(q.name) === qName);
1389
- return query?.alias && stateKeys.has(query.alias);
1390
- }).map(([qName]) => {
1391
- const query = queries.find((q) => normalizeQueryName(q.name) === qName);
1392
- const alias = query.alias;
1393
- return ` useEffect(() => { if (${qName}Data !== null && ${qName}Data !== undefined) set${capitalize(alias)}(${qName}Data as any); }, [${qName}Data]);`;
1394
- });
1395
- const handlerLines = Array.from(handlers.entries()).map(([name, { body, itemVar: hItemVar }]) => {
1396
- const deps = handlerDeps(body);
1397
- const needsAsync = body.some((l) => l.includes("__async__") || l.includes("await "));
1398
- const cleanBody = body.filter((l) => !l.includes("// __async__"));
1399
- const asyncKw = needsAsync ? "async " : "";
1400
- const param = hItemVar ? `${hItemVar}: any` : "";
1401
- return ` const ${name} = useCallback(${asyncKw}(${param}) => {
1402
- ${cleanBody.join("\n")}
1403
- }, [${deps}]);`;
1404
- });
1405
- const returnFields = [
1406
- ...Array.from(stateKeys.keys()).flatMap((k) => [` ${k},`, ` set${capitalize(k)},`]),
1407
- ...usesGlobal ? [" globalState,"] : [],
1408
- ...Array.from(apiCalls.keys()).flatMap((q) => [
1409
- ` ${q}Data,`,
1410
- ` ${q}Loading,`,
1411
- ` ${q}Error,`,
1412
- ` refetch${capitalize(q)},`
1413
- ]),
1414
- ...Array.from(handlers.keys()).map((k) => ` ${k},`)
1415
- ];
1416
- const bodyLines = [
1417
- needsRouter ? " const router = useRouter();" : "",
1418
- usesGlobal ? " const globalState = useGlobalState();" : "",
1419
- ...stateLines,
1420
- ...queryLines.length > 0 ? ["", ...queryLines] : [],
1421
- ...autoFetchEffects.length > 0 ? ["", ...autoFetchEffects] : [],
1422
- ...dataSyncEffects.length > 0 ? ["", ...dataSyncEffects] : [],
1423
- "",
1424
- ...handlerLines,
1425
- "",
1426
- " return {",
1427
- ...returnFields,
1428
- " };"
1429
- ].filter((l) => l !== void 0).join("\n");
1430
- return `${imports.join("\n")}
1431
-
1432
- export function ${hookName}() {
1433
- ${bodyLines}
1434
- }
1435
- `;
1436
- }
1437
- var NPMRC_CONTENT = `@flipova:registry=https://npm.pkg.github.com
1438
- //npm.pkg.github.com/:_authToken=\${GITHUB_TOKEN}
1439
- `;
1440
- function applyRegistryFoundation(files) {
1441
- let result = [...files];
1442
- if (!result.some((f) => f.path === ".npmrc")) {
1443
- result.push({ path: ".npmrc", content: NPMRC_CONTENT });
1444
- }
1445
- const pkgIndex = result.findIndex((f) => f.path === "package.json");
1446
- if (pkgIndex !== -1) {
1447
- const pkg = JSON.parse(result[pkgIndex].content);
1448
- if (!pkg.dependencies) pkg.dependencies = {};
1449
- if (!pkg.dependencies["@flipova/foundation"]) {
1450
- pkg.dependencies["@flipova/foundation"] = "latest";
1451
- }
1452
- result[pkgIndex] = { ...result[pkgIndex], content: JSON.stringify(pkg, null, 2) };
1453
- }
1454
- return result;
1455
- }
1456
- var LOCAL_FOUNDATION_PACKAGE_JSON = JSON.stringify({
1457
- name: "@flipova/foundation",
1458
- version: "0.0.0-local",
1459
- main: "./index.ts",
1460
- exports: {
1461
- ".": "./index.ts",
1462
- "./tokens": "./tokens/index.ts",
1463
- "./theme": "./theme/index.ts",
1464
- "./config": "./config/index.ts",
1465
- "./layout": "./layout/index.ts"
1466
- }
1467
- }, null, 2);
1468
- function relativeToModules(filePath) {
1469
- const depth = filePath.split("/").length - 1;
1470
- return depth === 0 ? "./flipova_modules" : "../".repeat(depth) + "flipova_modules";
1471
- }
1472
- function buildImportReplacements(filePath) {
1473
- const base = relativeToModules(filePath);
1474
- return [
1475
- [/from ["']@flipova\/foundation\/tokens["']/g, `from "${base}/flipova/foundation/tokens"`],
1476
- [/from ["']@flipova\/foundation\/theme["']/g, `from "${base}/flipova/foundation/theme"`],
1477
- [/from ["']@flipova\/foundation\/config["']/g, `from "${base}/flipova/foundation/config"`],
1478
- [/from ["']@flipova\/foundation\/layout["']/g, `from "${base}/flipova/foundation/layout"`],
1479
- [/from ["']@flipova\/foundation["']/g, `from "${base}/flipova/foundation"`]
1480
- ];
1481
- }
1482
- function applyLocalFoundation(files, foundationSourcePath) {
1483
- if (!fs2.existsSync(foundationSourcePath)) {
1484
- throw new Error(`Foundation source path not found: ${foundationSourcePath}`);
1485
- }
1486
- const allEntries = fs2.readdirSync(foundationSourcePath, { recursive: true });
1487
- const foundationFiles = [];
1488
- for (const entry of allEntries) {
1489
- const absolutePath = path2.join(foundationSourcePath, entry);
1490
- if (!fs2.statSync(absolutePath).isFile()) continue;
1491
- let content;
1492
- try {
1493
- content = fs2.readFileSync(absolutePath, "utf-8");
1494
- } catch {
1495
- throw new Error(`Cannot read foundation file: ${absolutePath}`);
1496
- }
1497
- const relativePath = entry.toString().replace(/\\/g, "/");
1498
- foundationFiles.push({
1499
- path: `flipova_modules/flipova/foundation/${relativePath}`,
1500
- content
1501
- });
1502
- }
1503
- const localPackageJson = {
1504
- path: "flipova_modules/flipova/foundation/package.json",
1505
- content: LOCAL_FOUNDATION_PACKAGE_JSON
1506
- };
1507
- const updatedFiles = files.map((file) => {
1508
- if (!file.path.endsWith(".ts") && !file.path.endsWith(".tsx")) return file;
1509
- const replacements = buildImportReplacements(file.path);
1510
- let content = file.content;
1511
- for (const [pattern, replacement] of replacements) {
1512
- content = content.replace(pattern, replacement);
1513
- }
1514
- return content !== file.content ? { ...file, content } : file;
1515
- });
1516
- const pkgIndex = updatedFiles.findIndex((f) => f.path === "package.json");
1517
- let result = [...updatedFiles];
1518
- if (pkgIndex !== -1) {
1519
- const pkg = JSON.parse(result[pkgIndex].content);
1520
- if (pkg.dependencies) delete pkg.dependencies["@flipova/foundation"];
1521
- result[pkgIndex] = { ...result[pkgIndex], content: JSON.stringify(pkg, null, 2) };
1522
- }
1523
- result = [...result, localPackageJson, ...foundationFiles];
1524
- return { files: result, warnings: [] };
1525
- }
1526
- var SNACK_SDK_VERSION = "53.0.0";
1527
- var SNACK_EXCLUDED_DEPS = /* @__PURE__ */ new Set([
1528
- "expo-secure-store",
1529
- "expo-file-system",
1530
- "expo-local-authentication",
1531
- "expo-contacts"
1532
- ]);
1533
- var SNACK_UNSUPPORTED_NATIVE = /* @__PURE__ */ new Set([
1534
- "expo-secure-store",
1535
- "expo-file-system",
1536
- "expo-local-authentication",
1537
- "expo-contacts"
1538
- ]);
1539
- var SNACK_COMPATIBLE_VERSIONS = {
1540
- "expo": "~53.0.0",
1541
- "react": "^19.0.0",
1542
- "react-native": "~0.79.0",
1543
- "expo-router": "~4.0.0",
1544
- "react-native-safe-area-context": "~5.4.0",
1545
- "react-native-screens": "~4.0.0",
1546
- "react-native-web": "~0.20.0",
1547
- "react-dom": "^19.0.0",
1548
- "@expo/vector-icons": "^14.0.0",
1549
- "@react-native-async-storage/async-storage": "~2.1.0",
1550
- "expo-linear-gradient": "~14.0.0"
1551
- };
1552
- var SNACK_REQUIRED_DEPS = {
1553
- "expo": "~53.0.0",
1554
- "react": "^19.0.0",
1555
- "react-native": "~0.79.0",
1556
- "@react-navigation/native": "^7.0.0",
1557
- "@react-navigation/stack": "^7.0.0",
1558
- "react-native-safe-area-context": "~5.4.0",
1559
- "react-native-screens": "~4.0.0",
1560
- "react-native-gesture-handler": "~2.20.0",
1561
- "expo-linear-gradient": "~14.0.0",
1562
- "expo-haptics": "~14.0.0"
1563
- };
1564
- function applySnackMode(files, project) {
1565
- const warnings = [];
1566
- let result = files.map((file) => {
1567
- if (file.path.startsWith("flipova_modules/")) return file;
1568
- const replacements = buildImportReplacements(file.path);
1569
- let content = file.content;
1570
- for (const [pattern, replacement] of replacements) {
1571
- content = content.replace(pattern, replacement);
1572
- }
1573
- return content !== file.content ? { ...file, content } : file;
1574
- });
1575
- const pkgIndex = result.findIndex((f) => f.path === "package.json");
1576
- let filteredDeps = { ...SNACK_REQUIRED_DEPS };
1577
- if (pkgIndex !== -1) {
1578
- const pkg = JSON.parse(result[pkgIndex].content);
1579
- const deps = pkg.dependencies ?? {};
1580
- for (const [name, version] of Object.entries(deps)) {
1581
- if (SNACK_EXCLUDED_DEPS.has(name)) continue;
1582
- filteredDeps[name] = SNACK_COMPATIBLE_VERSIONS[name] ?? version;
1583
- }
1584
- const updatedPkg = { ...pkg, dependencies: filteredDeps };
1585
- result = result.map(
1586
- (f, i) => i === pkgIndex ? { ...f, content: JSON.stringify(updatedPkg, null, 2) } : f
1587
- );
1588
- }
1589
- const snackJson = {
1590
- name: project.name,
1591
- description: "Generated by Flipova Studio",
1592
- sdkVersion: SNACK_SDK_VERSION,
1593
- dependencies: filteredDeps
1594
- };
1595
- result = result.filter((f) => f.path !== "snack.json");
1596
- result.push({ path: "snack.json", content: JSON.stringify(snackJson, null, 2) });
1597
- for (const file of result) {
1598
- for (const mod of SNACK_UNSUPPORTED_NATIVE) {
1599
- if (file.content.includes(`"${mod}"`) || file.content.includes(`'${mod}'`)) {
1600
- warnings.push(`Warning: ${mod} is not supported in Snack environment (file: ${file.path})`);
1601
- }
1602
- }
1603
- }
1604
- return { files: result, warnings };
1605
- }
1606
-
1607
- // studio/engine/codegen/project.ts
1608
- function generateProject(project, options) {
1609
- if (options?.foundationMode === "local" && !options.foundationSourcePath) {
1610
- throw new Error("foundationSourcePath is required when foundationMode is 'local'");
1611
- }
1612
- let files = generateCoreFiles(project);
1613
- const warnings = [];
1614
- const effectiveFoundationMode = options?.foundationMode ?? "registry";
1615
- if (effectiveFoundationMode === "registry") {
1616
- files = applyRegistryFoundation(files);
1617
- } else {
1618
- const result = applyLocalFoundation(files, options.foundationSourcePath);
1619
- files = result.files;
1620
- warnings.push(...result.warnings);
1621
- }
1622
- if (options?.snackMode) {
1623
- const result = applySnackMode(files, project);
1624
- files = result.files;
1625
- warnings.push(...result.warnings);
1626
- }
1627
- return { files, warnings };
1628
- }
1629
- function groupFolder(name) {
1630
- return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
1631
- }
1632
- function canonicalRoute(page) {
1633
- return page.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
1634
- }
1635
- function resolveScreenPath(page, project) {
1636
- const group = (project.screenGroups || []).find((g) => (g.screenIds || []).includes(page.id));
1637
- const names = deriveScreenNames(page.name, canonicalRoute(page));
1638
- if (group) {
1639
- return `src/screens/${groupFolder(group.name)}/${names.componentName}.tsx`;
1640
- }
1641
- return `src/screens/${names.componentName}.tsx`;
1642
- }
1643
- function generateCoreFiles(project) {
1644
- const files = [];
1645
- files.push({ path: "app.json", content: generateAppJson(project) });
1646
- files.push({ path: "package.json", content: generatePackageJson(project) });
1647
- files.push({ path: "tsconfig.json", content: generateTsConfig() });
1648
- files.push({ path: "flipova.config.ts", content: generateFoundationConfig(project) });
1649
- const seenPageIds = /* @__PURE__ */ new Set();
1650
- const allScreens = [];
1651
- for (const page of project.pages) {
1652
- if (seenPageIds.has(page.id)) continue;
1653
- seenPageIds.add(page.id);
1654
- const names = deriveScreenNames(page.name, canonicalRoute(page));
1655
- allScreens.push({ page, names });
1656
- const screenPath = resolveScreenPath(page, project);
1657
- const screenDir = screenPath.substring(0, screenPath.lastIndexOf("/"));
1658
- files.push({ path: screenPath, content: generatePageCode(page, project.queries) });
1659
- files.push({ path: `${screenDir}/${names.hookFileName}`, content: generatePageHook(page, project.queries, screenDir) });
1660
- }
1661
- files.push({ path: "App.tsx", content: generateAppEntry(project, allScreens) });
1662
- for (const service of project.services) {
1663
- files.push({ path: `services/${service.id}.ts`, content: generateServiceConfig(service) });
1664
- }
1665
- if (project.queries?.length) {
1666
- for (const query of project.queries) {
1667
- const qName = normalizeQueryName(query.name);
1668
- files.push({ path: `controllers/${qName}.controller.ts`, content: generateQueryController(query, project) });
1669
- }
1670
- }
1671
- const auth = project.auth;
1672
- if (auth?.enabled) {
1673
- files.push({ path: "src/providers/AuthProvider.tsx", content: generateAuthProvider(auth) });
1674
- files.push({ path: "hooks/useAuth.ts", content: generateUseAuth() });
1675
- }
1676
- files.push({ path: "eas.json", content: generateEasConfig() });
1677
- files.push({ path: ".github/workflows/build.yml", content: generateGithubWorkflow() });
1678
- for (const { page, names } of allScreens) {
1679
- files.push({ path: `__tests__/${names.componentName}.test.tsx`, content: generatePageTest(page) });
1680
- }
1681
- files.push({ path: "hooks/useStorage.ts", content: generateStorageHook() });
1682
- files.push({ path: "babel.config.js", content: `module.exports = function (api) {
1683
- api.cache(true);
1684
- return { presets: ["babel-preset-expo"] };
1685
- };
1686
- ` });
1687
- files.push({ path: ".gitignore", content: `node_modules/
1688
- .expo/
1689
- dist/
1690
- .env
1691
- *.log
1692
- ` });
1693
- files.push({ path: "README.md", content: `# ${project.name}
1694
-
1695
- Generated by Flipova Studio.
1696
-
1697
- ## Run
1698
-
1699
- \`\`\`bash
1700
- npm install
1701
- npx expo start
1702
- \`\`\`
1703
- ` });
1704
- const constants = project.constants || [];
1705
- if (constants.length > 0) {
1706
- files.push({ path: "constants.ts", content: generateConstants(constants) });
1707
- }
1708
- const envVars = project.envVars || [];
1709
- if (envVars.length > 0) {
1710
- files.push({ path: ".env", content: envVars.map((e) => `${e.key}=${e.value}`).join("\n") + "\n" });
1711
- }
1712
- const globalState = project.globalState || [];
1713
- if (globalState.length > 0) {
1714
- files.push({ path: "src/providers/GlobalStateProvider.tsx", content: generateGlobalStateProvider(globalState) });
1715
- }
1716
- return files;
1717
- }
1718
- function generateAppJson(project) {
1719
- const caps = project.capabilities || [];
1720
- const capPluginMap = {
1721
- camera: "expo-camera",
1722
- location: "expo-location",
1723
- notifications: "expo-notifications",
1724
- contacts: "expo-contacts",
1725
- biometrics: "expo-local-authentication",
1726
- haptics: "expo-haptics",
1727
- imagePicker: "expo-image-picker",
1728
- fileSystem: "expo-file-system",
1729
- secureStore: "expo-secure-store",
1730
- clipboard: "expo-clipboard"
1731
- };
1732
- const plugins = [];
1733
- for (const cap of caps) {
1734
- if (cap.enabled && capPluginMap[cap.id]) plugins.push(capPluginMap[cap.id]);
1735
- }
1736
- const slug = project.name.toLowerCase().replace(/[^a-z0-9]/g, "-");
1737
- return JSON.stringify({
1738
- expo: {
1739
- name: project.name,
1740
- slug,
1741
- version: project.version,
1742
- orientation: "portrait",
1743
- userInterfaceStyle: "light",
1744
- assetBundlePatterns: ["**/*"],
1745
- ios: { supportsTablet: true },
1746
- android: { adaptiveIcon: { backgroundColor: "#ffffff" } },
1747
- web: { bundler: "metro" },
1748
- ...plugins.length > 0 ? { plugins } : {}
1749
- }
1750
- }, null, 2);
1751
- }
1752
- function generatePackageJson(project) {
1753
- const deps = {
1754
- "@flipova/foundation": "latest",
1755
- "expo": "~53.0.0",
1756
- "expo-constants": "~17.0.0",
1757
- "expo-linear-gradient": "~14.0.0",
1758
- "react": "^19.0.0",
1759
- "react-native": "~0.79.0",
1760
- "react-native-safe-area-context": "~5.4.0",
1761
- "react-native-screens": "~4.0.0",
1762
- "@react-navigation/native": "^7.0.0",
1763
- "@react-navigation/stack": "^7.0.0",
1764
- "react-native-gesture-handler": "~2.20.0"
1765
- };
1766
- const groupTypes = new Set((project.screenGroups || []).map((g) => g.type));
1767
- if (groupTypes.has("tabs")) {
1768
- deps["@react-navigation/bottom-tabs"] = "^7.0.0";
1769
- }
1770
- if (groupTypes.has("drawer")) {
1771
- deps["@react-navigation/drawer"] = "^7.0.0";
1772
- deps["react-native-reanimated"] = "~3.16.0";
1773
- }
1774
- return JSON.stringify({
1775
- name: project.name.toLowerCase().replace(/[^a-z0-9]/g, "-"),
1776
- version: project.version,
1777
- main: "App.tsx",
1778
- repository: "https://github.com/flipova/foundation",
1779
- scripts: {
1780
- start: "expo start",
1781
- android: "expo start --android",
1782
- ios: "expo start --ios",
1783
- web: "expo start --web"
1784
- },
1785
- dependencies: deps
1786
- }, null, 2);
1787
- }
1788
- function generateTsConfig() {
1789
- return JSON.stringify({
1790
- extends: "expo/tsconfig.base",
1791
- compilerOptions: { strict: true }
1792
- }, null, 2);
1793
- }
1794
- function generateFoundationConfig(project) {
1795
- const overrides = project.themeOverrides;
1796
- const hasOverrides = overrides && Object.keys(overrides).some((k) => Object.keys(overrides[k] || {}).length > 0);
1797
- if (hasOverrides) {
1798
- const themeBlocks = Object.entries(overrides).filter(([, v]) => v && Object.keys(v).length > 0).map(([scheme, colors]) => {
1799
- const entries = Object.entries(colors).map(([k, v]) => ` ${k}: "${v}",`).join("\n");
1800
- return ` ${scheme}: {
1801
- ${entries}
1802
- },`;
1803
- }).join("\n");
1804
- return `import { defineConfig } from "@flipova/foundation";
1805
-
1806
- export default defineConfig({
1807
- defaultTheme: "${project.theme}",
1808
- themes: {
1809
- ${themeBlocks}
1810
- },
1811
- });
1812
- `;
1813
- }
1814
- return `import { defineConfig } from "@flipova/foundation";
1815
-
1816
- export default defineConfig({
1817
- defaultTheme: "${project.theme}",
1818
- });
1819
- `;
1820
- }
1821
- function generateAppEntry(project, screens) {
1822
- const rawGroups = project.screenGroups || [];
1823
- const groupedPageIds = new Set(rawGroups.flatMap((g) => g.screenIds));
1824
- const ungroupedPageIds = screens.map((s) => s.page.id).filter((id) => !groupedPageIds.has(id));
1825
- let groups = rawGroups;
1826
- if (ungroupedPageIds.length > 0) {
1827
- if (groups.length === 0) {
1828
- groups = [{ id: "grp_default", name: "tabs", type: "tabs", screenIds: ungroupedPageIds }];
1829
- } else {
1830
- groups = [
1831
- { ...groups[0], screenIds: [...groups[0].screenIds, ...ungroupedPageIds] },
1832
- ...groups.slice(1)
1833
- ];
1834
- }
1835
- }
1836
- const screenByPageId = new Map(screens.map((s) => [s.page.id, s]));
1837
- const navScreenByPageId = new Map(
1838
- (project.navigation.screens || []).map((s) => [s.pageId, s])
1839
- );
1840
- const importSet = /* @__PURE__ */ new Set();
1841
- const importLines = [];
1842
- screens.forEach(({ page, names }) => {
1843
- if (importSet.has(names.componentName)) return;
1844
- importSet.add(names.componentName);
1845
- const screenPath = resolveScreenPath(page, project);
1846
- importLines.push(`import ${names.componentName} from './${screenPath.replace(/\.tsx$/, "")}';`);
1847
- });
1848
- let needsTabs = false;
1849
- let needsDrawer = false;
1850
- const subNavigatorFunctions = [];
1851
- const rootStackScreens = [];
1852
- for (const group of groups) {
1853
- const groupScreens = group.screenIds.map((id) => screenByPageId.get(id)).filter(Boolean);
1854
- if (groupScreens.length === 0) continue;
1855
- const folder = groupFolder(group.name);
1856
- const navFnName = group.name.replace(/[^a-zA-Z0-9]/g, "_") + "Navigator";
1857
- const firstRoute = canonicalRoute(groupScreens[0].page);
1858
- if (group.type === "tabs") {
1859
- needsTabs = true;
1860
- const tabBarConfig = project.tabBarConfig;
1861
- const tabBarOpts = [];
1862
- if (tabBarConfig?.backgroundColor) tabBarOpts.push(`tabBarStyle: { backgroundColor: "${tabBarConfig.backgroundColor}" }`);
1863
- if (tabBarConfig?.activeTintColor) tabBarOpts.push(`tabBarActiveTintColor: "${tabBarConfig.activeTintColor}"`);
1864
- if (tabBarConfig?.inactiveTintColor) tabBarOpts.push(`tabBarInactiveTintColor: "${tabBarConfig.inactiveTintColor}"`);
1865
- if (tabBarConfig?.showLabels === false) tabBarOpts.push(`tabBarShowLabel: false`);
1866
- const screenOptsAttr = tabBarOpts.length > 0 ? ` screenOptions={{ ${tabBarOpts.join(", ")} }}` : "";
1867
- const tabScreenDecls = groupScreens.map(({ page, names }) => {
1868
- const sc = navScreenByPageId.get(page.id);
1869
- const label = sc?.name && sc.name !== page.name ? sc.name : page.name;
1870
- const icon = sc?.icon ?? "home";
1871
- return ` <_Tab_${navFnName}.Screen name="${canonicalRoute(page)}" component={${names.componentName}} options={{ title: "${label}", tabBarIcon: ({ color, size }: { color: string; size: number }) => <Ionicons name={"${icon}" as any} size={size} color={color} /> }} />`;
1872
- }).join("\n");
1873
- subNavigatorFunctions.push(
1874
- `const _Tab_${navFnName} = createBottomTabNavigator();
1875
- function ${navFnName}() {
1876
- return (
1877
- <_Tab_${navFnName}.Navigator initialRouteName="${firstRoute}"${screenOptsAttr}>
1878
- ${tabScreenDecls}
1879
- </_Tab_${navFnName}.Navigator>
1880
- );
1881
- }`
1882
- );
1883
- } else if (group.type === "drawer") {
1884
- needsDrawer = true;
1885
- const drawerConfig = project.drawerConfig;
1886
- const drawerOpts = [];
1887
- if (drawerConfig?.backgroundColor) drawerOpts.push(`drawerStyle: { backgroundColor: "${drawerConfig.backgroundColor}" }`);
1888
- if (drawerConfig?.activeTintColor) drawerOpts.push(`drawerActiveTintColor: "${drawerConfig.activeTintColor}"`);
1889
- if (drawerConfig?.inactiveTintColor) drawerOpts.push(`drawerInactiveTintColor: "${drawerConfig.inactiveTintColor}"`);
1890
- if (drawerConfig?.drawerPosition) drawerOpts.push(`drawerPosition: "${drawerConfig.drawerPosition}"`);
1891
- const screenOptsAttr = drawerOpts.length > 0 ? ` screenOptions={{ ${drawerOpts.join(", ")} }}` : "";
1892
- const drawerScreenDecls = groupScreens.map(({ page, names }) => {
1893
- const sc = navScreenByPageId.get(page.id);
1894
- const label = sc?.name && sc.name !== page.name ? sc.name : page.name;
1895
- const icon = sc?.icon;
1896
- const iconOpt = icon ? `, drawerIcon: ({ color, size }: { color: string; size: number }) => <Ionicons name={"${icon}" as any} size={size} color={color} />` : "";
1897
- return ` <_Drawer_${navFnName}.Screen name="${canonicalRoute(page)}" component={${names.componentName}} options={{ title: "${label}"${iconOpt} }} />`;
1898
- }).join("\n");
1899
- subNavigatorFunctions.push(
1900
- `const _Drawer_${navFnName} = createDrawerNavigator();
1901
- function ${navFnName}() {
1902
- return (
1903
- <_Drawer_${navFnName}.Navigator initialRouteName="${firstRoute}"${screenOptsAttr}>
1904
- ${drawerScreenDecls}
1905
- </_Drawer_${navFnName}.Navigator>
1906
- );
1907
- }`
1908
- );
1909
- } else {
1910
- const stackScreenDecls = groupScreens.map(({ page, names }) => {
1911
- const sc = navScreenByPageId.get(page.id);
1912
- const title = sc?.name && sc.name !== page.name ? sc.name : page.name;
1913
- return ` <_Stack_${navFnName}.Screen name="${canonicalRoute(page)}" options={{ title: "${title}", headerShown: false }}>
1914
- {(props: any) => <SafeScreen><${names.componentName} {...props} /></SafeScreen>}
1915
- </_Stack_${navFnName}.Screen>`;
1916
- }).join("\n");
1917
- subNavigatorFunctions.push(
1918
- `const _Stack_${navFnName} = createStackNavigator();
1919
- function ${navFnName}() {
1920
- return (
1921
- <_Stack_${navFnName}.Navigator initialRouteName="${firstRoute}" screenOptions={{ headerShown: false }}>
1922
- ${stackScreenDecls}
1923
- </_Stack_${navFnName}.Navigator>
1924
- );
1925
- }`
1926
- );
1927
- }
1928
- rootStackScreens.push(
1929
- ` <RootStack.Screen name="${folder}" component={${navFnName}} options={{ headerShown: false }} />`
1930
- );
1931
- }
1932
- const rootInitialRoute = groups[0] ? groupFolder(groups[0].name) : "home";
1933
- const navigatorImports = [`import { createStackNavigator } from '@react-navigation/stack';`];
1934
- if (needsTabs) navigatorImports.push(`import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
1935
- import { Ionicons } from '@expo/vector-icons';`);
1936
- if (needsDrawer) navigatorImports.push(`import { createDrawerNavigator } from '@react-navigation/drawer';
1937
- import { Ionicons } from '@expo/vector-icons';`);
1938
- const gestureHandlerImport = needsDrawer ? `import 'react-native-gesture-handler';
1939
- ` : "";
1940
- const gsImport = project.globalState?.length ? `
1941
- import { GlobalStateProvider } from './src/providers/GlobalStateProvider';` : "";
1942
- const gsOpen = project.globalState?.length ? "\n <GlobalStateProvider>" : "";
1943
- const gsClose = project.globalState?.length ? "\n </GlobalStateProvider>" : "";
1944
- return `${gestureHandlerImport}import React from 'react';
1945
- import { NavigationContainer } from '@react-navigation/native';
1946
- ${navigatorImports.join("\n")}
1947
- import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
1948
- import { FoundationProvider } from '@flipova/foundation';
1949
- import config from './flipova.config';${gsImport}
1950
- ${importLines.join("\n")}
1951
-
1952
- const RootStack = createStackNavigator();
1953
-
1954
- const SafeScreen = ({ children }: { children: React.ReactNode }) => (
1955
- <SafeAreaView style={{ flex: 1 }}>{children}</SafeAreaView>
1956
- );
1957
-
1958
- ${subNavigatorFunctions.join("\n\n")}
1959
-
1960
- export default function App() {
1961
- return (
1962
- <SafeAreaProvider>
1963
- <FoundationProvider config={config}>${gsOpen}
1964
- <NavigationContainer>
1965
- <RootStack.Navigator initialRouteName="${rootInitialRoute}" screenOptions={{ headerShown: false }}>
1966
- ${rootStackScreens.join("\n")}
1967
- </RootStack.Navigator>
1968
- </NavigationContainer>${gsClose}
1969
- </FoundationProvider>
1970
- </SafeAreaProvider>
1971
- );
1972
- }
1973
- `;
1974
- }
1975
- function generateServiceConfig(service) {
1976
- const cfg = service.config;
1977
- const baseUrl = cfg.baseUrl || "";
1978
- const apiKey = cfg.apiKey || "";
1979
- const headers = cfg.headers ? JSON.stringify(cfg.headers, null, 2) : "{}";
1980
- if (service.type === "supabase") {
1981
- return `import { createClient } from "@supabase/supabase-js";
1982
-
1983
- const SUPABASE_URL = ${JSON.stringify(baseUrl)};
1984
- const SUPABASE_KEY = ${JSON.stringify(apiKey)};
1985
-
1986
- export const ${service.id} = createClient(SUPABASE_URL, SUPABASE_KEY);
1987
- `;
1988
- }
1989
- if (service.type === "firebase") {
1990
- return `import { initializeApp } from "firebase/app";
1991
-
1992
- const firebaseConfig = ${JSON.stringify(cfg, null, 2)};
1993
-
1994
- export const ${service.id} = initializeApp(firebaseConfig);
1995
- `;
1996
- }
1997
- return `const BASE_URL = ${JSON.stringify(baseUrl)};
1998
- const DEFAULT_HEADERS: Record<string, string> = {
1999
- "Content-Type": "application/json",
2000
- ${apiKey ? `"Authorization": "Bearer " + ${JSON.stringify(apiKey)},` : ""}
2001
- ...${headers},
2002
- };
2003
-
2004
- async function request<T = any>(method: string, path: string, body?: any): Promise<T> {
2005
- const res = await fetch(BASE_URL + path, {
2006
- method,
2007
- headers: DEFAULT_HEADERS,
2008
- ...(body ? { body: JSON.stringify(body) } : {}),
2009
- });
2010
- if (!res.ok) throw new Error(\`\${method} \${path} failed: \${res.status}\`);
2011
- return res.json();
2012
- }
2013
-
2014
- export const ${service.id} = {
2015
- get: <T = any>(path: string, body?: any) => request<T>("GET", path, body),
2016
- post: <T = any>(path: string, body?: any) => request<T>("POST", path, body),
2017
- put: <T = any>(path: string, body?: any) => request<T>("PUT", path, body),
2018
- patch: <T = any>(path: string, body?: any) => request<T>("PATCH", path, body),
2019
- del: <T = any>(path: string, body?: any) => request<T>("DELETE", path, body),
2020
- };
2021
- `;
2022
- }
2023
- function generateQueryController(query, project) {
2024
- const svc = project.services.find((s) => s.id === query.serviceId);
2025
- const svcName = svc?.id || query.serviceId;
2026
- const qName = normalizeQueryName(query.name);
2027
- const hookName = `use${capitalize(qName)}`;
2028
- const transform = query.transform ? `.then((d: any) => d.${query.transform})` : "";
2029
- return `/**
2030
- * Controller: ${qName}
2031
- * Service: ${svcName} \u2014 ${query.method} ${query.path}
2032
- *
2033
- * Auto-generated by Flipova Studio. Do not edit manually.
2034
- */
2035
- import { useState, useEffect, useCallback } from "react";
2036
- import { ${svcName} } from "../services/${svcName}";
2037
-
2038
- export interface ${capitalize(qName)}State<T = any> {
2039
- data: T | null;
2040
- loading: boolean;
2041
- error: string | null;
2042
- /** Call with optional body override for POST/PUT/PATCH queries */
2043
- refetch: (body?: Record<string, any>) => Promise<T | null>;
2044
- }
2045
-
2046
- export function ${hookName}<T = any>(): ${capitalize(qName)}State<T> {
2047
- const [data, setData] = useState<T | null>(null);
2048
- const [loading, setLoading] = useState(${query.autoFetch !== false});
2049
- const [error, setError] = useState<string | null>(null);
2050
-
2051
- const refetch = useCallback(async (body?: Record<string, any>): Promise<T | null> => {
2052
- setLoading(true);
2053
- setError(null);
2054
- try {
2055
- const result = await ${svcName}.${query.method === "GET" ? "get" : query.method === "DELETE" ? "del" : query.method.toLowerCase()}<T>(${JSON.stringify(query.path)}, body)${transform};
2056
- setData(result);
2057
- return result;
2058
- } catch (e: any) {
2059
- setError(e.message || "Request failed");
2060
- throw e;
2061
- } finally {
2062
- setLoading(false);
2063
- }
2064
- }, []);
2065
-
2066
- ${query.autoFetch !== false ? "useEffect(() => { refetch(); }, [refetch]);" : ""}
2067
-
2068
- return { data, loading, error, refetch };
2069
- }
2070
- `;
2071
- }
2072
- function generateAuthProvider(auth, project) {
2073
- if (auth.provider === "supabase") {
2074
- return `import React, { createContext, useContext, useEffect, useState } from "react";
2075
- import { useRouter, useSegments } from "expo-router";
2076
- import { ${auth.serviceId || "supabase"} } from "../../services/${auth.serviceId || "supabase"}";
2077
-
2078
- interface AuthCtx { user: any; session: any; loading: boolean; signIn: (email: string, password: string) => Promise<void>; signUp: (email: string, password: string) => Promise<void>; signOut: () => Promise<void>; }
2079
- const Ctx = createContext<AuthCtx | null>(null);
2080
- export const useAuth = () => { const c = useContext(Ctx); if (!c) throw new Error("useAuth outside AuthProvider"); return c; };
2081
-
2082
- export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
2083
- const [user, setUser] = useState<any>(null);
2084
- const [session, setSession] = useState<any>(null);
2085
- const [loading, setLoading] = useState(true);
2086
- const router = useRouter();
2087
- const segments = useSegments();
2088
-
2089
- useEffect(() => {
2090
- ${auth.serviceId || "supabase"}.auth.getSession().then(({ data }) => { setSession(data.session); setUser(data.session?.user ?? null); setLoading(false); });
2091
- const { data: { subscription } } = ${auth.serviceId || "supabase"}.auth.onAuthStateChange((_event, session) => { setSession(session); setUser(session?.user ?? null); });
2092
- return () => subscription.unsubscribe();
2093
- }, []);
2094
-
2095
- useEffect(() => {
2096
- if (loading) return;
2097
- const inAuth = segments[0] === "(auth)";
2098
- if (!user && !inAuth) router.replace("/${auth.loginScreen || "login"}");
2099
- else if (user && inAuth) router.replace("/${auth.redirectAfterLogin || ""}");
2100
- }, [user, segments, loading]);
2101
-
2102
- const signIn = async (email: string, password: string) => { await ${auth.serviceId || "supabase"}.auth.signInWithPassword({ email, password }); };
2103
- const signUp = async (email: string, password: string) => { await ${auth.serviceId || "supabase"}.auth.signUp({ email, password }); };
2104
- const signOut = async () => { await ${auth.serviceId || "supabase"}.auth.signOut(); };
2105
-
2106
- return <Ctx.Provider value={{ user, session, loading, signIn, signUp, signOut }}>{children}</Ctx.Provider>;
2107
- };
2108
- `;
2109
- }
2110
- return `import React, { createContext, useContext, useState } from "react";
2111
- import { useRouter, useSegments } from "expo-router";
2112
-
2113
- interface AuthCtx { user: any; loading: boolean; signIn: (email: string, password: string) => Promise<void>; signOut: () => Promise<void>; }
2114
- const Ctx = createContext<AuthCtx | null>(null);
2115
- export const useAuth = () => { const c = useContext(Ctx); if (!c) throw new Error("useAuth outside AuthProvider"); return c; };
2116
-
2117
- export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
2118
- const [user, setUser] = useState<any>(null);
2119
- const [loading, setLoading] = useState(false);
2120
-
2121
- const signIn = async (email: string, password: string) => { /* TODO: implement */ setUser({ email }); };
2122
- const signOut = async () => { setUser(null); };
2123
-
2124
- return <Ctx.Provider value={{ user, loading, signIn, signOut }}>{children}</Ctx.Provider>;
2125
- };
2126
- `;
2127
- }
2128
- function generateUseAuth(auth) {
2129
- return `export { useAuth } from "../app/providers/AuthProvider";
2130
- `;
2131
- }
2132
- function generateEasConfig() {
2133
- return JSON.stringify({
2134
- cli: { version: ">= 12.0.0" },
2135
- build: {
2136
- development: { developmentClient: true, distribution: "internal" },
2137
- preview: { distribution: "internal" },
2138
- production: {}
2139
- },
2140
- submit: {
2141
- production: {}
2142
- }
2143
- }, null, 2);
2144
- }
2145
- function generateGithubWorkflow(project) {
2146
- return `name: Build & Deploy
2147
- on:
2148
- push:
2149
- branches: [main]
2150
- pull_request:
2151
- branches: [main]
2152
-
2153
- jobs:
2154
- build:
2155
- runs-on: ubuntu-latest
2156
- steps:
2157
- - uses: actions/checkout@v4
2158
- - uses: actions/setup-node@v4
2159
- with:
2160
- node-version: 20
2161
- cache: npm
2162
- - run: npm ci
2163
- - run: npx expo export --platform web
2164
- - uses: expo/expo-github-action@v8
2165
- with:
2166
- eas-version: latest
2167
- token: \${{ secrets.EXPO_TOKEN }}
2168
- - run: eas build --platform all --non-interactive --no-wait
2169
- if: github.ref == 'refs/heads/main'
2170
- `;
2171
- }
2172
- function generatePageTest(page) {
2173
- const { componentName } = deriveScreenNames(page.name, page.route);
2174
- return `import React from "react";
2175
- import { render } from "@testing-library/react-native";
2176
- import ${componentName} from "../src/screens/${componentName}";
2177
-
2178
- describe("${componentName}", () => {
2179
- it("renders without crashing", () => {
2180
- const { toJSON } = render(<${componentName} />);
2181
- expect(toJSON()).toBeTruthy();
2182
- });
2183
-
2184
- it("matches snapshot", () => {
2185
- const { toJSON } = render(<${componentName} />);
2186
- expect(toJSON()).toMatchSnapshot();
2187
- });
2188
- });
2189
- `;
2190
- }
2191
- function generateStorageHook() {
2192
- return `import { useState, useEffect, useCallback } from "react";
2193
- import AsyncStorage from "@react-native-async-storage/async-storage";
2194
-
2195
- export function useStorage<T = string>(key: string, defaultValue: T): [T, (value: T) => Promise<void>, boolean] {
2196
- const [value, setValue] = useState<T>(defaultValue);
2197
- const [loading, setLoading] = useState(true);
2198
-
2199
- useEffect(() => {
2200
- AsyncStorage.getItem(key).then(stored => {
2201
- if (stored !== null) {
2202
- try { setValue(JSON.parse(stored)); } catch { setValue(stored as unknown as T); }
2203
- }
2204
- setLoading(false);
2205
- });
2206
- }, [key]);
2207
-
2208
- const set = useCallback(async (newValue: T) => {
2209
- setValue(newValue);
2210
- await AsyncStorage.setItem(key, JSON.stringify(newValue));
2211
- }, [key]);
2212
-
2213
- return [value, set, loading];
2214
- }
2215
-
2216
- export function useSecureStorage<T = string>(key: string, defaultValue: T): [T, (value: T) => Promise<void>, boolean] {
2217
- const [value, setValue] = useState<T>(defaultValue);
2218
- const [loading, setLoading] = useState(true);
2219
-
2220
- useEffect(() => {
2221
- import("expo-secure-store").then(SecureStore => {
2222
- SecureStore.getItemAsync(key).then(stored => {
2223
- if (stored !== null) {
2224
- try { setValue(JSON.parse(stored)); } catch { setValue(stored as unknown as T); }
2225
- }
2226
- setLoading(false);
2227
- });
2228
- });
2229
- }, [key]);
2230
-
2231
- const set = useCallback(async (newValue: T) => {
2232
- setValue(newValue);
2233
- const SecureStore = await import("expo-secure-store");
2234
- await SecureStore.setItemAsync(key, JSON.stringify(newValue));
2235
- }, [key]);
2236
-
2237
- return [value, set, loading];
2238
- }
2239
- `;
2240
- }
2241
- function generateConstants(constants) {
2242
- const lines = constants.map((c) => `export const ${c.key} = ${JSON.stringify(c.value)};`);
2243
- return lines.join("\n") + "\n";
2244
- }
2245
- function generateGlobalStateProvider(state) {
2246
- const stateLines = state.map((s) => {
2247
- const def = s.default !== void 0 ? JSON.stringify(s.default) : s.type === "string" ? '""' : s.type === "number" ? "0" : s.type === "boolean" ? "false" : s.type === "array" ? "[]" : "{}";
2248
- return ` const [${s.name}, set${capitalize(s.name)}] = useState(${def});`;
2249
- });
2250
- const ctxFields = state.map((s) => `${s.name}, set${capitalize(s.name)}`).join(", ");
2251
- return `import React, { createContext, useContext, useState } from "react";
2252
-
2253
- interface GlobalState {
2254
- ${state.map((s) => ` ${s.name}: ${s.type === "array" ? "any[]" : s.type === "object" ? "Record<string, any>" : s.type};`).join("\n")}
2255
- ${state.map((s) => ` set${capitalize(s.name)}: (v: any) => void;`).join("\n")}
2256
- }
2257
-
2258
- const Ctx = createContext<GlobalState | null>(null);
2259
- export const useGlobalState = () => { const c = useContext(Ctx); if (!c) throw new Error("useGlobalState outside provider"); return c; };
2260
-
2261
- export const GlobalStateProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
2262
- ${stateLines.join("\n")}
2263
- return <Ctx.Provider value={{ ${ctxFields} }}>{children}</Ctx.Provider>;
2264
- };
2265
- `;
2266
- }
2267
- function createRouter(studioDir, projectDir) {
2268
- const router = Router();
2269
- const projectFile = path2__default.join(studioDir, "project.json");
2270
- function loadProject() {
2271
- if (fs2__default.existsSync(projectFile)) {
2272
- return JSON.parse(fs2__default.readFileSync(projectFile, "utf-8"));
2273
- }
2274
- const project = {
2275
- name: "My App",
2276
- version: "1.0.0",
2277
- theme: "light",
2278
- pages: [],
2279
- services: [],
2280
- navigation: { type: "stack", screens: [] }
2281
- };
2282
- saveProject(project);
2283
- return project;
2284
- }
2285
- function saveProject(project) {
2286
- fs2__default.writeFileSync(projectFile, JSON.stringify(project, null, 2));
2287
- }
2288
- router.get("/project", (_req, res) => {
2289
- res.json(loadProject());
2290
- });
2291
- router.put("/project", (req, res) => {
2292
- saveProject(req.body);
2293
- res.json({ ok: true });
2294
- });
2295
- router.post("/project/reset", (_req, res) => {
2296
- const project = {
2297
- name: "My App",
2298
- version: "1.0.0",
2299
- theme: "light",
2300
- pages: [],
2301
- services: [],
2302
- navigation: { type: "stack", screens: [] }
2303
- };
2304
- project.screenGroups = [{ id: "grp_default", name: "tabs", type: "tabs", screenIds: [] }];
2305
- saveProject(project);
2306
- const generatedDir = path2__default.join(projectDir, "generated");
2307
- if (fs2__default.existsSync(generatedDir)) {
2308
- fs2__default.rmSync(generatedDir, { recursive: true, force: true });
2309
- }
2310
- const broadcast = _req.app.broadcast;
2311
- if (broadcast) broadcast("project:reset", project);
2312
- res.json(project);
2313
- });
2314
- router.get("/registry", (_req, res) => {
2315
- res.json({
2316
- layouts: layoutRegistry,
2317
- components: componentRegistry,
2318
- blocks: blockRegistry,
2319
- primitives: primitiveRegistry
2320
- });
2321
- });
2322
- router.get("/registry/layouts", (_req, res) => {
2323
- res.json(layoutRegistry);
2324
- });
2325
- router.get("/registry/components", (_req, res) => {
2326
- res.json(componentRegistry);
2327
- });
2328
- router.get("/registry/blocks", (_req, res) => {
2329
- res.json(blockRegistry);
2330
- });
2331
- router.post("/pages", (req, res) => {
2332
- const project = loadProject();
2333
- const page = createPage(req.body.name, req.body.layoutId);
2334
- project.pages.push(page);
2335
- project.navigation.screens.push({ name: page.name, pageId: page.id });
2336
- const screenGroups = project.screenGroups || [];
2337
- let tabsGroup = screenGroups.find((g) => g.type === "tabs");
2338
- if (!tabsGroup) {
2339
- tabsGroup = { id: "grp_" + Date.now(), name: "tabs", type: "tabs", screenIds: [] };
2340
- screenGroups.push(tabsGroup);
2341
- }
2342
- tabsGroup.screenIds.push(page.id);
2343
- project.screenGroups = screenGroups;
2344
- saveProject(project);
2345
- const broadcast = req.app.broadcast;
2346
- if (broadcast) broadcast("page:created", page);
2347
- res.json(page);
2348
- });
2349
- router.put("/pages/:id", (req, res) => {
2350
- const project = loadProject();
2351
- const index = project.pages.findIndex((p) => p.id === req.params.id);
2352
- if (index === -1) {
2353
- res.status(404).json({ error: "Page not found" });
2354
- return;
2355
- }
2356
- project.pages[index] = { ...req.body, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
2357
- saveProject(project);
2358
- const broadcast = req.app.broadcast;
2359
- if (broadcast) broadcast("page:updated", project.pages[index]);
2360
- res.json(project.pages[index]);
2361
- });
2362
- router.delete("/pages/:id", (req, res) => {
2363
- const project = loadProject();
2364
- project.pages = project.pages.filter((p) => p.id !== req.params.id);
2365
- project.navigation.screens = project.navigation.screens.filter((s) => s.pageId !== req.params.id);
2366
- if (project.screenGroups) {
2367
- project.screenGroups = project.screenGroups.map((g) => ({
2368
- ...g,
2369
- screenIds: (g.screenIds || []).filter((sid) => sid !== req.params.id)
2370
- }));
2371
- }
2372
- saveProject(project);
2373
- const broadcast = req.app.broadcast;
2374
- if (broadcast) broadcast("page:deleted", { id: req.params.id });
2375
- res.json({ ok: true });
2376
- });
2377
- router.put("/pages/:id/rename", (req, res) => {
2378
- const { name } = req.body;
2379
- if (!name || !name.trim()) {
2380
- res.status(400).json({ error: "Name cannot be empty" });
2381
- return;
2382
- }
2383
- const project = loadProject();
2384
- const id = req.params.id;
2385
- const page = project.pages.find((p) => p.id === id);
2386
- if (!page) {
2387
- res.status(404).json({ error: "Page not found" });
2388
- return;
2389
- }
2390
- const newRoute = pageNameToRoute(name);
2391
- const conflict = project.pages.find((p) => p.id !== id && p.route === newRoute);
2392
- if (conflict) {
2393
- res.status(409).json({ error: `Route already exists: ${newRoute}` });
2394
- return;
2395
- }
2396
- const { project: updatedProject, oldRoute } = renamePage(project, id, name);
2397
- saveProject(updatedProject);
2398
- const broadcast = req.app.broadcast;
2399
- if (broadcast) broadcast("page:renamed", { id, name, route: newRoute, oldRoute });
2400
- res.json({ id, name, route: newRoute, oldRoute });
2401
- });
2402
- router.put("/project/theme", (req, res) => {
2403
- const project = loadProject();
2404
- project.theme = req.body.theme;
2405
- saveProject(project);
2406
- const broadcast = req.app.broadcast;
2407
- if (broadcast) broadcast("theme:changed", { theme: project.theme });
2408
- res.json({ ok: true });
2409
- });
2410
- router.put("/project/navigation", (req, res) => {
2411
- const project = loadProject();
2412
- project.navigation = req.body;
2413
- saveProject(project);
2414
- res.json({ ok: true });
2415
- });
2416
- router.post("/project/services", (req, res) => {
2417
- const project = loadProject();
2418
- project.services.push(req.body);
2419
- saveProject(project);
2420
- res.json({ ok: true });
2421
- });
2422
- router.post("/generate", (req, res) => {
2423
- const project = loadProject();
2424
- const useLocalFoundation = req.body?.localFoundation === true;
2425
- const foundationSourcePath = path2__default.resolve(process.cwd(), "foundation");
2426
- const options = useLocalFoundation ? { foundationMode: "local", foundationSourcePath } : void 0;
2427
- const { files } = generateProject(project, options);
2428
- const outputDir = path2__default.join(projectDir, "generated");
2429
- for (const file of files) {
2430
- const filePath = path2__default.join(outputDir, file.path);
2431
- fs2__default.mkdirSync(path2__default.dirname(filePath), { recursive: true });
2432
- fs2__default.writeFileSync(filePath, file.content);
2433
- }
2434
- res.json({ ok: true, files: files.map((f) => f.path), outputDir });
2435
- });
2436
- router.post("/generate/all", (req, res) => {
2437
- const project = loadProject();
2438
- const useLocalFoundation = req.body?.localFoundation === true;
2439
- const foundationSourcePath = path2__default.resolve(process.cwd(), "foundation");
2440
- const options = useLocalFoundation ? { foundationMode: "local", foundationSourcePath } : void 0;
2441
- const { files } = generateProject(project, options);
2442
- const outputDir = path2__default.join(projectDir, "generated");
2443
- for (const file of files) {
2444
- const filePath = path2__default.join(outputDir, file.path);
2445
- fs2__default.mkdirSync(path2__default.dirname(filePath), { recursive: true });
2446
- fs2__default.writeFileSync(filePath, file.content);
2447
- }
2448
- res.json({ ok: true, files });
2449
- });
2450
- router.post("/generate/write", (req, res) => {
2451
- const { path: filePath, content } = req.body;
2452
- if (!filePath || typeof content !== "string") {
2453
- res.status(400).json({ error: "Missing path or content" });
2454
- return;
2455
- }
2456
- const outputDir = path2__default.join(projectDir, "generated");
2457
- const fullPath = path2__default.join(outputDir, filePath);
2458
- if (!fullPath.startsWith(outputDir)) {
2459
- res.status(403).json({ error: "Forbidden" });
2460
- return;
2461
- }
2462
- fs2__default.mkdirSync(path2__default.dirname(fullPath), { recursive: true });
2463
- fs2__default.writeFileSync(fullPath, content);
2464
- const broadcast = req.app.broadcast;
2465
- if (broadcast) broadcast("file:written", { path: filePath });
2466
- res.json({ ok: true });
2467
- });
2468
- router.post("/generate/preview/:pageId", (req, res) => {
2469
- const project = loadProject();
2470
- const page = project.pages.find((p) => p.id === req.params.pageId);
2471
- if (!page) {
2472
- res.status(404).json({ error: "Page not found" });
2473
- return;
2474
- }
2475
- res.json({ code: generatePageCode(page) });
2476
- });
2477
- router.get("/placeholder/users", (_req, res) => {
2478
- res.json([
2479
- { id: 1, name: "Alice Martin", email: "alice@example.com", role: "admin", avatar: "https://i.pravatar.cc/150?u=alice", createdAt: "2024-01-15" },
2480
- { id: 2, name: "Bob Dupont", email: "bob@example.com", role: "user", avatar: "https://i.pravatar.cc/150?u=bob", createdAt: "2024-02-20" },
2481
- { id: 3, name: "Carol Smith", email: "carol@example.com", role: "user", avatar: "https://i.pravatar.cc/150?u=carol", createdAt: "2024-03-10" }
2482
- ]);
2483
- });
2484
- router.get("/placeholder/users/:id", (req, res) => {
2485
- const users = {
2486
- "1": { id: 1, name: "Alice Martin", email: "alice@example.com", role: "admin", bio: "Product designer", avatar: "https://i.pravatar.cc/150?u=alice" },
2487
- "2": { id: 2, name: "Bob Dupont", email: "bob@example.com", role: "user", bio: "Developer", avatar: "https://i.pravatar.cc/150?u=bob" }
2488
- };
2489
- res.json(users[req.params.id] || { error: "Not found" });
2490
- });
2491
- router.get("/placeholder/posts", (_req, res) => {
2492
- res.json([
2493
- { id: 1, title: "Getting started with Flipova", body: "Lorem ipsum dolor sit amet...", userId: 1, tags: ["tutorial", "intro"], publishedAt: "2024-03-01", likes: 42 },
2494
- { id: 2, title: "Building mobile apps fast", body: "Consectetur adipiscing elit...", userId: 2, tags: ["mobile", "tips"], publishedAt: "2024-03-15", likes: 18 },
2495
- { id: 3, title: "Design systems in 2025", body: "Sed do eiusmod tempor...", userId: 1, tags: ["design", "systems"], publishedAt: "2024-04-01", likes: 67 }
2496
- ]);
2497
- });
2498
- router.get("/placeholder/products", (_req, res) => {
2499
- res.json([
2500
- { id: 1, name: "Pro Plan", price: 29.99, currency: "USD", category: "subscription", inStock: true, image: "https://picsum.photos/seed/prod1/200" },
2501
- { id: 2, name: "Team Plan", price: 79.99, currency: "USD", category: "subscription", inStock: true, image: "https://picsum.photos/seed/prod2/200" },
2502
- { id: 3, name: "Enterprise", price: 299.99, currency: "USD", category: "subscription", inStock: false, image: "https://picsum.photos/seed/prod3/200" }
2503
- ]);
2504
- });
2505
- router.get("/placeholder/stats", (_req, res) => {
2506
- res.json({
2507
- totalUsers: 1284,
2508
- activeToday: 342,
2509
- revenue: 48920.5,
2510
- growth: 12.4,
2511
- topCountries: ["FR", "US", "DE", "GB"],
2512
- chartData: [120, 145, 132, 178, 195, 210, 234]
2513
- });
2514
- });
2515
- router.post("/placeholder/auth/login", (req, res) => {
2516
- const { email, password } = req.body || {};
2517
- if (!email || !password) {
2518
- res.status(400).json({ error: "Missing credentials" });
2519
- return;
2520
- }
2521
- res.json({ token: "placeholder_jwt_token_" + Date.now(), user: { id: 1, email, name: "Demo User", role: "user" } });
2522
- });
2523
- router.post("/placeholder/users", (req, res) => {
2524
- const { name, email, role } = req.body || {};
2525
- res.status(201).json({ id: Date.now(), name: name || "New User", email: email || "user@example.com", role: role || "user", createdAt: (/* @__PURE__ */ new Date()).toISOString() });
2526
- });
2527
- router.put("/placeholder/users/:id", (req, res) => {
2528
- const { name, email, role } = req.body || {};
2529
- res.json({ id: Number(req.params.id), name: name || "Updated User", email: email || "user@example.com", role: role || "user", updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
2530
- });
2531
- router.patch("/placeholder/users/:id", (req, res) => {
2532
- res.json({ id: Number(req.params.id), ...req.body, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
2533
- });
2534
- router.delete("/placeholder/users/:id", (req, res) => {
2535
- res.json({ ok: true, deleted: Number(req.params.id) });
2536
- });
2537
- router.post("/placeholder/posts", (req, res) => {
2538
- const { title, body, userId } = req.body || {};
2539
- res.status(201).json({ id: Date.now(), title: title || "New Post", body: body || "", userId: userId || 1, publishedAt: (/* @__PURE__ */ new Date()).toISOString() });
2540
- });
2541
- router.put("/placeholder/posts/:id", (req, res) => {
2542
- res.json({ id: Number(req.params.id), ...req.body, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
2543
- });
2544
- router.delete("/placeholder/posts/:id", (req, res) => {
2545
- res.json({ ok: true, deleted: Number(req.params.id) });
2546
- });
2547
- router.post("/snack/export", (_req, res) => {
2548
- const generatedDir = path2__default.join(projectDir, "generated");
2549
- if (!fs2__default.existsSync(generatedDir)) {
2550
- res.status(400).json({ error: "No generated files found. Run /generate first." });
2551
- return;
2552
- }
2553
- let diskFiles = [];
2554
- function readDir(dir) {
2555
- for (const entry of fs2__default.readdirSync(dir, { withFileTypes: true })) {
2556
- const fullPath = path2__default.join(dir, entry.name);
2557
- if (entry.isDirectory()) {
2558
- readDir(fullPath);
2559
- } else {
2560
- if (entry.name.endsWith(".yml") || entry.name === ".gitignore" || entry.name === ".npmrc") continue;
2561
- const relativePath = path2__default.relative(generatedDir, fullPath).replace(/\\/g, "/");
2562
- try {
2563
- diskFiles.push({ path: relativePath, content: fs2__default.readFileSync(fullPath, "utf-8") });
2564
- } catch {
2565
- }
2566
- }
2567
- }
2568
- }
2569
- readDir(generatedDir);
2570
- const snackFiles = {};
2571
- for (const file of diskFiles) {
2572
- snackFiles[file.path] = { type: "CODE", contents: file.content };
2573
- }
2574
- let dependencies = {};
2575
- const pkgFile = diskFiles.find((f) => f.path === "package.json");
2576
- if (pkgFile) {
2577
- try {
2578
- const pkg = JSON.parse(pkgFile.content);
2579
- for (const [name, version] of Object.entries(pkg.dependencies || {})) {
2580
- dependencies[name] = { version: String(version).replace(/^[~^]/, "") };
2581
- }
2582
- } catch {
2583
- }
2584
- }
2585
- const project = loadProject();
2586
- res.json({ files: snackFiles, dependencies, name: project.name });
2587
- });
2588
- return router;
2589
- }
2590
-
2591
- // studio/server/index.ts
2592
- var DEFAULT_PORT = 4200;
2593
- function findStudioDist() {
2594
- const candidates = [
2595
- path2__default.resolve(__dirname, "../app/dist"),
2596
- path2__default.resolve(__dirname, "../../studio/app/dist"),
2597
- path2__default.resolve(__dirname, "../../../studio/app/dist"),
2598
- path2__default.resolve(process.cwd(), "studio/app/dist"),
2599
- path2__default.resolve(process.cwd(), "node_modules/@flipova/foundation/studio/app/dist")
2600
- ];
2601
- for (const p of candidates) {
2602
- if (fs2__default.existsSync(p) && fs2__default.existsSync(path2__default.join(p, "index.html"))) return p;
2603
- }
2604
- return null;
2605
- }
2606
- function startServer(options = {}) {
2607
- const port = options.port || DEFAULT_PORT;
2608
- const projectDir = options.projectDir || process.cwd();
2609
- const studioDir = path2__default.join(projectDir, ".flipova-studio");
2610
- if (!fs2__default.existsSync(studioDir)) {
2611
- fs2__default.mkdirSync(studioDir, { recursive: true });
2612
- }
2613
- const app = express();
2614
- app.use(express.json({ limit: "10mb" }));
2615
- app.use("/api", createRouter(studioDir, projectDir));
2616
- const dist = findStudioDist();
2617
- if (dist) {
2618
- app.use(express.static(dist));
2619
- app.get("/{0,}", (_req, res) => {
2620
- res.sendFile(path2__default.join(dist, "index.html"));
2621
- });
2622
- } else {
2623
- app.get("/", (_req, res) => {
2624
- res.status(503).json({ error: "Studio UI not built. Run: npm run build" });
2625
- });
2626
- }
2627
- const server = http.createServer(app);
2628
- const wss = new WebSocketServer({ server, path: "/ws" });
2629
- const clients = /* @__PURE__ */ new Set();
2630
- wss.on("connection", (ws) => {
2631
- clients.add(ws);
2632
- ws.on("close", () => clients.delete(ws));
2633
- });
2634
- const broadcast = (type, payload) => {
2635
- const msg = JSON.stringify({ type, payload });
2636
- for (const c of clients) if (c.readyState === WebSocket.OPEN) c.send(msg);
2637
- };
2638
- app.broadcast = broadcast;
2639
- server.listen(port, () => {
2640
- console.log(` UI: ${dist ? "ready" : "NOT BUILT (run npm run build)"}`);
2641
- });
2642
- return { app, server, wss, broadcast };
2643
- }
2644
-
2645
- export { collectQueryRefs, collectStateRefs, createNode, createPage, extractItemFields, findNode, findParent, findRepeatAncestor, generateId, generatePageCode, generateProject, insertChild, moveNode, pageNameToComponent, pageNameToRoute, removeNode, renamePage, startServer, updateProps };
2646
- //# sourceMappingURL=chunk-ECBM426M.mjs.map
2647
- //# sourceMappingURL=chunk-ECBM426M.mjs.map