@nodestackapp/server 2.5.0 → 2.6.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 (221) hide show
  1. package/README.md +40 -28
  2. package/dist/NodeStack.d.ts +1 -1
  3. package/dist/NodeStack.d.ts.map +1 -1
  4. package/dist/NodeStack.js +73 -12
  5. package/dist/NodeStack.js.map +1 -1
  6. package/dist/admin/AdminUIBundler.d.ts.map +1 -1
  7. package/dist/admin/AdminUIBundler.js +1 -0
  8. package/dist/admin/AdminUIBundler.js.map +1 -1
  9. package/dist/admin/ui/css/main.css +34 -0
  10. package/dist/admin/ui/css/webhooks.css +8 -0
  11. package/dist/admin/ui/index.html +19150 -17212
  12. package/dist/admin/ui/js/api-keys.js +1381 -0
  13. package/dist/admin/ui/js/app.js +667 -641
  14. package/dist/admin/ui/js/apps.js +496 -489
  15. package/dist/admin/ui/js/collections.js +486 -484
  16. package/dist/admin/ui/js/command-palette.js +683 -673
  17. package/dist/admin/ui/js/flows-designer.js +1125 -1076
  18. package/dist/admin/ui/js/flows.js +908 -890
  19. package/dist/admin/ui/js/functions-tester.js +1 -1
  20. package/dist/admin/ui/js/functions-workbench.js +1144 -1101
  21. package/dist/admin/ui/js/functions.js +980 -979
  22. package/dist/admin/ui/js/rules.js +1080 -775
  23. package/dist/admin/ui/js/schema.js +346 -304
  24. package/dist/admin/ui/js/views.js +1 -1
  25. package/dist/apps/AppManager.d.ts +1 -1
  26. package/dist/apps/AppManager.d.ts.map +1 -1
  27. package/dist/apps/AppManager.js +4 -18
  28. package/dist/apps/AppManager.js.map +1 -1
  29. package/dist/apps/AppRegistry.d.ts +1 -0
  30. package/dist/apps/AppRegistry.d.ts.map +1 -1
  31. package/dist/apps/AppRegistry.js +78 -23
  32. package/dist/apps/AppRegistry.js.map +1 -1
  33. package/dist/apps/AppScope.d.ts +0 -1
  34. package/dist/apps/AppScope.d.ts.map +1 -1
  35. package/dist/apps/AppScope.js +5 -15
  36. package/dist/apps/AppScope.js.map +1 -1
  37. package/dist/auth/ApiKeyService.d.ts +62 -2
  38. package/dist/auth/ApiKeyService.d.ts.map +1 -1
  39. package/dist/auth/ApiKeyService.js +503 -8
  40. package/dist/auth/ApiKeyService.js.map +1 -1
  41. package/dist/auth/AuthService.d.ts +30 -1
  42. package/dist/auth/AuthService.d.ts.map +1 -1
  43. package/dist/auth/AuthService.js +468 -65
  44. package/dist/auth/AuthService.js.map +1 -1
  45. package/dist/auth/oauth/AppleProvider.d.ts +2 -0
  46. package/dist/auth/oauth/AppleProvider.d.ts.map +1 -1
  47. package/dist/auth/oauth/AppleProvider.js +40 -3
  48. package/dist/auth/oauth/AppleProvider.js.map +1 -1
  49. package/dist/auth/oauth/BaseOAuthProvider.d.ts +3 -2
  50. package/dist/auth/oauth/BaseOAuthProvider.d.ts.map +1 -1
  51. package/dist/auth/oauth/BaseOAuthProvider.js +29 -3
  52. package/dist/auth/oauth/BaseOAuthProvider.js.map +1 -1
  53. package/dist/auth/oauth/DiscordProvider.d.ts.map +1 -1
  54. package/dist/auth/oauth/DiscordProvider.js +4 -1
  55. package/dist/auth/oauth/DiscordProvider.js.map +1 -1
  56. package/dist/auth/oauth/GitHubProvider.d.ts.map +1 -1
  57. package/dist/auth/oauth/GitHubProvider.js +4 -1
  58. package/dist/auth/oauth/GitHubProvider.js.map +1 -1
  59. package/dist/auth/oauth/GoogleProvider.d.ts.map +1 -1
  60. package/dist/auth/oauth/GoogleProvider.js +4 -1
  61. package/dist/auth/oauth/GoogleProvider.js.map +1 -1
  62. package/dist/auth/oauth/MicrosoftProvider.d.ts.map +1 -1
  63. package/dist/auth/oauth/MicrosoftProvider.js +4 -1
  64. package/dist/auth/oauth/MicrosoftProvider.js.map +1 -1
  65. package/dist/auth/oauth/OAuthProviderRegistry.d.ts +6 -2
  66. package/dist/auth/oauth/OAuthProviderRegistry.d.ts.map +1 -1
  67. package/dist/auth/oauth/OAuthProviderRegistry.js +25 -10
  68. package/dist/auth/oauth/OAuthProviderRegistry.js.map +1 -1
  69. package/dist/auth/oauth/types.d.ts +4 -2
  70. package/dist/auth/oauth/types.d.ts.map +1 -1
  71. package/dist/cli/cli.d.ts.map +1 -1
  72. package/dist/cli/cli.js +228 -12
  73. package/dist/cli/cli.js.map +1 -1
  74. package/dist/core/config/ConfigService.d.ts.map +1 -1
  75. package/dist/core/config/ConfigService.js +5 -3
  76. package/dist/core/config/ConfigService.js.map +1 -1
  77. package/dist/core/config/EnvLoader.d.ts +14 -0
  78. package/dist/core/config/EnvLoader.d.ts.map +1 -1
  79. package/dist/core/config/EnvLoader.js +44 -0
  80. package/dist/core/config/EnvLoader.js.map +1 -1
  81. package/dist/core/container/Container.d.ts +14 -0
  82. package/dist/core/container/Container.d.ts.map +1 -1
  83. package/dist/core/container/Container.js +32 -0
  84. package/dist/core/container/Container.js.map +1 -1
  85. package/dist/core/errors/AppError.d.ts +7 -7
  86. package/dist/core/errors/AppError.d.ts.map +1 -1
  87. package/dist/core/errors/AppError.js +18 -14
  88. package/dist/core/errors/AppError.js.map +1 -1
  89. package/dist/core/events/EventBus.d.ts.map +1 -1
  90. package/dist/core/events/EventBus.js +36 -6
  91. package/dist/core/events/EventBus.js.map +1 -1
  92. package/dist/core/maintenance/MaintenanceGate.d.ts +47 -0
  93. package/dist/core/maintenance/MaintenanceGate.d.ts.map +1 -1
  94. package/dist/core/maintenance/MaintenanceGate.js +265 -7
  95. package/dist/core/maintenance/MaintenanceGate.js.map +1 -1
  96. package/dist/core/plugins/PluginManager.d.ts +20 -1
  97. package/dist/core/plugins/PluginManager.d.ts.map +1 -1
  98. package/dist/core/plugins/PluginManager.js +231 -146
  99. package/dist/core/plugins/PluginManager.js.map +1 -1
  100. package/dist/core/plugins/types.d.ts +48 -31
  101. package/dist/core/plugins/types.d.ts.map +1 -1
  102. package/dist/database/DatabaseService.d.ts +1 -0
  103. package/dist/database/DatabaseService.d.ts.map +1 -1
  104. package/dist/database/DatabaseService.js +24 -6
  105. package/dist/database/DatabaseService.js.map +1 -1
  106. package/dist/database/drivers/DriverRegistry.d.ts +1 -0
  107. package/dist/database/drivers/DriverRegistry.d.ts.map +1 -1
  108. package/dist/database/drivers/DriverRegistry.js +29 -0
  109. package/dist/database/drivers/DriverRegistry.js.map +1 -1
  110. package/dist/database/drivers/IDatabaseDriver.d.ts +1 -0
  111. package/dist/database/drivers/IDatabaseDriver.d.ts.map +1 -1
  112. package/dist/database/drivers/MssqlDriver.d.ts.map +1 -1
  113. package/dist/database/drivers/MssqlDriver.js +8 -2
  114. package/dist/database/drivers/MssqlDriver.js.map +1 -1
  115. package/dist/database/drivers/NodeSqliteDriver.d.ts.map +1 -1
  116. package/dist/database/drivers/NodeSqliteDriver.js +15 -1
  117. package/dist/database/drivers/NodeSqliteDriver.js.map +1 -1
  118. package/dist/database/migrations/SystemMigrations.d.ts.map +1 -1
  119. package/dist/database/migrations/SystemMigrations.js +62 -5
  120. package/dist/database/migrations/SystemMigrations.js.map +1 -1
  121. package/dist/flows/FlowEngine.js.map +1 -1
  122. package/dist/flows/FlowService.d.ts +7 -1
  123. package/dist/flows/FlowService.d.ts.map +1 -1
  124. package/dist/flows/FlowService.js +126 -12
  125. package/dist/flows/FlowService.js.map +1 -1
  126. package/dist/flows/FlowValidator.d.ts +1 -0
  127. package/dist/flows/FlowValidator.d.ts.map +1 -1
  128. package/dist/flows/FlowValidator.js +76 -1
  129. package/dist/flows/FlowValidator.js.map +1 -1
  130. package/dist/flows/types.d.ts +14 -2
  131. package/dist/flows/types.d.ts.map +1 -1
  132. package/dist/functions/FunctionService.d.ts +5 -1
  133. package/dist/functions/FunctionService.d.ts.map +1 -1
  134. package/dist/functions/FunctionService.js +84 -33
  135. package/dist/functions/FunctionService.js.map +1 -1
  136. package/dist/functions/runtime/QuickJsWasmRuntime.d.ts.map +1 -1
  137. package/dist/functions/runtime/QuickJsWasmRuntime.js +19 -10
  138. package/dist/functions/runtime/QuickJsWasmRuntime.js.map +1 -1
  139. package/dist/functions/types.d.ts +16 -2
  140. package/dist/functions/types.d.ts.map +1 -1
  141. package/dist/http/HttpServer.d.ts +3 -0
  142. package/dist/http/HttpServer.d.ts.map +1 -1
  143. package/dist/http/HttpServer.js +153 -6
  144. package/dist/http/HttpServer.js.map +1 -1
  145. package/dist/http/controllers/ApiKeyController.d.ts +1 -0
  146. package/dist/http/controllers/ApiKeyController.d.ts.map +1 -1
  147. package/dist/http/controllers/ApiKeyController.js +47 -1
  148. package/dist/http/controllers/ApiKeyController.js.map +1 -1
  149. package/dist/http/controllers/AuthController.d.ts +12 -0
  150. package/dist/http/controllers/AuthController.d.ts.map +1 -1
  151. package/dist/http/controllers/AuthController.js +40 -2
  152. package/dist/http/controllers/AuthController.js.map +1 -1
  153. package/dist/http/controllers/FlowController.d.ts.map +1 -1
  154. package/dist/http/controllers/FlowController.js +45 -4
  155. package/dist/http/controllers/FlowController.js.map +1 -1
  156. package/dist/http/controllers/FunctionController.d.ts.map +1 -1
  157. package/dist/http/controllers/FunctionController.js +16 -2
  158. package/dist/http/controllers/FunctionController.js.map +1 -1
  159. package/dist/http/controllers/HealthController.js +2 -2
  160. package/dist/http/middleware/AppResolutionMiddleware.d.ts +1 -1
  161. package/dist/http/middleware/AppResolutionMiddleware.d.ts.map +1 -1
  162. package/dist/http/middleware/AppResolutionMiddleware.js +2 -3
  163. package/dist/http/middleware/AppResolutionMiddleware.js.map +1 -1
  164. package/dist/http/middleware/AuthMiddleware.d.ts.map +1 -1
  165. package/dist/http/middleware/AuthMiddleware.js +6 -3
  166. package/dist/http/middleware/AuthMiddleware.js.map +1 -1
  167. package/dist/http/middleware/ChaosMiddleware.js +6 -6
  168. package/dist/http/middleware/ChaosMiddleware.js.map +1 -1
  169. package/dist/index.d.ts +2 -2
  170. package/dist/index.d.ts.map +1 -1
  171. package/dist/index.js +6 -2
  172. package/dist/index.js.map +1 -1
  173. package/dist/queue/QueueService.d.ts +9 -0
  174. package/dist/queue/QueueService.d.ts.map +1 -1
  175. package/dist/queue/QueueService.js +143 -60
  176. package/dist/queue/QueueService.js.map +1 -1
  177. package/dist/queue/drivers/SqliteQueueDriver.d.ts +3 -0
  178. package/dist/queue/drivers/SqliteQueueDriver.d.ts.map +1 -1
  179. package/dist/queue/drivers/SqliteQueueDriver.js +315 -255
  180. package/dist/queue/drivers/SqliteQueueDriver.js.map +1 -1
  181. package/dist/records/FtsService.d.ts +7 -3
  182. package/dist/records/FtsService.d.ts.map +1 -1
  183. package/dist/records/FtsService.js +69 -5
  184. package/dist/records/FtsService.js.map +1 -1
  185. package/dist/records/QueryFilterParser.d.ts.map +1 -1
  186. package/dist/records/QueryFilterParser.js +58 -20
  187. package/dist/records/QueryFilterParser.js.map +1 -1
  188. package/dist/records/RecordSanitizer.d.ts.map +1 -1
  189. package/dist/records/RecordSanitizer.js +32 -4
  190. package/dist/records/RecordSanitizer.js.map +1 -1
  191. package/dist/records/RecordService.d.ts +6 -0
  192. package/dist/records/RecordService.d.ts.map +1 -1
  193. package/dist/records/RecordService.js +95 -14
  194. package/dist/records/RecordService.js.map +1 -1
  195. package/dist/records/RecordValidator.d.ts +10 -0
  196. package/dist/records/RecordValidator.d.ts.map +1 -1
  197. package/dist/records/RecordValidator.js +110 -2
  198. package/dist/records/RecordValidator.js.map +1 -1
  199. package/dist/records/fts/IFtsDriver.d.ts +7 -6
  200. package/dist/records/fts/IFtsDriver.d.ts.map +1 -1
  201. package/dist/records/fts/MssqlFtsDriver.d.ts +5 -1
  202. package/dist/records/fts/MssqlFtsDriver.d.ts.map +1 -1
  203. package/dist/records/fts/MssqlFtsDriver.js +35 -3
  204. package/dist/records/fts/MssqlFtsDriver.js.map +1 -1
  205. package/dist/records/fts/PostgresFtsDriver.d.ts +9 -2
  206. package/dist/records/fts/PostgresFtsDriver.d.ts.map +1 -1
  207. package/dist/records/fts/PostgresFtsDriver.js +116 -11
  208. package/dist/records/fts/PostgresFtsDriver.js.map +1 -1
  209. package/dist/records/fts/SqliteFts5Driver.d.ts +7 -1
  210. package/dist/records/fts/SqliteFts5Driver.d.ts.map +1 -1
  211. package/dist/records/fts/SqliteFts5Driver.js +66 -6
  212. package/dist/records/fts/SqliteFts5Driver.js.map +1 -1
  213. package/dist/schema/OpenApiGenerator.d.ts.map +1 -1
  214. package/dist/schema/OpenApiGenerator.js +103 -3
  215. package/dist/schema/OpenApiGenerator.js.map +1 -1
  216. package/dist/schema/models/Field.d.ts +1 -0
  217. package/dist/schema/models/Field.d.ts.map +1 -1
  218. package/dist/templates/definitions/ecommerce.js +6 -6
  219. package/dist/templates/definitions/ecommerce.js.map +1 -1
  220. package/dist/webhooks/WebhookService.js +1 -1
  221. package/package.json +4 -3
