@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,890 +1,908 @@
1
- // Functions Flow Manager Module for NodeStack Admin UI
2
- // State, flows list overview, executions history, and serverless functions lookup
3
-
4
- let flowsState = {
5
- currentView: 'list', // 'list' | 'designer'
6
- subTab: 'flows', // 'flows' | 'executions'
7
- flows: [],
8
- executions: [],
9
- functions: [], // loaded from /api/functions for dropdowns
10
- filter: {
11
- search: '',
12
- status: 'all',
13
- },
14
- activeFlowForEdit: null,
15
- };
16
-
17
- if (typeof window !== 'undefined') {
18
- window.flowsState = flowsState;
19
- }
20
-
21
- // ==========================================
22
- // 1. API Fetching
23
- // ==========================================
24
-
25
- function getFlowsApiBase() {
26
- const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : (typeof state !== 'undefined' && state?.activeApp?.slug ? state.activeApp.slug : 'default');
27
- return slug && slug !== 'default' ? `/api/apps/${slug}/flows` : '/api/flows';
28
- }
29
-
30
- function 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
- if (typeof window !== 'undefined') {
36
- window.getFlowsApiBase = getFlowsApiBase;
37
- window.getFunctionsApiBase = getFunctionsApiBase;
38
- }
39
-
40
- async function loadFlows() {
41
- try {
42
- const endpoint = getFlowsApiBase();
43
- const res = await api(endpoint);
44
- flowsState.flows = Array.isArray(res) ? res : res?.data || [];
45
- updateSidebarFlowsCount();
46
- return flowsState.flows;
47
- } catch (err) {
48
- console.error('Failed to load flows:', err);
49
- return [];
50
- }
51
- }
52
-
53
- async function loadFlowExecutions(flowId = '') {
54
- try {
55
- const base = getFlowsApiBase();
56
- const statusParam = flowsState.filter?.status && flowsState.filter.status !== 'all'
57
- ? `?status=${encodeURIComponent(flowsState.filter.status)}`
58
- : '';
59
- const url = flowId ? `${base}/${flowId}/executions${statusParam}` : `${base}/executions${statusParam}`;
60
- const res = await api(url);
61
- flowsState.executions = res?.items || (Array.isArray(res) ? res : []);
62
- return flowsState.executions;
63
- } catch (err) {
64
- console.error('Failed to load flow executions:', err);
65
- return [];
66
- }
67
- }
68
-
69
- async function loadFunctionsForPicker() {
70
- try {
71
- const endpoint = getFunctionsApiBase();
72
- const res = await api(endpoint);
73
- flowsState.functions = Array.isArray(res) ? res : res?.data || [];
74
- } catch (err) {
75
- console.error('Failed to load functions for picker:', err);
76
- }
77
- }
78
-
79
- function updateSidebarFlowsCount() {
80
- const count = (flowsState.flows || []).length;
81
- const badge = document.getElementById('sidebar-flows-count');
82
- if (badge) {
83
- badge.textContent = count;
84
- badge.style.display = count > 0 ? 'inline-block' : 'none';
85
- }
86
-
87
- const homeFlowEl = document.getElementById('home-stat-flows');
88
- const homeFlowSubEl = document.getElementById('home-stat-flows-sub');
89
- if (homeFlowEl) {
90
- homeFlowEl.textContent = String(count);
91
- }
92
- if (homeFlowSubEl) {
93
- const active = (flowsState.flows || []).filter(f => f.enabled !== false).length;
94
- const runs = (flowsState.executions && Array.isArray(flowsState.executions)) ? flowsState.executions.length : 0;
95
- homeFlowSubEl.textContent = `${active} active${runs > 0 ? ` • ${runs} runs` : ' • visual pipelines'}`;
96
- }
97
- }
98
-
99
- // ==========================================
100
- // 2. Flows Overview Page Render
101
- // ==========================================
102
-
103
- async function renderFlowsView() {
104
- if (flowsState.currentView === 'designer') {
105
- const active = (typeof designerState !== 'undefined' && designerState.activeFlow)
106
- ? designerState.activeFlow
107
- : flowsState.activeFlowForEdit;
108
- if (active && typeof renderFlowDesignerWorkbench === 'function') {
109
- renderFlowDesignerWorkbench(active);
110
- }
111
- return;
112
- }
113
-
114
- const container = document.getElementById('page-view-flows') || document.getElementById('main-body');
115
- if (!container) return;
116
-
117
- container.innerHTML = `
118
- <div class="flows-container">
119
- <!-- Header -->
120
- <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 1rem;">
121
- <div>
122
- <h2 style="font-size: 1.35rem; font-weight: 700; color: var(--text-main); margin: 0 0 0.25rem 0; display: flex; align-items: center; gap: 0.5rem;">
123
- <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
124
- <circle cx="12" cy="5" r="3"/><line x1="12" y1="8" x2="12" y2="12"/><circle cx="6" cy="19" r="3"/><circle cx="18" cy="19" r="3"/><path d="M12 12h-6v4"/><path d="M12 12h6v4"/>
125
- </svg>
126
- Functions Flow
127
- </h2>
128
- <p style="font-size: 0.85rem; color: var(--text-muted); margin: 0;">
129
- Visual state machine orchestration for chaining serverless functions with branching, loops, and map-reduce.
130
- </p>
131
- </div>
132
- <div style="display: flex; align-items: center; gap: 8px;">
133
- <button class="btn btn-secondary btn-sm" onclick="refreshFlowsView()" title="Refresh Flows">
134
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M23 4v6h-6M1 20v-6h6"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>
135
- Refresh
136
- </button>
137
- <button class="btn btn-primary btn-sm" onclick="openCreateFlowModal()">
138
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
139
- New Flow
140
- </button>
141
- </div>
142
- </div>
143
-
144
- <!-- Stats Grid -->
145
- <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem;">
146
- <div class="webhook-stat-card">
147
- <span class="webhook-stat-label">Total Flows</span>
148
- <div class="webhook-stat-value">
149
- <span id="flow-stat-total">${flowsState.flows.length}</span>
150
- </div>
151
- </div>
152
- <div class="webhook-stat-card">
153
- <span class="webhook-stat-label">Active Flows</span>
154
- <div class="webhook-stat-value">
155
- <span id="flow-stat-active" style="color: var(--accent-success);">${flowsState.flows.filter(f => f.enabled).length}</span>
156
- </div>
157
- </div>
158
- <div class="webhook-stat-card">
159
- <span class="webhook-stat-label">Available Functions</span>
160
- <div class="webhook-stat-value" id="flow-stat-functions">
161
- ${flowsState.functions.length}
162
- </div>
163
- </div>
164
- </div>
165
-
166
- <!-- Subtabs Bar -->
167
- <div style="display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--border-subtle, #334155); padding-bottom: 0.5rem; margin-top: 0.5rem;">
168
- <div style="display: flex; gap: 1rem;">
169
- <button class="btn-subtab ${flowsState.subTab === 'flows' ? 'active' : ''}" onclick="switchFlowsTab('flows')" style="background:none; border:none; color: ${flowsState.subTab === 'flows' ? 'var(--accent-primary, #6366f1)' : 'var(--text-muted)'}; font-weight: 600; font-size: 0.9rem; cursor: pointer; padding: 0.25rem 0.5rem; border-bottom: 2px solid ${flowsState.subTab === 'flows' ? 'var(--accent-primary, #6366f1)' : 'transparent'};">
170
- Configured Flows (${flowsState.flows.length})
171
- </button>
172
- <button class="btn-subtab ${flowsState.subTab === 'executions' ? 'active' : ''}" onclick="switchFlowsTab('executions')" style="background:none; border:none; color: ${flowsState.subTab === 'executions' ? 'var(--accent-primary, #6366f1)' : 'var(--text-muted)'}; font-weight: 600; font-size: 0.9rem; cursor: pointer; padding: 0.25rem 0.5rem; border-bottom: 2px solid ${flowsState.subTab === 'executions' ? 'var(--accent-primary, #6366f1)' : 'transparent'};">
173
- Execution History
174
- </button>
175
- </div>
176
- <div style="display: flex; align-items: center; gap: 8px;">
177
- ${flowsState.subTab === 'executions' ? `
178
- <select
179
- id="flows-status-filter"
180
- class="flow-field-select"
181
- style="width: 145px; font-size: 0.8rem;"
182
- onchange="handleFlowExecutionsStatusFilter(this.value)"
183
- >
184
- <option value="all" ${(flowsState.filter.status || 'all') === 'all' ? 'selected' : ''}>All Statuses</option>
185
- <option value="queued" ${flowsState.filter.status === 'queued' ? 'selected' : ''}>Queued</option>
186
- <option value="running" ${flowsState.filter.status === 'running' ? 'selected' : ''}>Running</option>
187
- <option value="succeeded" ${flowsState.filter.status === 'succeeded' ? 'selected' : ''}>Succeeded</option>
188
- <option value="failed" ${flowsState.filter.status === 'failed' ? 'selected' : ''}>Failed</option>
189
- <option value="aborted" ${flowsState.filter.status === 'aborted' ? 'selected' : ''}>Aborted</option>
190
- <option value="timeout" ${flowsState.filter.status === 'timeout' ? 'selected' : ''}>Timeout</option>
191
- </select>
192
- ` : ''}
193
- <input
194
- type="text"
195
- id="flows-search-input"
196
- class="flow-field-input"
197
- placeholder="Search flows by name..."
198
- style="width: 220px;"
199
- value="${escapeHtml(flowsState.filter.search || '')}"
200
- oninput="handleFlowsSearch(this.value)"
201
- />
202
- </div>
203
- </div>
204
-
205
- <!-- Content Section -->
206
- <div id="flows-subtab-content">
207
- ${flowsState.subTab === 'flows' ? renderFlowsListHtml() : renderFlowExecutionsListHtml()}
208
- </div>
209
- </div>
210
- `;
211
-
212
- // Pre-load data in background
213
- if (flowsState.functions.length === 0) {
214
- loadFunctionsForPicker().then(() => {
215
- const el = document.getElementById('flow-stat-functions');
216
- if (el) el.textContent = flowsState.functions.length;
217
- });
218
- }
219
- }
220
-
221
- function renderFlowsListHtml() {
222
- const filtered = flowsState.flows.filter(f => {
223
- if (!flowsState.filter.search) return true;
224
- const q = flowsState.filter.search.toLowerCase();
225
- return f.name.toLowerCase().includes(q) || (f.description && f.description.toLowerCase().includes(q));
226
- });
227
-
228
- if (filtered.length === 0) {
229
- return `
230
- <div style="text-align: center; padding: 4rem 2rem; background: var(--bg-card); border: 1px dashed var(--border-subtle); border-radius: 8px;">
231
- <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="var(--text-muted)" stroke-width="1.5" style="margin-bottom: 1rem;"><circle cx="12" cy="5" r="3"/><line x1="12" y1="8" x2="12" y2="12"/><circle cx="6" cy="19" r="3"/><circle cx="18" cy="19" r="3"/><path d="M12 12h-6v4"/><path d="M12 12h6v4"/></svg>
232
- <h3 style="font-size: 1.1rem; color: var(--text-main); margin: 0 0 0.5rem 0;">No Functions Flows Yet</h3>
233
- <p style="color: var(--text-muted); font-size: 0.85rem; max-width: 420px; margin: 0 auto 1.25rem auto;">
234
- Create a state machine flow to connect serverless functions, add conditional branching, loops, or batch map-reduce.
235
- </p>
236
- <button class="btn btn-primary btn-sm" onclick="openCreateFlowModal()">
237
- + Create First Flow
238
- </button>
239
- </div>
240
- `;
241
- }
242
-
243
- return `
244
- <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(360px, 1fr)); gap: 1rem;">
245
- ${filtered.map(flow => {
246
- const stateCount = flow.definition && flow.definition.states ? Object.keys(flow.definition.states).length : 0;
247
- return `
248
- <div class="webhook-stat-card" style="cursor: default;">
249
- <div style="display: flex; align-items: flex-start; justify-content: space-between; gap: 0.5rem;">
250
- <div>
251
- <h4 style="margin: 0 0 0.25rem 0; font-size: 1rem; color: var(--text-main); font-weight: 600;">
252
- ${escapeHtml(flow.name)}
253
- </h4>
254
- <p style="margin: 0; font-size: 0.8rem; color: var(--text-muted); min-height: 1.2rem;">
255
- ${escapeHtml(flow.description || 'No description provided')}
256
- </p>
257
- </div>
258
- <span class="badge ${flow.enabled ? 'badge-get' : 'badge-danger'}" style="font-size: 10px;">
259
- ${flow.enabled ? 'ACTIVE' : 'DISABLED'}
260
- </span>
261
- </div>
262
-
263
- <div style="display: flex; align-items: center; gap: 0.75rem; margin: 0.75rem 0; font-size: 0.75rem; color: var(--text-muted); flex-wrap: wrap;">
264
- <span><strong>Trigger:</strong> <code style="color: var(--accent-primary);">${formatFlowTriggerLabel(flow)}</code></span>
265
- <span>•</span>
266
- <span><strong>Steps:</strong> ${stateCount} states</span>
267
- <span>•</span>
268
- <span><strong>Concurrency:</strong> ${flow.maxConcurrentExecutions ? escapeHtml(String(flow.maxConcurrentExecutions)) : 'Unlimited'}</span>
269
- </div>
270
-
271
- <div style="display: flex; align-items: center; justify-content: space-between; border-top: 1px solid var(--border-subtle); padding-top: 0.75rem; margin-top: auto;">
272
- <div style="display: flex; gap: 6px;">
273
- <button class="btn btn-primary btn-sm" data-flow-id="${escapeHtml(flow.id)}" onclick="openFlowDesigner(this.getAttribute('data-flow-id'))" style="font-weight: 600;">
274
- Open Designer
275
- </button>
276
- <button class="btn btn-secondary btn-sm" data-flow-id="${escapeHtml(flow.id)}" onclick="quickTestFlow(this.getAttribute('data-flow-id'))" title="Test Flow Execution">
277
- ▶ Run
278
- </button>
279
- </div>
280
- <div style="display: flex; gap: 6px;">
281
- <button class="btn btn-secondary btn-sm" data-flow-id="${escapeHtml(flow.id)}" data-enabled="${!flow.enabled}" onclick="toggleFlowStatus(this.getAttribute('data-flow-id'), this.getAttribute('data-enabled') === 'true')" title="${flow.enabled ? 'Disable' : 'Enable'}">
282
- ${flow.enabled ? 'Disable' : 'Enable'}
283
- </button>
284
- <button class="btn btn-danger btn-sm" data-flow-id="${escapeHtml(flow.id)}" data-flow-name="${escapeHtml(flow.name)}" onclick="deleteFlowPrompt(this.getAttribute('data-flow-id'), this.getAttribute('data-flow-name'))" title="Delete Flow">
285
- 🗑
286
- </button>
287
- </div>
288
- </div>
289
- </div>
290
- `;
291
- }).join('')}
292
- </div>
293
- `;
294
- }
295
-
296
- function renderFlowExecutionsListHtml() {
297
- const executions = flowsState.executions || [];
298
- if (executions.length === 0) {
299
- return `
300
- <div style="text-align: center; padding: 3rem; background: var(--bg-card); border-radius: 8px; color: var(--text-muted);">
301
- <p style="margin: 0;">No flow executions recorded yet. Run a flow to inspect step timeline and logs.</p>
302
- </div>
303
- `;
304
- }
305
-
306
- return `
307
- <div style="background: var(--bg-card); border: 1px solid var(--border-subtle); border-radius: 8px; overflow: hidden;">
308
- <table style="width: 100%; border-collapse: collapse; font-size: 0.85rem; text-align: left;">
309
- <thead>
310
- <tr style="background: rgba(0,0,0,0.15); border-bottom: 1px solid var(--border-subtle); color: var(--text-muted);">
311
- <th style="padding: 0.75rem 1rem;">Status</th>
312
- <th style="padding: 0.75rem 1rem;">Flow Name</th>
313
- <th style="padding: 0.75rem 1rem;">Duration</th>
314
- <th style="padding: 0.75rem 1rem;">Steps</th>
315
- <th style="padding: 0.75rem 1rem;">Caller</th>
316
- <th style="padding: 0.75rem 1rem;">Started At</th>
317
- <th style="padding: 0.75rem 1rem; text-align: right;">Action</th>
318
- </tr>
319
- </thead>
320
- <tbody>
321
- ${executions.map(exec => {
322
- const statusColor = exec.status === 'succeeded' ? 'var(--accent-success)' : exec.status === 'failed' ? 'var(--accent-danger)' : (exec.status === 'aborted' || exec.status === 'queued') ? 'var(--accent-warning, #f59e0b)' : '#3b82f6';
323
- const stepCount = (exec.stepLogs || []).length;
324
- return `
325
- <tr style="border-bottom: 1px solid var(--border-subtle);">
326
- <td style="padding: 0.75rem 1rem;">
327
- <span style="font-weight: 700; color: ${statusColor}; text-transform: uppercase; font-size: 0.75rem;">
328
- ● ${exec.status}
329
- </span>
330
- </td>
331
- <td style="padding: 0.75rem 1rem; font-weight: 600; color: var(--text-main);">
332
- ${escapeHtml(exec.flowName)}
333
- </td>
334
- <td style="padding: 0.75rem 1rem; color: var(--text-muted);">
335
- ${exec.durationMs}ms
336
- </td>
337
- <td style="padding: 0.75rem 1rem; color: var(--text-muted);">
338
- ${stepCount} steps
339
- </td>
340
- <td style="padding: 0.75rem 1rem; font-family: var(--font-mono, monospace); font-size: 0.8rem; color: var(--text-muted);">
341
- <span class="badge" style="font-size: 11px; font-weight: 500; background: rgba(255,255,255,0.06);">${escapeHtml(exec.actorId || 'public')}</span>
342
- </td>
343
- <td style="padding: 0.75rem 1rem; color: var(--text-muted); font-size: 0.8rem;">
344
- ${new Date(exec.startedAt).toLocaleString()}
345
- </td>
346
- <td style="padding: 0.75rem 1rem; text-align: right;">
347
- <button class="btn btn-secondary btn-sm" data-exec-id="${escapeHtml(exec.id)}" onclick="inspectExecutionDetail(this.getAttribute('data-exec-id'))">
348
- Inspect
349
- </button>
350
- </td>
351
- </tr>
352
- `;
353
- }).join('')}
354
- </tbody>
355
- </table>
356
- </div>
357
- `;
358
- }
359
-
360
- // ==========================================
361
- // 3. User Actions
362
- // ==========================================
363
-
364
- async function refreshFlowsView() {
365
- await loadFlows();
366
- if (flowsState.subTab === 'executions') {
367
- await loadFlowExecutions();
368
- }
369
- renderFlowsView();
370
- }
371
-
372
- function switchFlowsTab(tab, pushState = true) {
373
- flowsState.subTab = tab;
374
- if (pushState && typeof updateUrl === 'function') {
375
- const path = (tab === 'executions') ? '/_/flows/executions' : '/_/flows';
376
- updateUrl(path);
377
- }
378
- if (typeof updateBreadcrumbs === 'function') {
379
- updateBreadcrumbs();
380
- }
381
- if (tab === 'executions') {
382
- loadFlowExecutions().then(() => renderFlowsView());
383
- } else {
384
- renderFlowsView();
385
- }
386
- }
387
-
388
- function handleFlowsSearch(val) {
389
- flowsState.filter.search = val;
390
- const content = document.getElementById('flows-subtab-content');
391
- if (content && flowsState.subTab === 'flows') {
392
- content.innerHTML = renderFlowsListHtml();
393
- }
394
- }
395
-
396
- async function handleFlowExecutionsStatusFilter(status) {
397
- flowsState.filter.status = status || 'all';
398
- await loadFlowExecutions();
399
- const content = document.getElementById('flows-subtab-content');
400
- if (content && flowsState.subTab === 'executions') {
401
- content.innerHTML = renderFlowExecutionsListHtml();
402
- }
403
- }
404
-
405
- async function toggleFlowStatus(flowId, enabled) {
406
- try {
407
- const base = getFlowsApiBase();
408
- await api(`${base}/${flowId}`, {
409
- method: 'PATCH',
410
- body: JSON.stringify({ enabled }),
411
- });
412
- await refreshFlowsView();
413
- toast(`Flow ${enabled ? 'enabled' : 'disabled'} successfully`, 'success');
414
- } catch (err) {
415
- toast('Failed to update flow: ' + (err.message || err), 'error');
416
- }
417
- }
418
-
419
- function openDeleteFlowModal(flowId, name) {
420
- let modalRoot = document.getElementById('modal-root');
421
- if (!modalRoot) {
422
- modalRoot = document.createElement('div');
423
- modalRoot.id = 'modal-root';
424
- document.body.appendChild(modalRoot);
425
- }
426
-
427
- const safeId = typeof escapeHtml === 'function' ? escapeHtml(flowId) : flowId;
428
- const safeName = typeof escapeHtml === 'function' ? escapeHtml(name) : name;
429
-
430
- modalRoot.innerHTML = `
431
- <div class="modal-backdrop" id="delete-flow-backdrop" onclick="if(event.target===this)closeDeleteFlowModal()">
432
- <div class="modal confirm-dialog">
433
- <div class="modal-header" style="border-bottom-color: rgba(239, 68, 68, 0.2);">
434
- <div style="display: flex; align-items: center; gap: 0.5rem;">
435
- <span style="font-size: 18px;">⚠️</span>
436
- <h2 class="modal-title danger" style="font-size: 16px;">Delete Flow</h2>
437
- </div>
438
- <button type="button" class="btn btn-secondary btn-sm" onclick="closeDeleteFlowModal()" aria-label="Close">✕</button>
439
- </div>
440
- <div class="modal-body" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
441
- <p style="font-size: 13px; color: var(--text-main, #cbd5e1); line-height: 1.5; margin: 0;">
442
- Are you sure you want to delete flow <strong style="color: var(--text-heading); font-family: var(--font-mono);">${safeName}</strong>? All execution history and logs will be permanently removed.
443
- </p>
444
- <div class="confirm-dialog-banner danger">
445
- This action cannot be undone. Invocations to <code>/api/flows/${safeId}/execute</code> will return 404 Not Found.
446
- </div>
447
- </div>
448
- <div class="modal-footer" style="padding: 0.75rem 1.25rem;">
449
- <button type="button" class="btn btn-secondary" onclick="closeDeleteFlowModal()">Cancel</button>
450
- <button type="button" class="btn btn-danger" id="btn-confirm-delete-flow" data-flow-id="${safeId}">
451
- Delete Flow
452
- </button>
453
- </div>
454
- </div>
455
- </div>
456
- `;
457
-
458
- const confirmBtn = document.getElementById('btn-confirm-delete-flow');
459
- if (confirmBtn) {
460
- confirmBtn.addEventListener('click', () => confirmDeleteFlow(flowId, name));
461
- }
462
-
463
- setTimeout(() => {
464
- document.getElementById('btn-confirm-delete-flow')?.focus();
465
- }, 50);
466
- }
467
-
468
- function closeDeleteFlowModal() {
469
- const modalRoot = document.getElementById('modal-root');
470
- if (modalRoot) modalRoot.innerHTML = '';
471
- }
472
-
473
- async function confirmDeleteFlow(flowId, name) {
474
- const btn = document.getElementById('btn-confirm-delete-flow');
475
- if (btn) {
476
- btn.disabled = true;
477
- btn.textContent = 'Deleting...';
478
- }
479
- try {
480
- const base = getFlowsApiBase();
481
- await api(`${base}/${flowId}`, { method: 'DELETE' });
482
- closeDeleteFlowModal();
483
- await refreshFlowsView();
484
- toast(`Flow "${name}" deleted successfully`, 'success');
485
- } catch (err) {
486
- if (btn) {
487
- btn.disabled = false;
488
- btn.textContent = 'Delete Flow';
489
- }
490
- toast('Failed to delete flow: ' + (err.message || err), 'error');
491
- }
492
- }
493
-
494
- function deleteFlowPrompt(flowId, name) {
495
- openDeleteFlowModal(flowId, name);
496
- }
497
-
498
- function openCreateFlowModal() {
499
- const modalRoot = document.getElementById('modal-root');
500
- if (!modalRoot) return;
501
-
502
- modalRoot.innerHTML = `
503
- <div class="modal-backdrop" onclick="if(event.target===this)closeFlowModal()">
504
- <div class="modal" style="max-width: 520px;">
505
- <div class="modal-header">
506
- <h2 class="modal-title" style="display: flex; align-items: center; gap: 8px;">
507
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="5" r="3"/><line x1="12" y1="8" x2="12" y2="12"/><circle cx="6" cy="19" r="3"/><circle cx="18" cy="19" r="3"/><path d="M12 12h-6v4"/><path d="M12 12h6v4"/></svg>
508
- Create New Functions Flow
509
- </h2>
510
- <button type="button" class="btn btn-secondary btn-sm" onclick="closeFlowModal()">✕</button>
511
- </div>
512
- <form onsubmit="handleCreateFlowSubmit(event)">
513
- <div class="modal-body">
514
- <div class="form-group">
515
- <label class="form-label" for="new-flow-name">Flow Name *</label>
516
- <input
517
- type="text"
518
- id="new-flow-name"
519
- class="form-input"
520
- placeholder="e.g. OrderProcessingFlow"
521
- required
522
- autofocus
523
- />
524
- </div>
525
- <div class="form-group">
526
- <label class="form-label" for="new-flow-desc">Description</label>
527
- <textarea
528
- id="new-flow-desc"
529
- class="form-textarea"
530
- style="min-height: 60px;"
531
- placeholder="Brief description of what this workflow orchestrates..."
532
- ></textarea>
533
- </div>
534
- <div class="form-group">
535
- <label class="form-label" for="new-flow-trigger">Trigger Type</label>
536
- <select id="new-flow-trigger" class="form-select" onchange="toggleFlowTriggerInput(this.value)">
537
- <option value="http">HTTP Endpoint (POST /api/flows/:id/execute)</option>
538
- <option value="event">Database Event Hook (e.g. orders:create)</option>
539
- <option value="manual">Manual Execution Only</option>
540
- </select>
541
- </div>
542
- <div class="form-group" id="flow-event-field" style="display: none;">
543
- <label class="form-label" for="new-flow-event">Target Event Pattern</label>
544
- <input
545
- type="text"
546
- id="new-flow-event"
547
- class="form-input"
548
- placeholder="collection:action (e.g. orders:create, users:*)"
549
- />
550
- </div>
551
- <div class="form-group">
552
- <label class="form-label" for="new-flow-concurrency">Max Concurrent Executions (Optional)</label>
553
- <input
554
- type="number"
555
- id="new-flow-concurrency"
556
- class="form-input"
557
- min="1"
558
- step="1"
559
- placeholder="Unlimited (default)"
560
- />
561
- </div>
562
- </div>
563
- <div class="modal-footer">
564
- <button type="button" class="btn btn-secondary" onclick="closeFlowModal()">Cancel</button>
565
- <button type="submit" class="btn btn-primary" style="font-weight: 600;">+ Create & Open Designer</button>
566
- </div>
567
- </form>
568
- </div>
569
- </div>
570
- `;
571
- }
572
-
573
- function closeFlowModal() {
574
- const modalRoot = document.getElementById('modal-root');
575
- if (modalRoot) modalRoot.innerHTML = '';
576
- }
577
-
578
- function toggleFlowTriggerInput(val) {
579
- const field = document.getElementById('flow-event-field');
580
- if (field) field.style.display = val === 'event' ? 'flex' : 'none';
581
- }
582
-
583
- async function handleCreateFlowSubmit(e) {
584
- e.preventDefault();
585
- const nameInput = document.getElementById('new-flow-name');
586
- const descInput = document.getElementById('new-flow-desc');
587
- const triggerInput = document.getElementById('new-flow-trigger');
588
- const eventInput = document.getElementById('new-flow-event');
589
- const concurrencyInput = document.getElementById('new-flow-concurrency');
590
-
591
- const name = nameInput ? nameInput.value.trim() : '';
592
- if (!name) return;
593
-
594
- const triggerType = triggerInput ? triggerInput.value : 'http';
595
- const eventTrigger = triggerType === 'event' && eventInput ? eventInput.value.trim() : null;
596
- const rawConcurrency = concurrencyInput ? concurrencyInput.value.trim() : '';
597
- const maxConcurrentExecutions = rawConcurrency !== '' ? parseInt(rawConcurrency, 10) : null;
598
-
599
- const initialFlow = {
600
- name,
601
- description: descInput ? descInput.value.trim() : '',
602
- enabled: true,
603
- triggerType,
604
- eventTrigger,
605
- maxConcurrentExecutions,
606
- definition: {
607
- startAt: 'FirstStep',
608
- states: {
609
- FirstStep: {
610
- type: 'Pass',
611
- result: { message: 'Hello from NodeStack Functions Flow!' },
612
- end: true,
613
- },
614
- },
615
- },
616
- };
617
-
618
- try {
619
- const base = getFlowsApiBase();
620
- const created = await api(base, {
621
- method: 'POST',
622
- body: JSON.stringify(initialFlow),
623
- });
624
- closeFlowModal();
625
- await loadFlows();
626
- openFlowDesigner(created.id);
627
- } catch (err) {
628
- toast('Failed to create flow: ' + (err.message || err), 'error');
629
- }
630
- }
631
-
632
- function formatFlowTriggerLabel(flow) {
633
- if (flow.triggerType === 'event') {
634
- return `DB Event${flow.eventTrigger ? `: ${escapeHtml(flow.eventTrigger)}` : ''}`;
635
- }
636
- if (flow.triggerType === 'manual') {
637
- return 'Manual (On-demand)';
638
- }
639
- return 'HTTP API';
640
- }
641
-
642
- function quickTestFlow(flowId) {
643
- if (typeof openFlowDesigner === 'function') {
644
- return openFlowDesigner(flowId, true);
645
- }
646
- }
647
-
648
- async function inspectExecutionDetail(executionId) {
649
- try {
650
- let exec = (flowsState.executions || []).find((e) => e.id === executionId);
651
- if (!exec || !exec.stepLogs) {
652
- const base = getFlowsApiBase();
653
- exec = await api(`${base}/executions/${executionId}`);
654
- }
655
- if (!exec) {
656
- toast('Execution record not found', 'error');
657
- return;
658
- }
659
-
660
- let root = document.getElementById('drawer-root');
661
- if (!root) {
662
- root = document.createElement('div');
663
- root.id = 'drawer-root';
664
- document.body.appendChild(root);
665
- }
666
-
667
- const isSuccess = exec.status === 'succeeded';
668
- const statusColor = isSuccess ? 'var(--accent-success)' : exec.status === 'failed' ? 'var(--accent-danger)' : (exec.status === 'aborted' || exec.status === 'queued') ? 'var(--accent-warning, #f59e0b)' : '#3b82f6';
669
- const stepCount = (exec.stepLogs || []).length;
670
-
671
- root.innerHTML = `
672
- <div id="flow-exec-drawer-backdrop" class="drawer-backdrop" onclick="closeFlowExecutionDrawer()" aria-hidden="true"></div>
673
- <aside id="flow-exec-drawer-panel" class="record-drawer flow-execution-drawer" role="dialog" aria-modal="true" aria-labelledby="flow-exec-drawer-title" tabindex="-1">
674
- <!-- Drawer Header -->
675
- <div class="drawer-header" style="display: flex; align-items: center; justify-content: space-between;">
676
- <div class="drawer-title-area" style="display: flex; align-items: center; gap: 0.75rem;">
677
- <span style="font-weight: 800; color: ${statusColor}; text-transform: uppercase; font-size: 0.78rem; background: rgba(0,0,0,0.2); padding: 4px 8px; border-radius: 6px; border: 1px solid ${statusColor}44;">
678
- ● ${escapeHtml(exec.status).toUpperCase()}
679
- </span>
680
- <div>
681
- <h3 class="drawer-title" id="flow-exec-drawer-title" style="margin: 0; font-size: 1.1rem; color: var(--text-main);">
682
- ${escapeHtml(exec.flowName)}
683
- </h3>
684
- <span style="font-size: 11px; color: var(--text-muted); font-family: var(--font-mono, monospace);">
685
- ${escapeHtml(exec.id)} • ${exec.durationMs}ms
686
- </span>
687
- </div>
688
- </div>
689
- <div style="display: flex; align-items: center; gap: 8px;">
690
- <button
691
- class="btn btn-secondary btn-sm"
692
- data-flow-id="${escapeHtml(exec.flowId)}"
693
- data-exec-id="${escapeHtml(exec.id)}"
694
- onclick="openFlowFromExecution(this.getAttribute('data-flow-id'), this.getAttribute('data-exec-id'))"
695
- title="Open flow in visual designer with this execution"
696
- style="font-size: 11px; padding: 4px 8px; font-weight: 600;"
697
- >
698
- Open in Designer ↗
699
- </button>
700
- <button class="drawer-close-btn" onclick="closeFlowExecutionDrawer()" aria-label="Close drawer">✕</button>
701
- </div>
702
- </div>
703
-
704
- <!-- Drawer Body -->
705
- <div class="drawer-body" style="padding: 1.25rem 1.5rem; overflow-y: auto; flex: 1; display: flex; flex-direction: column; gap: 1.25rem;">
706
- <!-- Meta Grid -->
707
- <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: 8px; background: rgba(255,255,255,0.03); border: 1px solid var(--border-subtle); border-radius: 8px; padding: 10px 14px; font-size: 12px;">
708
- <div>
709
- <span style="font-size: 10px; text-transform: uppercase; color: var(--text-muted); font-weight: 700; display: block;">Status</span>
710
- <strong style="color: ${statusColor}; text-transform: uppercase;">${escapeHtml(exec.status)}</strong>
711
- </div>
712
- <div>
713
- <span style="font-size: 10px; text-transform: uppercase; color: var(--text-muted); font-weight: 700; display: block;">Duration</span>
714
- <span style="font-weight: 600; color: var(--text-main);">${exec.durationMs}ms</span>
715
- </div>
716
- <div>
717
- <span style="font-size: 10px; text-transform: uppercase; color: var(--text-muted); font-weight: 700; display: block;">Steps</span>
718
- <span style="font-weight: 600; color: var(--text-main);">${stepCount} steps</span>
719
- </div>
720
- <div>
721
- <span style="font-size: 10px; text-transform: uppercase; color: var(--text-muted); font-weight: 700; display: block;">Caller</span>
722
- <span style="font-weight: 600; color: var(--accent-primary, #6366f1); font-family: monospace;">${escapeHtml(exec.actorId || 'public')}</span>
723
- </div>
724
- <div>
725
- <span style="font-size: 10px; text-transform: uppercase; color: var(--text-muted); font-weight: 700; display: block;">Started</span>
726
- <span style="color: var(--text-muted);" title="${escapeHtml(exec.startedAt)}">${new Date(exec.startedAt).toLocaleTimeString()}</span>
727
- </div>
728
- </div>
729
-
730
- <!-- Error Alert Banner (if failed) -->
731
- ${exec.error ? `
732
- <div style="background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.3); border-radius: 6px; padding: 10px 14px; font-size: 12px; color: var(--accent-danger);">
733
- <strong>Execution Error:</strong> ${escapeHtml(exec.error)}
734
- </div>
735
- ` : ''}
736
-
737
- <!-- Step-by-Step Execution Timeline -->
738
- <div>
739
- <span style="font-size: 11px; font-weight: 700; text-transform: uppercase; color: var(--text-muted); display: block; margin-bottom: 8px; letter-spacing: 0.05em;">
740
- Step-by-Step Timeline (${stepCount})
741
- </span>
742
- <div style="display: flex; flex-direction: column; gap: 8px;">
743
- ${(exec.stepLogs || []).map((log, idx) => {
744
- const stepSuccess = log.status === 'succeeded';
745
- const stepColor = stepSuccess ? 'var(--accent-success)' : 'var(--accent-danger)';
746
- return `
747
- <div style="background: var(--bg-card); border: 1px solid var(--border-subtle); border-left: 3px solid ${stepColor}; border-radius: 6px; padding: 10px 12px; font-size: 12px;">
748
- <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px;">
749
- <div style="display: flex; align-items: center; gap: 6px;">
750
- <span style="font-size: 10px; color: var(--text-muted); font-weight: 700;">#${idx + 1}</span>
751
- <strong style="color: var(--text-main); font-size: 13px;">${escapeHtml(log.step)}</strong>
752
- <span class="flow-step-type-pill pill-${(log.type || 'Task').toLowerCase()}" style="font-size: 9px; padding: 1px 6px;">
753
- ${escapeHtml((log.type || 'TASK')).toUpperCase()}
754
- </span>
755
- </div>
756
- <span style="color: var(--text-muted); font-size: 11px; font-family: var(--font-mono, monospace);">
757
- ${log.durationMs}ms
758
- </span>
759
- </div>
760
- ${log.error ? `
761
- <div style="color: var(--accent-danger); font-size: 11px; margin-top: 4px;">
762
- ${escapeHtml(log.error)}
763
- </div>
764
- ` : ''}
765
- ${log.output !== undefined ? `
766
- <details style="margin-top: 6px; font-size: 11px;">
767
- <summary style="cursor: pointer; color: var(--text-muted); font-weight: 600;">View Step Result</summary>
768
- <pre style="background: var(--bg-input); border: 1px solid var(--border-subtle); border-radius: 4px; padding: 6px 8px; margin-top: 4px; max-height: 120px; overflow-y: auto; font-size: 11px; color: var(--text-main); font-family: var(--font-mono, monospace);">${escapeHtml(JSON.stringify(log.output, null, 2))}</pre>
769
- </details>
770
- ` : ''}
771
- </div>
772
- `;
773
- }).join('')}
774
- </div>
775
- </div>
776
-
777
- <!-- Input Payload -->
778
- <div>
779
- <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px;">
780
- <span style="font-size: 11px; font-weight: 700; text-transform: uppercase; color: var(--text-muted); letter-spacing: 0.05em;">
781
- Input Payload
782
- </span>
783
- <button class="btn btn-secondary btn-sm" onclick="copyFlowJson(this, 'flow-exec-input-json')" style="padding: 2px 8px; font-size: 10px;">
784
- Copy JSON
785
- </button>
786
- </div>
787
- <pre id="flow-exec-input-json" style="background: var(--bg-input); border: 1px solid var(--border-subtle); border-radius: 6px; padding: 10px 12px; font-family: var(--font-mono, monospace); font-size: 11px; color: var(--text-main); max-height: 160px; overflow-y: auto; margin: 0;">${escapeHtml(JSON.stringify(exec.input || {}, null, 2))}</pre>
788
- </div>
789
-
790
- <!-- Final Output Payload -->
791
- <div>
792
- <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px;">
793
- <span style="font-size: 11px; font-weight: 700; text-transform: uppercase; color: var(--text-muted); letter-spacing: 0.05em;">
794
- Final Output Payload
795
- </span>
796
- <button class="btn btn-secondary btn-sm" onclick="copyFlowJson(this, 'flow-exec-output-json')" style="padding: 2px 8px; font-size: 10px;">
797
- Copy JSON
798
- </button>
799
- </div>
800
- <pre id="flow-exec-output-json" style="background: var(--bg-input); border: 1px solid var(--border-subtle); border-radius: 6px; padding: 10px 12px; font-family: var(--font-mono, monospace); font-size: 11px; color: var(--text-main); max-height: 200px; overflow-y: auto; margin: 0;">${escapeHtml(JSON.stringify(exec.output !== undefined ? exec.output : (exec.error ? { error: exec.error } : {}), null, 2))}</pre>
801
- </div>
802
- </div>
803
- </aside>
804
- `;
805
-
806
- setTimeout(() => {
807
- document.getElementById('flow-exec-drawer-backdrop')?.classList.add('open');
808
- document.getElementById('flow-exec-drawer-panel')?.classList.add('open');
809
- }, 10);
810
- } catch (err) {
811
- toast('Failed to inspect flow execution: ' + (err.message || err), 'error');
812
- }
813
- }
814
-
815
- function closeFlowExecutionDrawer() {
816
- const backdrop = document.getElementById('flow-exec-drawer-backdrop');
817
- const panel = document.getElementById('flow-exec-drawer-panel');
818
- if (backdrop) backdrop.classList.remove('open');
819
- if (panel) panel.classList.remove('open');
820
- setTimeout(() => {
821
- const root = document.getElementById('drawer-root');
822
- if (root && root.querySelector('#flow-exec-drawer-panel')) {
823
- root.innerHTML = '';
824
- }
825
- }, 200);
826
- }
827
-
828
- async function openFlowFromExecution(flowId, executionId) {
829
- const exec = (flowsState.executions || []).find((e) => e.id === executionId);
830
- closeFlowExecutionDrawer();
831
- if (typeof openFlowDesigner === 'function') {
832
- await openFlowDesigner(flowId, true);
833
- if (exec && typeof designerState !== 'undefined') {
834
- designerState.latestExecution = exec;
835
- const drawer = document.getElementById('flow-test-drawer');
836
- if (drawer && typeof renderTestDrawerHtml === 'function') {
837
- drawer.innerHTML = renderTestDrawerHtml(designerState.activeFlow);
838
- }
839
- if (typeof renderSvgFlowchart === 'function') {
840
- renderSvgFlowchart(designerState.activeFlow);
841
- }
842
- }
843
- }
844
- }
845
-
846
- function copyFlowJson(btn, elementId) {
847
- const el = document.getElementById(elementId);
848
- if (!el) return;
849
- try {
850
- if (navigator.clipboard && navigator.clipboard.writeText) {
851
- navigator.clipboard.writeText(el.textContent || '').then(() => {
852
- const orig = btn.textContent;
853
- btn.textContent = 'Copied!';
854
- setTimeout(() => { btn.textContent = orig; }, 1500);
855
- });
856
- } else {
857
- toast('Copied to clipboard', 'info');
858
- }
859
- } catch (_) {
860
- toast('Copied to clipboard', 'info');
861
- }
862
- }
863
-
864
- if (typeof window !== 'undefined') {
865
- window.renderFlowsView = renderFlowsView;
866
- window.loadFlows = loadFlows;
867
- window.refreshFlowsView = refreshFlowsView;
868
- window.switchFlowsTab = switchFlowsTab;
869
- window.handleFlowsSearch = handleFlowsSearch;
870
- window.handleFlowExecutionsStatusFilter = handleFlowExecutionsStatusFilter;
871
- window.toggleFlowStatus = toggleFlowStatus;
872
- window.deleteFlowPrompt = deleteFlowPrompt;
873
- window.openDeleteFlowModal = openDeleteFlowModal;
874
- window.closeDeleteFlowModal = closeDeleteFlowModal;
875
- window.confirmDeleteFlow = confirmDeleteFlow;
876
- window.openCreateFlowModal = openCreateFlowModal;
877
- window.closeFlowModal = closeFlowModal;
878
- window.toggleFlowTriggerInput = toggleFlowTriggerInput;
879
- window.handleCreateFlowSubmit = handleCreateFlowSubmit;
880
- window.quickTestFlow = quickTestFlow;
881
- window.formatFlowTriggerLabel = formatFlowTriggerLabel;
882
- window.inspectExecutionDetail = inspectExecutionDetail;
883
- window.closeFlowExecutionDrawer = closeFlowExecutionDrawer;
884
- window.openFlowFromExecution = openFlowFromExecution;
885
- window.copyFlowJson = copyFlowJson;
886
- }
887
-
888
- if (typeof state !== 'undefined' && state.token && typeof loadFlows === 'function') {
889
- loadFlows();
890
- }
1
+ // Functions Flow Manager Module for NodeStack Admin UI
2
+ // State, flows list overview, executions history, and serverless functions lookup
3
+
4
+ let flowsState = {
5
+ currentView: 'list', // 'list' | 'designer'
6
+ subTab: 'flows', // 'flows' | 'executions'
7
+ flows: [],
8
+ executions: [],
9
+ functions: [], // loaded from /api/functions for dropdowns
10
+ filter: {
11
+ search: '',
12
+ status: 'all',
13
+ },
14
+ activeFlowForEdit: null,
15
+ };
16
+
17
+ if (typeof window !== 'undefined') {
18
+ window.flowsState = flowsState;
19
+ }
20
+
21
+ // ==========================================
22
+ // 1. API Fetching
23
+ // ==========================================
24
+
25
+ function getFlowsApiBase() {
26
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : (typeof state !== 'undefined' && state?.activeApp?.slug ? state.activeApp.slug : 'default');
27
+ return slug && slug !== 'default' ? `/api/apps/${slug}/flows` : '/api/flows';
28
+ }
29
+
30
+ function 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
+ if (typeof window !== 'undefined') {
36
+ window.getFlowsApiBase = getFlowsApiBase;
37
+ window.getFunctionsApiBase = getFunctionsApiBase;
38
+ }
39
+
40
+ async function loadFlows() {
41
+ try {
42
+ const endpoint = getFlowsApiBase();
43
+ const res = await api(endpoint);
44
+ flowsState.flows = Array.isArray(res) ? res : res?.data || [];
45
+ updateSidebarFlowsCount();
46
+ return flowsState.flows;
47
+ } catch (err) {
48
+ console.error('Failed to load flows:', err);
49
+ return [];
50
+ }
51
+ }
52
+
53
+ async function loadFlowExecutions(flowId = '') {
54
+ try {
55
+ const base = getFlowsApiBase();
56
+ const statusParam = flowsState.filter?.status && flowsState.filter.status !== 'all'
57
+ ? `?status=${encodeURIComponent(flowsState.filter.status)}`
58
+ : '';
59
+ const url = flowId ? `${base}/${flowId}/executions${statusParam}` : `${base}/executions${statusParam}`;
60
+ const res = await api(url);
61
+ flowsState.executions = res?.items || (Array.isArray(res) ? res : []);
62
+ return flowsState.executions;
63
+ } catch (err) {
64
+ console.error('Failed to load flow executions:', err);
65
+ return [];
66
+ }
67
+ }
68
+
69
+ async function loadFunctionsForPicker() {
70
+ try {
71
+ const endpoint = getFunctionsApiBase();
72
+ const res = await api(endpoint);
73
+ flowsState.functions = Array.isArray(res) ? res : res?.data || [];
74
+ } catch (err) {
75
+ console.error('Failed to load functions for picker:', err);
76
+ }
77
+ }
78
+
79
+ function updateSidebarFlowsCount() {
80
+ const count = (flowsState.flows || []).length;
81
+ const badge = document.getElementById('sidebar-flows-count');
82
+ if (badge) {
83
+ badge.textContent = count;
84
+ badge.style.display = count > 0 ? 'inline-block' : 'none';
85
+ }
86
+
87
+ const homeFlowEl = document.getElementById('home-stat-flows');
88
+ const homeFlowSubEl = document.getElementById('home-stat-flows-sub');
89
+ if (homeFlowEl) {
90
+ homeFlowEl.textContent = String(count);
91
+ }
92
+ if (homeFlowSubEl) {
93
+ const active = (flowsState.flows || []).filter(f => f.enabled !== false).length;
94
+ const runs = (flowsState.executions && Array.isArray(flowsState.executions)) ? flowsState.executions.length : 0;
95
+ homeFlowSubEl.textContent = `${active} active${runs > 0 ? ` • ${runs} runs` : ' • visual pipelines'}`;
96
+ }
97
+ }
98
+
99
+ // ==========================================
100
+ // 2. Flows Overview Page Render
101
+ // ==========================================
102
+
103
+ async function renderFlowsView() {
104
+ if (flowsState.currentView === 'designer') {
105
+ const active = (typeof designerState !== 'undefined' && designerState.activeFlow)
106
+ ? designerState.activeFlow
107
+ : flowsState.activeFlowForEdit;
108
+ if (active && typeof renderFlowDesignerWorkbench === 'function') {
109
+ renderFlowDesignerWorkbench(active);
110
+ }
111
+ return;
112
+ }
113
+
114
+ const container = document.getElementById('page-view-flows') || document.getElementById('main-body');
115
+ if (!container) return;
116
+
117
+ container.innerHTML = `
118
+ <div class="flows-container">
119
+ <!-- Header -->
120
+ <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 1rem;">
121
+ <div>
122
+ <h2 style="font-size: 1.35rem; font-weight: 700; color: var(--text-main); margin: 0 0 0.25rem 0; display: flex; align-items: center; gap: 0.5rem;">
123
+ <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
124
+ <circle cx="12" cy="5" r="3"/><line x1="12" y1="8" x2="12" y2="12"/><circle cx="6" cy="19" r="3"/><circle cx="18" cy="19" r="3"/><path d="M12 12h-6v4"/><path d="M12 12h6v4"/>
125
+ </svg>
126
+ Functions Flow
127
+ </h2>
128
+ <p style="font-size: 0.85rem; color: var(--text-muted); margin: 0;">
129
+ Visual state machine orchestration for chaining serverless functions with branching, loops, and map-reduce.
130
+ </p>
131
+ </div>
132
+ <div style="display: flex; align-items: center; gap: 8px;">
133
+ <button class="btn btn-secondary btn-sm" onclick="refreshFlowsView()" title="Refresh Flows">
134
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M23 4v6h-6M1 20v-6h6"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>
135
+ Refresh
136
+ </button>
137
+ <button class="btn btn-primary btn-sm" onclick="openCreateFlowModal()">
138
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
139
+ New Flow
140
+ </button>
141
+ </div>
142
+ </div>
143
+
144
+ <!-- Stats Grid -->
145
+ <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem;">
146
+ <div class="webhook-stat-card">
147
+ <span class="webhook-stat-label">Total Flows</span>
148
+ <div class="webhook-stat-value">
149
+ <span id="flow-stat-total">${flowsState.flows.length}</span>
150
+ </div>
151
+ </div>
152
+ <div class="webhook-stat-card">
153
+ <span class="webhook-stat-label">Active Flows</span>
154
+ <div class="webhook-stat-value">
155
+ <span id="flow-stat-active" style="color: var(--accent-success);">${flowsState.flows.filter(f => f.enabled).length}</span>
156
+ </div>
157
+ </div>
158
+ <div class="webhook-stat-card">
159
+ <span class="webhook-stat-label">Available Functions</span>
160
+ <div class="webhook-stat-value" id="flow-stat-functions">
161
+ ${flowsState.functions.length}
162
+ </div>
163
+ </div>
164
+ </div>
165
+
166
+ <!-- Subtabs Bar -->
167
+ <div style="display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--border-subtle, #334155); padding-bottom: 0.5rem; margin-top: 0.5rem;">
168
+ <div style="display: flex; gap: 1rem;">
169
+ <button class="btn-subtab ${flowsState.subTab === 'flows' ? 'active' : ''}" onclick="switchFlowsTab('flows')" style="background:none; border:none; color: ${flowsState.subTab === 'flows' ? 'var(--accent-primary, #6366f1)' : 'var(--text-muted)'}; font-weight: 600; font-size: 0.9rem; cursor: pointer; padding: 0.25rem 0.5rem; border-bottom: 2px solid ${flowsState.subTab === 'flows' ? 'var(--accent-primary, #6366f1)' : 'transparent'};">
170
+ Configured Flows (${flowsState.flows.length})
171
+ </button>
172
+ <button class="btn-subtab ${flowsState.subTab === 'executions' ? 'active' : ''}" onclick="switchFlowsTab('executions')" style="background:none; border:none; color: ${flowsState.subTab === 'executions' ? 'var(--accent-primary, #6366f1)' : 'var(--text-muted)'}; font-weight: 600; font-size: 0.9rem; cursor: pointer; padding: 0.25rem 0.5rem; border-bottom: 2px solid ${flowsState.subTab === 'executions' ? 'var(--accent-primary, #6366f1)' : 'transparent'};">
173
+ Execution History
174
+ </button>
175
+ </div>
176
+ <div style="display: flex; align-items: center; gap: 8px;">
177
+ ${flowsState.subTab === 'executions' ? `
178
+ <select
179
+ id="flows-status-filter"
180
+ class="flow-field-select"
181
+ style="width: 145px; font-size: 0.8rem;"
182
+ onchange="handleFlowExecutionsStatusFilter(this.value)"
183
+ >
184
+ <option value="all" ${(flowsState.filter.status || 'all') === 'all' ? 'selected' : ''}>All Statuses</option>
185
+ <option value="queued" ${flowsState.filter.status === 'queued' ? 'selected' : ''}>Queued</option>
186
+ <option value="running" ${flowsState.filter.status === 'running' ? 'selected' : ''}>Running</option>
187
+ <option value="succeeded" ${flowsState.filter.status === 'succeeded' ? 'selected' : ''}>Succeeded</option>
188
+ <option value="failed" ${flowsState.filter.status === 'failed' ? 'selected' : ''}>Failed</option>
189
+ <option value="aborted" ${flowsState.filter.status === 'aborted' ? 'selected' : ''}>Aborted</option>
190
+ <option value="timeout" ${flowsState.filter.status === 'timeout' ? 'selected' : ''}>Timeout</option>
191
+ </select>
192
+ ` : ''}
193
+ <input
194
+ type="text"
195
+ id="flows-search-input"
196
+ class="flow-field-input"
197
+ placeholder="Search flows by name..."
198
+ style="width: 220px;"
199
+ value="${escapeHtml(flowsState.filter.search || '')}"
200
+ oninput="handleFlowsSearch(this.value)"
201
+ />
202
+ </div>
203
+ </div>
204
+
205
+ <!-- Content Section -->
206
+ <div id="flows-subtab-content">
207
+ ${flowsState.subTab === 'flows' ? renderFlowsListHtml() : renderFlowExecutionsListHtml()}
208
+ </div>
209
+ </div>
210
+ `;
211
+
212
+ // Pre-load data in background
213
+ if (flowsState.functions.length === 0) {
214
+ loadFunctionsForPicker().then(() => {
215
+ const el = document.getElementById('flow-stat-functions');
216
+ if (el) el.textContent = flowsState.functions.length;
217
+ });
218
+ }
219
+ }
220
+
221
+ function renderFlowsListHtml() {
222
+ const filtered = flowsState.flows.filter(f => {
223
+ if (!flowsState.filter.search) return true;
224
+ const q = flowsState.filter.search.toLowerCase();
225
+ return f.name.toLowerCase().includes(q) || (f.description && f.description.toLowerCase().includes(q));
226
+ });
227
+
228
+ if (filtered.length === 0) {
229
+ return `
230
+ <div style="text-align: center; padding: 4rem 2rem; background: var(--bg-card); border: 1px dashed var(--border-subtle); border-radius: 8px;">
231
+ <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="var(--text-muted)" stroke-width="1.5" style="margin-bottom: 1rem;"><circle cx="12" cy="5" r="3"/><line x1="12" y1="8" x2="12" y2="12"/><circle cx="6" cy="19" r="3"/><circle cx="18" cy="19" r="3"/><path d="M12 12h-6v4"/><path d="M12 12h6v4"/></svg>
232
+ <h3 style="font-size: 1.1rem; color: var(--text-main); margin: 0 0 0.5rem 0;">No Functions Flows Yet</h3>
233
+ <p style="color: var(--text-muted); font-size: 0.85rem; max-width: 420px; margin: 0 auto 1.25rem auto;">
234
+ Create a state machine flow to connect serverless functions, add conditional branching, loops, or batch map-reduce.
235
+ </p>
236
+ <button class="btn btn-primary btn-sm" onclick="openCreateFlowModal()">
237
+ + Create First Flow
238
+ </button>
239
+ </div>
240
+ `;
241
+ }
242
+
243
+ return `
244
+ <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(360px, 1fr)); gap: 1rem;">
245
+ ${filtered.map(flow => {
246
+ const stateCount = flow.definition && flow.definition.states ? Object.keys(flow.definition.states).length : 0;
247
+ return `
248
+ <div class="webhook-stat-card" style="cursor: default;">
249
+ <div style="display: flex; align-items: flex-start; justify-content: space-between; gap: 0.5rem;">
250
+ <div>
251
+ <h4 style="margin: 0 0 0.25rem 0; font-size: 1rem; color: var(--text-main); font-weight: 600;">
252
+ ${escapeHtml(flow.name)}
253
+ </h4>
254
+ <p style="margin: 0; font-size: 0.8rem; color: var(--text-muted); min-height: 1.2rem;">
255
+ ${escapeHtml(flow.description || 'No description provided')}
256
+ </p>
257
+ </div>
258
+ <span class="badge ${flow.enabled ? 'badge-get' : 'badge-danger'}" style="font-size: 10px;">
259
+ ${flow.enabled ? 'ACTIVE' : 'DISABLED'}
260
+ </span>
261
+ </div>
262
+
263
+ <div style="display: flex; align-items: center; gap: 0.75rem; margin: 0.75rem 0; font-size: 0.75rem; color: var(--text-muted); flex-wrap: wrap;">
264
+ <span><strong>Trigger:</strong> <code style="color: var(--accent-primary);">${formatFlowTriggerLabel(flow)}</code></span>
265
+ ${flow.triggerType === 'http' ? `<span>•</span><span><strong>Auth:</strong> <code style="color: var(--text-heading);">${escapeHtml((flow.authPolicy || 'public').toUpperCase())}</code></span>` : ''}
266
+ <span>•</span>
267
+ <span><strong>Steps:</strong> ${stateCount} states</span>
268
+ <span>•</span>
269
+ <span><strong>Concurrency:</strong> ${flow.maxConcurrentExecutions ? escapeHtml(String(flow.maxConcurrentExecutions)) : 'Unlimited'}</span>
270
+ </div>
271
+
272
+ <div style="display: flex; align-items: center; justify-content: space-between; border-top: 1px solid var(--border-subtle); padding-top: 0.75rem; margin-top: auto;">
273
+ <div style="display: flex; gap: 6px;">
274
+ <button class="btn btn-primary btn-sm" data-flow-id="${escapeHtml(flow.id)}" onclick="openFlowDesigner(this.getAttribute('data-flow-id'))" style="font-weight: 600;">
275
+ Open Designer
276
+ </button>
277
+ <button class="btn btn-secondary btn-sm" data-flow-id="${escapeHtml(flow.id)}" onclick="quickTestFlow(this.getAttribute('data-flow-id'))" title="Test Flow Execution">
278
+ ▶ Run
279
+ </button>
280
+ </div>
281
+ <div style="display: flex; gap: 6px;">
282
+ <button class="btn btn-secondary btn-sm" data-flow-id="${escapeHtml(flow.id)}" data-enabled="${!flow.enabled}" onclick="toggleFlowStatus(this.getAttribute('data-flow-id'), this.getAttribute('data-enabled') === 'true')" title="${flow.enabled ? 'Disable' : 'Enable'}">
283
+ ${flow.enabled ? 'Disable' : 'Enable'}
284
+ </button>
285
+ <button class="btn btn-danger btn-sm" data-flow-id="${escapeHtml(flow.id)}" data-flow-name="${escapeHtml(flow.name)}" onclick="deleteFlowPrompt(this.getAttribute('data-flow-id'), this.getAttribute('data-flow-name'))" title="Delete Flow">
286
+ 🗑
287
+ </button>
288
+ </div>
289
+ </div>
290
+ </div>
291
+ `;
292
+ }).join('')}
293
+ </div>
294
+ `;
295
+ }
296
+
297
+ function renderFlowExecutionsListHtml() {
298
+ const executions = flowsState.executions || [];
299
+ if (executions.length === 0) {
300
+ return `
301
+ <div style="text-align: center; padding: 3rem; background: var(--bg-card); border-radius: 8px; color: var(--text-muted);">
302
+ <p style="margin: 0;">No flow executions recorded yet. Run a flow to inspect step timeline and logs.</p>
303
+ </div>
304
+ `;
305
+ }
306
+
307
+ return `
308
+ <div style="background: var(--bg-card); border: 1px solid var(--border-subtle); border-radius: 8px; overflow: hidden;">
309
+ <table style="width: 100%; border-collapse: collapse; font-size: 0.85rem; text-align: left;">
310
+ <thead>
311
+ <tr style="background: rgba(0,0,0,0.15); border-bottom: 1px solid var(--border-subtle); color: var(--text-muted);">
312
+ <th style="padding: 0.75rem 1rem;">Status</th>
313
+ <th style="padding: 0.75rem 1rem;">Flow Name</th>
314
+ <th style="padding: 0.75rem 1rem;">Duration</th>
315
+ <th style="padding: 0.75rem 1rem;">Steps</th>
316
+ <th style="padding: 0.75rem 1rem;">Caller</th>
317
+ <th style="padding: 0.75rem 1rem;">Started At</th>
318
+ <th style="padding: 0.75rem 1rem; text-align: right;">Action</th>
319
+ </tr>
320
+ </thead>
321
+ <tbody>
322
+ ${executions.map(exec => {
323
+ const statusColor = exec.status === 'succeeded' ? 'var(--accent-success)' : exec.status === 'failed' ? 'var(--accent-danger)' : (exec.status === 'aborted' || exec.status === 'queued') ? 'var(--accent-warning, #f59e0b)' : '#3b82f6';
324
+ const stepCount = (exec.stepLogs || []).length;
325
+ return `
326
+ <tr style="border-bottom: 1px solid var(--border-subtle);">
327
+ <td style="padding: 0.75rem 1rem;">
328
+ <span style="font-weight: 700; color: ${statusColor}; text-transform: uppercase; font-size: 0.75rem;">
329
+ ● ${exec.status}
330
+ </span>
331
+ </td>
332
+ <td style="padding: 0.75rem 1rem; font-weight: 600; color: var(--text-main);">
333
+ ${escapeHtml(exec.flowName)}
334
+ </td>
335
+ <td style="padding: 0.75rem 1rem; color: var(--text-muted);">
336
+ ${exec.durationMs}ms
337
+ </td>
338
+ <td style="padding: 0.75rem 1rem; color: var(--text-muted);">
339
+ ${stepCount} steps
340
+ </td>
341
+ <td style="padding: 0.75rem 1rem; font-family: var(--font-mono, monospace); font-size: 0.8rem; color: var(--text-muted);">
342
+ <span class="badge" style="font-size: 11px; font-weight: 500; background: rgba(255,255,255,0.06);">${escapeHtml(exec.actorId || 'public')}</span>
343
+ </td>
344
+ <td style="padding: 0.75rem 1rem; color: var(--text-muted); font-size: 0.8rem;">
345
+ ${new Date(exec.startedAt).toLocaleString()}
346
+ </td>
347
+ <td style="padding: 0.75rem 1rem; text-align: right;">
348
+ <button class="btn btn-secondary btn-sm" data-exec-id="${escapeHtml(exec.id)}" onclick="inspectExecutionDetail(this.getAttribute('data-exec-id'))">
349
+ Inspect
350
+ </button>
351
+ </td>
352
+ </tr>
353
+ `;
354
+ }).join('')}
355
+ </tbody>
356
+ </table>
357
+ </div>
358
+ `;
359
+ }
360
+
361
+ // ==========================================
362
+ // 3. User Actions
363
+ // ==========================================
364
+
365
+ async function refreshFlowsView() {
366
+ await loadFlows();
367
+ if (flowsState.subTab === 'executions') {
368
+ await loadFlowExecutions();
369
+ }
370
+ renderFlowsView();
371
+ }
372
+
373
+ function switchFlowsTab(tab, pushState = true) {
374
+ flowsState.subTab = tab;
375
+ if (pushState && typeof updateUrl === 'function') {
376
+ const path = (tab === 'executions') ? '/_/flows/executions' : '/_/flows';
377
+ updateUrl(path);
378
+ }
379
+ if (typeof updateBreadcrumbs === 'function') {
380
+ updateBreadcrumbs();
381
+ }
382
+ if (tab === 'executions') {
383
+ loadFlowExecutions().then(() => renderFlowsView());
384
+ } else {
385
+ renderFlowsView();
386
+ }
387
+ }
388
+
389
+ function handleFlowsSearch(val) {
390
+ flowsState.filter.search = val;
391
+ const content = document.getElementById('flows-subtab-content');
392
+ if (content && flowsState.subTab === 'flows') {
393
+ content.innerHTML = renderFlowsListHtml();
394
+ }
395
+ }
396
+
397
+ async function handleFlowExecutionsStatusFilter(status) {
398
+ flowsState.filter.status = status || 'all';
399
+ await loadFlowExecutions();
400
+ const content = document.getElementById('flows-subtab-content');
401
+ if (content && flowsState.subTab === 'executions') {
402
+ content.innerHTML = renderFlowExecutionsListHtml();
403
+ }
404
+ }
405
+
406
+ async function toggleFlowStatus(flowId, enabled) {
407
+ try {
408
+ const base = getFlowsApiBase();
409
+ await api(`${base}/${flowId}`, {
410
+ method: 'PATCH',
411
+ body: JSON.stringify({ enabled }),
412
+ });
413
+ await refreshFlowsView();
414
+ toast(`Flow ${enabled ? 'enabled' : 'disabled'} successfully`, 'success');
415
+ } catch (err) {
416
+ toast('Failed to update flow: ' + (err.message || err), 'error');
417
+ }
418
+ }
419
+
420
+ function openDeleteFlowModal(flowId, name) {
421
+ let modalRoot = document.getElementById('modal-root');
422
+ if (!modalRoot) {
423
+ modalRoot = document.createElement('div');
424
+ modalRoot.id = 'modal-root';
425
+ document.body.appendChild(modalRoot);
426
+ }
427
+
428
+ const safeId = typeof escapeHtml === 'function' ? escapeHtml(flowId) : flowId;
429
+ const safeName = typeof escapeHtml === 'function' ? escapeHtml(name) : name;
430
+
431
+ modalRoot.innerHTML = `
432
+ <div class="modal-backdrop" id="delete-flow-backdrop" onclick="if(event.target===this)closeDeleteFlowModal()">
433
+ <div class="modal confirm-dialog">
434
+ <div class="modal-header" style="border-bottom-color: rgba(239, 68, 68, 0.2);">
435
+ <div style="display: flex; align-items: center; gap: 0.5rem;">
436
+ <span style="font-size: 18px;">⚠️</span>
437
+ <h2 class="modal-title danger" style="font-size: 16px;">Delete Flow</h2>
438
+ </div>
439
+ <button type="button" class="btn btn-secondary btn-sm" onclick="closeDeleteFlowModal()" aria-label="Close">✕</button>
440
+ </div>
441
+ <div class="modal-body" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
442
+ <p style="font-size: 13px; color: var(--text-main, #cbd5e1); line-height: 1.5; margin: 0;">
443
+ Are you sure you want to delete flow <strong style="color: var(--text-heading); font-family: var(--font-mono);">${safeName}</strong>? All execution history and logs will be permanently removed.
444
+ </p>
445
+ <div class="confirm-dialog-banner danger">
446
+ This action cannot be undone. Invocations to <code>/api/flows/${safeId}/execute</code> will return 404 Not Found.
447
+ </div>
448
+ </div>
449
+ <div class="modal-footer" style="padding: 0.75rem 1.25rem;">
450
+ <button type="button" class="btn btn-secondary" onclick="closeDeleteFlowModal()">Cancel</button>
451
+ <button type="button" class="btn btn-danger" id="btn-confirm-delete-flow" data-flow-id="${safeId}">
452
+ Delete Flow
453
+ </button>
454
+ </div>
455
+ </div>
456
+ </div>
457
+ `;
458
+
459
+ const confirmBtn = document.getElementById('btn-confirm-delete-flow');
460
+ if (confirmBtn) {
461
+ confirmBtn.addEventListener('click', () => confirmDeleteFlow(flowId, name));
462
+ }
463
+
464
+ setTimeout(() => {
465
+ document.getElementById('btn-confirm-delete-flow')?.focus();
466
+ }, 50);
467
+ }
468
+
469
+ function closeDeleteFlowModal() {
470
+ const modalRoot = document.getElementById('modal-root');
471
+ if (modalRoot) modalRoot.innerHTML = '';
472
+ }
473
+
474
+ async function confirmDeleteFlow(flowId, name) {
475
+ const btn = document.getElementById('btn-confirm-delete-flow');
476
+ if (btn) {
477
+ btn.disabled = true;
478
+ btn.textContent = 'Deleting...';
479
+ }
480
+ try {
481
+ const base = getFlowsApiBase();
482
+ await api(`${base}/${flowId}`, { method: 'DELETE' });
483
+ closeDeleteFlowModal();
484
+ await refreshFlowsView();
485
+ toast(`Flow "${name}" deleted successfully`, 'success');
486
+ } catch (err) {
487
+ if (btn) {
488
+ btn.disabled = false;
489
+ btn.textContent = 'Delete Flow';
490
+ }
491
+ toast('Failed to delete flow: ' + (err.message || err), 'error');
492
+ }
493
+ }
494
+
495
+ function deleteFlowPrompt(flowId, name) {
496
+ openDeleteFlowModal(flowId, name);
497
+ }
498
+
499
+ function openCreateFlowModal() {
500
+ const modalRoot = document.getElementById('modal-root');
501
+ if (!modalRoot) return;
502
+
503
+ modalRoot.innerHTML = `
504
+ <div class="modal-backdrop" onclick="if(event.target===this)closeFlowModal()">
505
+ <div class="modal" style="max-width: 520px;">
506
+ <div class="modal-header">
507
+ <h2 class="modal-title" style="display: flex; align-items: center; gap: 8px;">
508
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="5" r="3"/><line x1="12" y1="8" x2="12" y2="12"/><circle cx="6" cy="19" r="3"/><circle cx="18" cy="19" r="3"/><path d="M12 12h-6v4"/><path d="M12 12h6v4"/></svg>
509
+ Create New Functions Flow
510
+ </h2>
511
+ <button type="button" class="btn btn-secondary btn-sm" onclick="closeFlowModal()">✕</button>
512
+ </div>
513
+ <form onsubmit="handleCreateFlowSubmit(event)">
514
+ <div class="modal-body">
515
+ <div class="form-group">
516
+ <label class="form-label" for="new-flow-name">Flow Name *</label>
517
+ <input
518
+ type="text"
519
+ id="new-flow-name"
520
+ class="form-input"
521
+ placeholder="e.g. OrderProcessingFlow"
522
+ required
523
+ autofocus
524
+ />
525
+ </div>
526
+ <div class="form-group">
527
+ <label class="form-label" for="new-flow-desc">Description</label>
528
+ <textarea
529
+ id="new-flow-desc"
530
+ class="form-textarea"
531
+ style="min-height: 60px;"
532
+ placeholder="Brief description of what this workflow orchestrates..."
533
+ ></textarea>
534
+ </div>
535
+ <div class="form-group">
536
+ <label class="form-label" for="new-flow-trigger">Trigger Type</label>
537
+ <select id="new-flow-trigger" class="form-select" onchange="toggleFlowTriggerInput(this.value)">
538
+ <option value="http">HTTP Endpoint (POST /api/flows/:id/execute)</option>
539
+ <option value="event">Database Event Hook (e.g. orders:create)</option>
540
+ <option value="manual">Manual Execution Only</option>
541
+ </select>
542
+ </div>
543
+ <div class="form-group" id="flow-http-auth-field" style="display: flex;">
544
+ <label class="form-label" for="new-flow-auth-policy">HTTP Authorization Policy</label>
545
+ <select id="new-flow-auth-policy" class="form-select">
546
+ <option value="admin" selected>Admin Only (Requires Admin Token)</option>
547
+ <option value="auth">User Token (Bearer JWT or Scoped API Key)</option>
548
+ <option value="apiKey">API Key (Requires flows scope)</option>
549
+ <option value="custom">Custom Rule (@request.auth.* or Scoped API Key)</option>
550
+ <option value="public">Public (No Token Required)</option>
551
+ </select>
552
+ </div>
553
+ <div class="form-group" id="flow-event-field" style="display: none;">
554
+ <label class="form-label" for="new-flow-event">Target Event Pattern</label>
555
+ <input
556
+ type="text"
557
+ id="new-flow-event"
558
+ class="form-input"
559
+ placeholder="collection:action (e.g. orders:create, users:*)"
560
+ />
561
+ </div>
562
+ <div class="form-group">
563
+ <label class="form-label" for="new-flow-concurrency">Max Concurrent Executions (Optional)</label>
564
+ <input
565
+ type="number"
566
+ id="new-flow-concurrency"
567
+ class="form-input"
568
+ min="1"
569
+ step="1"
570
+ placeholder="Unlimited (default)"
571
+ />
572
+ </div>
573
+ </div>
574
+ <div class="modal-footer">
575
+ <button type="button" class="btn btn-secondary" onclick="closeFlowModal()">Cancel</button>
576
+ <button type="submit" class="btn btn-primary" style="font-weight: 600;">+ Create & Open Designer</button>
577
+ </div>
578
+ </form>
579
+ </div>
580
+ </div>
581
+ `;
582
+ }
583
+
584
+ function closeFlowModal() {
585
+ const modalRoot = document.getElementById('modal-root');
586
+ if (modalRoot) modalRoot.innerHTML = '';
587
+ }
588
+
589
+ function toggleFlowTriggerInput(val) {
590
+ const field = document.getElementById('flow-event-field');
591
+ if (field) field.style.display = val === 'event' ? 'flex' : 'none';
592
+ const httpAuthField = document.getElementById('flow-http-auth-field');
593
+ if (httpAuthField) httpAuthField.style.display = val === 'http' ? 'flex' : 'none';
594
+ }
595
+
596
+ async function handleCreateFlowSubmit(e) {
597
+ e.preventDefault();
598
+ const nameInput = document.getElementById('new-flow-name');
599
+ const descInput = document.getElementById('new-flow-desc');
600
+ const triggerInput = document.getElementById('new-flow-trigger');
601
+ const authInput = document.getElementById('new-flow-auth-policy');
602
+ const eventInput = document.getElementById('new-flow-event');
603
+ const concurrencyInput = document.getElementById('new-flow-concurrency');
604
+
605
+ const name = nameInput ? nameInput.value.trim() : '';
606
+ if (!name) return;
607
+
608
+ const triggerType = triggerInput ? triggerInput.value : 'http';
609
+ const authPolicy = triggerType === 'http' && authInput ? authInput.value : 'admin';
610
+ const invokeRule = triggerType === 'http' && authPolicy === 'custom' ? '@request.auth.id != ""' : null;
611
+ const eventTrigger = triggerType === 'event' && eventInput ? eventInput.value.trim() : null;
612
+ const rawConcurrency = concurrencyInput ? concurrencyInput.value.trim() : '';
613
+ const maxConcurrentExecutions = rawConcurrency !== '' ? parseInt(rawConcurrency, 10) : null;
614
+
615
+ const initialFlow = {
616
+ name,
617
+ description: descInput ? descInput.value.trim() : '',
618
+ enabled: true,
619
+ triggerType,
620
+ authPolicy,
621
+ invokeRule,
622
+ eventTrigger,
623
+ maxConcurrentExecutions,
624
+ definition: {
625
+ startAt: 'FirstStep',
626
+ states: {
627
+ FirstStep: {
628
+ type: 'Pass',
629
+ result: { message: 'Hello from NodeStack Functions Flow!' },
630
+ end: true,
631
+ },
632
+ },
633
+ },
634
+ };
635
+
636
+ try {
637
+ const base = getFlowsApiBase();
638
+ const created = await api(base, {
639
+ method: 'POST',
640
+ body: JSON.stringify(initialFlow),
641
+ });
642
+ closeFlowModal();
643
+ await loadFlows();
644
+ openFlowDesigner(created.id);
645
+ } catch (err) {
646
+ toast('Failed to create flow: ' + (err.message || err), 'error');
647
+ }
648
+ }
649
+
650
+ function formatFlowTriggerLabel(flow) {
651
+ if (flow.triggerType === 'event') {
652
+ return `DB Event${flow.eventTrigger ? `: ${escapeHtml(flow.eventTrigger)}` : ''}`;
653
+ }
654
+ if (flow.triggerType === 'manual') {
655
+ return 'Manual (On-demand)';
656
+ }
657
+ return 'HTTP API';
658
+ }
659
+
660
+ function quickTestFlow(flowId) {
661
+ if (typeof openFlowDesigner === 'function') {
662
+ return openFlowDesigner(flowId, true);
663
+ }
664
+ }
665
+
666
+ async function inspectExecutionDetail(executionId) {
667
+ try {
668
+ let exec = (flowsState.executions || []).find((e) => e.id === executionId);
669
+ if (!exec || !exec.stepLogs) {
670
+ const base = getFlowsApiBase();
671
+ exec = await api(`${base}/executions/${executionId}`);
672
+ }
673
+ if (!exec) {
674
+ toast('Execution record not found', 'error');
675
+ return;
676
+ }
677
+
678
+ let root = document.getElementById('drawer-root');
679
+ if (!root) {
680
+ root = document.createElement('div');
681
+ root.id = 'drawer-root';
682
+ document.body.appendChild(root);
683
+ }
684
+
685
+ const isSuccess = exec.status === 'succeeded';
686
+ const statusColor = isSuccess ? 'var(--accent-success)' : exec.status === 'failed' ? 'var(--accent-danger)' : (exec.status === 'aborted' || exec.status === 'queued') ? 'var(--accent-warning, #f59e0b)' : '#3b82f6';
687
+ const stepCount = (exec.stepLogs || []).length;
688
+
689
+ root.innerHTML = `
690
+ <div id="flow-exec-drawer-backdrop" class="drawer-backdrop" onclick="closeFlowExecutionDrawer()" aria-hidden="true"></div>
691
+ <aside id="flow-exec-drawer-panel" class="record-drawer flow-execution-drawer" role="dialog" aria-modal="true" aria-labelledby="flow-exec-drawer-title" tabindex="-1">
692
+ <!-- Drawer Header -->
693
+ <div class="drawer-header" style="display: flex; align-items: center; justify-content: space-between;">
694
+ <div class="drawer-title-area" style="display: flex; align-items: center; gap: 0.75rem;">
695
+ <span style="font-weight: 800; color: ${statusColor}; text-transform: uppercase; font-size: 0.78rem; background: rgba(0,0,0,0.2); padding: 4px 8px; border-radius: 6px; border: 1px solid ${statusColor}44;">
696
+ ● ${escapeHtml(exec.status).toUpperCase()}
697
+ </span>
698
+ <div>
699
+ <h3 class="drawer-title" id="flow-exec-drawer-title" style="margin: 0; font-size: 1.1rem; color: var(--text-main);">
700
+ ${escapeHtml(exec.flowName)}
701
+ </h3>
702
+ <span style="font-size: 11px; color: var(--text-muted); font-family: var(--font-mono, monospace);">
703
+ ${escapeHtml(exec.id)} • ${exec.durationMs}ms
704
+ </span>
705
+ </div>
706
+ </div>
707
+ <div style="display: flex; align-items: center; gap: 8px;">
708
+ <button
709
+ class="btn btn-secondary btn-sm"
710
+ data-flow-id="${escapeHtml(exec.flowId)}"
711
+ data-exec-id="${escapeHtml(exec.id)}"
712
+ onclick="openFlowFromExecution(this.getAttribute('data-flow-id'), this.getAttribute('data-exec-id'))"
713
+ title="Open flow in visual designer with this execution"
714
+ style="font-size: 11px; padding: 4px 8px; font-weight: 600;"
715
+ >
716
+ Open in Designer ↗
717
+ </button>
718
+ <button class="drawer-close-btn" onclick="closeFlowExecutionDrawer()" aria-label="Close drawer">✕</button>
719
+ </div>
720
+ </div>
721
+
722
+ <!-- Drawer Body -->
723
+ <div class="drawer-body" style="padding: 1.25rem 1.5rem; overflow-y: auto; flex: 1; display: flex; flex-direction: column; gap: 1.25rem;">
724
+ <!-- Meta Grid -->
725
+ <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: 8px; background: rgba(255,255,255,0.03); border: 1px solid var(--border-subtle); border-radius: 8px; padding: 10px 14px; font-size: 12px;">
726
+ <div>
727
+ <span style="font-size: 10px; text-transform: uppercase; color: var(--text-muted); font-weight: 700; display: block;">Status</span>
728
+ <strong style="color: ${statusColor}; text-transform: uppercase;">${escapeHtml(exec.status)}</strong>
729
+ </div>
730
+ <div>
731
+ <span style="font-size: 10px; text-transform: uppercase; color: var(--text-muted); font-weight: 700; display: block;">Duration</span>
732
+ <span style="font-weight: 600; color: var(--text-main);">${exec.durationMs}ms</span>
733
+ </div>
734
+ <div>
735
+ <span style="font-size: 10px; text-transform: uppercase; color: var(--text-muted); font-weight: 700; display: block;">Steps</span>
736
+ <span style="font-weight: 600; color: var(--text-main);">${stepCount} steps</span>
737
+ </div>
738
+ <div>
739
+ <span style="font-size: 10px; text-transform: uppercase; color: var(--text-muted); font-weight: 700; display: block;">Caller</span>
740
+ <span style="font-weight: 600; color: var(--accent-primary, #6366f1); font-family: monospace;">${escapeHtml(exec.actorId || 'public')}</span>
741
+ </div>
742
+ <div>
743
+ <span style="font-size: 10px; text-transform: uppercase; color: var(--text-muted); font-weight: 700; display: block;">Started</span>
744
+ <span style="color: var(--text-muted);" title="${escapeHtml(exec.startedAt)}">${new Date(exec.startedAt).toLocaleTimeString()}</span>
745
+ </div>
746
+ </div>
747
+
748
+ <!-- Error Alert Banner (if failed) -->
749
+ ${exec.error ? `
750
+ <div style="background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.3); border-radius: 6px; padding: 10px 14px; font-size: 12px; color: var(--accent-danger);">
751
+ <strong>Execution Error:</strong> ${escapeHtml(exec.error)}
752
+ </div>
753
+ ` : ''}
754
+
755
+ <!-- Step-by-Step Execution Timeline -->
756
+ <div>
757
+ <span style="font-size: 11px; font-weight: 700; text-transform: uppercase; color: var(--text-muted); display: block; margin-bottom: 8px; letter-spacing: 0.05em;">
758
+ Step-by-Step Timeline (${stepCount})
759
+ </span>
760
+ <div style="display: flex; flex-direction: column; gap: 8px;">
761
+ ${(exec.stepLogs || []).map((log, idx) => {
762
+ const stepSuccess = log.status === 'succeeded';
763
+ const stepColor = stepSuccess ? 'var(--accent-success)' : 'var(--accent-danger)';
764
+ return `
765
+ <div style="background: var(--bg-card); border: 1px solid var(--border-subtle); border-left: 3px solid ${stepColor}; border-radius: 6px; padding: 10px 12px; font-size: 12px;">
766
+ <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px;">
767
+ <div style="display: flex; align-items: center; gap: 6px;">
768
+ <span style="font-size: 10px; color: var(--text-muted); font-weight: 700;">#${idx + 1}</span>
769
+ <strong style="color: var(--text-main); font-size: 13px;">${escapeHtml(log.step)}</strong>
770
+ <span class="flow-step-type-pill pill-${(log.type || 'Task').toLowerCase()}" style="font-size: 9px; padding: 1px 6px;">
771
+ ${escapeHtml((log.type || 'TASK')).toUpperCase()}
772
+ </span>
773
+ </div>
774
+ <span style="color: var(--text-muted); font-size: 11px; font-family: var(--font-mono, monospace);">
775
+ ${log.durationMs}ms
776
+ </span>
777
+ </div>
778
+ ${log.error ? `
779
+ <div style="color: var(--accent-danger); font-size: 11px; margin-top: 4px;">
780
+ ${escapeHtml(log.error)}
781
+ </div>
782
+ ` : ''}
783
+ ${log.output !== undefined ? `
784
+ <details style="margin-top: 6px; font-size: 11px;">
785
+ <summary style="cursor: pointer; color: var(--text-muted); font-weight: 600;">View Step Result</summary>
786
+ <pre style="background: var(--bg-input); border: 1px solid var(--border-subtle); border-radius: 4px; padding: 6px 8px; margin-top: 4px; max-height: 120px; overflow-y: auto; font-size: 11px; color: var(--text-main); font-family: var(--font-mono, monospace);">${escapeHtml(JSON.stringify(log.output, null, 2))}</pre>
787
+ </details>
788
+ ` : ''}
789
+ </div>
790
+ `;
791
+ }).join('')}
792
+ </div>
793
+ </div>
794
+
795
+ <!-- Input Payload -->
796
+ <div>
797
+ <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px;">
798
+ <span style="font-size: 11px; font-weight: 700; text-transform: uppercase; color: var(--text-muted); letter-spacing: 0.05em;">
799
+ Input Payload
800
+ </span>
801
+ <button class="btn btn-secondary btn-sm" onclick="copyFlowJson(this, 'flow-exec-input-json')" style="padding: 2px 8px; font-size: 10px;">
802
+ Copy JSON
803
+ </button>
804
+ </div>
805
+ <pre id="flow-exec-input-json" style="background: var(--bg-input); border: 1px solid var(--border-subtle); border-radius: 6px; padding: 10px 12px; font-family: var(--font-mono, monospace); font-size: 11px; color: var(--text-main); max-height: 160px; overflow-y: auto; margin: 0;">${escapeHtml(JSON.stringify(exec.input || {}, null, 2))}</pre>
806
+ </div>
807
+
808
+ <!-- Final Output Payload -->
809
+ <div>
810
+ <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px;">
811
+ <span style="font-size: 11px; font-weight: 700; text-transform: uppercase; color: var(--text-muted); letter-spacing: 0.05em;">
812
+ Final Output Payload
813
+ </span>
814
+ <button class="btn btn-secondary btn-sm" onclick="copyFlowJson(this, 'flow-exec-output-json')" style="padding: 2px 8px; font-size: 10px;">
815
+ Copy JSON
816
+ </button>
817
+ </div>
818
+ <pre id="flow-exec-output-json" style="background: var(--bg-input); border: 1px solid var(--border-subtle); border-radius: 6px; padding: 10px 12px; font-family: var(--font-mono, monospace); font-size: 11px; color: var(--text-main); max-height: 200px; overflow-y: auto; margin: 0;">${escapeHtml(JSON.stringify(exec.output !== undefined ? exec.output : (exec.error ? { error: exec.error } : {}), null, 2))}</pre>
819
+ </div>
820
+ </div>
821
+ </aside>
822
+ `;
823
+
824
+ setTimeout(() => {
825
+ document.getElementById('flow-exec-drawer-backdrop')?.classList.add('open');
826
+ document.getElementById('flow-exec-drawer-panel')?.classList.add('open');
827
+ }, 10);
828
+ } catch (err) {
829
+ toast('Failed to inspect flow execution: ' + (err.message || err), 'error');
830
+ }
831
+ }
832
+
833
+ function closeFlowExecutionDrawer() {
834
+ const backdrop = document.getElementById('flow-exec-drawer-backdrop');
835
+ const panel = document.getElementById('flow-exec-drawer-panel');
836
+ if (backdrop) backdrop.classList.remove('open');
837
+ if (panel) panel.classList.remove('open');
838
+ setTimeout(() => {
839
+ const root = document.getElementById('drawer-root');
840
+ if (root && root.querySelector('#flow-exec-drawer-panel')) {
841
+ root.innerHTML = '';
842
+ }
843
+ }, 200);
844
+ }
845
+
846
+ async function openFlowFromExecution(flowId, executionId) {
847
+ const exec = (flowsState.executions || []).find((e) => e.id === executionId);
848
+ closeFlowExecutionDrawer();
849
+ if (typeof openFlowDesigner === 'function') {
850
+ await openFlowDesigner(flowId, true);
851
+ if (exec && typeof designerState !== 'undefined') {
852
+ designerState.latestExecution = exec;
853
+ const drawer = document.getElementById('flow-test-drawer');
854
+ if (drawer && typeof renderTestDrawerHtml === 'function') {
855
+ drawer.innerHTML = renderTestDrawerHtml(designerState.activeFlow);
856
+ }
857
+ if (typeof renderSvgFlowchart === 'function') {
858
+ renderSvgFlowchart(designerState.activeFlow);
859
+ }
860
+ }
861
+ }
862
+ }
863
+
864
+ function copyFlowJson(btn, elementId) {
865
+ const el = document.getElementById(elementId);
866
+ if (!el) return;
867
+ try {
868
+ if (navigator.clipboard && navigator.clipboard.writeText) {
869
+ navigator.clipboard.writeText(el.textContent || '').then(() => {
870
+ const orig = btn.textContent;
871
+ btn.textContent = 'Copied!';
872
+ setTimeout(() => { btn.textContent = orig; }, 1500);
873
+ });
874
+ } else {
875
+ toast('Copied to clipboard', 'info');
876
+ }
877
+ } catch (_) {
878
+ toast('Copied to clipboard', 'info');
879
+ }
880
+ }
881
+
882
+ if (typeof window !== 'undefined') {
883
+ window.renderFlowsView = renderFlowsView;
884
+ window.loadFlows = loadFlows;
885
+ window.refreshFlowsView = refreshFlowsView;
886
+ window.switchFlowsTab = switchFlowsTab;
887
+ window.handleFlowsSearch = handleFlowsSearch;
888
+ window.handleFlowExecutionsStatusFilter = handleFlowExecutionsStatusFilter;
889
+ window.toggleFlowStatus = toggleFlowStatus;
890
+ window.deleteFlowPrompt = deleteFlowPrompt;
891
+ window.openDeleteFlowModal = openDeleteFlowModal;
892
+ window.closeDeleteFlowModal = closeDeleteFlowModal;
893
+ window.confirmDeleteFlow = confirmDeleteFlow;
894
+ window.openCreateFlowModal = openCreateFlowModal;
895
+ window.closeFlowModal = closeFlowModal;
896
+ window.toggleFlowTriggerInput = toggleFlowTriggerInput;
897
+ window.handleCreateFlowSubmit = handleCreateFlowSubmit;
898
+ window.quickTestFlow = quickTestFlow;
899
+ window.formatFlowTriggerLabel = formatFlowTriggerLabel;
900
+ window.inspectExecutionDetail = inspectExecutionDetail;
901
+ window.closeFlowExecutionDrawer = closeFlowExecutionDrawer;
902
+ window.openFlowFromExecution = openFlowFromExecution;
903
+ window.copyFlowJson = copyFlowJson;
904
+ }
905
+
906
+ if (typeof state !== 'undefined' && state.token && typeof loadFlows === 'function') {
907
+ loadFlows();
908
+ }