@@ -1,1076 +1,1125 @@
1
- // Functions Flow Visual Designer & Workbench Module for NodeStack Admin UI
2
- // Provides Visual Step Card Builder, Live Auto-Layout SVG Diagram, and Interactive Test Runner
3
-
4
- let designerState = {
5
- activeFlow: null,
6
- activeMode: 'visual', // 'visual' | 'code'
7
- cmDslEditor: null,
8
- selectedStepName: null,
9
- isTestDrawerOpen: false,
10
- testPayload: '{\n "order": {\n "amount": 250,\n "discount": 25\n }\n}',
11
- latestExecution: null,
12
- addStepSelectedType: 'Task',
13
- };
14
-
15
- if (typeof window !== 'undefined') {
16
- window.designerState = designerState;
17
- }
18
-
19
- // ==========================================
20
- // 1. Navigation & Workbench Shell
21
- // ==========================================
22
-
23
- function getDesignerFlowsApiBase() {
24
- if (typeof getFlowsApiBase === 'function') return getFlowsApiBase();
25
- const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : (typeof state !== 'undefined' && state?.activeApp?.slug ? state.activeApp.slug : 'default');
26
- return slug && slug !== 'default' ? `/api/apps/${slug}/flows` : '/api/flows';
27
- }
28
-
29
- function getDesignerFunctionsApiBase() {
30
- if (typeof getFunctionsApiBase === 'function') return getFunctionsApiBase();
31
- const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : (typeof state !== 'undefined' && state?.activeApp?.slug ? state.activeApp.slug : 'default');
32
- return slug && slug !== 'default' ? `/api/apps/${slug}/functions` : '/api/functions';
33
- }
34
-
35
- async function openFlowDesigner(flowId, openTestDrawer = false, pushState = true) {
36
- try {
37
- const base = getDesignerFlowsApiBase();
38
- const flow = await api(`${base}/${encodeURIComponent(flowId)}`);
39
- flowsState.currentView = 'designer';
40
- flowsState.activeFlowForEdit = flow;
41
- designerState.activeFlow = JSON.parse(JSON.stringify(flow));
42
- designerState.latestExecution = null;
43
- designerState.isTestDrawerOpen = !!openTestDrawer;
44
-
45
- if (pushState && typeof updateUrl === 'function') {
46
- const flowIdentifier = flow.name ? encodeURIComponent(flow.name) : encodeURIComponent(flow.id);
47
- updateUrl('/_/flows/' + flowIdentifier);
48
- }
49
-
50
- if (typeof updateBreadcrumbs === 'function') {
51
- updateBreadcrumbs();
52
- }
53
-
54
- if (typeof loadFunctionsForPicker === 'function') {
55
- await loadFunctionsForPicker();
56
- }
57
-
58
- renderFlowDesignerWorkbench(designerState.activeFlow);
59
- } catch (err) {
60
- toast('Failed to load flow: ' + (err.message || err), 'error');
61
- }
62
- }
63
-
64
- function closeFlowDesigner(pushState = true) {
65
- flowsState.currentView = 'list';
66
- flowsState.activeFlowForEdit = null;
67
- designerState.activeFlow = null;
68
- designerState.isTestDrawerOpen = false;
69
-
70
- if (pushState && typeof updateUrl === 'function') {
71
- const sub = (typeof flowsState !== 'undefined' && flowsState.subTab === 'executions') ? '/executions' : '';
72
- updateUrl('/_/flows' + sub);
73
- }
74
-
75
- if (typeof updateBreadcrumbs === 'function') {
76
- updateBreadcrumbs();
77
- }
78
-
79
- if (typeof renderFlowsView === 'function') {
80
- renderFlowsView();
81
- }
82
- }
83
-
84
- function renderTriggerConfigHtml(flow) {
85
- const triggerType = flow.triggerType || 'http';
86
-
87
- if (triggerType === 'event') {
88
- return `
89
- <input
90
- type="text"
91
- id="flow-edit-event-trigger"
92
- class="flow-field-input"
93
- placeholder="collection:action (e.g. orders:create)"
94
- value="${escapeHtml(flow.eventTrigger || '')}"
95
- style="width: 190px; padding: 0.25rem 0.5rem; font-size: 0.8rem; font-family: var(--font-mono, monospace);"
96
- title="Triggered automatically on database record event (e.g. orders:create, users:update, *:delete)"
97
- onchange="updateFlowMeta('eventTrigger', this.value)"
98
- />
99
- <span style="font-size: 0.72rem; color: var(--text-muted); cursor: help;" title="Format: &lt;collection&gt;:&lt;action&gt;&#10;Examples:&#10;• orders:create - Run when order is created&#10;• users:update - Run when user is updated&#10;• *:delete - Run when any record is deleted">ℹ️</span>
100
- `;
101
- }
102
-
103
- if (triggerType === 'http') {
104
- const base = getDesignerFlowsApiBase();
105
- const endpointPath = `${base}/${flow.id}/execute`;
106
- return `
107
- <span style="display: inline-flex; align-items: center; gap: 4px; font-size: 0.75rem; color: var(--text-muted);">
108
- Endpoint:
109
- <code
110
- style="font-size: 0.72rem; color: var(--accent-primary); background: var(--bg-main, #0f172a); padding: 2px 6px; border-radius: 4px; border: 1px solid var(--border-subtle); cursor: pointer;"
111
- data-endpoint="POST ${endpointPath}"
112
- title="Click to copy endpoint"
113
- onclick="if (navigator.clipboard) { navigator.clipboard.writeText(this.getAttribute('data-endpoint')); toast('Copied endpoint: ' + this.getAttribute('data-endpoint'), 'success'); }"
114
- >
115
- POST ${endpointPath} 📋
116
- </code>
117
- </span>
118
- `;
119
- }
120
-
121
- // Manual
122
- return `
123
- <span style="font-size: 0.75rem; color: var(--text-muted); font-style: italic;">
124
- Triggered on-demand via Run / Test Flow
125
- </span>
126
- `;
127
- }
128
-
129
- function handleFlowTriggerTypeChange(newType) {
130
- if (!designerState.activeFlow) return;
131
- designerState.activeFlow.triggerType = newType;
132
- if (newType === 'event') {
133
- if (!designerState.activeFlow.eventTrigger) {
134
- designerState.activeFlow.eventTrigger = 'orders:create';
135
- }
136
- } else {
137
- designerState.activeFlow.eventTrigger = null;
138
- }
139
-
140
- const configArea = document.getElementById('flow-trigger-config-area');
141
- if (configArea) {
142
- configArea.innerHTML = renderTriggerConfigHtml(designerState.activeFlow);
143
- }
144
- }
145
-
146
- function renderFlowDesignerWorkbench(flow) {
147
- const container = document.getElementById('page-view-flows') || document.getElementById('main-body');
148
- if (!container || !flow) return;
149
-
150
- container.innerHTML = `
151
- <div class="flows-container">
152
- <!-- Toolbar -->
153
- <div class="flows-designer-toolbar">
154
- <div style="display: flex; align-items: center; gap: 1rem; flex-wrap: wrap;">
155
- <button class="btn btn-secondary btn-sm" onclick="closeFlowDesigner()">
156
- ← Back to Flows
157
- </button>
158
- <div style="display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap;">
159
- <input
160
- type="text"
161
- id="flow-edit-name"
162
- class="flow-field-input"
163
- value="${escapeHtml(flow.name)}"
164
- style="font-weight: 700; font-size: 1rem; width: 210px;"
165
- onchange="updateFlowMeta('name', this.value)"
166
- />
167
- <div style="display: flex; align-items: center; gap: 0.4rem; background: var(--bg-card); padding: 3px 8px; border-radius: 6px; border: 1px solid var(--border-subtle);">
168
- <span style="font-size: 0.72rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.04em;">Trigger:</span>
169
- <select
170
- id="flow-edit-trigger-type"
171
- class="flow-field-select"
172
- style="width: 110px; padding: 0.25rem 0.5rem; font-size: 0.8rem; font-weight: 600;"
173
- onchange="handleFlowTriggerTypeChange(this.value)"
174
- >
175
- <option value="http" ${flow.triggerType === 'http' ? 'selected' : ''}>HTTP API</option>
176
- <option value="event" ${flow.triggerType === 'event' ? 'selected' : ''}>DB Event</option>
177
- <option value="manual" ${flow.triggerType === 'manual' ? 'selected' : ''}>Manual</option>
178
- </select>
179
- <div id="flow-trigger-config-area" style="display: flex; align-items: center; gap: 6px;">
180
- ${renderTriggerConfigHtml(flow)}
181
- </div>
182
- </div>
183
- <div style="display: flex; align-items: center; gap: 0.4rem; background: var(--bg-card); padding: 3px 8px; border-radius: 6px; border: 1px solid var(--border-subtle);" title="Maximum concurrent instances allowed to run simultaneously (empty = unlimited)">
184
- <span style="font-size: 0.72rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.04em;">Concurrency:</span>
185
- <input
186
- type="number"
187
- id="flow-edit-concurrency"
188
- class="flow-field-input"
189
- min="1"
190
- step="1"
191
- placeholder="Unlimited"
192
- value="${flow.maxConcurrentExecutions ? escapeHtml(String(flow.maxConcurrentExecutions)) : ''}"
193
- style="width: 90px; padding: 0.25rem 0.5rem; font-size: 0.8rem; font-weight: 600;"
194
- onchange="updateFlowMeta('maxConcurrentExecutions', this.value !== '' ? parseInt(this.value, 10) : null)"
195
- />
196
- </div>
197
- </div>
198
- </div>
199
-
200
- <div style="display: flex; align-items: center; gap: 0.5rem;">
201
- <div style="display: flex; background: var(--bg-hover-subtle); border: 1px solid var(--border-subtle); border-radius: 6px; padding: 2px;">
202
- <button
203
- class="btn btn-sm ${designerState.activeMode === 'visual' ? 'btn-primary' : 'btn-secondary'}"
204
- style="border:none; padding: 4px 12px; font-weight: 600;"
205
- onclick="switchDesignerMode('visual')"
206
- >
207
- Visual
208
- </button>
209
- <button
210
- class="btn btn-sm ${designerState.activeMode === 'code' ? 'btn-primary' : 'btn-secondary'}"
211
- style="border:none; padding: 4px 12px; font-weight: 600;"
212
- onclick="switchDesignerMode('code')"
213
- >
214
- Code DSL
215
- </button>
216
- </div>
217
- <button class="btn btn-secondary btn-sm" onclick="toggleTestDrawer()" title="Test Run Flow" style="font-weight: 600;">
218
- ▶ Test Flow
219
- </button>
220
- <button class="btn btn-primary btn-sm" onclick="saveFlowChanges()" style="font-weight: 600;">
221
- Save Flow
222
- </button>
223
- </div>
224
- </div>
225
-
226
- <!-- Main Designer Workspace -->
227
- ${designerState.activeMode === 'visual' ? renderVisualWorkspaceHtml(flow) : renderCodeDslWorkspaceHtml(flow)}
228
-
229
- <!-- Slide-over Test Runner Drawer -->
230
- <div id="flow-test-drawer" class="flow-test-drawer ${designerState.isTestDrawerOpen ? 'open' : ''}">
231
- ${renderTestDrawerHtml(flow)}
232
- </div>
233
- </div>
234
- `;
235
-
236
- if (designerState.activeMode === 'visual') {
237
- renderSvgFlowchart(flow);
238
- } else {
239
- initDslCodeMirror(flow);
240
- }
241
- }
242
-
243
- // ==========================================
244
- // 2. Visual Builder & Step Cards Pane
245
- // ==========================================
246
-
247
- function renderVisualWorkspaceHtml(flow) {
248
- const states = flow.definition?.states || {};
249
- const stateKeys = Object.keys(states);
250
- const startAt = flow.definition?.startAt || stateKeys[0] || '';
251
-
252
- return `
253
- <div class="flows-split-pane">
254
- <!-- Left: Step Sequence Editor -->
255
- <div class="flows-steps-pane">
256
- <div class="flows-steps-header">
257
- <div style="display: flex; align-items: center; gap: 0.5rem;">
258
- <span style="font-size: 0.75rem; color: var(--text-muted); font-weight: 700;">START AT:</span>
259
- <select
260
- class="flow-field-select"
261
- style="width: 160px; font-weight: 600; padding: 0.35rem 0.6rem;"
262
- onchange="updateFlowStartAt(this.value)"
263
- >
264
- ${stateKeys.map(k => `<option value="${escapeHtml(k)}" ${k === startAt ? 'selected' : ''}>${escapeHtml(k)}</option>`).join('')}
265
- </select>
266
- </div>
267
- <button class="btn btn-primary btn-sm" onclick="openAddStepModal()" style="font-weight: 600; font-size: 0.8rem; padding: 0.35rem 0.85rem;">
268
- + Add Step
269
- </button>
270
- </div>
271
-
272
- <div class="flows-steps-list" id="flows-steps-list">
273
- ${stateKeys.length === 0 ? `
274
- <div style="text-align: center; padding: 3rem 1.5rem; color: var(--text-muted);">
275
- <p style="margin: 0 0 1rem 0;">No steps defined in this flow.</p>
276
- <button class="btn btn-primary btn-sm" onclick="openAddStepModal()">+ Add First Step</button>
277
- </div>
278
- ` : stateKeys.map((stepName, idx) => renderStepCardHtml(stepName, states[stepName], idx, stateKeys)).join('')}
279
- </div>
280
- </div>
281
-
282
- <!-- Right: Live Auto-Layout SVG Diagram -->
283
- <div class="flows-diagram-pane">
284
- <div class="flows-diagram-header">
285
- <div style="display: flex; align-items: center; gap: 8px;">
286
- <span style="font-size: 0.75rem; color: var(--text-muted); font-weight: 700;">LIVE FLOW DIAGRAM</span>
287
- <span style="font-size: 0.7rem; color: var(--text-subtle); font-weight: 500;">(Click a node to select)</span>
288
- </div>
289
- </div>
290
- <div id="flow-diagram-container" class="flows-diagram-canvas-wrap"></div>
291
- </div>
292
- </div>
293
- `;
294
- }
295
-
296
- // ==========================================
297
- // 6. Code DSL View (CodeMirror)
298
- // ==========================================
299
-
300
- function renderCodeDslWorkspaceHtml(flow) {
301
- return `
302
- <div style="background: var(--bg-card); border: 1px solid var(--border-default); border-radius: 10px; height: 100%; min-height: 0; flex: 1; display: flex; flex-direction: column;">
303
- <div style="padding: 0.85rem 1.25rem; border-bottom: 1px solid var(--border-subtle); display: flex; align-items: center; justify-content: space-between;">
304
- <span style="font-size: 0.85rem; font-weight: 700; color: var(--text-muted);">
305
- JSON Definition (Flow States Language / DSL)
306
- </span>
307
- <button class="btn btn-secondary btn-sm" onclick="syncDslToVisual()" style="font-weight: 600;">
308
- Apply Changes to Visual
309
- </button>
310
- </div>
311
- <div id="flow-dsl-editor-container" style="flex: 1; overflow: hidden;"></div>
312
- </div>
313
- `;
314
- }
315
-
316
- function initDslCodeMirror(flow) {
317
- const el = document.getElementById('flow-dsl-editor-container');
318
- if (!el || typeof CodeMirror === 'undefined') return;
319
-
320
- el.innerHTML = '';
321
- designerState.cmDslEditor = CodeMirror(el, {
322
- value: JSON.stringify(flow.definition || {}, null, 2),
323
- mode: 'application/json',
324
- theme: 'dracula',
325
- lineNumbers: true,
326
- tabSize: 2,
327
- });
328
- }
329
-
330
- function syncDslToVisual() {
331
- if (!designerState.cmDslEditor) return;
332
- try {
333
- const parsed = JSON.parse(designerState.cmDslEditor.getValue());
334
- const validationError = validateFlowDefinitionClient(parsed);
335
- if (validationError) {
336
- toast('DSL Validation Error: ' + validationError, 'error');
337
- return;
338
- }
339
- designerState.activeFlow.definition = parsed;
340
- switchDesignerMode('visual');
341
- } catch (err) {
342
- toast('Invalid JSON in definition: ' + err.message, 'error');
343
- }
344
- }
345
-
346
- // ==========================================
347
- // 7. Test Runner Drawer & Execution Visualizer
348
- // ==========================================
349
-
350
- function renderTestDrawerHtml(flow) {
351
- const exec = designerState.latestExecution;
352
-
353
- return `
354
- <div style="padding: 1rem 1.25rem; border-bottom: 1px solid var(--border-subtle); display: flex; align-items: center; justify-content: space-between; background: var(--bg-card-hover, rgba(0,0,0,0.05));">
355
- <h3 style="margin: 0; font-size: 1rem; color: var(--text-main); font-weight: 700; display: flex; align-items: center; gap: 0.5rem;">
356
- ▶ Test Flow Execution
357
- </h3>
358
- <button class="btn btn-secondary btn-sm" style="padding: 2px 8px;" onclick="toggleTestDrawer()">✕</button>
359
- </div>
360
-
361
- <div style="padding: 1.25rem; overflow-y: auto; display: flex; flex-direction: column; gap: 1.15rem; flex: 1;">
362
- <div class="flow-field-row">
363
- <label class="flow-field-label">Initial Input Payload (JSON):</label>
364
- <textarea
365
- id="flow-test-input"
366
- class="flow-field-input"
367
- style="height: 130px; font-family: var(--font-mono, monospace); font-size: 0.8rem; resize: vertical;"
368
- >${escapeHtml(designerState.testPayload)}</textarea>
369
- </div>
370
-
371
- <button class="btn btn-primary" onclick="runFlowTest()" style="font-weight: 700; padding: 0.65rem 1rem;">
372
- ⚡ Execute Flow Now
373
- </button>
374
-
375
- ${exec ? `
376
- <div style="border-top: 1px solid var(--border-subtle); padding-top: 1rem; display: flex; flex-direction: column; gap: 0.85rem;">
377
- <div style="display: flex; align-items: center; justify-content: space-between;">
378
- <span style="font-weight: 800; color: ${exec.status === 'succeeded' ? 'var(--accent-success)' : 'var(--accent-danger)'}; font-size: 0.85rem; text-transform: uppercase;">
379
- ● ${exec.status} (${exec.durationMs}ms)
380
- </span>
381
- <span style="font-size: 0.75rem; color: var(--text-muted);">${new Date(exec.startedAt).toLocaleTimeString()} • Caller: <code style="font-size: 10px; font-weight: 600;">${escapeHtml(exec.actorId || 'admin / test')}</code></span>
382
- </div>
383
-
384
- <!-- Step Timeline -->
385
- <div style="font-size: 0.75rem; font-weight: 700; color: var(--text-muted);">STEP TIMELINE:</div>
386
- <div style="display: flex; flex-direction: column; gap: 0.5rem;">
387
- ${(exec.stepLogs || []).map(log => `
388
- <div class="flow-timeline-item status-${log.status}">
389
- <div style="display: flex; align-items: center; justify-content: space-between;">
390
- <strong style="color: var(--text-main); font-size: 0.85rem;">${escapeHtml(log.step)}</strong>
391
- <span style="font-size: 0.72rem; color: var(--text-muted); font-weight: 600;">${log.durationMs}ms</span>
392
- </div>
393
- ${log.error ? `<div style="color: var(--accent-danger); font-size: 0.75rem; margin-top: 2px;">${escapeHtml(log.error)}</div>` : ''}
394
- </div>
395
- `).join('')}
396
- </div>
397
-
398
- <!-- Output Payload -->
399
- <div class="flow-field-row">
400
- <label class="flow-field-label">Final Output Payload:</label>
401
- <pre style="background: var(--bg-input); border: 1px solid var(--border-default); border-radius: 6px; padding: 0.75rem; font-size: 0.78rem; overflow-x: auto; max-height: 200px; margin: 0; color: var(--text-main); font-family: var(--font-mono, monospace);">${escapeHtml(JSON.stringify(exec.output, null, 2))}</pre>
402
- </div>
403
- </div>
404
- ` : ''}
405
- </div>
406
- `;
407
- }
408
-
409
- function toggleTestDrawer() {
410
- designerState.isTestDrawerOpen = !designerState.isTestDrawerOpen;
411
- const drawer = document.getElementById('flow-test-drawer');
412
- if (drawer) {
413
- drawer.classList.toggle('open', designerState.isTestDrawerOpen);
414
- }
415
- }
416
-
417
- async function runFlowTest() {
418
- const inputEl = document.getElementById('flow-test-input');
419
- let parsedPayload = {};
420
- if (inputEl) {
421
- designerState.testPayload = inputEl.value;
422
- try {
423
- parsedPayload = JSON.parse(inputEl.value);
424
- } catch (e) {
425
- toast('Invalid JSON in test payload input', 'error');
426
- return;
427
- }
428
- }
429
-
430
- const flow = designerState.activeFlow;
431
- if (!flow || !flow.id) return;
432
-
433
- // Validate and persist edits before execution so server runs the up-to-date definition
434
- const saved = await saveFlowChanges({ silent: true });
435
- if (!saved) {
436
- return;
437
- }
438
-
439
- const flowId = designerState.activeFlow.id;
440
-
441
- try {
442
- const base = getDesignerFlowsApiBase();
443
- const res = await api(`${base}/${flowId}/execute?wait=true`, {
444
- method: 'POST',
445
- body: JSON.stringify(parsedPayload),
446
- });
447
-
448
- designerState.latestExecution = res;
449
- // Update drawer content
450
- const drawer = document.getElementById('flow-test-drawer');
451
- if (drawer) {
452
- drawer.innerHTML = renderTestDrawerHtml(designerState.activeFlow);
453
- }
454
-
455
- // Refresh flowchart diagram to show status highlights (green / red)
456
- renderSvgFlowchart(designerState.activeFlow);
457
- } catch (err) {
458
- toast('Flow execution failed: ' + (err.message || err), 'error');
459
- }
460
- }
461
-
462
- // ==========================================
463
- // 8. Flow Mutators
464
- // ==========================================
465
-
466
- function updateFlowMeta(key, value) {
467
- if (designerState.activeFlow) {
468
- designerState.activeFlow[key] = value;
469
- if (key === 'name' && typeof updateBreadcrumbs === 'function') {
470
- updateBreadcrumbs();
471
- }
472
- }
473
- }
474
-
475
- function updateFlowStartAt(val) {
476
- if (designerState.activeFlow?.definition) {
477
- designerState.activeFlow.definition.startAt = val;
478
- renderSvgFlowchart(designerState.activeFlow);
479
- }
480
- }
481
-
482
- function handleStepEndToggle(stepName, isEnd) {
483
- const step = designerState.activeFlow?.definition?.states?.[stepName];
484
- if (!step) return;
485
-
486
- const nextSelect = document.getElementById(`step-next-select-${stepName}`);
487
- const endCheck = document.getElementById(`step-end-check-${stepName}`);
488
-
489
- if (isEnd) {
490
- step.end = true;
491
- delete step.next;
492
- if (nextSelect) {
493
- nextSelect.value = '';
494
- nextSelect.disabled = true;
495
- }
496
- } else {
497
- delete step.end;
498
- if (nextSelect) {
499
- nextSelect.disabled = false;
500
- nextSelect.focus();
501
- }
502
- }
503
-
504
- if (endCheck) {
505
- endCheck.checked = !!step.end;
506
- }
507
-
508
- renderSvgFlowchart(designerState.activeFlow);
509
- }
510
-
511
- function handleStepNextChange(stepName, nextStep) {
512
- const step = designerState.activeFlow?.definition?.states?.[stepName];
513
- if (!step) return;
514
-
515
- const nextSelect = document.getElementById(`step-next-select-${stepName}`);
516
- const endCheck = document.getElementById(`step-end-check-${stepName}`);
517
-
518
- if (nextStep) {
519
- step.next = nextStep;
520
- delete step.end;
521
- if (endCheck) {
522
- endCheck.checked = false;
523
- }
524
- } else {
525
- delete step.next;
526
- }
527
-
528
- if (nextSelect) {
529
- nextSelect.disabled = false;
530
- }
531
-
532
- renderSvgFlowchart(designerState.activeFlow);
533
- }
534
-
535
- function updateStepProp(stepName, prop, val) {
536
- const step = designerState.activeFlow?.definition?.states?.[stepName];
537
- if (!step) return;
538
-
539
- if (prop === 'end') {
540
- handleStepEndToggle(stepName, !!val);
541
- return;
542
- }
543
- if (prop === 'next') {
544
- handleStepNextChange(stepName, val);
545
- return;
546
- }
547
-
548
- step[prop] = val;
549
- renderSvgFlowchart(designerState.activeFlow);
550
- }
551
-
552
- function updateMapIteratorFunction(stepName, fnName) {
553
- const step = designerState.activeFlow?.definition?.states?.[stepName];
554
- if (!step) return;
555
-
556
- step.iterator = {
557
- startAt: 'ProcessItem',
558
- states: {
559
- ProcessItem: {
560
- type: 'Task',
561
- function: fnName,
562
- end: true,
563
- },
564
- },
565
- };
566
- renderSvgFlowchart(designerState.activeFlow);
567
- }
568
-
569
- function addParallelBranch(stepName) {
570
- const step = designerState.activeFlow?.definition?.states?.[stepName];
571
- if (!step) return;
572
- if (!Array.isArray(step.branches)) step.branches = [];
573
- const bNum = step.branches.length + 1;
574
- const startKey = `Branch${bNum}_Task`;
575
- step.branches.push({
576
- startAt: startKey,
577
- states: {
578
- [startKey]: {
579
- type: 'Task',
580
- function: '',
581
- end: true,
582
- },
583
- },
584
- });
585
- renderFlowDesignerWorkbench(designerState.activeFlow);
586
- }
587
-
588
- function removeParallelBranch(stepName, branchIdx) {
589
- const step = designerState.activeFlow?.definition?.states?.[stepName];
590
- if (!step || !Array.isArray(step.branches)) return;
591
- if (step.branches.length <= 1) {
592
- toast('A Parallel step must have at least one branch.', 'warning');
593
- return;
594
- }
595
- step.branches.splice(branchIdx, 1);
596
- renderFlowDesignerWorkbench(designerState.activeFlow);
597
- }
598
-
599
- function updateParallelBranchFunction(stepName, branchIdx, fnName) {
600
- const step = designerState.activeFlow?.definition?.states?.[stepName];
601
- if (!step || !Array.isArray(step.branches) || !step.branches[branchIdx]) return;
602
- const branch = step.branches[branchIdx];
603
- const startKey = branch.startAt || Object.keys(branch.states || {})[0] || `Branch${branchIdx + 1}_Task`;
604
- branch.startAt = startKey;
605
- if (!branch.states) branch.states = {};
606
- if (!branch.states[startKey]) {
607
- branch.states[startKey] = {
608
- type: 'Task',
609
- function: fnName,
610
- end: true,
611
- };
612
- } else {
613
- branch.states[startKey].type = 'Task';
614
- branch.states[startKey].function = fnName;
615
- branch.states[startKey].end = true;
616
- }
617
- renderSvgFlowchart(designerState.activeFlow);
618
- }
619
-
620
- function updateLoopCondition(stepName, prop, val) {
621
- const step = designerState.activeFlow?.definition?.states?.[stepName];
622
- if (!step) return;
623
- if (!step.condition) step.condition = { variable: '$.counter' };
624
- if (prop === 'variable') {
625
- let cleanVal = String(val || '').trim();
626
- if (cleanVal && !cleanVal.startsWith('$')) {
627
- cleanVal = cleanVal.startsWith('[') ? '$' + cleanVal : '$.' + cleanVal;
628
- }
629
- step.condition.variable = cleanVal;
630
- } else if (prop === 'numericLessThan') {
631
- const num = typeof val === 'number' ? val : parseFloat(val);
632
- if (isNaN(num)) {
633
- delete step.condition.numericLessThan;
634
- } else {
635
- step.condition.numericLessThan = num;
636
- }
637
- } else {
638
- step.condition[prop] = val;
639
- }
640
- }
641
-
642
- function updatePassResult(stepName, jsonStr) {
643
- const step = designerState.activeFlow?.definition?.states?.[stepName];
644
- if (!step) return;
645
- try {
646
- step.result = JSON.parse(jsonStr);
647
- } catch (e) {
648
- step.result = jsonStr;
649
- }
650
- }
651
-
652
- function addChoiceBranch(stepName) {
653
- const step = designerState.activeFlow?.definition?.states?.[stepName];
654
- if (!step) return;
655
- if (!step.choices) step.choices = [];
656
- step.choices.push({ variable: '$.status', stringEquals: 'approved', next: '' });
657
- renderFlowDesignerWorkbench(designerState.activeFlow);
658
- }
659
-
660
- function removeChoiceBranch(stepName, index) {
661
- const step = designerState.activeFlow?.definition?.states?.[stepName];
662
- if (!step || !step.choices) return;
663
- step.choices.splice(index, 1);
664
- renderFlowDesignerWorkbench(designerState.activeFlow);
665
- }
666
-
667
- function updateChoiceBranch(stepName, index, prop, val) {
668
- const step = designerState.activeFlow?.definition?.states?.[stepName];
669
- if (step?.choices?.[index]) {
670
- if (prop === 'variable') {
671
- let v = (val || '').trim();
672
- if (v && !v.startsWith('$')) {
673
- v = '$.' + v;
674
- }
675
- step.choices[index].variable = v;
676
- } else {
677
- step.choices[index][prop] = val;
678
- }
679
- renderSvgFlowchart(designerState.activeFlow);
680
- }
681
- }
682
-
683
- function updateChoiceBranchOp(stepName, index, op) {
684
- const branch = designerState.activeFlow?.definition?.states?.[stepName]?.choices?.[index];
685
- if (!branch) return;
686
-
687
- delete branch.stringEquals;
688
- delete branch.numericEquals;
689
- delete branch.numericGreaterThan;
690
- delete branch.numericLessThan;
691
- delete branch.numericGreaterThanEquals;
692
- delete branch.numericLessThanEquals;
693
- delete branch.booleanEquals;
694
- delete branch.isPresent;
695
-
696
- if (op === 'booleanEquals') {
697
- branch.booleanEquals = true;
698
- } else if (op === 'isPresent') {
699
- branch.isPresent = true;
700
- } else if (op === 'numericGreaterThan') {
701
- branch.numericGreaterThan = 0;
702
- } else if (op === 'numericLessThan') {
703
- branch.numericLessThan = 10;
704
- } else if (op === 'numericEquals') {
705
- branch.numericEquals = 0;
706
- } else if (op === 'numericGreaterThanEquals') {
707
- branch.numericGreaterThanEquals = 0;
708
- } else if (op === 'numericLessThanEquals') {
709
- branch.numericLessThanEquals = 10;
710
- } else {
711
- branch.stringEquals = '';
712
- }
713
-
714
- renderFlowDesignerWorkbench(designerState.activeFlow);
715
- }
716
-
717
- function updateChoiceBranchVal(stepName, index, val) {
718
- const branch = designerState.activeFlow?.definition?.states?.[stepName]?.choices?.[index];
719
- if (!branch) return;
720
-
721
- if (branch.booleanEquals !== undefined) {
722
- branch.booleanEquals = val === 'true';
723
- } else if (branch.isPresent !== undefined) {
724
- branch.isPresent = val === 'true';
725
- } else if (branch.numericGreaterThan !== undefined ||
726
- branch.numericLessThan !== undefined ||
727
- branch.numericEquals !== undefined ||
728
- branch.numericGreaterThanEquals !== undefined ||
729
- branch.numericLessThanEquals !== undefined) {
730
- const num = Number(val);
731
- if (isNaN(num) || String(val).trim() === '') {
732
- toast('Please enter a valid numeric value for number conditions.', 'warning');
733
- renderFlowDesignerWorkbench(designerState.activeFlow);
734
- return;
735
- }
736
- if (branch.numericGreaterThan !== undefined) branch.numericGreaterThan = num;
737
- else if (branch.numericLessThan !== undefined) branch.numericLessThan = num;
738
- else if (branch.numericEquals !== undefined) branch.numericEquals = num;
739
- else if (branch.numericGreaterThanEquals !== undefined) branch.numericGreaterThanEquals = num;
740
- else if (branch.numericLessThanEquals !== undefined) branch.numericLessThanEquals = num;
741
- } else {
742
- branch.stringEquals = String(val);
743
- }
744
-
745
- renderSvgFlowchart(designerState.activeFlow);
746
- }
747
-
748
- function deleteStep(stepName, evt) {
749
- if (evt) evt.stopPropagation();
750
- if (!confirm(`Delete step "${stepName}"?`)) return;
751
-
752
- const states = designerState.activeFlow.definition.states;
753
- delete states[stepName];
754
-
755
- // Clean up references across all remaining states
756
- Object.values(states).forEach((st) => {
757
- if (st.next === stepName) delete st.next;
758
- if (st.target === stepName) delete st.target;
759
- if (st.default === stepName) delete st.default;
760
- if (Array.isArray(st.choices)) {
761
- st.choices.forEach((c) => {
762
- if (c.next === stepName) c.next = '';
763
- });
764
- }
765
- });
766
-
767
- if (designerState.activeFlow.definition.startAt === stepName) {
768
- const keys = Object.keys(states);
769
- designerState.activeFlow.definition.startAt = keys[0] || '';
770
- }
771
- renderFlowDesignerWorkbench(designerState.activeFlow);
772
- }
773
-
774
- function renameStep(oldName, newName) {
775
- const trimmed = newName ? newName.trim() : '';
776
- if (!trimmed || oldName === trimmed) return;
777
- const states = designerState.activeFlow.definition.states;
778
- if (states[trimmed]) {
779
- toast(`A step with name "${trimmed}" already exists`, 'warning');
780
- renderFlowDesignerWorkbench(designerState.activeFlow);
781
- return;
782
- }
783
-
784
- // Preserve exact key position in states object so renamed step does not jump to the end
785
- const keys = Object.keys(states);
786
- const newStates = {};
787
- keys.forEach((k) => {
788
- if (k === oldName) {
789
- newStates[trimmed] = states[oldName];
790
- } else {
791
- newStates[k] = states[k];
792
- }
793
- });
794
- designerState.activeFlow.definition.states = newStates;
795
-
796
- // Synchronize references across all other states
797
- Object.values(newStates).forEach((st) => {
798
- if (st.next === oldName) st.next = trimmed;
799
- if (st.target === oldName) st.target = trimmed;
800
- if (st.default === oldName) st.default = trimmed;
801
- if (Array.isArray(st.choices)) {
802
- st.choices.forEach((c) => {
803
- if (c.next === oldName) c.next = trimmed;
804
- });
805
- }
806
- });
807
-
808
- if (designerState.activeFlow.definition.startAt === oldName) {
809
- designerState.activeFlow.definition.startAt = trimmed;
810
- }
811
- if (designerState.selectedStepName === oldName) {
812
- designerState.selectedStepName = trimmed;
813
- }
814
-
815
- renderFlowDesignerWorkbench(designerState.activeFlow);
816
- }
817
-
818
- function validateFlowDefinitionClient(def) {
819
- if (!def || typeof def !== 'object') return 'Flow definition is empty or invalid.';
820
- if (!def.startAt || typeof def.startAt !== 'string' || !def.startAt.trim()) {
821
- return 'Flow must have a Start Step configured.';
822
- }
823
- if (!def.states || typeof def.states !== 'object' || Object.keys(def.states).length === 0) {
824
- return 'Flow must contain at least one step in definition.';
825
- }
826
- if (!def.states[def.startAt]) {
827
- return `Start Step "${def.startAt}" does not exist in flow steps.`;
828
- }
829
-
830
- const keys = Object.keys(def.states);
831
- for (const [name, state] of Object.entries(def.states)) {
832
- if (!state || typeof state !== 'object') {
833
- return `Step "${name}" is invalid.`;
834
- }
835
-
836
- if (state.next && !keys.includes(state.next)) {
837
- return `Step "${name}" points to non-existent step "${state.next}".`;
838
- }
839
-
840
- if (state.type === 'Task') {
841
- if (!state.function || !state.function.trim()) {
842
- return `Task step "${name}" must specify a serverless function.`;
843
- }
844
- if (!state.next && !state.end) {
845
- return `Task step "${name}" must configure "Then Go To" or mark as "End State".`;
846
- }
847
- } else if (state.type === 'Choice') {
848
- if (!Array.isArray(state.choices) || state.choices.length === 0) {
849
- return `Choice step "${name}" must have at least one condition rule.`;
850
- }
851
- for (let i = 0; i < state.choices.length; i++) {
852
- const c = state.choices[i];
853
- if (!c.variable || !c.variable.trim() || !c.variable.startsWith('$')) {
854
- return `Choice step "${name}" rule #${i + 1} variable must start with '$' (e.g. $.status).`;
855
- }
856
- if (!c.next || !keys.includes(c.next)) {
857
- return `Choice step "${name}" rule #${i + 1} must select a valid target step.`;
858
- }
859
-
860
- const isNumeric = c.numericGreaterThan !== undefined ||
861
- c.numericLessThan !== undefined ||
862
- c.numericEquals !== undefined ||
863
- c.numericGreaterThanEquals !== undefined ||
864
- c.numericLessThanEquals !== undefined;
865
-
866
- if (isNumeric) {
867
- const num = c.numericGreaterThan ??
868
- c.numericLessThan ??
869
- c.numericEquals ??
870
- c.numericGreaterThanEquals ??
871
- c.numericLessThanEquals;
872
- if (typeof num !== 'number' || isNaN(num) || !Number.isFinite(num)) {
873
- return `Choice step "${name}" rule #${i + 1} has invalid non-numeric value: ${JSON.stringify(num)}.`;
874
- }
875
- }
876
-
877
- if (c.booleanEquals !== undefined && typeof c.booleanEquals !== 'boolean') {
878
- return `Choice step "${name}" rule #${i + 1} boolean condition must be true or false.`;
879
- }
880
- }
881
-
882
- if (state.default && !keys.includes(state.default)) {
883
- return `Choice step "${name}" default fallback step "${state.default}" does not exist.`;
884
- }
885
- } else if (state.type === 'Loop') {
886
- if (!state.target || !keys.includes(state.target)) {
887
- return `Loop step "${name}" must select a valid jump target step.`;
888
- }
889
- if (state.maxIterations !== undefined) {
890
- if (typeof state.maxIterations !== 'number' || state.maxIterations < 1) {
891
- return `Loop step "${name}" max iterations must be a positive number.`;
892
- }
893
- }
894
- if (!state.condition || typeof state.condition !== 'object') {
895
- return `Loop step "${name}" must specify a condition choice rule.`;
896
- }
897
- if (!state.next && !state.end) {
898
- return `Loop step "${name}" must configure "Then Go To" or mark as "End State".`;
899
- }
900
- } else if (state.type === 'Wait') {
901
- if (typeof state.seconds !== 'number' || isNaN(state.seconds) || state.seconds < 0) {
902
- return `Wait step "${name}" seconds delay must be a non-negative number.`;
903
- }
904
- if (!state.next && !state.end) {
905
- return `Wait step "${name}" must configure "Then Go To" or mark as "End State".`;
906
- }
907
- } else if (state.type === 'Map') {
908
- if (!state.itemsPath || !state.itemsPath.startsWith('$')) {
909
- return `Map step "${name}" itemsPath must be a valid JSONPath starting with '$'.`;
910
- }
911
- if (!state.iterator || typeof state.iterator !== 'object') {
912
- return `Map step "${name}" must specify an iterator with startAt and states.`;
913
- }
914
- const subErr = validateFlowDefinitionClient(state.iterator);
915
- if (subErr) {
916
- return `Map step "${name}" iterator: ${subErr}`;
917
- }
918
- if (!state.next && !state.end) {
919
- return `Map step "${name}" must configure "Then Go To" or mark as "End State".`;
920
- }
921
- } else if (state.type === 'Parallel') {
922
- if (!Array.isArray(state.branches) || state.branches.length === 0) {
923
- return `Parallel step "${name}" must have at least one branch in "branches".`;
924
- }
925
- for (let bIdx = 0; bIdx < state.branches.length; bIdx++) {
926
- const branch = state.branches[bIdx];
927
- if (!branch || typeof branch !== 'object') {
928
- return `Parallel step "${name}" branch #${bIdx + 1} is invalid.`;
929
- }
930
- const subErr = validateFlowDefinitionClient(branch);
931
- if (subErr) {
932
- return `Parallel step "${name}" branch #${bIdx + 1}: ${subErr}`;
933
- }
934
- }
935
- if (!state.next && !state.end) {
936
- return `Parallel step "${name}" must configure "Then Go To" or mark as "End State".`;
937
- }
938
- } else if (state.type === 'Pass') {
939
- if (!state.next && !state.end) {
940
- return `Pass step "${name}" must configure "Then Go To" or mark as "End State".`;
941
- }
942
- } else if (state.type === 'Succeed' || state.type === 'Fail') {
943
- // Terminal states must not have next or end transitions
944
- if (state.next) {
945
- delete state.next;
946
- }
947
- if (state.end) {
948
- delete state.end;
949
- }
950
- }
951
- }
952
-
953
- return null;
954
- }
955
-
956
- function selectStepCard(name) {
957
- designerState.selectedStepName = name;
958
- document.querySelectorAll('.flow-step-card').forEach((el) => el.classList.remove('active-step'));
959
- const safeSelector = typeof CSS !== 'undefined' && CSS.escape ? `.flow-step-card[data-step-name="${CSS.escape(name)}"]` : null;
960
- const card = (safeSelector ? document.querySelector(safeSelector) : null) || document.getElementById(`step-card-${name}`);
961
- if (card) card.classList.add('active-step');
962
- }
963
-
964
- function selectStepFromDiagram(name) {
965
- selectStepCard(name);
966
- const safeSelector = typeof CSS !== 'undefined' && CSS.escape ? `.flow-step-card[data-step-name="${CSS.escape(name)}"]` : null;
967
- const card = (safeSelector ? document.querySelector(safeSelector) : null) || document.getElementById(`step-card-${name}`);
968
- if (card && typeof card.scrollIntoView === 'function') {
969
- card.scrollIntoView({ behavior: 'smooth', block: 'center' });
970
- }
971
- }
972
-
973
- function switchDesignerMode(mode) {
974
- if (designerState.activeMode === 'code' && designerState.cmDslEditor) {
975
- try {
976
- const parsed = JSON.parse(designerState.cmDslEditor.getValue());
977
- const validationError = validateFlowDefinitionClient(parsed);
978
- if (validationError) {
979
- toast('DSL Validation Warning: ' + validationError, 'warning');
980
- } else {
981
- designerState.activeFlow.definition = parsed;
982
- }
983
- } catch (e) {
984
- toast('Invalid JSON in editor: ' + e.message, 'warning');
985
- }
986
- }
987
- designerState.activeMode = mode;
988
- renderFlowDesignerWorkbench(designerState.activeFlow);
989
- }
990
-
991
- async function saveFlowChanges(options = {}) {
992
- const flow = designerState.activeFlow;
993
- if (!flow || !flow.id) return false;
994
-
995
- if (designerState.activeMode === 'code' && designerState.cmDslEditor) {
996
- try {
997
- const parsed = JSON.parse(designerState.cmDslEditor.getValue());
998
- flow.definition = parsed;
999
- } catch (e) {
1000
- toast('Invalid JSON in DSL editor: ' + e.message, 'error');
1001
- return false;
1002
- }
1003
- }
1004
-
1005
- const validationError = validateFlowDefinitionClient(flow.definition);
1006
- if (validationError) {
1007
- toast('Validation Error: ' + validationError, 'error');
1008
- return false;
1009
- }
1010
-
1011
- try {
1012
- const base = getDesignerFlowsApiBase();
1013
- const updated = await api(`${base}/${flow.id}`, {
1014
- method: 'PATCH',
1015
- body: JSON.stringify({
1016
- name: flow.name,
1017
- description: flow.description,
1018
- triggerType: flow.triggerType,
1019
- eventTrigger: flow.triggerType === 'event' ? (flow.eventTrigger || null) : null,
1020
- maxConcurrentExecutions: flow.maxConcurrentExecutions ?? null,
1021
- definition: flow.definition,
1022
- }),
1023
- });
1024
- flowsState.activeFlowForEdit = updated;
1025
- designerState.activeFlow = JSON.parse(JSON.stringify(updated));
1026
-
1027
- if (typeof updateUrl === 'function') {
1028
- const flowIdentifier = updated.name ? encodeURIComponent(updated.name) : encodeURIComponent(updated.id);
1029
- updateUrl('/_/flows/' + flowIdentifier, true);
1030
- }
1031
-
1032
- if (typeof updateBreadcrumbs === 'function') {
1033
- updateBreadcrumbs();
1034
- }
1035
-
1036
- if (!options || !options.silent) {
1037
- toast('Flow changes saved successfully!', 'success');
1038
- }
1039
- return true;
1040
- } catch (err) {
1041
- toast('Failed to save flow: ' + (err.message || err), 'error');
1042
- return false;
1043
- }
1044
- }
1045
-
1046
- if (typeof window !== 'undefined') {
1047
- window.openFlowDesigner = openFlowDesigner;
1048
- window.closeFlowDesigner = closeFlowDesigner;
1049
- window.renderFlowDesignerWorkbench = renderFlowDesignerWorkbench;
1050
- window.updateFlowMeta = updateFlowMeta;
1051
- window.handleFlowTriggerTypeChange = handleFlowTriggerTypeChange;
1052
- window.updateFlowStartAt = updateFlowStartAt;
1053
- window.updateStepProp = updateStepProp;
1054
- window.handleStepEndToggle = handleStepEndToggle;
1055
- window.handleStepNextChange = handleStepNextChange;
1056
- window.updateMapIteratorFunction = updateMapIteratorFunction;
1057
- window.addParallelBranch = addParallelBranch;
1058
- window.removeParallelBranch = removeParallelBranch;
1059
- window.updateParallelBranchFunction = updateParallelBranchFunction;
1060
- window.updateLoopCondition = updateLoopCondition;
1061
- window.updatePassResult = updatePassResult;
1062
- window.addChoiceBranch = addChoiceBranch;
1063
- window.removeChoiceBranch = removeChoiceBranch;
1064
- window.updateChoiceBranch = updateChoiceBranch;
1065
- window.updateChoiceBranchOp = updateChoiceBranchOp;
1066
- window.updateChoiceBranchVal = updateChoiceBranchVal;
1067
- window.deleteStep = deleteStep;
1068
- window.renameStep = renameStep;
1069
- window.selectStepCard = selectStepCard;
1070
- window.selectStepFromDiagram = selectStepFromDiagram;
1071
- window.switchDesignerMode = switchDesignerMode;
1072
- window.syncDslToVisual = syncDslToVisual;
1073
- window.toggleTestDrawer = toggleTestDrawer;
1074
- window.runFlowTest = runFlowTest;
1075
- window.saveFlowChanges = saveFlowChanges;
1076
- }
1
+ // Functions Flow Visual Designer & Workbench Module for NodeStack Admin UI
2
+ // Provides Visual Step Card Builder, Live Auto-Layout SVG Diagram, and Interactive Test Runner
3
+
4
+ let designerState = {
5
+ activeFlow: null,
6
+ activeMode: 'visual', // 'visual' | 'code'
7
+ cmDslEditor: null,
8
+ selectedStepName: null,
9
+ isTestDrawerOpen: false,
10
+ testPayload: '{\n "order": {\n "amount": 250,\n "discount": 25\n }\n}',
11
+ latestExecution: null,
12
+ addStepSelectedType: 'Task',
13
+ };
14
+
15
+ if (typeof window !== 'undefined') {
16
+ window.designerState = designerState;
17
+ }
18
+
19
+ // ==========================================
20
+ // 1. Navigation & Workbench Shell
21
+ // ==========================================
22
+
23
+ function getDesignerFlowsApiBase() {
24
+ if (typeof getFlowsApiBase === 'function') return getFlowsApiBase();
25
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : (typeof state !== 'undefined' && state?.activeApp?.slug ? state.activeApp.slug : 'default');
26
+ return slug && slug !== 'default' ? `/api/apps/${slug}/flows` : '/api/flows';
27
+ }
28
+
29
+ function getDesignerFunctionsApiBase() {
30
+ if (typeof getFunctionsApiBase === 'function') return getFunctionsApiBase();
31
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : (typeof state !== 'undefined' && state?.activeApp?.slug ? state.activeApp.slug : 'default');
32
+ return slug && slug !== 'default' ? `/api/apps/${slug}/functions` : '/api/functions';
33
+ }
34
+
35
+ async function openFlowDesigner(flowId, openTestDrawer = false, pushState = true) {
36
+ try {
37
+ const base = getDesignerFlowsApiBase();
38
+ const flow = await api(`${base}/${encodeURIComponent(flowId)}`);
39
+ flowsState.currentView = 'designer';
40
+ flowsState.activeFlowForEdit = flow;
41
+ designerState.activeFlow = JSON.parse(JSON.stringify(flow));
42
+ designerState.latestExecution = null;
43
+ designerState.isTestDrawerOpen = !!openTestDrawer;
44
+
45
+ if (pushState && typeof updateUrl === 'function') {
46
+ const flowIdentifier = flow.name ? encodeURIComponent(flow.name) : encodeURIComponent(flow.id);
47
+ updateUrl('/_/flows/' + flowIdentifier);
48
+ }
49
+
50
+ if (typeof updateBreadcrumbs === 'function') {
51
+ updateBreadcrumbs();
52
+ }
53
+
54
+ if (typeof loadFunctionsForPicker === 'function') {
55
+ await loadFunctionsForPicker();
56
+ }
57
+
58
+ renderFlowDesignerWorkbench(designerState.activeFlow);
59
+ } catch (err) {
60
+ toast('Failed to load flow: ' + (err.message || err), 'error');
61
+ }
62
+ }
63
+
64
+ function closeFlowDesigner(pushState = true) {
65
+ flowsState.currentView = 'list';
66
+ flowsState.activeFlowForEdit = null;
67
+ designerState.activeFlow = null;
68
+ designerState.isTestDrawerOpen = false;
69
+
70
+ if (pushState && typeof updateUrl === 'function') {
71
+ const sub = (typeof flowsState !== 'undefined' && flowsState.subTab === 'executions') ? '/executions' : '';
72
+ updateUrl('/_/flows' + sub);
73
+ }
74
+
75
+ if (typeof updateBreadcrumbs === 'function') {
76
+ updateBreadcrumbs();
77
+ }
78
+
79
+ if (typeof renderFlowsView === 'function') {
80
+ renderFlowsView();
81
+ }
82
+ }
83
+
84
+ function renderTriggerConfigHtml(flow) {
85
+ const triggerType = flow.triggerType || 'http';
86
+
87
+ if (triggerType === 'event') {
88
+ return `
89
+ <input
90
+ type="text"
91
+ id="flow-edit-event-trigger"
92
+ class="flow-field-input"
93
+ placeholder="collection:action (e.g. orders:create)"
94
+ value="${escapeHtml(flow.eventTrigger || '')}"
95
+ style="width: 190px; padding: 0.25rem 0.5rem; font-size: 0.8rem; font-family: var(--font-mono, monospace);"
96
+ title="Triggered automatically on database record event (e.g. orders:create, users:update, *:delete)"
97
+ onchange="updateFlowMeta('eventTrigger', this.value)"
98
+ />
99
+ <span style="font-size: 0.72rem; color: var(--text-muted); cursor: help;" title="Format: &lt;collection&gt;:&lt;action&gt;&#10;Examples:&#10;• orders:create - Run when order is created&#10;• users:update - Run when user is updated&#10;• *:delete - Run when any record is deleted">ℹ️</span>
100
+ `;
101
+ }
102
+
103
+ if (triggerType === 'http') {
104
+ const base = getDesignerFlowsApiBase();
105
+ const endpointPath = `${base}/${flow.id}/execute`;
106
+ const authPolicy = flow.authPolicy || 'public';
107
+ return `
108
+ <span style="display: inline-flex; align-items: center; gap: 4px; font-size: 0.75rem; color: var(--text-muted);">
109
+ Endpoint:
110
+ <code
111
+ style="font-size: 0.72rem; color: var(--accent-primary); background: var(--bg-main, #0f172a); padding: 2px 6px; border-radius: 4px; border: 1px solid var(--border-subtle); cursor: pointer;"
112
+ data-endpoint="POST ${endpointPath}"
113
+ title="Click to copy endpoint"
114
+ onclick="if (navigator.clipboard) { navigator.clipboard.writeText(this.getAttribute('data-endpoint')); toast('Copied endpoint: ' + this.getAttribute('data-endpoint'), 'success'); }"
115
+ >
116
+ POST ${endpointPath} 📋
117
+ </code>
118
+ </span>
119
+ <span style="font-size: 0.72rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.04em; margin-left: 4px;">Auth:</span>
120
+ <select
121
+ id="flow-edit-auth-policy"
122
+ class="flow-field-select"
123
+ aria-label="HTTP Flow Authorization Policy"
124
+ style="width: 130px; padding: 0.25rem 0.5rem; font-size: 0.8rem; font-weight: 600;"
125
+ onchange="handleFlowAuthPolicyChange(this.value)"
126
+ >
127
+ <option value="admin" ${authPolicy === 'admin' ? 'selected' : ''}>Admin Only</option>
128
+ <option value="auth" ${authPolicy === 'auth' ? 'selected' : ''}>User Token</option>
129
+ <option value="apiKey" ${authPolicy === 'apiKey' ? 'selected' : ''}>API Key</option>
130
+ <option value="custom" ${authPolicy === 'custom' ? 'selected' : ''}>Custom Rule</option>
131
+ <option value="public" ${authPolicy === 'public' ? 'selected' : ''}>Public</option>
132
+ </select>
133
+ `;
134
+ }
135
+
136
+ // Manual
137
+ return `
138
+ <span style="font-size: 0.75rem; color: var(--text-muted); font-style: italic;">
139
+ Triggered on-demand via Run / Test Flow
140
+ </span>
141
+ `;
142
+ }
143
+
144
+ function handleFlowTriggerTypeChange(newType) {
145
+ if (!designerState.activeFlow) return;
146
+ designerState.activeFlow.triggerType = newType;
147
+ if (newType === 'event') {
148
+ if (!designerState.activeFlow.eventTrigger) {
149
+ designerState.activeFlow.eventTrigger = 'orders:create';
150
+ }
151
+ } else {
152
+ designerState.activeFlow.eventTrigger = null;
153
+ }
154
+
155
+ const configArea = document.getElementById('flow-trigger-config-area');
156
+ if (configArea) {
157
+ configArea.innerHTML = renderTriggerConfigHtml(designerState.activeFlow);
158
+ }
159
+ const rulePanel = document.getElementById('flow-custom-rule-panel');
160
+ if (rulePanel) {
161
+ const showCustom = newType === 'http' && (designerState.activeFlow.authPolicy || 'public') === 'custom';
162
+ rulePanel.style.display = showCustom ? 'block' : 'none';
163
+ }
164
+ }
165
+
166
+ function handleFlowAuthPolicyChange(policy) {
167
+ if (!designerState.activeFlow) return;
168
+ designerState.activeFlow.authPolicy = policy;
169
+ const rulePanel = document.getElementById('flow-custom-rule-panel');
170
+ if (rulePanel) {
171
+ const showCustom = (designerState.activeFlow.triggerType || 'http') === 'http' && policy === 'custom';
172
+ rulePanel.style.display = showCustom ? 'block' : 'none';
173
+ if (showCustom && typeof renderStandaloneRuleEditor === 'function') {
174
+ if (typeof initStandaloneRule === 'function' && (!state.standaloneRules || !state.standaloneRules.flow_invoke)) {
175
+ initStandaloneRule('flow_invoke', designerState.activeFlow.invokeRule || '@request.auth.id != ""');
176
+ }
177
+ rulePanel.innerHTML = renderStandaloneRuleEditor('flow_invoke');
178
+ }
179
+ }
180
+ }
181
+
182
+ function renderFlowDesignerWorkbench(flow) {
183
+ const container = document.getElementById('page-view-flows') || document.getElementById('main-body');
184
+ if (!container || !flow) return;
185
+ if (typeof initStandaloneRule === 'function') {
186
+ initStandaloneRule('flow_invoke', flow.invokeRule || '@request.auth.id != ""');
187
+ }
188
+
189
+ container.innerHTML = `
190
+ <div class="flows-container">
191
+ <!-- Toolbar -->
192
+ <div class="flows-designer-toolbar">
193
+ <div style="display: flex; align-items: center; gap: 1rem; flex-wrap: wrap;">
194
+ <button class="btn btn-secondary btn-sm" onclick="closeFlowDesigner()">
195
+ ← Back to Flows
196
+ </button>
197
+ <div style="display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap;">
198
+ <input
199
+ type="text"
200
+ id="flow-edit-name"
201
+ class="flow-field-input"
202
+ value="${escapeHtml(flow.name)}"
203
+ style="font-weight: 700; font-size: 1rem; width: 210px;"
204
+ onchange="updateFlowMeta('name', this.value)"
205
+ />
206
+ <div style="display: flex; align-items: center; gap: 0.4rem; background: var(--bg-card); padding: 3px 8px; border-radius: 6px; border: 1px solid var(--border-subtle);">
207
+ <span style="font-size: 0.72rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.04em;">Trigger:</span>
208
+ <select
209
+ id="flow-edit-trigger-type"
210
+ class="flow-field-select"
211
+ style="width: 110px; padding: 0.25rem 0.5rem; font-size: 0.8rem; font-weight: 600;"
212
+ onchange="handleFlowTriggerTypeChange(this.value)"
213
+ >
214
+ <option value="http" ${flow.triggerType === 'http' ? 'selected' : ''}>HTTP API</option>
215
+ <option value="event" ${flow.triggerType === 'event' ? 'selected' : ''}>DB Event</option>
216
+ <option value="manual" ${flow.triggerType === 'manual' ? 'selected' : ''}>Manual</option>
217
+ </select>
218
+ <div id="flow-trigger-config-area" style="display: flex; align-items: center; gap: 6px;">
219
+ ${renderTriggerConfigHtml(flow)}
220
+ </div>
221
+ </div>
222
+ <div style="display: flex; align-items: center; gap: 0.4rem; background: var(--bg-card); padding: 3px 8px; border-radius: 6px; border: 1px solid var(--border-subtle);" title="Maximum concurrent instances allowed to run simultaneously (empty = unlimited)">
223
+ <span style="font-size: 0.72rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.04em;">Concurrency:</span>
224
+ <input
225
+ type="number"
226
+ id="flow-edit-concurrency"
227
+ class="flow-field-input"
228
+ min="1"
229
+ step="1"
230
+ placeholder="Unlimited"
231
+ value="${flow.maxConcurrentExecutions ? escapeHtml(String(flow.maxConcurrentExecutions)) : ''}"
232
+ style="width: 90px; padding: 0.25rem 0.5rem; font-size: 0.8rem; font-weight: 600;"
233
+ onchange="updateFlowMeta('maxConcurrentExecutions', this.value !== '' ? parseInt(this.value, 10) : null)"
234
+ />
235
+ </div>
236
+ </div>
237
+ </div>
238
+
239
+ <div style="display: flex; align-items: center; gap: 0.5rem;">
240
+ <div style="display: flex; background: var(--bg-hover-subtle); border: 1px solid var(--border-subtle); border-radius: 6px; padding: 2px;">
241
+ <button
242
+ class="btn btn-sm ${designerState.activeMode === 'visual' ? 'btn-primary' : 'btn-secondary'}"
243
+ style="border:none; padding: 4px 12px; font-weight: 600;"
244
+ onclick="switchDesignerMode('visual')"
245
+ >
246
+ Visual
247
+ </button>
248
+ <button
249
+ class="btn btn-sm ${designerState.activeMode === 'code' ? 'btn-primary' : 'btn-secondary'}"
250
+ style="border:none; padding: 4px 12px; font-weight: 600;"
251
+ onclick="switchDesignerMode('code')"
252
+ >
253
+ Code DSL
254
+ </button>
255
+ </div>
256
+ <button class="btn btn-secondary btn-sm" onclick="toggleTestDrawer()" title="Test Run Flow" style="font-weight: 600;">
257
+ ▶ Test Flow
258
+ </button>
259
+ <button class="btn btn-primary btn-sm" onclick="saveFlowChanges()" style="font-weight: 600;">
260
+ Save Flow
261
+ </button>
262
+ </div>
263
+ </div>
264
+
265
+ <!-- Conditional Custom Invoke Rule Panel (HTTP Trigger + Custom Policy) -->
266
+ <div id="flow-custom-rule-panel" style="display: ${(flow.triggerType || 'http') === 'http' && flow.authPolicy === 'custom' ? 'block' : 'none'}; padding: 0.75rem 1.25rem; background: var(--bg-card); border-bottom: 1px solid var(--border-subtle);">
267
+ ${typeof renderStandaloneRuleEditor === 'function' ? renderStandaloneRuleEditor('flow_invoke') : ''}
268
+ </div>
269
+
270
+ <!-- Main Designer Workspace -->
271
+ ${designerState.activeMode === 'visual' ? renderVisualWorkspaceHtml(flow) : renderCodeDslWorkspaceHtml(flow)}
272
+
273
+ <!-- Slide-over Test Runner Drawer -->
274
+ <div id="flow-test-drawer" class="flow-test-drawer ${designerState.isTestDrawerOpen ? 'open' : ''}">
275
+ ${renderTestDrawerHtml(flow)}
276
+ </div>
277
+ </div>
278
+ `;
279
+
280
+ if (designerState.activeMode === 'visual') {
281
+ renderSvgFlowchart(flow);
282
+ } else {
283
+ initDslCodeMirror(flow);
284
+ }
285
+ }
286
+
287
+ // ==========================================
288
+ // 2. Visual Builder & Step Cards Pane
289
+ // ==========================================
290
+
291
+ function renderVisualWorkspaceHtml(flow) {
292
+ const states = flow.definition?.states || {};
293
+ const stateKeys = Object.keys(states);
294
+ const startAt = flow.definition?.startAt || stateKeys[0] || '';
295
+
296
+ return `
297
+ <div class="flows-split-pane">
298
+ <!-- Left: Step Sequence Editor -->
299
+ <div class="flows-steps-pane">
300
+ <div class="flows-steps-header">
301
+ <div style="display: flex; align-items: center; gap: 0.5rem;">
302
+ <span style="font-size: 0.75rem; color: var(--text-muted); font-weight: 700;">START AT:</span>
303
+ <select
304
+ class="flow-field-select"
305
+ style="width: 160px; font-weight: 600; padding: 0.35rem 0.6rem;"
306
+ onchange="updateFlowStartAt(this.value)"
307
+ >
308
+ ${stateKeys.map(k => `<option value="${escapeHtml(k)}" ${k === startAt ? 'selected' : ''}>${escapeHtml(k)}</option>`).join('')}
309
+ </select>
310
+ </div>
311
+ <button class="btn btn-primary btn-sm" onclick="openAddStepModal()" style="font-weight: 600; font-size: 0.8rem; padding: 0.35rem 0.85rem;">
312
+ + Add Step
313
+ </button>
314
+ </div>
315
+
316
+ <div class="flows-steps-list" id="flows-steps-list">
317
+ ${stateKeys.length === 0 ? `
318
+ <div style="text-align: center; padding: 3rem 1.5rem; color: var(--text-muted);">
319
+ <p style="margin: 0 0 1rem 0;">No steps defined in this flow.</p>
320
+ <button class="btn btn-primary btn-sm" onclick="openAddStepModal()">+ Add First Step</button>
321
+ </div>
322
+ ` : stateKeys.map((stepName, idx) => renderStepCardHtml(stepName, states[stepName], idx, stateKeys)).join('')}
323
+ </div>
324
+ </div>
325
+
326
+ <!-- Right: Live Auto-Layout SVG Diagram -->
327
+ <div class="flows-diagram-pane">
328
+ <div class="flows-diagram-header">
329
+ <div style="display: flex; align-items: center; gap: 8px;">
330
+ <span style="font-size: 0.75rem; color: var(--text-muted); font-weight: 700;">LIVE FLOW DIAGRAM</span>
331
+ <span style="font-size: 0.7rem; color: var(--text-subtle); font-weight: 500;">(Click a node to select)</span>
332
+ </div>
333
+ </div>
334
+ <div id="flow-diagram-container" class="flows-diagram-canvas-wrap"></div>
335
+ </div>
336
+ </div>
337
+ `;
338
+ }
339
+
340
+ // ==========================================
341
+ // 6. Code DSL View (CodeMirror)
342
+ // ==========================================
343
+
344
+ function renderCodeDslWorkspaceHtml(flow) {
345
+ return `
346
+ <div style="background: var(--bg-card); border: 1px solid var(--border-default); border-radius: 10px; height: 100%; min-height: 0; flex: 1; display: flex; flex-direction: column;">
347
+ <div style="padding: 0.85rem 1.25rem; border-bottom: 1px solid var(--border-subtle); display: flex; align-items: center; justify-content: space-between;">
348
+ <span style="font-size: 0.85rem; font-weight: 700; color: var(--text-muted);">
349
+ JSON Definition (Flow States Language / DSL)
350
+ </span>
351
+ <button class="btn btn-secondary btn-sm" onclick="syncDslToVisual()" style="font-weight: 600;">
352
+ Apply Changes to Visual
353
+ </button>
354
+ </div>
355
+ <div id="flow-dsl-editor-container" style="flex: 1; overflow: hidden;"></div>
356
+ </div>
357
+ `;
358
+ }
359
+
360
+ function initDslCodeMirror(flow) {
361
+ const el = document.getElementById('flow-dsl-editor-container');
362
+ if (!el || typeof CodeMirror === 'undefined') return;
363
+
364
+ el.innerHTML = '';
365
+ designerState.cmDslEditor = CodeMirror(el, {
366
+ value: JSON.stringify(flow.definition || {}, null, 2),
367
+ mode: 'application/json',
368
+ theme: 'dracula',
369
+ lineNumbers: true,
370
+ tabSize: 2,
371
+ });
372
+ }
373
+
374
+ function syncDslToVisual() {
375
+ if (!designerState.cmDslEditor) return;
376
+ try {
377
+ const parsed = JSON.parse(designerState.cmDslEditor.getValue());
378
+ const validationError = validateFlowDefinitionClient(parsed);
379
+ if (validationError) {
380
+ toast('DSL Validation Error: ' + validationError, 'error');
381
+ return;
382
+ }
383
+ designerState.activeFlow.definition = parsed;
384
+ switchDesignerMode('visual');
385
+ } catch (err) {
386
+ toast('Invalid JSON in definition: ' + err.message, 'error');
387
+ }
388
+ }
389
+
390
+ // ==========================================
391
+ // 7. Test Runner Drawer & Execution Visualizer
392
+ // ==========================================
393
+
394
+ function renderTestDrawerHtml(flow) {
395
+ const exec = designerState.latestExecution;
396
+
397
+ return `
398
+ <div style="padding: 1rem 1.25rem; border-bottom: 1px solid var(--border-subtle); display: flex; align-items: center; justify-content: space-between; background: var(--bg-card-hover, rgba(0,0,0,0.05));">
399
+ <h3 style="margin: 0; font-size: 1rem; color: var(--text-main); font-weight: 700; display: flex; align-items: center; gap: 0.5rem;">
400
+ ▶ Test Flow Execution
401
+ </h3>
402
+ <button class="btn btn-secondary btn-sm" style="padding: 2px 8px;" onclick="toggleTestDrawer()">✕</button>
403
+ </div>
404
+
405
+ <div style="padding: 1.25rem; overflow-y: auto; display: flex; flex-direction: column; gap: 1.15rem; flex: 1;">
406
+ <div class="flow-field-row">
407
+ <label class="flow-field-label">Initial Input Payload (JSON):</label>
408
+ <textarea
409
+ id="flow-test-input"
410
+ class="flow-field-input"
411
+ style="height: 130px; font-family: var(--font-mono, monospace); font-size: 0.8rem; resize: vertical;"
412
+ >${escapeHtml(designerState.testPayload)}</textarea>
413
+ </div>
414
+
415
+ <button class="btn btn-primary" onclick="runFlowTest()" style="font-weight: 700; padding: 0.65rem 1rem;">
416
+ ⚡ Execute Flow Now
417
+ </button>
418
+
419
+ ${exec ? `
420
+ <div style="border-top: 1px solid var(--border-subtle); padding-top: 1rem; display: flex; flex-direction: column; gap: 0.85rem;">
421
+ <div style="display: flex; align-items: center; justify-content: space-between;">
422
+ <span style="font-weight: 800; color: ${exec.status === 'succeeded' ? 'var(--accent-success)' : 'var(--accent-danger)'}; font-size: 0.85rem; text-transform: uppercase;">
423
+ ● ${exec.status} (${exec.durationMs}ms)
424
+ </span>
425
+ <span style="font-size: 0.75rem; color: var(--text-muted);">${new Date(exec.startedAt).toLocaleTimeString()} • Caller: <code style="font-size: 10px; font-weight: 600;">${escapeHtml(exec.actorId || 'admin / test')}</code></span>
426
+ </div>
427
+
428
+ <!-- Step Timeline -->
429
+ <div style="font-size: 0.75rem; font-weight: 700; color: var(--text-muted);">STEP TIMELINE:</div>
430
+ <div style="display: flex; flex-direction: column; gap: 0.5rem;">
431
+ ${(exec.stepLogs || []).map(log => `
432
+ <div class="flow-timeline-item status-${log.status}">
433
+ <div style="display: flex; align-items: center; justify-content: space-between;">
434
+ <strong style="color: var(--text-main); font-size: 0.85rem;">${escapeHtml(log.step)}</strong>
435
+ <span style="font-size: 0.72rem; color: var(--text-muted); font-weight: 600;">${log.durationMs}ms</span>
436
+ </div>
437
+ ${log.error ? `<div style="color: var(--accent-danger); font-size: 0.75rem; margin-top: 2px;">${escapeHtml(log.error)}</div>` : ''}
438
+ </div>
439
+ `).join('')}
440
+ </div>
441
+
442
+ <!-- Output Payload -->
443
+ <div class="flow-field-row">
444
+ <label class="flow-field-label">Final Output Payload:</label>
445
+ <pre style="background: var(--bg-input); border: 1px solid var(--border-default); border-radius: 6px; padding: 0.75rem; font-size: 0.78rem; overflow-x: auto; max-height: 200px; margin: 0; color: var(--text-main); font-family: var(--font-mono, monospace);">${escapeHtml(JSON.stringify(exec.output, null, 2))}</pre>
446
+ </div>
447
+ </div>
448
+ ` : ''}
449
+ </div>
450
+ `;
451
+ }
452
+
453
+ function toggleTestDrawer() {
454
+ designerState.isTestDrawerOpen = !designerState.isTestDrawerOpen;
455
+ const drawer = document.getElementById('flow-test-drawer');
456
+ if (drawer) {
457
+ drawer.classList.toggle('open', designerState.isTestDrawerOpen);
458
+ }
459
+ }
460
+
461
+ async function runFlowTest() {
462
+ const inputEl = document.getElementById('flow-test-input');
463
+ let parsedPayload = {};
464
+ if (inputEl) {
465
+ designerState.testPayload = inputEl.value;
466
+ try {
467
+ parsedPayload = JSON.parse(inputEl.value);
468
+ } catch (e) {
469
+ toast('Invalid JSON in test payload input', 'error');
470
+ return;
471
+ }
472
+ }
473
+
474
+ const flow = designerState.activeFlow;
475
+ if (!flow || !flow.id) return;
476
+
477
+ // Validate and persist edits before execution so server runs the up-to-date definition
478
+ const saved = await saveFlowChanges({ silent: true });
479
+ if (!saved) {
480
+ return;
481
+ }
482
+
483
+ const flowId = designerState.activeFlow.id;
484
+
485
+ try {
486
+ const base = getDesignerFlowsApiBase();
487
+ const res = await api(`${base}/${flowId}/execute?wait=true`, {
488
+ method: 'POST',
489
+ body: JSON.stringify(parsedPayload),
490
+ });
491
+
492
+ designerState.latestExecution = res;
493
+ // Update drawer content
494
+ const drawer = document.getElementById('flow-test-drawer');
495
+ if (drawer) {
496
+ drawer.innerHTML = renderTestDrawerHtml(designerState.activeFlow);
497
+ }
498
+
499
+ // Refresh flowchart diagram to show status highlights (green / red)
500
+ renderSvgFlowchart(designerState.activeFlow);
501
+ } catch (err) {
502
+ toast('Flow execution failed: ' + (err.message || err), 'error');
503
+ }
504
+ }
505
+
506
+ // ==========================================
507
+ // 8. Flow Mutators
508
+ // ==========================================
509
+
510
+ function updateFlowMeta(key, value) {
511
+ if (designerState.activeFlow) {
512
+ designerState.activeFlow[key] = value;
513
+ if (key === 'name' && typeof updateBreadcrumbs === 'function') {
514
+ updateBreadcrumbs();
515
+ }
516
+ }
517
+ }
518
+
519
+ function updateFlowStartAt(val) {
520
+ if (designerState.activeFlow?.definition) {
521
+ designerState.activeFlow.definition.startAt = val;
522
+ renderSvgFlowchart(designerState.activeFlow);
523
+ }
524
+ }
525
+
526
+ function handleStepEndToggle(stepName, isEnd) {
527
+ const step = designerState.activeFlow?.definition?.states?.[stepName];
528
+ if (!step) return;
529
+
530
+ const nextSelect = document.getElementById(`step-next-select-${stepName}`);
531
+ const endCheck = document.getElementById(`step-end-check-${stepName}`);
532
+
533
+ if (isEnd) {
534
+ step.end = true;
535
+ delete step.next;
536
+ if (nextSelect) {
537
+ nextSelect.value = '';
538
+ nextSelect.disabled = true;
539
+ }
540
+ } else {
541
+ delete step.end;
542
+ if (nextSelect) {
543
+ nextSelect.disabled = false;
544
+ nextSelect.focus();
545
+ }
546
+ }
547
+
548
+ if (endCheck) {
549
+ endCheck.checked = !!step.end;
550
+ }
551
+
552
+ renderSvgFlowchart(designerState.activeFlow);
553
+ }
554
+
555
+ function handleStepNextChange(stepName, nextStep) {
556
+ const step = designerState.activeFlow?.definition?.states?.[stepName];
557
+ if (!step) return;
558
+
559
+ const nextSelect = document.getElementById(`step-next-select-${stepName}`);
560
+ const endCheck = document.getElementById(`step-end-check-${stepName}`);
561
+
562
+ if (nextStep) {
563
+ step.next = nextStep;
564
+ delete step.end;
565
+ if (endCheck) {
566
+ endCheck.checked = false;
567
+ }
568
+ } else {
569
+ delete step.next;
570
+ }
571
+
572
+ if (nextSelect) {
573
+ nextSelect.disabled = false;
574
+ }
575
+
576
+ renderSvgFlowchart(designerState.activeFlow);
577
+ }
578
+
579
+ function updateStepProp(stepName, prop, val) {
580
+ const step = designerState.activeFlow?.definition?.states?.[stepName];
581
+ if (!step) return;
582
+
583
+ if (prop === 'end') {
584
+ handleStepEndToggle(stepName, !!val);
585
+ return;
586
+ }
587
+ if (prop === 'next') {
588
+ handleStepNextChange(stepName, val);
589
+ return;
590
+ }
591
+
592
+ step[prop] = val;
593
+ renderSvgFlowchart(designerState.activeFlow);
594
+ }
595
+
596
+ function updateMapIteratorFunction(stepName, fnName) {
597
+ const step = designerState.activeFlow?.definition?.states?.[stepName];
598
+ if (!step) return;
599
+
600
+ step.iterator = {
601
+ startAt: 'ProcessItem',
602
+ states: {
603
+ ProcessItem: {
604
+ type: 'Task',
605
+ function: fnName,
606
+ end: true,
607
+ },
608
+ },
609
+ };
610
+ renderSvgFlowchart(designerState.activeFlow);
611
+ }
612
+
613
+ function addParallelBranch(stepName) {
614
+ const step = designerState.activeFlow?.definition?.states?.[stepName];
615
+ if (!step) return;
616
+ if (!Array.isArray(step.branches)) step.branches = [];
617
+ const bNum = step.branches.length + 1;
618
+ const startKey = `Branch${bNum}_Task`;
619
+ step.branches.push({
620
+ startAt: startKey,
621
+ states: {
622
+ [startKey]: {
623
+ type: 'Task',
624
+ function: '',
625
+ end: true,
626
+ },
627
+ },
628
+ });
629
+ renderFlowDesignerWorkbench(designerState.activeFlow);
630
+ }
631
+
632
+ function removeParallelBranch(stepName, branchIdx) {
633
+ const step = designerState.activeFlow?.definition?.states?.[stepName];
634
+ if (!step || !Array.isArray(step.branches)) return;
635
+ if (step.branches.length <= 1) {
636
+ toast('A Parallel step must have at least one branch.', 'warning');
637
+ return;
638
+ }
639
+ step.branches.splice(branchIdx, 1);
640
+ renderFlowDesignerWorkbench(designerState.activeFlow);
641
+ }
642
+
643
+ function updateParallelBranchFunction(stepName, branchIdx, fnName) {
644
+ const step = designerState.activeFlow?.definition?.states?.[stepName];
645
+ if (!step || !Array.isArray(step.branches) || !step.branches[branchIdx]) return;
646
+ const branch = step.branches[branchIdx];
647
+ const startKey = branch.startAt || Object.keys(branch.states || {})[0] || `Branch${branchIdx + 1}_Task`;
648
+ branch.startAt = startKey;
649
+ if (!branch.states) branch.states = {};
650
+ if (!branch.states[startKey]) {
651
+ branch.states[startKey] = {
652
+ type: 'Task',
653
+ function: fnName,
654
+ end: true,
655
+ };
656
+ } else {
657
+ branch.states[startKey].type = 'Task';
658
+ branch.states[startKey].function = fnName;
659
+ branch.states[startKey].end = true;
660
+ }
661
+ renderSvgFlowchart(designerState.activeFlow);
662
+ }
663
+
664
+ function updateLoopCondition(stepName, prop, val) {
665
+ const step = designerState.activeFlow?.definition?.states?.[stepName];
666
+ if (!step) return;
667
+ if (!step.condition) step.condition = { variable: '$.counter' };
668
+ if (prop === 'variable') {
669
+ let cleanVal = String(val || '').trim();
670
+ if (cleanVal && !cleanVal.startsWith('$')) {
671
+ cleanVal = cleanVal.startsWith('[') ? '$' + cleanVal : '$.' + cleanVal;
672
+ }
673
+ step.condition.variable = cleanVal;
674
+ } else if (prop === 'numericLessThan') {
675
+ const num = typeof val === 'number' ? val : parseFloat(val);
676
+ if (isNaN(num)) {
677
+ delete step.condition.numericLessThan;
678
+ } else {
679
+ step.condition.numericLessThan = num;
680
+ }
681
+ } else {
682
+ step.condition[prop] = val;
683
+ }
684
+ }
685
+
686
+ function updatePassResult(stepName, jsonStr) {
687
+ const step = designerState.activeFlow?.definition?.states?.[stepName];
688
+ if (!step) return;
689
+ try {
690
+ step.result = JSON.parse(jsonStr);
691
+ } catch (e) {
692
+ step.result = jsonStr;
693
+ }
694
+ }
695
+
696
+ function addChoiceBranch(stepName) {
697
+ const step = designerState.activeFlow?.definition?.states?.[stepName];
698
+ if (!step) return;
699
+ if (!step.choices) step.choices = [];
700
+ step.choices.push({ variable: '$.status', stringEquals: 'approved', next: '' });
701
+ renderFlowDesignerWorkbench(designerState.activeFlow);
702
+ }
703
+
704
+ function removeChoiceBranch(stepName, index) {
705
+ const step = designerState.activeFlow?.definition?.states?.[stepName];
706
+ if (!step || !step.choices) return;
707
+ step.choices.splice(index, 1);
708
+ renderFlowDesignerWorkbench(designerState.activeFlow);
709
+ }
710
+
711
+ function updateChoiceBranch(stepName, index, prop, val) {
712
+ const step = designerState.activeFlow?.definition?.states?.[stepName];
713
+ if (step?.choices?.[index]) {
714
+ if (prop === 'variable') {
715
+ let v = (val || '').trim();
716
+ if (v && !v.startsWith('$')) {
717
+ v = '$.' + v;
718
+ }
719
+ step.choices[index].variable = v;
720
+ } else {
721
+ step.choices[index][prop] = val;
722
+ }
723
+ renderSvgFlowchart(designerState.activeFlow);
724
+ }
725
+ }
726
+
727
+ function updateChoiceBranchOp(stepName, index, op) {
728
+ const branch = designerState.activeFlow?.definition?.states?.[stepName]?.choices?.[index];
729
+ if (!branch) return;
730
+
731
+ delete branch.stringEquals;
732
+ delete branch.numericEquals;
733
+ delete branch.numericGreaterThan;
734
+ delete branch.numericLessThan;
735
+ delete branch.numericGreaterThanEquals;
736
+ delete branch.numericLessThanEquals;
737
+ delete branch.booleanEquals;
738
+ delete branch.isPresent;
739
+
740
+ if (op === 'booleanEquals') {
741
+ branch.booleanEquals = true;
742
+ } else if (op === 'isPresent') {
743
+ branch.isPresent = true;
744
+ } else if (op === 'numericGreaterThan') {
745
+ branch.numericGreaterThan = 0;
746
+ } else if (op === 'numericLessThan') {
747
+ branch.numericLessThan = 10;
748
+ } else if (op === 'numericEquals') {
749
+ branch.numericEquals = 0;
750
+ } else if (op === 'numericGreaterThanEquals') {
751
+ branch.numericGreaterThanEquals = 0;
752
+ } else if (op === 'numericLessThanEquals') {
753
+ branch.numericLessThanEquals = 10;
754
+ } else {
755
+ branch.stringEquals = '';
756
+ }
757
+
758
+ renderFlowDesignerWorkbench(designerState.activeFlow);
759
+ }
760
+
761
+ function updateChoiceBranchVal(stepName, index, val) {
762
+ const branch = designerState.activeFlow?.definition?.states?.[stepName]?.choices?.[index];
763
+ if (!branch) return;
764
+
765
+ if (branch.booleanEquals !== undefined) {
766
+ branch.booleanEquals = val === 'true';
767
+ } else if (branch.isPresent !== undefined) {
768
+ branch.isPresent = val === 'true';
769
+ } else if (branch.numericGreaterThan !== undefined ||
770
+ branch.numericLessThan !== undefined ||
771
+ branch.numericEquals !== undefined ||
772
+ branch.numericGreaterThanEquals !== undefined ||
773
+ branch.numericLessThanEquals !== undefined) {
774
+ const num = Number(val);
775
+ if (isNaN(num) || String(val).trim() === '') {
776
+ toast('Please enter a valid numeric value for number conditions.', 'warning');
777
+ renderFlowDesignerWorkbench(designerState.activeFlow);
778
+ return;
779
+ }
780
+ if (branch.numericGreaterThan !== undefined) branch.numericGreaterThan = num;
781
+ else if (branch.numericLessThan !== undefined) branch.numericLessThan = num;
782
+ else if (branch.numericEquals !== undefined) branch.numericEquals = num;
783
+ else if (branch.numericGreaterThanEquals !== undefined) branch.numericGreaterThanEquals = num;
784
+ else if (branch.numericLessThanEquals !== undefined) branch.numericLessThanEquals = num;
785
+ } else {
786
+ branch.stringEquals = String(val);
787
+ }
788
+
789
+ renderSvgFlowchart(designerState.activeFlow);
790
+ }
791
+
792
+ function deleteStep(stepName, evt) {
793
+ if (evt) evt.stopPropagation();
794
+ if (!confirm(`Delete step "${stepName}"?`)) return;
795
+
796
+ const states = designerState.activeFlow.definition.states;
797
+ delete states[stepName];
798
+
799
+ // Clean up references across all remaining states
800
+ Object.values(states).forEach((st) => {
801
+ if (st.next === stepName) delete st.next;
802
+ if (st.target === stepName) delete st.target;
803
+ if (st.default === stepName) delete st.default;
804
+ if (Array.isArray(st.choices)) {
805
+ st.choices.forEach((c) => {
806
+ if (c.next === stepName) c.next = '';
807
+ });
808
+ }
809
+ });
810
+
811
+ if (designerState.activeFlow.definition.startAt === stepName) {
812
+ const keys = Object.keys(states);
813
+ designerState.activeFlow.definition.startAt = keys[0] || '';
814
+ }
815
+ renderFlowDesignerWorkbench(designerState.activeFlow);
816
+ }
817
+
818
+ function renameStep(oldName, newName) {
819
+ const trimmed = newName ? newName.trim() : '';
820
+ if (!trimmed || oldName === trimmed) return;
821
+ const states = designerState.activeFlow.definition.states;
822
+ if (states[trimmed]) {
823
+ toast(`A step with name "${trimmed}" already exists`, 'warning');
824
+ renderFlowDesignerWorkbench(designerState.activeFlow);
825
+ return;
826
+ }
827
+
828
+ // Preserve exact key position in states object so renamed step does not jump to the end
829
+ const keys = Object.keys(states);
830
+ const newStates = {};
831
+ keys.forEach((k) => {
832
+ if (k === oldName) {
833
+ newStates[trimmed] = states[oldName];
834
+ } else {
835
+ newStates[k] = states[k];
836
+ }
837
+ });
838
+ designerState.activeFlow.definition.states = newStates;
839
+
840
+ // Synchronize references across all other states
841
+ Object.values(newStates).forEach((st) => {
842
+ if (st.next === oldName) st.next = trimmed;
843
+ if (st.target === oldName) st.target = trimmed;
844
+ if (st.default === oldName) st.default = trimmed;
845
+ if (Array.isArray(st.choices)) {
846
+ st.choices.forEach((c) => {
847
+ if (c.next === oldName) c.next = trimmed;
848
+ });
849
+ }
850
+ });
851
+
852
+ if (designerState.activeFlow.definition.startAt === oldName) {
853
+ designerState.activeFlow.definition.startAt = trimmed;
854
+ }
855
+ if (designerState.selectedStepName === oldName) {
856
+ designerState.selectedStepName = trimmed;
857
+ }
858
+
859
+ renderFlowDesignerWorkbench(designerState.activeFlow);
860
+ }
861
+
862
+ function validateFlowDefinitionClient(def) {
863
+ if (!def || typeof def !== 'object') return 'Flow definition is empty or invalid.';
864
+ if (!def.startAt || typeof def.startAt !== 'string' || !def.startAt.trim()) {
865
+ return 'Flow must have a Start Step configured.';
866
+ }
867
+ if (!def.states || typeof def.states !== 'object' || Object.keys(def.states).length === 0) {
868
+ return 'Flow must contain at least one step in definition.';
869
+ }
870
+ if (!def.states[def.startAt]) {
871
+ return `Start Step "${def.startAt}" does not exist in flow steps.`;
872
+ }
873
+
874
+ const keys = Object.keys(def.states);
875
+ for (const [name, state] of Object.entries(def.states)) {
876
+ if (!state || typeof state !== 'object') {
877
+ return `Step "${name}" is invalid.`;
878
+ }
879
+
880
+ if (state.next && !keys.includes(state.next)) {
881
+ return `Step "${name}" points to non-existent step "${state.next}".`;
882
+ }
883
+
884
+ if (state.type === 'Task') {
885
+ if (!state.function || !state.function.trim()) {
886
+ return `Task step "${name}" must specify a serverless function.`;
887
+ }
888
+ if (!state.next && !state.end) {
889
+ return `Task step "${name}" must configure "Then Go To" or mark as "End State".`;
890
+ }
891
+ } else if (state.type === 'Choice') {
892
+ if (!Array.isArray(state.choices) || state.choices.length === 0) {
893
+ return `Choice step "${name}" must have at least one condition rule.`;
894
+ }
895
+ for (let i = 0; i < state.choices.length; i++) {
896
+ const c = state.choices[i];
897
+ if (!c.variable || !c.variable.trim() || !c.variable.startsWith('$')) {
898
+ return `Choice step "${name}" rule #${i + 1} variable must start with '$' (e.g. $.status).`;
899
+ }
900
+ if (!c.next || !keys.includes(c.next)) {
901
+ return `Choice step "${name}" rule #${i + 1} must select a valid target step.`;
902
+ }
903
+
904
+ const isNumeric = c.numericGreaterThan !== undefined ||
905
+ c.numericLessThan !== undefined ||
906
+ c.numericEquals !== undefined ||
907
+ c.numericGreaterThanEquals !== undefined ||
908
+ c.numericLessThanEquals !== undefined;
909
+
910
+ if (isNumeric) {
911
+ const num = c.numericGreaterThan ??
912
+ c.numericLessThan ??
913
+ c.numericEquals ??
914
+ c.numericGreaterThanEquals ??
915
+ c.numericLessThanEquals;
916
+ if (typeof num !== 'number' || isNaN(num) || !Number.isFinite(num)) {
917
+ return `Choice step "${name}" rule #${i + 1} has invalid non-numeric value: ${JSON.stringify(num)}.`;
918
+ }
919
+ }
920
+
921
+ if (c.booleanEquals !== undefined && typeof c.booleanEquals !== 'boolean') {
922
+ return `Choice step "${name}" rule #${i + 1} boolean condition must be true or false.`;
923
+ }
924
+ }
925
+
926
+ if (state.default && !keys.includes(state.default)) {
927
+ return `Choice step "${name}" default fallback step "${state.default}" does not exist.`;
928
+ }
929
+ } else if (state.type === 'Loop') {
930
+ if (!state.target || !keys.includes(state.target)) {
931
+ return `Loop step "${name}" must select a valid jump target step.`;
932
+ }
933
+ if (state.maxIterations !== undefined) {
934
+ if (typeof state.maxIterations !== 'number' || state.maxIterations < 1) {
935
+ return `Loop step "${name}" max iterations must be a positive number.`;
936
+ }
937
+ }
938
+ if (!state.condition || typeof state.condition !== 'object') {
939
+ return `Loop step "${name}" must specify a condition choice rule.`;
940
+ }
941
+ if (!state.next && !state.end) {
942
+ return `Loop step "${name}" must configure "Then Go To" or mark as "End State".`;
943
+ }
944
+ } else if (state.type === 'Wait') {
945
+ if (typeof state.seconds !== 'number' || isNaN(state.seconds) || state.seconds < 0) {
946
+ return `Wait step "${name}" seconds delay must be a non-negative number.`;
947
+ }
948
+ if (!state.next && !state.end) {
949
+ return `Wait step "${name}" must configure "Then Go To" or mark as "End State".`;
950
+ }
951
+ } else if (state.type === 'Map') {
952
+ if (!state.itemsPath || !state.itemsPath.startsWith('$')) {
953
+ return `Map step "${name}" itemsPath must be a valid JSONPath starting with '$'.`;
954
+ }
955
+ if (!state.iterator || typeof state.iterator !== 'object') {
956
+ return `Map step "${name}" must specify an iterator with startAt and states.`;
957
+ }
958
+ const subErr = validateFlowDefinitionClient(state.iterator);
959
+ if (subErr) {
960
+ return `Map step "${name}" iterator: ${subErr}`;
961
+ }
962
+ if (!state.next && !state.end) {
963
+ return `Map step "${name}" must configure "Then Go To" or mark as "End State".`;
964
+ }
965
+ } else if (state.type === 'Parallel') {
966
+ if (!Array.isArray(state.branches) || state.branches.length === 0) {
967
+ return `Parallel step "${name}" must have at least one branch in "branches".`;
968
+ }
969
+ for (let bIdx = 0; bIdx < state.branches.length; bIdx++) {
970
+ const branch = state.branches[bIdx];
971
+ if (!branch || typeof branch !== 'object') {
972
+ return `Parallel step "${name}" branch #${bIdx + 1} is invalid.`;
973
+ }
974
+ const subErr = validateFlowDefinitionClient(branch);
975
+ if (subErr) {
976
+ return `Parallel step "${name}" branch #${bIdx + 1}: ${subErr}`;
977
+ }
978
+ }
979
+ if (!state.next && !state.end) {
980
+ return `Parallel step "${name}" must configure "Then Go To" or mark as "End State".`;
981
+ }
982
+ } else if (state.type === 'Pass') {
983
+ if (!state.next && !state.end) {
984
+ return `Pass step "${name}" must configure "Then Go To" or mark as "End State".`;
985
+ }
986
+ } else if (state.type === 'Succeed' || state.type === 'Fail') {
987
+ // Terminal states must not have next or end transitions
988
+ if (state.next) {
989
+ delete state.next;
990
+ }
991
+ if (state.end) {
992
+ delete state.end;
993
+ }
994
+ }
995
+ }
996
+
997
+ return null;
998
+ }
999
+
1000
+ function selectStepCard(name) {
1001
+ designerState.selectedStepName = name;
1002
+ document.querySelectorAll('.flow-step-card').forEach((el) => el.classList.remove('active-step'));
1003
+ const safeSelector = typeof CSS !== 'undefined' && CSS.escape ? `.flow-step-card[data-step-name="${CSS.escape(name)}"]` : null;
1004
+ const card = (safeSelector ? document.querySelector(safeSelector) : null) || document.getElementById(`step-card-${name}`);
1005
+ if (card) card.classList.add('active-step');
1006
+ }
1007
+
1008
+ function selectStepFromDiagram(name) {
1009
+ selectStepCard(name);
1010
+ const safeSelector = typeof CSS !== 'undefined' && CSS.escape ? `.flow-step-card[data-step-name="${CSS.escape(name)}"]` : null;
1011
+ const card = (safeSelector ? document.querySelector(safeSelector) : null) || document.getElementById(`step-card-${name}`);
1012
+ if (card && typeof card.scrollIntoView === 'function') {
1013
+ card.scrollIntoView({ behavior: 'smooth', block: 'center' });
1014
+ }
1015
+ }
1016
+
1017
+ function switchDesignerMode(mode) {
1018
+ if (designerState.activeMode === 'code' && designerState.cmDslEditor) {
1019
+ try {
1020
+ const parsed = JSON.parse(designerState.cmDslEditor.getValue());
1021
+ const validationError = validateFlowDefinitionClient(parsed);
1022
+ if (validationError) {
1023
+ toast('DSL Validation Warning: ' + validationError, 'warning');
1024
+ } else {
1025
+ designerState.activeFlow.definition = parsed;
1026
+ }
1027
+ } catch (e) {
1028
+ toast('Invalid JSON in editor: ' + e.message, 'warning');
1029
+ }
1030
+ }
1031
+ designerState.activeMode = mode;
1032
+ renderFlowDesignerWorkbench(designerState.activeFlow);
1033
+ }
1034
+
1035
+ async function saveFlowChanges(options = {}) {
1036
+ const flow = designerState.activeFlow;
1037
+ if (!flow || !flow.id) return false;
1038
+
1039
+ if (designerState.activeMode === 'code' && designerState.cmDslEditor) {
1040
+ try {
1041
+ const parsed = JSON.parse(designerState.cmDslEditor.getValue());
1042
+ flow.definition = parsed;
1043
+ } catch (e) {
1044
+ toast('Invalid JSON in DSL editor: ' + e.message, 'error');
1045
+ return false;
1046
+ }
1047
+ }
1048
+
1049
+ const validationError = validateFlowDefinitionClient(flow.definition);
1050
+ if (validationError) {
1051
+ toast('Validation Error: ' + validationError, 'error');
1052
+ return false;
1053
+ }
1054
+
1055
+ try {
1056
+ const base = getDesignerFlowsApiBase();
1057
+ const updated = await api(`${base}/${flow.id}`, {
1058
+ method: 'PATCH',
1059
+ body: JSON.stringify({
1060
+ name: flow.name,
1061
+ description: flow.description,
1062
+ triggerType: flow.triggerType,
1063
+ authPolicy: flow.authPolicy || 'public',
1064
+ invokeRule: (flow.triggerType || 'http') === 'http' && flow.authPolicy === 'custom'
1065
+ ? (typeof getStandaloneRuleValue === 'function' ? getStandaloneRuleValue('flow_invoke') : (flow.invokeRule || null))
1066
+ : null,
1067
+ eventTrigger: flow.triggerType === 'event' ? (flow.eventTrigger || null) : null,
1068
+ maxConcurrentExecutions: flow.maxConcurrentExecutions ?? null,
1069
+ definition: flow.definition,
1070
+ }),
1071
+ });
1072
+ flowsState.activeFlowForEdit = updated;
1073
+ designerState.activeFlow = JSON.parse(JSON.stringify(updated));
1074
+
1075
+ if (typeof updateUrl === 'function') {
1076
+ const flowIdentifier = updated.name ? encodeURIComponent(updated.name) : encodeURIComponent(updated.id);
1077
+ updateUrl('/_/flows/' + flowIdentifier, true);
1078
+ }
1079
+
1080
+ if (typeof updateBreadcrumbs === 'function') {
1081
+ updateBreadcrumbs();
1082
+ }
1083
+
1084
+ if (!options || !options.silent) {
1085
+ toast('Flow changes saved successfully!', 'success');
1086
+ }
1087
+ return true;
1088
+ } catch (err) {
1089
+ toast('Failed to save flow: ' + (err.message || err), 'error');
1090
+ return false;
1091
+ }
1092
+ }
1093
+
1094
+ if (typeof window !== 'undefined') {
1095
+ window.openFlowDesigner = openFlowDesigner;
1096
+ window.closeFlowDesigner = closeFlowDesigner;
1097
+ window.renderFlowDesignerWorkbench = renderFlowDesignerWorkbench;
1098
+ window.updateFlowMeta = updateFlowMeta;
1099
+ window.handleFlowTriggerTypeChange = handleFlowTriggerTypeChange;
1100
+ window.handleFlowAuthPolicyChange = handleFlowAuthPolicyChange;
1101
+ window.updateFlowStartAt = updateFlowStartAt;
1102
+ window.updateStepProp = updateStepProp;
1103
+ window.handleStepEndToggle = handleStepEndToggle;
1104
+ window.handleStepNextChange = handleStepNextChange;
1105
+ window.updateMapIteratorFunction = updateMapIteratorFunction;
1106
+ window.addParallelBranch = addParallelBranch;
1107
+ window.removeParallelBranch = removeParallelBranch;
1108
+ window.updateParallelBranchFunction = updateParallelBranchFunction;
1109
+ window.updateLoopCondition = updateLoopCondition;
1110
+ window.updatePassResult = updatePassResult;
1111
+ window.addChoiceBranch = addChoiceBranch;
1112
+ window.removeChoiceBranch = removeChoiceBranch;
1113
+ window.updateChoiceBranch = updateChoiceBranch;
1114
+ window.updateChoiceBranchOp = updateChoiceBranchOp;
1115
+ window.updateChoiceBranchVal = updateChoiceBranchVal;
1116
+ window.deleteStep = deleteStep;
1117
+ window.renameStep = renameStep;
1118
+ window.selectStepCard = selectStepCard;
1119
+ window.selectStepFromDiagram = selectStepFromDiagram;
1120
+ window.switchDesignerMode = switchDesignerMode;
1121
+ window.syncDslToVisual = syncDslToVisual;
1122
+ window.toggleTestDrawer = toggleTestDrawer;
1123
+ window.runFlowTest = runFlowTest;
1124
+ window.saveFlowChanges = saveFlowChanges;
1125
+ }